polotno 4.1.2 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/blueprint/side-panel/select-video.d.ts +10 -0
  2. package/blueprint/toolbar/html-toolbar.js +2 -2
  3. package/canvas/drawing-layer.d.ts +3 -2
  4. package/canvas/drawing-layer.js +1 -1
  5. package/canvas/element.js +1 -1
  6. package/canvas/hotkeys.js +1 -1
  7. package/canvas/page-controls.js +1 -1
  8. package/canvas/page.js +1 -1
  9. package/canvas/quill-font-formats.js +1 -1
  10. package/canvas/render-tag-element.js +1 -1
  11. package/canvas/rich-editor.d.ts +3 -1
  12. package/canvas/rich-editor.js +16 -3
  13. package/canvas/rules.js +1 -1
  14. package/canvas/text-element/font-specs-loader.d.ts +3 -0
  15. package/canvas/text-element/font-specs-loader.js +1 -0
  16. package/canvas/workspace-canvas.js +1 -1
  17. package/config.d.ts +1 -1
  18. package/config.js +1 -1
  19. package/icons/registry.d.ts +2 -0
  20. package/icons/registry.js +1 -1
  21. package/model/figure-model.d.ts +5 -0
  22. package/model/gif-model.d.ts +5 -0
  23. package/model/group-model.d.ts +40 -0
  24. package/model/group-model.js +1 -1
  25. package/model/image-model.d.ts +5 -0
  26. package/model/line-model.d.ts +5 -0
  27. package/model/page-model.d.ts +56 -0
  28. package/model/page-model.js +1 -1
  29. package/model/shape-model.d.ts +5 -0
  30. package/model/shape-model.js +1 -1
  31. package/model/store.d.ts +521 -0
  32. package/model/store.js +1 -1
  33. package/model/svg-model.d.ts +5 -0
  34. package/model/table-model.d.ts +5 -0
  35. package/model/text-model.d.ts +5 -0
  36. package/model/video-model.d.ts +5 -0
  37. package/package.json +4 -3
  38. package/pages-timeline/current-time.js +1 -1
  39. package/pages-timeline/element-track.js +1 -1
  40. package/pages-timeline/elements.js +1 -1
  41. package/pages-timeline/page-preview.js +1 -1
  42. package/pages-timeline/play-button.js +1 -1
  43. package/polotno.bundle.js +206 -130
  44. package/side-panel/select-video.d.ts +10 -0
  45. package/side-panel/size-panel.js +1 -1
  46. package/themes/carbon.css +157 -0
  47. package/toolbar/download-button.js +1 -1
  48. package/toolbar/html-toolbar.js +4 -4
  49. package/toolbar/image-toolbar.js +1 -1
  50. package/toolbar/text-toolbar.js +1 -1
  51. package/toolbar/video-toolbar.js +1 -1
  52. package/ui.css +1 -1
  53. package/utils/fonts.js +1 -1
  54. package/utils/l10n.d.ts +8 -0
  55. package/utils/l10n.js +1 -1
  56. package/utils/rich-text-html.d.ts +12 -0
  57. package/utils/rich-text-html.js +1 -1
  58. package/utils/split-element.d.ts +2 -0
  59. package/utils/split-element.js +1 -0
  60. package/utils/text-format-state.js +1 -1
  61. package/utils/text-format.d.ts +2 -2
  62. package/utils/text-format.js +1 -1
  63. package/utils/text.js +1 -1
  64. package/utils/timeline.d.ts +3 -0
  65. package/utils/timeline.js +1 -1
  66. package/utils/to-html.js +1 -1
  67. package/utils/to-pptx.js +1 -1
  68. package/utils/to-svg.js +1 -1
  69. package/utils/validate-key.js +1 -1
@@ -1 +1 @@
1
- export const QUILL_FONT_CLASS_TO_FAMILY={"ql-font-serif":"Georgia, Times New Roman, serif","ql-font-monospace":"Monaco, Courier New, monospace","ql-font-sans":"system-ui, -apple-system, BlinkMacSystemFont, sans-serif"};export const QUILL_SIZE_CLASS_TO_EM={"ql-size-small":.75,"ql-size-large":1.5,"ql-size-huge":2.5};export function guessFontFamilyFromQlClass(t){return t.replace(/^ql-font-/,"").split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}export function parsePrimaryFontFamily(t){return t.replace(/&quot;/g,'"').replace(/&amp;/g,"&").split(",")[0].trim().replace(/^["']|["']$/g,"")||null}export function parseFontSizeToPx(t,e){if(!t){return}const r=t.trim(),o=r.match(/^(\d+(?:\.\d+)?)px$/i);if(o){return parseFloat(o[1])}const n=r.match(/^(\d+(?:\.\d+)?)em$/i);if(n){return e*parseFloat(n[1])}const l=r.match(/^(\d+(?:\.\d+)?)rem$/i);return l?e*parseFloat(l[1]):void 0}export function parseHtmlRoot(t){return(new DOMParser).parseFromString(`<div id="polotno-rich-root">${t}</div>`,"text/html").getElementById("polotno-rich-root")}function t(t){for(const e of Array.from(t.classList)){if(e.startsWith("ql-indent-")){const t=parseInt(e.slice(10),10);if(t>0){return t}}}return 0}const e=new Set(["SPAN","STRONG","B","EM","I","U","S","DEL","SUB","SUP"]);function r(t,e){if(t.attributes.length!==e.attributes.length){return!1}for(const r of Array.from(t.attributes)){if(e.getAttribute(r.name)!==r.value){return!1}}return!0}export function cleanupInlineWrappers(t){const o=t=>{for(const e of Array.from(t.children)){o(e)}if(function(t){if("SPAN"!==t.tagName){return!1}for(const e of Array.from(t.attributes)){if(e.value.trim()){return!1}}return!0}(t)&&t.parentNode){const e=t.parentNode;for(;t.firstChild;){e.insertBefore(t.firstChild,t)}e.removeChild(t)}};for(const e of Array.from(t.children)){o(e)}const n=t=>{for(const e of Array.from(t.children)){n(e)}let o=t.firstElementChild;for(;o;){const t=o.nextElementSibling;if(t&&o.nextSibling===t&&e.has(o.tagName)&&o.tagName===t.tagName&&r(o,t)){for(;t.firstChild;){o.appendChild(t.firstChild)}t.remove(),n(o)}else{o=t}}};n(t)}export function normalizeRichTextHtml(e,r){var o;if(!e||!e.includes("<")){return e}const n=parseHtmlRoot(e);if(!n){return e}const l=t=>{for(const r of Array.from(t.children)){l(r)}const e=t.getAttribute("class");if(e){const o=e.split(/\s+/).filter(Boolean),n=[];for(const e of o){if(e.startsWith("ql-font-")){if(!t.style.fontFamily){const r=QUILL_FONT_CLASS_TO_FAMILY[e]||guessFontFamilyFromQlClass(e);t.style.fontFamily=r}continue}const o=QUILL_SIZE_CLASS_TO_EM[e];if(null==o){if(!e.startsWith("ql-align-")){if(e.startsWith("ql-indent-")){if("LI"===t.tagName){n.push(e);continue}const r=parseInt(e.slice(10),10);r>0&&!t.style.getPropertyValue("margin-inline-start")&&t.style.setProperty("margin-inline-start",.5*r+"em");continue}"ql-direction-rtl"!==e?n.push(e):t.style.direction||(t.style.direction="rtl")}}else{t.style.fontSize||(t.style.fontSize=r.fontSize*o+"px")}}n.length?t.setAttribute("class",n.join(" ")):t.removeAttribute("class")}const o=t.style.fontSize;if(o){const e=parseFontSizeToPx(o,r.fontSize);null!=e&&(t.style.fontSize=`${e}px`)}};l(n),cleanupInlineWrappers(n),function(e){for(const t of Array.from(e.querySelectorAll("span.ql-ui"))){t.remove()}const r=e.ownerDocument,o=t=>{const e=t.children;for(let r=e.length-1;r>=0;r--){if("li"===e[r].tagName.toLowerCase()){return e[r]}}return null};for(const n of Array.from(e.querySelectorAll("ol, ul"))){const e=n.tagName.toLowerCase(),l=Array.from(n.children).filter(t=>"li"===t.tagName.toLowerCase());if(0===l.length){continue}if(!l.some(e=>e.hasAttribute("data-list")||t(e)>0)){continue}const i=t=>{const r=t.getAttribute("data-list");return"ordered"===r?"ol":"bullet"===r||"checked"===r||"unchecked"===r?"ul":"ol"===e?"ol":"ul"},s=r.createDocumentFragment(),a=[{list:s,level:-1,type:""}];for(const n of l){const e=t(n),l=i(n);n.removeAttribute("data-list");for(const t of Array.from(n.classList)){t.startsWith("ql-indent-")&&n.classList.remove(t)}for(n.getAttribute("class")||n.removeAttribute("class");a.length>1&&a[a.length-1].level>e;){a.pop()}if(a[a.length-1].level===e&&a[a.length-1].type!==l&&a.pop(),a[a.length-1].level<e){const t=a[a.length-1],n=o(t.list)||t.list,i=r.createElement(l);n.appendChild(i),a.push({list:i,level:e,type:l})}a[a.length-1].list.appendChild(n)}n.replaceWith(s)}for(const t of Array.from(e.querySelectorAll("ul, ol"))){const e=Array.from(t.children).filter(t=>"li"===t.tagName.toLowerCase());e.length>0&&e.every(t=>"rtl"===t.style.direction||"rtl"===t.getAttribute("dir"))&&"rtl"!==t.style.direction&&(t.style.direction="rtl")}}(n);for(const t of Array.from(n.querySelectorAll("p"))){let e=t,r="",n="",l="";for(;1===e.childNodes.length&&null!=e.firstChild&&1===e.firstChild.nodeType;){const t=e.firstChild;t.style.fontFamily&&(r=t.style.fontFamily),t.style.fontWeight&&(n=t.style.fontWeight),"STRONG"!==t.tagName&&"B"!==t.tagName||(n="bold"),"EM"!==t.tagName&&"I"!==t.tagName&&"italic"!==(null===(o=t.style)||void 0===o?void 0:o.fontStyle)||(l="italic"),e=t}r&&(t.style.fontFamily=r),n&&(t.style.fontWeight=n),l&&(t.style.fontStyle=l)}return n.innerHTML}export function shrinkParagraphStrutForRaster(t){var e;if(!t||!t.includes("<p")){return t}const r=parseHtmlRoot(t);if(!r){return t}for(const o of Array.from(r.querySelectorAll("p"))){let t=!1;const n=[],l=r.ownerDocument.createTreeWalker(o,NodeFilter.SHOW_TEXT);let i=l.nextNode();for(;i;){if((i.textContent||"").length>0){let r=i.parentElement,l=null;for(;r&&r!==o;){const t=null===(e=r.style)||void 0===e?void 0:e.fontSize;if(t){const e=parseFloat(t);if(!Number.isNaN(e)){l=e;break}}r=r.parentElement}if(null==l){t=!0;break}n.push(l)}i=l.nextNode()}!t&&n.length>0&&(o.style.fontSize=`${Math.min(...n)}px`)}return r.innerHTML}export function extractFontFamiliesFromHtml(t){const e=new Set;if(!t||!t.includes("<")){return[]}const r=parseHtmlRoot(t);if(r){const t=r.querySelectorAll("[style]");for(const r of t){if(r.style.fontFamily){const t=parsePrimaryFontFamily(r.style.fontFamily);t&&e.add(t)}}}for(const o of t.matchAll(/\bfont-family="([^"]+)"/g)){const t=parsePrimaryFontFamily(o[1]);t&&e.add(t)}for(const o of t.matchAll(/\bql-font-([a-z0-9_-]+)\b/gi)){const t=`ql-font-${o[1]}`,r=parsePrimaryFontFamily(QUILL_FONT_CLASS_TO_FAMILY[t]||guessFontFamilyFromQlClass(t));r&&e.add(r)}return[...e]}export function scaleRichTextFontSizesInHtml(t,e){if(!t||1===e||e<=0||!Number.isFinite(e)){return t}const r=parseHtmlRoot(t);if(!r){return t}const o=t=>{const r=t.style.fontSize;if(r){const o=r.match(/^(\d+(?:\.\d+)?)(px|em|rem)$/i);if(o){const r=Math.round(parseFloat(o[1])*e*1e3)/1e3;t.style.fontSize=`${r}${o[2].toLowerCase()}`}}for(const e of Array.from(t.children)){o(e)}};return o(r),r.innerHTML}const o={bold:["STRONG","B"],italic:["EM","I"],underline:["U"],strike:["S","DEL"]},n={bold:t=>t.style.removeProperty("font-weight"),italic:t=>t.style.removeProperty("font-style"),color:t=>t.style.removeProperty("color"),underline:t=>{const e=t.style.textDecoration.replace(/\bunderline\b/g,"").trim();e?t.style.textDecoration=e:t.style.removeProperty("text-decoration")},strike:t=>{const e=t.style.textDecoration.replace(/\bline-through\b/g,"").trim();e?t.style.textDecoration=e:t.style.removeProperty("text-decoration")}};export function stripInlineFormat(t,e){var r,l;if(!t||!t.includes("<")){return t}const i=parseHtmlRoot(t);if(!i){return t}const s=o[e]||[],a=n[e];for(const o of s){let t;for(;t=i.querySelector(o);){const e=t.parentNode;a&&a(t);const o=null===(r=t.getAttribute("style"))||void 0===r?void 0:r.trim();if(o){const r=i.ownerDocument.createElement("span");for(r.setAttribute("style",o);t.firstChild;){r.appendChild(t.firstChild)}e.insertBefore(r,t)}else{for(;t.firstChild;){e.insertBefore(t.firstChild,t)}}e.removeChild(t)}}if(a){for(const o of Array.from(i.querySelectorAll("[style]"))){a(o),(null===(l=o.getAttribute("style"))||void 0===l?void 0:l.trim())||o.removeAttribute("style")}}return cleanupInlineWrappers(i),i.innerHTML}const l=Symbol("unset");export function isQuillFormatMixed(t,e){var r;let o=l;for(const n of t.ops){if("string"!=typeof n.insert||"\n"===n.insert){continue}const t=null===(r=n.attributes)||void 0===r?void 0:r[e];if(o===l){o=t}else if(t!==o){return!0}}return!1}export function stripInlineFontSizes(t){var e;if(!t||!t.includes("font-size")){return t}const r=parseHtmlRoot(t);if(!r){return t}const o=r.querySelectorAll("[style]");for(let n=0;n<o.length;n++){const t=o[n];t.style.fontSize&&(t.style.removeProperty("font-size"),(null===(e=t.getAttribute("style"))||void 0===e?void 0:e.trim())||t.removeAttribute("style"))}return cleanupInlineWrappers(r),r.innerHTML}export function stripInlineFontFamilies(t){var e;if(!t||!t.includes("font-family")&&!t.includes("ql-font-")){return t}const r=parseHtmlRoot(t);if(!r){return t}for(const o of Array.from(r.querySelectorAll("[style]"))){o.style.fontFamily&&(o.style.removeProperty("font-family"),(null===(e=o.getAttribute("style"))||void 0===e?void 0:e.trim())||o.removeAttribute("style"))}for(const o of Array.from(r.querySelectorAll("[class]"))){const t=o.getAttribute("class")||"",e=t.split(/\s+/).filter(t=>t&&!t.startsWith("ql-font-"));e.length!==t.split(/\s+/).filter(Boolean).length&&(e.length?o.setAttribute("class",e.join(" ")):o.removeAttribute("class"))}return cleanupInlineWrappers(r),r.innerHTML}export function hasMultipleDistinctInlineFontSizes(t){if(!t||!t.includes("<")){return!1}const e=parseHtmlRoot(t);if(!e){return!1}const r=new Set;for(const o of e.querySelectorAll("[style]")){const t=o.style.fontSize;if(t){const e=t.match(/^(\d+(?:\.\d+)?)px$/i);if(e&&(r.add(parseFloat(e[1])),r.size>1)){return!0}}}return!1}export function hasAnyInlineFontSize(t){if(!t||!t.includes("<")){return!1}const e=parseHtmlRoot(t);if(!e){return!1}for(const r of e.querySelectorAll("[style]")){if(r.style.fontSize){return!0}}return!1}export function listEffectiveFontFamilies(t,e){const r=[],o=e?parsePrimaryFontFamily(e)||e:"";o&&r.push(o);for(const i of extractFontFamiliesFromHtml(t||"")){const t=parsePrimaryFontFamily(i)||i;t&&r.push(t)}const n=new Set,l=[];for(const i of r){n.has(i)||(n.add(i),l.push(i))}return l.sort((t,e)=>t.localeCompare(e,void 0,{sensitivity:"base"})),l}
1
+ export const QUILL_FONT_CLASS_TO_FAMILY={"ql-font-serif":"Georgia, Times New Roman, serif","ql-font-monospace":"Monaco, Courier New, monospace","ql-font-sans":"system-ui, -apple-system, BlinkMacSystemFont, sans-serif"};export const QUILL_SIZE_CLASS_TO_EM={"ql-size-small":.75,"ql-size-large":1.5,"ql-size-huge":2.5};export function guessFontFamilyFromQlClass(t){return t.replace(/^ql-font-/,"").split("-").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" ")}export function parsePrimaryFontFamily(t){return t.replace(/&quot;/g,'"').replace(/&amp;/g,"&").split(",")[0].trim().replace(/^["']|["']$/g,"")||null}export function parseFontSizeToPx(t,e){if(!t){return}const r=t.trim(),o=r.match(/^(\d+(?:\.\d+)?)px$/i);if(o){return parseFloat(o[1])}const n=r.match(/^(\d+(?:\.\d+)?)em$/i);if(n){return e*parseFloat(n[1])}const i=r.match(/^(\d+(?:\.\d+)?)rem$/i);return i?e*parseFloat(i[1]):void 0}export function toNumericWeight(t){if("number"==typeof t){return t}if(!t){return 400}const e=String(t).trim().toLowerCase();if("normal"===e){return 400}if("bold"===e){return 700}if("bolder"===e){return 700}if("lighter"===e){return 300}const r=parseInt(e,10);return Number.isNaN(r)?400:r}export function isBoldWeight(t){return toNumericWeight(t)>=600}export function parseHtmlRoot(t){return(new DOMParser).parseFromString(`<div id="polotno-rich-root">${t}</div>`,"text/html").getElementById("polotno-rich-root")}function t(t){for(const e of Array.from(t.classList)){if(e.startsWith("ql-indent-")){const t=parseInt(e.slice(10),10);if(t>0){return t}}}return 0}const e=new Set(["SPAN","STRONG","B","EM","I","U","S","DEL","SUB","SUP"]);function r(t,e){if(t.attributes.length!==e.attributes.length){return!1}for(const r of Array.from(t.attributes)){if(e.getAttribute(r.name)!==r.value){return!1}}return!0}export function cleanupInlineWrappers(t){const o=t=>{for(const e of Array.from(t.children)){o(e)}if(function(t){if("SPAN"!==t.tagName){return!1}for(const e of Array.from(t.attributes)){if(e.value.trim()){return!1}}return!0}(t)&&t.parentNode){const e=t.parentNode;for(;t.firstChild;){e.insertBefore(t.firstChild,t)}e.removeChild(t)}};for(const e of Array.from(t.children)){o(e)}const n=t=>{for(const e of Array.from(t.children)){n(e)}let o=t.firstElementChild;for(;o;){const t=o.nextElementSibling;if(t&&o.nextSibling===t&&e.has(o.tagName)&&o.tagName===t.tagName&&r(o,t)){for(;t.firstChild;){o.appendChild(t.firstChild)}t.remove(),n(o)}else{o=t}}};n(t)}export function normalizeRichTextHtml(e,r){var o;if(!e||!e.includes("<")){return e}const n=parseHtmlRoot(e);if(!n){return e}const i=t=>{for(const r of Array.from(t.children)){i(r)}const e=t.getAttribute("class");if(e){const o=e.split(/\s+/).filter(Boolean),n=[];for(const e of o){if(e.startsWith("ql-font-")){if(!t.style.fontFamily){const r=QUILL_FONT_CLASS_TO_FAMILY[e]||guessFontFamilyFromQlClass(e);t.style.fontFamily=r}continue}const o=QUILL_SIZE_CLASS_TO_EM[e];if(null==o){if(!e.startsWith("ql-align-")){if(e.startsWith("ql-indent-")){if("LI"===t.tagName){n.push(e);continue}const r=parseInt(e.slice(10),10);r>0&&!t.style.getPropertyValue("margin-inline-start")&&t.style.setProperty("margin-inline-start",.5*r+"em");continue}"ql-direction-rtl"!==e?n.push(e):t.style.direction||(t.style.direction="rtl")}}else{t.style.fontSize||(t.style.fontSize=r.fontSize*o+"px")}}n.length?t.setAttribute("class",n.join(" ")):t.removeAttribute("class")}const o=t.style.fontSize;if(o){const e=parseFontSizeToPx(o,r.fontSize);null!=e&&(t.style.fontSize=`${e}px`)}};i(n),cleanupInlineWrappers(n),function(e){for(const t of Array.from(e.querySelectorAll("span.ql-ui"))){t.remove()}const r=e.ownerDocument,o=t=>{const e=t.children;for(let r=e.length-1;r>=0;r--){if("li"===e[r].tagName.toLowerCase()){return e[r]}}return null};for(const n of Array.from(e.querySelectorAll("ol, ul"))){const e=n.tagName.toLowerCase(),i=Array.from(n.children).filter(t=>"li"===t.tagName.toLowerCase());if(0===i.length){continue}if(!i.some(e=>e.hasAttribute("data-list")||t(e)>0)){continue}const l=t=>{const r=t.getAttribute("data-list");return"ordered"===r?"ol":"bullet"===r||"checked"===r||"unchecked"===r?"ul":"ol"===e?"ol":"ul"},s=r.createDocumentFragment(),a=[{list:s,level:-1,type:""}];for(const n of i){const e=t(n),i=l(n);n.removeAttribute("data-list");for(const t of Array.from(n.classList)){t.startsWith("ql-indent-")&&n.classList.remove(t)}for(n.getAttribute("class")||n.removeAttribute("class");a.length>1&&a[a.length-1].level>e;){a.pop()}if(a[a.length-1].level===e&&a[a.length-1].type!==i&&a.pop(),a[a.length-1].level<e){const t=a[a.length-1],n=o(t.list)||t.list,l=r.createElement(i);n.appendChild(l),a.push({list:l,level:e,type:i})}a[a.length-1].list.appendChild(n)}n.replaceWith(s)}for(const t of Array.from(e.querySelectorAll("ul, ol"))){const e=Array.from(t.children).filter(t=>"li"===t.tagName.toLowerCase());e.length>0&&e.every(t=>"rtl"===t.style.direction||"rtl"===t.getAttribute("dir"))&&"rtl"!==t.style.direction&&(t.style.direction="rtl")}}(n);for(const t of Array.from(n.querySelectorAll("p"))){let e=t,r="",n="",i="";for(;1===e.childNodes.length&&null!=e.firstChild&&1===e.firstChild.nodeType;){const t=e.firstChild;t.style.fontFamily&&(r=t.style.fontFamily),t.style.fontWeight&&(n=t.style.fontWeight),"STRONG"!==t.tagName&&"B"!==t.tagName||(n="bold"),"EM"!==t.tagName&&"I"!==t.tagName&&"italic"!==(null===(o=t.style)||void 0===o?void 0:o.fontStyle)||(i="italic"),e=t}r&&(t.style.fontFamily=r),n&&(t.style.fontWeight=n),i&&(t.style.fontStyle=i)}return n.innerHTML}export function shrinkParagraphStrutForRaster(t){var e;if(!t||!t.includes("<p")){return t}const r=parseHtmlRoot(t);if(!r){return t}for(const o of Array.from(r.querySelectorAll("p"))){let t=!1;const n=[],i=r.ownerDocument.createTreeWalker(o,NodeFilter.SHOW_TEXT);let l=i.nextNode();for(;l;){if((l.textContent||"").length>0){let r=l.parentElement,i=null;for(;r&&r!==o;){const t=null===(e=r.style)||void 0===e?void 0:e.fontSize;if(t){const e=parseFloat(t);if(!Number.isNaN(e)){i=e;break}}r=r.parentElement}if(null==i){t=!0;break}n.push(i)}l=i.nextNode()}!t&&n.length>0&&(o.style.fontSize=`${Math.min(...n)}px`)}return r.innerHTML}export function extractFontFamiliesFromHtml(t){const e=new Set;if(!t||!t.includes("<")){return[]}const r=parseHtmlRoot(t);if(r){const t=r.querySelectorAll("[style]");for(const r of t){if(r.style.fontFamily){const t=parsePrimaryFontFamily(r.style.fontFamily);t&&e.add(t)}}}for(const o of t.matchAll(/\bfont-family="([^"]+)"/g)){const t=parsePrimaryFontFamily(o[1]);t&&e.add(t)}for(const o of t.matchAll(/\bql-font-([a-z0-9_-]+)\b/gi)){const t=`ql-font-${o[1]}`,r=parsePrimaryFontFamily(QUILL_FONT_CLASS_TO_FAMILY[t]||guessFontFamilyFromQlClass(t));r&&e.add(r)}return[...e]}export function extractFontSpecsFromHtml(t,e){const r=parsePrimaryFontFamily(e.fontFamily)||e.fontFamily,o=String(toNumericWeight(e.fontWeight)),n="italic"===e.fontStyle?"italic":"normal",i=new Map,l=(t,e,o)=>{const n=parsePrimaryFontFamily(t)||t||r,l=`${n}\0${e}\0${o}`;i.has(l)||i.set(l,{family:n,weight:e,style:o})};if(l(r,o,n),t&&t.includes("<")){const e=parseHtmlRoot(t);if(e){const t=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT);let i=t.nextNode();for(;i;){if((i.textContent||"").trim().length>0){let t="",s="",a="",f=i.parentElement;for(;f&&f!==e;){if(!t){if(f.style.fontFamily){t=f.style.fontFamily}else{const e=(f.getAttribute("class")||"").split(/\s+/).find(t=>t.startsWith("ql-font-"));e&&(t=QUILL_FONT_CLASS_TO_FAMILY[e]||guessFontFamilyFromQlClass(e))}}s||(f.style.fontWeight?s=String(toNumericWeight(f.style.fontWeight)):"STRONG"!==f.tagName&&"B"!==f.tagName||(s="700")),a||(f.style.fontStyle?a=f.style.fontStyle:"EM"!==f.tagName&&"I"!==f.tagName||(a="italic")),f=f.parentElement}l(t||r,s||o,a||n)}i=t.nextNode()}}}return[...i.values()]}export function scaleRichTextFontSizesInHtml(t,e){if(!t||1===e||e<=0||!Number.isFinite(e)){return t}const r=parseHtmlRoot(t);if(!r){return t}const o=t=>{const r=t.style.fontSize;if(r){const o=r.match(/^(\d+(?:\.\d+)?)(px|em|rem)$/i);if(o){const r=Math.round(parseFloat(o[1])*e*1e3)/1e3;t.style.fontSize=`${r}${o[2].toLowerCase()}`}}for(const e of Array.from(t.children)){o(e)}};return o(r),r.innerHTML}const o={bold:["STRONG","B"],italic:["EM","I"],underline:["U"],strike:["S","DEL"]},n={bold:t=>t.style.removeProperty("font-weight"),italic:t=>t.style.removeProperty("font-style"),color:t=>t.style.removeProperty("color"),underline:t=>{const e=t.style.textDecoration.replace(/\bunderline\b/g,"").trim();e?t.style.textDecoration=e:t.style.removeProperty("text-decoration")},strike:t=>{const e=t.style.textDecoration.replace(/\bline-through\b/g,"").trim();e?t.style.textDecoration=e:t.style.removeProperty("text-decoration")}};export function stripInlineFormat(t,e){var r,i;if(!t||!t.includes("<")){return t}const l=parseHtmlRoot(t);if(!l){return t}const s=o[e]||[],a=n[e];for(const o of s){let t;for(;t=l.querySelector(o);){const e=t.parentNode;a&&a(t);const o=null===(r=t.getAttribute("style"))||void 0===r?void 0:r.trim();if(o){const r=l.ownerDocument.createElement("span");for(r.setAttribute("style",o);t.firstChild;){r.appendChild(t.firstChild)}e.insertBefore(r,t)}else{for(;t.firstChild;){e.insertBefore(t.firstChild,t)}}e.removeChild(t)}}if(a){for(const o of Array.from(l.querySelectorAll("[style]"))){a(o),(null===(i=o.getAttribute("style"))||void 0===i?void 0:i.trim())||o.removeAttribute("style")}}return cleanupInlineWrappers(l),l.innerHTML}const i=Symbol("unset");export function isQuillFormatMixed(t,e){var r;let o=i;for(const n of t.ops){if("string"!=typeof n.insert||"\n"===n.insert){continue}const t=null===(r=n.attributes)||void 0===r?void 0:r[e];if(o===i){o=t}else if(t!==o){return!0}}return!1}export function stripInlineFontSizes(t){var e;if(!t||!t.includes("font-size")){return t}const r=parseHtmlRoot(t);if(!r){return t}const o=r.querySelectorAll("[style]");for(let n=0;n<o.length;n++){const t=o[n];t.style.fontSize&&(t.style.removeProperty("font-size"),(null===(e=t.getAttribute("style"))||void 0===e?void 0:e.trim())||t.removeAttribute("style"))}return cleanupInlineWrappers(r),r.innerHTML}export function stripInlineFontFamilies(t){var e;if(!t||!t.includes("font-family")&&!t.includes("ql-font-")){return t}const r=parseHtmlRoot(t);if(!r){return t}for(const o of Array.from(r.querySelectorAll("[style]"))){o.style.fontFamily&&(o.style.removeProperty("font-family"),(null===(e=o.getAttribute("style"))||void 0===e?void 0:e.trim())||o.removeAttribute("style"))}for(const o of Array.from(r.querySelectorAll("[class]"))){const t=o.getAttribute("class")||"",e=t.split(/\s+/).filter(t=>t&&!t.startsWith("ql-font-"));e.length!==t.split(/\s+/).filter(Boolean).length&&(e.length?o.setAttribute("class",e.join(" ")):o.removeAttribute("class"))}return cleanupInlineWrappers(r),r.innerHTML}export function hasMultipleDistinctInlineFontSizes(t){if(!t||!t.includes("<")){return!1}const e=parseHtmlRoot(t);if(!e){return!1}const r=new Set;for(const o of e.querySelectorAll("[style]")){const t=o.style.fontSize;if(t){const e=t.match(/^(\d+(?:\.\d+)?)px$/i);if(e&&(r.add(parseFloat(e[1])),r.size>1)){return!0}}}return!1}export function hasAnyInlineFontSize(t){if(!t||!t.includes("<")){return!1}const e=parseHtmlRoot(t);if(!e){return!1}for(const r of e.querySelectorAll("[style]")){if(r.style.fontSize){return!0}}return!1}export function listEffectiveFontFamilies(t,e){const r=[],o=e?parsePrimaryFontFamily(e)||e:"";o&&r.push(o);for(const l of extractFontFamiliesFromHtml(t||"")){const t=parsePrimaryFontFamily(l)||l;t&&r.push(t)}const n=new Set,i=[];for(const l of r){n.has(l)||(n.add(l),i.push(l))}return i.sort((t,e)=>t.localeCompare(e,void 0,{sensitivity:"base"})),i}
@@ -0,0 +1,2 @@
1
+ export declare function canSplitAtPlayhead(element: any, tLocal: number): boolean;
2
+ export declare function splitElementAtPlayhead(element: any, tLocal: number): any | null;
@@ -0,0 +1 @@
1
+ import{getElementTimeRange as t,getVideoRestMs as e,MIN_DURATION as n}from"./timeline.js";import{clamp as i}from"../lib/utils.js";export function canSplitAtPlayhead(e,i){var a;const o=null===(a=e.page)||void 0===a?void 0:a.duration;if(!o){return!1}const{start:r,end:s}=t(e.animations,o);return i>r+n&&i<s-n}export function splitElementAtPlayhead(n,a){if(!canSplitAtPlayhead(n,a)){return null}const o=n.page.duration,{start:r}=t(n.animations,o),s=n.clone({},{skipSelect:!0});if(s.setZIndex(n.zIndex+1),n.setAnimation("exit",{name:"none",delay:o-a,enabled:!0}),s.setAnimation("enter",{name:"none",delay:a,enabled:!0}),"video"===n.type){const t=(n.endTime-n.startTime)*n.duration,o=n.speed||1;if(t>0){const d=e(a,0,r,t,n.startTime*n.duration,o),l=i(d/n.duration,n.startTime,n.endTime);s.set({startTime:l}),(a-r)*o<t&&n.set({endTime:l})}}return s}
@@ -1 +1 @@
1
- import*as t from"react";import*as e from"mobx";import{parsePrimaryFontFamily as o,parseFontSizeToPx as n}from"./rich-text-html.js";import{getTextFormat as i,applyTextFormat as r,FORMAT_KEYS as l}from"./text-format.js";const c=e.observable({active:null},{},{deep:!1});export function getActiveTextEditor(){return c.active}export function setActiveTextEditor(t){e.runInAction(()=>{c.active=Object.assign(Object.assign({},t),{currentFormat:{},mixedFormats:{},lastSelection:null})})}export function updateActiveTextFormat(t,o,n){e.runInAction(()=>{c.active&&(c.active=Object.assign(Object.assign({},c.active),{currentFormat:t,mixedFormats:o,lastSelection:n||c.active.lastSelection}))})}export function clearActiveTextEditor(t){e.runInAction(()=>{var e;t&&(null===(e=c.active)||void 0===e?void 0:e.instance)!==t||(c.active=null)})}const a={fontSize:["size"],fontFamily:["font"],fill:["color"],fontWeight:["bold"],fontStyle:["italic"],textDecoration:["underline","strike"]};export const ALL_QUILL_MIXED_KEYS=Array.from(new Set(l.flatMap(t=>a[t])));function s(t,e,i){var r,l;switch(t){case"fontSize":return null!==(r=n(e.size,i.fontSize))&&void 0!==r?r:i.fontSize;case"fontFamily":return e.font&&o(String(e.font))||i.fontFamily;case"fill":return null!==(l=e.color)&&void 0!==l?l:i.fill;case"fontWeight":return e.bold?"bold":i.fontWeight;case"fontStyle":return e.italic?"italic":i.fontStyle;case"textDecoration":{const t=[];return e.underline&&t.push("underline"),e.strike&&t.push("line-through"),t.join(" ")}}}export function quillToTextFormat(t,e,o){const n={};for(const i of l){if(a[i].some(t=>!0===e[t])){n[i]={value:void 0,mixed:!0,values:[]}}else{const e=s(i,t,o);n[i]={value:e,mixed:!1,values:[e]}}}return n}export function attrsToQuillOps(t){const e=[];return void 0!==t.fontFamily&&e.push(["font",t.fontFamily]),void 0!==t.fontSize&&e.push(["size",`${t.fontSize}px`]),void 0!==t.fill&&e.push(["color",t.fill]),void 0!==t.fontWeight&&e.push(["bold","bold"===t.fontWeight]),void 0!==t.fontStyle&&e.push(["italic","italic"===t.fontStyle]),void 0!==t.textDecoration&&(e.push(["underline",/\bunderline\b/.test(t.textDecoration)]),e.push(["strike",/\bline-through\b/.test(t.textDecoration)])),e}function u(t){return((null==t?void 0:t.selectedElements)||[]).filter(t=>"text"===t.type)}function f(t){const e=getActiveTextEditor();return e&&e.instance&&e.store===t?e:null}export function resolveSelectionScope(t,e){const o=t.getSelection()||e||{index:0,length:0},n="function"==typeof t.getLength?t.getLength():0,i=n<=1;return o.length<=0?{scope:"collapsed",sel:o,isEmpty:i}:{scope:o.length>=n-1?"full":"partial",sel:o,isEmpty:i}}export function applyToLiveEditor(t,e,o){const n=attrsToQuillOps(e);if(!n.length){return}const{scope:i,sel:r}=resolveSelectionScope(t,null!=o?o:null);for(const[l,c]of n){"collapsed"===i?t.format(l,c,"user"):t.formatText(r.index,r.length,l,c,"user")}}export function getTextFormatState(t){const e=f(t),o=u(t),n=!!e||o.length>0;var l;return{format:e?quillToTextFormat(e.currentFormat||{},e.mixedFormats||{},{fontSize:(l=e.element).fontSize,fontFamily:l.fontFamily,fill:l.fill,fontWeight:l.fontWeight,fontStyle:l.fontStyle,textDecoration:l.textDecoration}):i(o),enabled:n,applyTextFormat:e=>function(t,e){const o=f(t);if(!o){return void r(u(t),e)}const{scope:n,sel:i,isEmpty:l}=resolveSelectionScope(o.instance,o.lastSelection);"full"===n||"collapsed"===n&&!l?r([o.element],e):applyToLiveEditor(o.instance,e,i)}(t,e)}}export function observeTextFormatState(t,o){return e.reaction(()=>getTextFormatState(t),t=>o(t),{fireImmediately:!0})}export function useTextFormat(e){const[o,n]=t.useState(()=>getTextFormatState(e));return t.useEffect(()=>observeTextFormatState(e,n),[e]),o}
1
+ import*as t from"react";import*as e from"mobx";import{parsePrimaryFontFamily as o,parseFontSizeToPx as n,toNumericWeight as i}from"./rich-text-html.js";import{getTextFormat as r,applyTextFormat as l,FORMAT_KEYS as c}from"./text-format.js";const a=e.observable({active:null},{},{deep:!1});export function getActiveTextEditor(){return a.active}export function setActiveTextEditor(t){e.runInAction(()=>{a.active=Object.assign(Object.assign({},t),{currentFormat:{},mixedFormats:{},lastSelection:null})})}export function updateActiveTextFormat(t,o,n){e.runInAction(()=>{a.active&&(a.active=Object.assign(Object.assign({},a.active),{currentFormat:t,mixedFormats:o,lastSelection:n||a.active.lastSelection}))})}export function clearActiveTextEditor(t){e.runInAction(()=>{var e;t&&(null===(e=a.active)||void 0===e?void 0:e.instance)!==t||(a.active=null)})}const s={fontSize:["size"],fontFamily:["font"],fill:["color"],fontWeight:["font-weight"],fontStyle:["italic"],textDecoration:["underline","strike"]};export const ALL_QUILL_MIXED_KEYS=Array.from(new Set(c.flatMap(t=>s[t])));function f(t,e,r){var l,c;switch(t){case"fontSize":return null!==(l=n(e.size,r.fontSize))&&void 0!==l?l:r.fontSize;case"fontFamily":return e.font&&o(String(e.font))||r.fontFamily;case"fill":return null!==(c=e.color)&&void 0!==c?c:r.fill;case"fontWeight":return null!=e["font-weight"]?i(e["font-weight"]):i(r.fontWeight);case"fontStyle":return e.italic?"italic":r.fontStyle;case"textDecoration":{const t=[];return e.underline&&t.push("underline"),e.strike&&t.push("line-through"),t.join(" ")}}}export function quillToTextFormat(t,e,o){const n={};for(const i of c){if(s[i].some(t=>!0===e[t])){n[i]={value:void 0,mixed:!0,values:[]}}else{const e=f(i,t,o);n[i]={value:e,mixed:!1,values:[e]}}}return n}export function attrsToQuillOps(t){const e=[];return void 0!==t.fontFamily&&e.push(["font",t.fontFamily]),void 0!==t.fontSize&&e.push(["size",`${t.fontSize}px`]),void 0!==t.fill&&e.push(["color",t.fill]),void 0!==t.fontWeight&&e.push(["font-weight",String(i(t.fontWeight))]),void 0!==t.fontStyle&&e.push(["italic","italic"===t.fontStyle]),void 0!==t.textDecoration&&(e.push(["underline",/\bunderline\b/.test(t.textDecoration)]),e.push(["strike",/\bline-through\b/.test(t.textDecoration)])),e}function u(t){return((null==t?void 0:t.selectedElements)||[]).filter(t=>"text"===t.type)}function p(t){const e=getActiveTextEditor();return e&&e.instance&&e.store===t?e:null}export function resolveSelectionScope(t,e){const o=t.getSelection()||e||{index:0,length:0},n="function"==typeof t.getLength?t.getLength():0,i=n<=1;return o.length<=0?{scope:"collapsed",sel:o,isEmpty:i}:{scope:o.length>=n-1?"full":"partial",sel:o,isEmpty:i}}export function applyToLiveEditor(t,e,o){const n=attrsToQuillOps(e);if(!n.length){return}const{scope:i,sel:r}=resolveSelectionScope(t,null!=o?o:null);for(const[l,c]of n){"collapsed"===i?t.format(l,c,"user"):t.formatText(r.index,r.length,l,c,"user")}}export function getTextFormatState(t){const e=p(t),o=u(t),n=!!e||o.length>0;var i;return{format:e?quillToTextFormat(e.currentFormat||{},e.mixedFormats||{},{fontSize:(i=e.element).fontSize,fontFamily:i.fontFamily,fill:i.fill,fontWeight:i.fontWeight,fontStyle:i.fontStyle,textDecoration:i.textDecoration}):r(o),enabled:n,applyTextFormat:e=>function(t,e){const o=p(t);if(!o){return void l(u(t),e)}const{scope:n,sel:i,isEmpty:r}=resolveSelectionScope(o.instance,o.lastSelection);"full"===n||"collapsed"===n&&!r?l([o.element],e):applyToLiveEditor(o.instance,e,i)}(t,e)}}export function observeTextFormatState(t,o){return e.reaction(()=>getTextFormatState(t),t=>o(t),{fireImmediately:!0})}export function useTextFormat(e){const[o,n]=t.useState(()=>getTextFormatState(e));return t.useEffect(()=>observeTextFormatState(e,n),[e]),o}
@@ -9,7 +9,7 @@ export type TextFormat = {
9
9
  fontSize: FormatValue<number>;
10
10
  fontFamily: FormatValue<string>;
11
11
  fill: FormatValue<string>;
12
- fontWeight: FormatValue<string>;
12
+ fontWeight: FormatValue<number>;
13
13
  fontStyle: FormatValue<string>;
14
14
  textDecoration: FormatValue<string>;
15
15
  };
@@ -17,7 +17,7 @@ export type TextFormatAttrs = Partial<{
17
17
  fontSize: number;
18
18
  fontFamily: string;
19
19
  fill: string;
20
- fontWeight: string;
20
+ fontWeight: number | 'bold' | 'normal' | string;
21
21
  fontStyle: string;
22
22
  textDecoration: string;
23
23
  }>;
@@ -1 +1 @@
1
- import{parsePrimaryFontFamily as t,parseFontSizeToPx as e,parseHtmlRoot as o,stripInlineFontSizes as n,stripInlineFontFamilies as r,stripInlineFormat as s,QUILL_FONT_CLASS_TO_FAMILY as i,guessFontFamilyFromQlClass as c}from"./rich-text-html.js";export const FORMAT_KEYS=["fontSize","fontFamily","fill","fontWeight","fontStyle","textDecoration"];function a(o,n,r){switch(n){case"fontSize":return e(o.style.fontSize,r.fontSize);case"fontFamily":{if(o.style.fontFamily){return t(o.style.fontFamily)||void 0}const e=(o.getAttribute("class")||"").split(/\s+/).find(t=>t.startsWith("ql-font-"));if(e){const o=i[e]||c(e);return t(o)||void 0}return}case"fill":return o.style.color||void 0;case"fontWeight":return o.style.fontWeight?o.style.fontWeight:"STRONG"===o.tagName||"B"===o.tagName?"bold":void 0;case"fontStyle":return o.style.fontStyle?o.style.fontStyle:"EM"===o.tagName||"I"===o.tagName?"italic":void 0;case"textDecoration":return o.style.textDecoration?o.style.textDecoration:"U"===o.tagName?"underline":"S"===o.tagName||"DEL"===o.tagName?"line-through":void 0}}function f(t,e,o){const n={},r=new Set;let s=t.parentElement;for(;s&&s!==e;){for(const t of FORMAT_KEYS){if(r.has(t)){continue}const e=a(s,t,o);void 0!==e&&(n[t]=e,r.add(t))}s=s.parentElement}for(const i of FORMAT_KEYS){r.has(i)||(n[i]=o[i])}return n}function l(t,e){return 0===t.length?{value:e,mixed:!1,values:void 0===e?[]:[e]}:1===t.length?{value:t[0],mixed:!1,values:t}:{value:void 0,mixed:!0,values:t}}function u(t){const e=function(t){const e=t.text||"";if(!e.includes("<")){if(0===e.trim().length){return[]}const o={};for(const e of FORMAT_KEYS){o[e]=t[e]}return[o]}const n=o(e);if(!n){return[]}const r=[],s=n.ownerDocument.createTreeWalker(n,NodeFilter.SHOW_TEXT);let i=s.nextNode();for(;i;){const e=i;(e.textContent||"").trim().length>0&&r.push(f(e,n,t)),i=s.nextNode()}return r}(t),n={};for(const o of FORMAT_KEYS){const r=[];for(const t of e){const e=t[o];void 0===e||r.includes(e)||r.push(e)}const s=0===r.length?t[o]:void 0;n[o]=l(r,s)}return n}export function getTextFormat(t){return Array.isArray(t)?function(t){const e={};for(const o of FORMAT_KEYS){const n=[];for(const e of t){for(const t of e[o].values){n.includes(t)||n.push(t)}}e[o]=l(n,void 0)}return e}(t.map(u)):u(t)}function d(t,e){switch(e){case"fontSize":return n(t);case"fontFamily":return r(t);case"fill":return s(t,"color");case"fontWeight":return s(t,"bold");case"fontStyle":return s(t,"italic");case"textDecoration":return s(s(t,"underline"),"strike")}}export function patchTextFormat(t,e){const o=FORMAT_KEYS.filter(t=>void 0!==e[t]);if(0===o.length){return{attrsToSet:{}}}const n={};for(const s of o){n[s]=e[s]}let r=t.text||"";for(const s of o){r=d(r,s)}return r!==(t.text||"")&&(n.text=r),{attrsToSet:n}}export function applyTextFormat(t,e){var o;const n=Array.isArray(t)?t:[t];if(0===n.length){return}const r=t=>{const{attrsToSet:o}=patchTextFormat(t,e);Object.keys(o).length&&t.set(o)};if(1===n.length){return void r(n[0])}const s=new Map;for(const i of n){const t=i.store,e=s.get(t)||[];e.push(i),s.set(t,e)}for(const[i,c]of s){(null===(o=null==i?void 0:i.history)||void 0===o?void 0:o.transaction)?i.history.transaction(()=>c.forEach(r)):c.forEach(r)}}
1
+ import{parsePrimaryFontFamily as t,parseFontSizeToPx as e,parseHtmlRoot as o,stripInlineFontSizes as n,stripInlineFontFamilies as r,stripInlineFormat as i,toNumericWeight as s,QUILL_FONT_CLASS_TO_FAMILY as c,guessFontFamilyFromQlClass as a}from"./rich-text-html.js";export const FORMAT_KEYS=["fontSize","fontFamily","fill","fontWeight","fontStyle","textDecoration"];function f(o,n,r){switch(n){case"fontSize":return e(o.style.fontSize,r.fontSize);case"fontFamily":{if(o.style.fontFamily){return t(o.style.fontFamily)||void 0}const e=(o.getAttribute("class")||"").split(/\s+/).find(t=>t.startsWith("ql-font-"));if(e){const o=c[e]||a(e);return t(o)||void 0}return}case"fill":return o.style.color||void 0;case"fontWeight":return o.style.fontWeight?s(o.style.fontWeight):"STRONG"===o.tagName||"B"===o.tagName?700:void 0;case"fontStyle":return o.style.fontStyle?o.style.fontStyle:"EM"===o.tagName||"I"===o.tagName?"italic":void 0;case"textDecoration":return o.style.textDecoration?o.style.textDecoration:"U"===o.tagName?"underline":"S"===o.tagName||"DEL"===o.tagName?"line-through":void 0}}function l(t,e){return"fontWeight"===e?s(t.fontWeight):t[e]}function u(t,e,o){const n={},r=new Set;let i=t.parentElement;for(;i&&i!==e;){for(const t of FORMAT_KEYS){if(r.has(t)){continue}const e=f(i,t,o);void 0!==e&&(n[t]=e,r.add(t))}i=i.parentElement}for(const s of FORMAT_KEYS){r.has(s)||(n[s]=l(o,s))}return n}function h(t,e){return 0===t.length?{value:e,mixed:!1,values:void 0===e?[]:[e]}:1===t.length?{value:t[0],mixed:!1,values:t}:{value:void 0,mixed:!0,values:t}}function d(t){const e=function(t){const e=t.text||"";if(!e.includes("<")){if(0===e.trim().length){return[]}const o={};for(const e of FORMAT_KEYS){o[e]=l(t,e)}return[o]}const n=o(e);if(!n){return[]}const r=[],i=n.ownerDocument.createTreeWalker(n,NodeFilter.SHOW_TEXT);let s=i.nextNode();for(;s;){const e=s;(e.textContent||"").trim().length>0&&r.push(u(e,n,t)),s=i.nextNode()}return r}(t),n={};for(const o of FORMAT_KEYS){const r=[];for(const t of e){const e=t[o];void 0===e||r.includes(e)||r.push(e)}const i=0===r.length?l(t,o):void 0;n[o]=h(r,i)}return n}export function getTextFormat(t){return Array.isArray(t)?function(t){const e={};for(const o of FORMAT_KEYS){const n=[];for(const e of t){for(const t of e[o].values){n.includes(t)||n.push(t)}}e[o]=h(n,void 0)}return e}(t.map(d)):d(t)}function g(t,e){switch(e){case"fontSize":return n(t);case"fontFamily":return r(t);case"fill":return i(t,"color");case"fontWeight":return i(t,"bold");case"fontStyle":return i(t,"italic");case"textDecoration":return i(i(t,"underline"),"strike")}}let m=!1;function y(t){return"string"!=typeof t||/^\d+$/.test(t.trim())||m||(m=!0,console.warn("[polotno] applyTextFormat({ fontWeight }) with a string such as 'bold'/'normal' is deprecated; pass a number (100–900), e.g. 700.")),s(t)}export function patchTextFormat(t,e){const o=FORMAT_KEYS.filter(t=>void 0!==e[t]);if(0===o.length){return{attrsToSet:{}}}const n={};for(const i of o){n[i]="fontWeight"===i?String(y(e.fontWeight)):e[i]}let r=t.text||"";for(const i of o){r=g(r,i)}return r!==(t.text||"")&&(n.text=r),{attrsToSet:n}}export function applyTextFormat(t,e){var o;const n=Array.isArray(t)?t:[t];if(0===n.length){return}const r=t=>{const{attrsToSet:o}=patchTextFormat(t,e);Object.keys(o).length&&t.set(o)};if(1===n.length){return void r(n[0])}const i=new Map;for(const s of n){const t=s.store,e=i.get(t)||[];e.push(s),i.set(t,e)}for(const[s,c]of i){(null===(o=null==s?void 0:s.history)||void 0===o?void 0:o.transaction)?s.history.transaction(()=>c.forEach(r)):c.forEach(r)}}
package/utils/text.js CHANGED
@@ -1 +1 @@
1
- import{parsePrimaryFontFamily as t,parseFontSizeToPx as e}from"./rich-text-html.js";export function removeTags(t=""){return(t.match(/<\/p>/gi)||[]).length>1&&(t=t.replace(/<\/p>/gi,(t,e,n)=>(n.slice(e+t.length).match(/<\/p>/gi)||[]).length>0?"\n":t)),t.replace(/(<([^>]+)>)/gi,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&nbsp;/g," ")}function n(t,e){var n,o;return!!t.bold==!!e.bold&&!!t.italic==!!e.italic&&!!t.underline==!!e.underline&&!!t.strike==!!e.strike&&(t.color||"")===(e.color||"")&&(t.fontFamily||"")===(e.fontFamily||"")&&(null!==(n=t.fontSize)&&void 0!==n?n:-1)===(null!==(o=e.fontSize)&&void 0!==o?o:-1)}export function parseHtmlToSegments(o,i){var l;if(!o){return[]}const r=(new DOMParser).parseFromString(o,"text/html"),c=[],a=r.body.querySelectorAll("p"),s=null!==(l=null==i?void 0:i.fontSize)&&void 0!==l?l:14;function f(n,o){var i;if(n.nodeType===Node.TEXT_NODE){const t=n.textContent||"";return void(t&&c.push(function(t,e){const n={text:t};return e.bold&&(n.bold=!0),e.italic&&(n.italic=!0),e.underline&&(n.underline=!0),e.strike&&(n.strike=!0),e.color&&(n.color=e.color),e.fontFamily&&(n.fontFamily=e.fontFamily),null!=e.fontSize&&(n.fontSize=e.fontSize),n}(t,o)))}if(n.nodeType!==Node.ELEMENT_NODE){return}const l=n,r=l.tagName.toLowerCase(),a=Object.assign({},o);"strong"!==r&&"b"!==r||(a.bold=!0),"em"!==r&&"i"!==r||(a.italic=!0),"u"===r&&(a.underline=!0),"s"===r&&(a.strike=!0);const u=l.style;u.color&&(a.color=u.color),("bold"===u.fontWeight||parseInt(u.fontWeight)>=700)&&(a.bold=!0),"italic"===u.fontStyle&&(a.italic=!0);const g=u.textDecoration||u.textDecorationLine||"";if(g.includes("underline")&&(a.underline=!0),g.includes("line-through")&&(a.strike=!0),u.fontFamily){const e=t(u.fontFamily);e&&(a.fontFamily=e)}if(u.fontSize){const t=null!==(i=o.fontSize)&&void 0!==i?i:s,n=e(u.fontSize,t);null!=n&&(a.fontSize=n)}for(const t of Array.from(l.childNodes)){f(t,a)}}a.length>0?a.forEach((t,e)=>{f(t,{}),e<a.length-1&&c.push({text:"\n"})}):f(r.body,{});const u=[];for(const t of c){if(!t.text){continue}const e=u[u.length-1];e&&n(e,t)?e.text+=t.text:u.push(t)}return u}export function sanitizeHtml(t){return t?/<[a-z][a-z0-9]*(\s[^>]*)?>[^<]*<\/[a-z][a-z0-9]*>/i.test(t)?t=(t=t.replace(/<(?![a-z/!])/gi,"&lt;")).replace(/([^a-z0-9"'\s/])>/gi,"$1&gt;"):t.replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}
1
+ import{parsePrimaryFontFamily as t,parseFontSizeToPx as e,isBoldWeight as n}from"./rich-text-html.js";export function removeTags(t=""){return(t.match(/<\/p>/gi)||[]).length>1&&(t=t.replace(/<\/p>/gi,(t,e,n)=>(n.slice(e+t.length).match(/<\/p>/gi)||[]).length>0?"\n":t)),t.replace(/(<([^>]+)>)/gi,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&nbsp;/g," ")}function o(t,e){var n,o;return!!t.bold==!!e.bold&&!!t.italic==!!e.italic&&!!t.underline==!!e.underline&&!!t.strike==!!e.strike&&(t.color||"")===(e.color||"")&&(t.fontFamily||"")===(e.fontFamily||"")&&(null!==(n=t.fontSize)&&void 0!==n?n:-1)===(null!==(o=e.fontSize)&&void 0!==o?o:-1)}export function parseHtmlToSegments(i,l){var r;if(!i){return[]}const c=(new DOMParser).parseFromString(i,"text/html"),a=[],s=c.body.querySelectorAll("p"),f=null!==(r=null==l?void 0:l.fontSize)&&void 0!==r?r:14;function u(o,i){var l;if(o.nodeType===Node.TEXT_NODE){const t=o.textContent||"";return void(t&&a.push(function(t,e){const n={text:t};return e.bold&&(n.bold=!0),e.italic&&(n.italic=!0),e.underline&&(n.underline=!0),e.strike&&(n.strike=!0),e.color&&(n.color=e.color),e.fontFamily&&(n.fontFamily=e.fontFamily),null!=e.fontSize&&(n.fontSize=e.fontSize),n}(t,i)))}if(o.nodeType!==Node.ELEMENT_NODE){return}const r=o,c=r.tagName.toLowerCase(),s=Object.assign({},i);"strong"!==c&&"b"!==c||(s.bold=!0),"em"!==c&&"i"!==c||(s.italic=!0),"u"===c&&(s.underline=!0),"s"===c&&(s.strike=!0);const g=r.style;g.color&&(s.color=g.color),n(g.fontWeight)&&(s.bold=!0),"italic"===g.fontStyle&&(s.italic=!0);const p=g.textDecoration||g.textDecorationLine||"";if(p.includes("underline")&&(s.underline=!0),p.includes("line-through")&&(s.strike=!0),g.fontFamily){const e=t(g.fontFamily);e&&(s.fontFamily=e)}if(g.fontSize){const t=null!==(l=i.fontSize)&&void 0!==l?l:f,n=e(g.fontSize,t);null!=n&&(s.fontSize=n)}for(const t of Array.from(r.childNodes)){u(t,s)}}s.length>0?s.forEach((t,e)=>{u(t,{}),e<s.length-1&&a.push({text:"\n"})}):u(c.body,{});const g=[];for(const t of a){if(!t.text){continue}const e=g[g.length-1];e&&o(e,t)?e.text+=t.text:g.push(t)}return g}export function sanitizeHtml(t){return t?/<[a-z][a-z0-9]*(\s[^>]*)?>[^<]*<\/[a-z][a-z0-9]*>/i.test(t)?t=(t=t.replace(/<(?![a-z/!])/gi,"&lt;")).replace(/([^a-z0-9"'\s/])>/gi,"$1&gt;"):t.replace(/</g,"&lt;").replace(/>/g,"&gt;"):""}
@@ -3,9 +3,12 @@ type AnimationTiming = {
3
3
  enabled: boolean;
4
4
  delay: number;
5
5
  };
6
+ export declare const MIN_DURATION = 100;
6
7
  export declare function getElementTimeRange(animations: AnimationTiming[] | undefined, pageDuration: number): {
7
8
  start: number;
8
9
  end: number;
9
10
  };
11
+ export declare function getPlayheadLocalTime(self: any): number | null;
12
+ export declare function revealElementAtPlayhead(element: any): void;
10
13
  export declare function getVideoRestMs(currentTime: number, pageStartTime: number, enterStart: number, trimDurationMs: number, offsetMs: number, speed?: number): number;
11
14
  export {};
package/utils/timeline.js CHANGED
@@ -1 +1 @@
1
- export function getElementTimeRange(e,n){const t=null==e?void 0:e.find(e=>"enter"===e.type),l=null==e?void 0:e.find(e=>"exit"===e.type);return{start:(null==t?void 0:t.enabled)?t.delay:0,end:(null==l?void 0:l.enabled)?n-l.delay:n}}export function getVideoRestMs(e,n,t,l,d,i=1){const o=(e||n)-n-t;return(o<=0?0:o*i%l)+d}
1
+ export const MIN_DURATION=100;export function getElementTimeRange(e,t){const n=null==e?void 0:e.find(e=>"enter"===e.type),a=null==e?void 0:e.find(e=>"exit"===e.type),i=Math.max(0,Math.min(t,(null==n?void 0:n.enabled)?n.delay:0)),l=Math.min(t,(null==a?void 0:a.enabled)?t-a.delay:t);return{start:i,end:Math.max(i,l)}}export function getPlayheadLocalTime(e){var t,n;return null!==(n=null===(t=e.page)||void 0===t?void 0:t.playheadLocalTime)&&void 0!==n?n:null}export function revealElementAtPlayhead(e){const t=e.store,n=e.page;if("playhead"!==t.timingPreview||!n){return}const{start:a,end:i}=getElementTimeRange(e.animations,n.duration),l=t.effectiveTime-n.startTime;if(l>=a&&l<i){return}const o=Math.max(a,Math.min(l,Math.max(a,i-1)));t.setCurrentTime(n.startTime+o)}export function getVideoRestMs(e,t,n,a,i,l=1){const o=(e||t)-t-n;return(o<=0?0:o*l%a)+i}
package/utils/to-html.js CHANGED
@@ -1 +1 @@
1
- var t=this&&this.__rest||function(t,e){var o={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(o[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++){e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(o[i[n]]=t[i[n]])}}return o};import{getCrop as e,loadImage as o}from"./image.js";import*as i from"./svg.js";import{figureToSvg as n}from"./figure-to-svg.js";import{resetStyleContent as r}from"./reset-style.js";import{Effects as a,shapeFilterToCSS as s}from"./filters.js";import{getVideoSize as l}from"./video.js";import{getGoogleFontsUrl as d}from"./fonts.js";import{forEveryNode as c}from"../model/group-model.js";import{getCurvePath as g}from"../canvas/text-element.js";import{removeTags as p,parseHtmlToSegments as f}from"./text.js";import b from"konva";import*as m from"./gradient.js";import{createSVGGradientDef as u,segmentsToTspans as y,getHtml as k}from"./text-html.js";import{generateBackgroundShapeFromRects as x}from"./background-shape.js";import{detectLineRects as w,detectSize as $}from"./html2canvas.js";import{normalizeRichTextHtml as v,extractFontFamiliesFromHtml as j}from"./rich-text-html.js";export const h=(t,e,...o)=>({type:t,props:e,children:o||[]});function S(t){return m.isGradient(t),t}export function fixRatio(t){var e=(new DOMParser).parseFromString(t,"image/svg+xml");return e.documentElement.setAttribute("preserveAspectRatio","none"),(new XMLSerializer).serializeToString(e)}const O=async({element:t,page:e,store:n})=>{let{src:r}=t;if("svg"===t.type){let e=await i.urlToString(r);e=fixRatio(e),r=Object.keys(t.colorsReplace).length?i.replaceColors(e,new Map(Object.entries(t.colorsReplace))):i.svgToURL(e)}let a="";t.flipX&&(a+="scaleX(-1)"),t.flipY&&(a+="scaleY(-1)"),a||(a="none");const s={};if("svg"===t.type&&t.maskSrc){const e=await i.urlToBase64(r);s["mask-image"]=`url(${e})`,s["mask-size"]="100% 100%",s["mask-position"]="0 0",s["mask-repeat"]="no-repeat",s["-webkit-mask-image"]=`url(${e})`,s["-webkit-mask-size"]="100% 100%",s["-webkit-mask-position"]="0 0",s["-webkit-mask-repeat"]="no-repeat",r=t.maskSrc}else if(t.clipSrc){const e=t.clipSrc,o=await i.urlToBase64(e);s["mask-image"]=`url(${o})`,s["mask-size"]="100% 100%",s["mask-position"]="0 0",s["mask-repeat"]="no-repeat",s["-webkit-mask-image"]=`url(${o})`,s["-webkit-mask-size"]="100% 100%",s["-webkit-mask-position"]="0 0",s["-webkit-mask-repeat"]="no-repeat"}const l=await o(r),d=l.width*t.cropWidth,c=l.height*t.cropHeight,g=t.width/t.height;let p,f;const b=d/c,u="svg"===t.type||t.stretchEnabled;u?(p=d,f=c):g>=b?(p=d,f=d/g):(p=c*g,f=c);const y=p/l.width,k=f/l.height,x=p/f>t.width/t.height?t.height/f:t.width/p,w=u?t.width/p:x,$=u?t.height/f:x,v=p*w/y,j=f*$/k;let O=t.cropX*w*l.width,z=t.cropY*$*l.height;t.flipX&&(O=(1-t.cropX-t.cropWidth)*w*l.width),t.flipY&&(z=(1-t.cropY-t.cropHeight)*$*l.height);const H=t.borderSize&&m.isGradient(t.borderColor),W=H?Math.max(0,t.cornerRadius-t.borderSize):t.cornerRadius,M=h("div",{style:Object.assign(Object.assign({},s),{width:"100%",height:"100%",borderRadius:W+"px",border:t.borderSize&&!H?`${t.borderSize}px solid ${t.borderColor}`:"none",backgroundRepeat:"no-repeat",backgroundImage:`url(${r})`,transform:a,backgroundSize:`${Math.round(v)}px ${Math.round(j)}px`,backgroundPositionX:-Math.round(O)+"px",backgroundPositionY:-Math.round(z)+"px"})});return H?h("div",{style:{width:"100%",height:"100%",borderRadius:t.cornerRadius+"px",background:S(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},M):M},z=({element:t,type:e})=>{const o={"stroke-width":t.height,stroke:t.color,"stroke-linecap":"round","stroke-linejoin":"round",opacity:t.opacity},i=Object.assign(Object.assign({},o),{fill:t.color}),n=Object.assign(Object.assign({},o),{fill:"none"});return"arrow"===e?h("polyline",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},n)):"triangle"===e?h("polygon",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},i)):"bar"===e?h("polyline",Object.assign({points:`0,${2*-t.height} 0,${2*t.height}`},n)):"circle"===e?h("circle",Object.assign({cx:2*t.height,cy:0,r:2*t.height},i)):"square"===e?h("polygon",Object.assign({points:`0,${2*-t.height} ${4*t.height},${2*-t.height} ${4*t.height},${2*t.height} 0,${2*t.height}`},i)):null},H={image:O,svg:O,text:async({element:t,page:e,store:o})=>{const i=m.isGradient(t.fill),n=m.isGradient(t.stroke);if(t.curveEnabled){const e=v(t.text,{fontSize:t.fontSize,fontFamily:t.fontFamily}),o=f(e,{fontSize:t.fontSize,fontFamily:t.fontFamily}),r=Math.max(t.fontSize,...o.map(e=>{var o;return null!==(o=e.fontSize)&&void 0!==o?o:t.fontSize})),a=g(t.width,t.height,t.curvePower,r),s={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black",fontFamily:t.fontFamily,fontSize:t.fontSize},l=y(o,s);let d=`\n <svg xmlns="http://www.w3.org/2000/svg" width="${t.width}" height="${t.height}" style="display: block;">\n <defs>\n <path id="curve-${t.id}" d="${a}" fill="none" />`;if(i){const e=`curve-fill-grad-${t.id}`;d+=u(t.fill,e)}if(n&&t.strokeWidth){const e=`curve-stroke-grad-${t.id}`;d+=u(t.stroke,e)}d+=`</defs>\n <text\n font-family="'${t.fontFamily}'"\n font-size="${t.fontSize}"\n font-weight="${t.fontWeight}"\n font-style="${t.fontStyle}"\n fill="${i?`url(#curve-fill-grad-${t.id})`:t.fill}"\n text-anchor="middle"\n dominant-baseline="central"\n letter-spacing="${t.letterSpacing*r}"${t.textDecoration?` text-decoration="${t.textDecoration}"`:""}${t.strokeWidth?` stroke="${n?`url(#curve-stroke-grad-${t.id})`:t.stroke}" stroke-width="${t.strokeWidth}" paint-order="stroke fill"`:""}>\n <textPath href="#curve-${t.id}" startOffset="50%">${l}</textPath>\n </text>\n </svg>`;const c=t.backgroundPadding*(t.fontSize*t.lineHeight),p=t.backgroundEnabled&&h("div",{style:{position:"absolute",top:-c/2+"px",left:-c/2+"px",width:t.width+c+"px",height:t.height+c+"px",backgroundColor:t.backgroundColor,opacity:t.backgroundOpacity,borderRadius:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)+"px"}}),b=h("div",{style:{width:"100%",height:"100%",position:"absolute",top:0,left:0},innerHTML:d});return h("div",{style:{position:"relative",width:"100%",height:"100%"}},p,b)}const a=t=>({backgroundImage:t,backgroundSize:"100% 100%",backgroundRepeat:"repeat",WebkitBackgroundClip:"text",MozBackgroundClip:"text",backgroundClip:"text",WebkitTextFillColor:"transparent",MozTextFillColor:"transparent",color:"transparent"}),s="middle"===t.verticalAlign?{top:"50%",transform:"translateY(-50%)"}:"bottom"===t.verticalAlign?{bottom:0}:{top:0};let l=Object.assign(Object.assign({left:0},s),i?a(t.fill):{}),d=null;if(t.backgroundEnabled){if(t.legacyBackground){const e=t.backgroundPadding*(t.fontSize*t.lineHeight);d=h("div",{style:{position:"absolute",top:-e/2+"px",left:-e/2+"px",display:"block",width:t.width+e+"px",height:t.height+e+"px",backgroundColor:t.backgroundColor,opacity:t.backgroundOpacity,borderRadius:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)+"px"}})}else{const e=k(t);let o=[];try{o=w(e)}catch(H){o=[]}if(o.length){const i=t.backgroundPadding*(t.fontSize*t.lineHeight*.5),n=t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5),r=x({rects:o,padding:i,cornerRadius:n});if(r){let n=0;try{const{height:o}=$(e);"middle"===t.verticalAlign?n=(t.height-o)/2:"bottom"===t.verticalAlign&&(n=t.height-o)}catch(W){}const a=Math.min(...o.map(t=>t.top)),s=Math.max(...o.map(t=>t.bottom)),l=Math.min(...o.map(t=>t.left)),c=l-i,g=a-i,p=Math.max(...o.map(t=>t.right))-l+2*i,f=s-a+2*i;d=h("svg",{xmlns:"http://www.w3.org/2000/svg",width:p,height:f,viewBox:`${c} ${g} ${p} ${f}`,style:{position:"absolute",top:n+g+"px",left:c+"px",opacity:t.backgroundOpacity,pointerEvents:"none"},innerHTML:`<path d="${r}" fill="${t.backgroundColor}" />`})}}}}else{d=null}const c=/<[a-z][\s\S]*>/i.test(t.text),p=c?v(t.text,{fontSize:t.fontSize,fontFamily:t.fontFamily}):t.text.split("\n").join("<br />");if(t.strokeWidth&&(n||i&&!n)){const e={position:"absolute",width:t.width+"px",whiteSpace:"pre-wrap",overflowWrap:"break-word",fontSize:t.fontSize+"px",textAlign:t.align,fontFamily:`'${t.fontFamily}'`,textDecoration:t.textDecoration||"none",textDecorationColor:t.textDecoration?t.fill:void 0,textTransform:t.textTransform||"none",lineHeight:t.lineHeight,letterSpacing:t.letterSpacing*t.fontSize+"px",fontStyle:t.fontStyle,fontWeight:t.fontWeight},o=n?Object.assign(Object.assign(Object.assign({},e),a(t.stroke)),{WebkitTextStroke:`${t.strokeWidth}px transparent`}):Object.assign(Object.assign({},e),{color:"transparent",WebkitTextStroke:`${t.strokeWidth}px ${t.stroke}`}),l=i?Object.assign(Object.assign({},e),a(t.fill)):Object.assign(Object.assign({},e),{color:t.fill}),g="el-"+t.id,f=c?`<style>#${g} {${r}}</style>`:"",b=h("div",{style:Object.assign(Object.assign({},o),{position:"absolute",top:0,left:0,pointerEvents:"none"}),"aria-hidden":"true",innerHTML:c?`${f}${p}`:p}),m=h("div",Object.assign(Object.assign({style:Object.assign(Object.assign({},l),{position:"relative"})},c?{id:g}:{}),{innerHTML:c?`${f}${p}`:p}));return h("div",{style:{position:"relative",width:"100%",height:"100%"}},d,h("div",{style:Object.assign({position:"absolute",width:t.width+"px",left:0},s)},b,m))}const b=Object.assign(Object.assign({},l),{position:"absolute",width:t.width+"px",color:t.fill,whiteSpace:"pre-wrap",overflowWrap:"break-word",fontSize:t.fontSize+"px",textAlign:t.align,fontFamily:`'${t.fontFamily}'`,textDecoration:t.textDecoration||"none",textDecorationColor:t.textDecoration?t.fill:void 0,textTransform:t.textTransform||"none",lineHeight:t.lineHeight,letterSpacing:t.letterSpacing*t.fontSize+"px",fontStyle:t.fontStyle,fontWeight:t.fontWeight,WebkitTextStroke:t.strokeWidth?`${t.strokeWidth}px ${t.stroke}`:void 0,paintOrder:t.strokeWidth?"stroke fill":void 0}),j="el-"+t.id,S=c?{id:j}:{},O=`<style>#${j} {${r}}</style>`,z=h("div",Object.assign(Object.assign({style:b},S),{innerHTML:c?`${O}${p}`:p}));return h("div",{style:{position:"relative",width:"100%",height:"100%"}},d,z)},line:async({element:t,page:e,store:o})=>h("svg",{style:{width:"100%",height:"100%",contain:"layout style size",overflow:"visible"}},h("line",{x1:0,y1:t.height/2,x2:t.width,y2:t.height/2,stroke:t.color,"stroke-width":t.height,"stroke-dasharray":t.dash&&t.dash.length?t.dash.map(e=>e*t.height).join(" "):void 0}),h("g",{transform:`translate(0 ${t.height/2})`},z({element:t,type:t.startHead})),h("g",{transform:`translate(${t.width} ${t.height/2}) rotate(180)`},z({element:t,type:t.endHead}))),figure:async({element:t,page:e,store:o,elementHook:i})=>{let r=n(t);if(t.strokeWidth&&m.isGradient(t.stroke)){const e=`figure-stroke-grad-${t.id}`,o=u(t.stroke,e);r=r.replace(new RegExp(`stroke="${t.stroke.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"`,"g"),`stroke="url(#${e})"`),r=r.replace("</defs>",`${o}</defs>`)}if(m.isGradient(t.fill)){const e=`figure-fill-grad-${t.id}`,o=u(t.fill,e);r=r.replace(new RegExp(`fill="${t.fill.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"`,"g"),`fill="url(#${e})"`),r=r.replace("</defs>",`${o}</defs>`)}const a=h("div",{innerHTML:r});return i&&i({dom:a,element:t})||a},group:async({element:t,page:e,store:o,elementHook:i})=>{const n=await Promise.all(t.children.map(t=>W({element:t,page:e,store:o,elementHook:i}))),r=h("div",{style:{transformOrigin:"top left",opacity:t.opacity}},...n);return i&&i({dom:r,element:t})||r},video:async({element:t,page:e,store:o,elementHook:i})=>{const{cropX:n,cropY:r,cropWidth:a,cropHeight:s}=t,d=await l(t.src),c=d.width*a,g=d.height*s,p=t.width/t.height;let f,b;p>=c/g?(f=c,b=c/p):(f=g*p,b=g);const u=f/a,y=b/s,k=n*d.width,x=r*d.height,w=Math.max(t.width/d.width,t.height/d.height),$={position:"absolute",width:`${Math.round(u*w)}px`,height:`${Math.round(y*w)}px`,left:-Math.round(k*w)+"px",top:-Math.round(x*w)+"px",objectFit:"fill"},v=`video-${t.id}`,j=t.borderSize&&m.isGradient(t.borderColor),O=j?Math.max(0,t.cornerRadius-t.borderSize):t.cornerRadius,z=h("div",{style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",borderRadius:O+"px",border:t.borderSize&&!j?`${t.borderSize}px solid ${t.borderColor}`:"none"}},h("video",{id:v,src:t.src,style:$,controls:!0,playsInline:!0,muted:!0,volume:t.volume}));if(j){const e=h("div",{style:{width:"100%",height:"100%",borderRadius:t.cornerRadius+"px",background:S(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},z);return i&&i({dom:e,element:t})||e}return i&&i({dom:z,element:t})||z},gif:O,table:async({element:t})=>{const e=t.rows,o=t.cols,i=t.colWidths,n=t.rowHeights,r=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],a=(t.cells||[]).map(e=>{if(!e){return e}const o=Object.assign({},e);for(const i of r){void 0===o[i]&&(o[i]=t[i])}return o}),s=[];for(let d=0;d<e;d++){const e=[];for(let i=0;i<o;i++){const r=a[d*o+i];if(!r||r.mergedInto){continue}const s=r.cellPadding||4,l=r.colSpan||1,c=r.rowSpan||1,g=e=>{var o,i,n,a,s;const l=null===(o=r.borders)||void 0===o?void 0:o[e];return`${null!==(i=null==l?void 0:l.width)&&void 0!==i?i:t.borderWidth}px ${null!==(a=null!==(n=null==l?void 0:l.style)&&void 0!==n?n:t.borderStyle)&&void 0!==a?a:"solid"} ${null!==(s=null==l?void 0:l.color)&&void 0!==s?s:t.borderColor}`},f={style:{padding:s+"px",background:r.cellBackground||"transparent",fontSize:(r.fontSize||12)+"px",fontFamily:`'${r.fontFamily||"Roboto"}'`,fontWeight:r.fontWeight||"normal",fontStyle:r.fontStyle||"normal",color:r.fill||"black",textAlign:r.align||"left",verticalAlign:r.verticalAlign||"top",lineHeight:String(r.lineHeight||1.2),letterSpacing:r.letterSpacing?r.letterSpacing*(r.fontSize||12)+"px":void 0,textDecoration:r.textDecoration||"none",textTransform:r.textTransform||"none",borderTop:g("top"),borderRight:g("right"),borderBottom:g("bottom"),borderLeft:g("left"),overflow:"hidden",overflowWrap:"break-word",whiteSpace:"pre-wrap",height:n[d]*t.height+"px"}};l>1&&(f.colspan=String(l)),c>1&&(f.rowspan=String(c)),e.push(h("td",f,p(r.text||"")))}s.push(h("tr",{},...e))}const l=i.map(t=>h("col",{style:{width:100*t+"%"}}));return h("table",{style:{width:"100%",height:"100%",borderCollapse:"collapse",tableLayout:"fixed"}},h("colgroup",{},...l),h("tbody",{},...s))}};async function W({element:t,page:e,store:o,elementHook:i}){var n;let r=await H[t.type];if(r||(r=()=>h("div",{}),console.error(`HTML export does not support ${t.type} type...`)),!t.visible){return null}const l=await r({element:t,page:e,store:o}),d=[],c=[];if(t.blurEnabled&&d.push(`blur(${t.blurRadius/2}px)`),t.brightnessEnabled&&d.push(`brightness(${100*t.brightness+100}%)`),t.sepiaEnabled&&d.push("sepia()"),t.grayscaleEnabled&&d.push("grayscale()"),t.filters){for(const[p,f]of Object.entries(t.filters)){const t=s(a[p],f.intensity);t&&(d.push(t.filter),t.html&&c.push(t.html))}}if(t.shadowEnabled){const e=function(t,e){if(1===e){return t}const o=b.Util.colorToRGBA(t);return o?`rgba(${o.r}, ${o.g}, ${o.b}, ${o.a*e})`:t}(t.shadowColor,null!==(n=t.shadowOpacity)&&void 0!==n?n:1);d.push(`drop-shadow(${t.shadowOffsetX}px ${t.shadowOffsetY}px ${t.shadowBlur/2}px ${e})`)}const g=h("div",{id:t.id,style:{position:"absolute",left:t.x+"px",top:t.y+"px",width:t.width+"px",height:t.height+"px",transform:`rotate(${t.rotation}deg)`,transformOrigin:"top left",opacity:t.opacity,display:t.visible&&t.showInExport?"block":"none",filter:d.join(" ")||"none"}},l,...c);return i&&i({dom:g,element:t})||g}export async function jsonToDOM({json:t,elementHook:i}){const n=await Promise.all(t.pages.map(n=>async function({page:t,store:i,elementHook:n}){const r=await Promise.all(t.children.map(e=>W({element:e,page:t,store:i,elementHook:n}))),a="auto"===t.width?i.width:t.width,s="auto"===t.height?i.height:t.height;let l={};if(t.background.indexOf("url")>=0||t.background.indexOf("http")>=0||t.background.indexOf(".jpg")>=0||t.background.indexOf(".png")>=0||t.background.indexOf(".jpeg")>=0){const{width:n,height:l}=await o(t.background),d=await O({element:Object.assign({x:0,y:0,width:a,height:s,src:t.background,cornerRadius:0},e({width:a,height:s},{width:n,height:l})),page:t,store:i});r.unshift(d)}else{l=m.isGradient(t.background)?Object.assign(Object.assign({},l),{backgroundImage:t.background}):Object.assign(Object.assign({},l),{backgroundColor:t.background})}return h("div",{className:"page",id:t.id,style:Object.assign(Object.assign({},l),{width:a+"px",height:s+"px",overflow:"hidden",position:"relative"})},...r)}({page:n,store:t,elementHook:i}))),r=[];c({children:t.pages},t=>{if(("text"===t.type||"tablecell"===t.type||"table"===t.type)&&(t.fontFamily&&-1===r.indexOf(t.fontFamily)&&r.push(t.fontFamily),t.text)){for(const e of j(t.text)){-1===r.indexOf(e)&&r.push(e)}}});const a=r.map(e=>{const o=t.fonts.find(t=>t.fontFamily===e);if(o){const t=(o.styles||(o.url?[{src:`url("${o.url}")`}]:[])).map(t=>`\n @font-face {\n font-family: '${o.fontFamily}';\n src: ${t.src};\n font-style: ${t.fontStyle||"normal"};\n font-weight: ${t.fontWeight||"normal"};\n font-display: swap;\n }`).join("\n");return h("style",{},t)}return h("link",{href:d(e),rel:"stylesheet"})});return h("div",{className:"design"},...a,...n)}const M=({dom:e})=>{if("string"==typeof e){return e}if(!e){return""}const o=e.props,{innerHTML:i}=o,n=t(o,["innerHTML"]),r=Object.keys(n).map(t=>"style"===t&&"object"==typeof n[t]?`style="${Object.keys(n[t]).filter(e=>null!=n[t][e]).map(e=>`${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}: ${n[t][e]}`).join("; ")}"`:((t,e)=>null==e||""===e?"":"object"==typeof e?`${t}="${Object.keys(e).map(t=>`${t.replace(/-([a-z])/g,t=>t[1].toUpperCase())}:${e[t]};`).join(" ")}"`:`${t}="${e}"`)(t,n[t])).filter(t=>t&&t.trim().length>0).join(" ");return`<${e.type} ${r}>${i||e.children.map(t=>M({dom:t})).join("")}</${e.type}>`};export async function jsonToHTML({json:t,elementHook:e}){const o=await jsonToDOM({json:t,elementHook:e});return M({dom:o})}
1
+ var t=this&&this.__rest||function(t,e){var o={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(o[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++){e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(o[i[n]]=t[i[n]])}}return o};import{getCrop as e,loadImage as o}from"./image.js";import*as i from"./svg.js";import{figureToSvg as n}from"./figure-to-svg.js";import{resetStyleContent as r}from"./reset-style.js";import{Effects as a,shapeFilterToCSS as s}from"./filters.js";import{getVideoSize as l}from"./video.js";import{getGoogleFontsUrl as d}from"./fonts.js";import{forEveryNode as c}from"../model/group-model.js";import{getCurvePath as p}from"../canvas/text-element.js";import{removeTags as g,parseHtmlToSegments as f}from"./text.js";import b from"konva";import*as m from"./gradient.js";import{createSVGGradientDef as u,segmentsToTspans as y,getHtml as k}from"./text-html.js";import{generateBackgroundShapeFromRects as x}from"./background-shape.js";import{detectLineRects as w,detectSize as $}from"./html2canvas.js";import{normalizeRichTextHtml as v,extractFontFamiliesFromHtml as j}from"./rich-text-html.js";export const h=(t,e,...o)=>({type:t,props:e,children:o||[]});function S(t){return m.isGradient(t),t}export function fixRatio(t){var e=(new DOMParser).parseFromString(t,"image/svg+xml");return e.documentElement.setAttribute("preserveAspectRatio","none"),(new XMLSerializer).serializeToString(e)}const O=async({element:t,page:e,store:n})=>{let{src:r}=t;if("svg"===t.type){let e=await i.urlToString(r);e=fixRatio(e),r=Object.keys(t.colorsReplace).length?i.replaceColors(e,new Map(Object.entries(t.colorsReplace))):i.svgToURL(e)}let a="";t.flipX&&(a+="scaleX(-1)"),t.flipY&&(a+="scaleY(-1)"),a||(a="none");const s={};if("svg"===t.type&&t.maskSrc){const e=await i.urlToBase64(r);s["mask-image"]=`url(${e})`,s["mask-size"]="100% 100%",s["mask-position"]="0 0",s["mask-repeat"]="no-repeat",s["-webkit-mask-image"]=`url(${e})`,s["-webkit-mask-size"]="100% 100%",s["-webkit-mask-position"]="0 0",s["-webkit-mask-repeat"]="no-repeat",r=t.maskSrc}else if(t.clipSrc){const e=t.clipSrc,o=await i.urlToBase64(e);s["mask-image"]=`url(${o})`,s["mask-size"]="100% 100%",s["mask-position"]="0 0",s["mask-repeat"]="no-repeat",s["-webkit-mask-image"]=`url(${o})`,s["-webkit-mask-size"]="100% 100%",s["-webkit-mask-position"]="0 0",s["-webkit-mask-repeat"]="no-repeat"}const l=await o(r),d=l.width*t.cropWidth,c=l.height*t.cropHeight,p=t.width/t.height;let g,f;const b=d/c,u="svg"===t.type||t.stretchEnabled;u?(g=d,f=c):p>=b?(g=d,f=d/p):(g=c*p,f=c);const y=g/l.width,k=f/l.height,x=g/f>t.width/t.height?t.height/f:t.width/g,w=u?t.width/g:x,$=u?t.height/f:x,v=g*w/y,j=f*$/k;let O=t.cropX*w*l.width,z=t.cropY*$*l.height;t.flipX&&(O=(1-t.cropX-t.cropWidth)*w*l.width),t.flipY&&(z=(1-t.cropY-t.cropHeight)*$*l.height);const H=t.borderSize&&m.isGradient(t.borderColor),W=H?Math.max(0,t.cornerRadius-t.borderSize):t.cornerRadius,T=h("div",{style:Object.assign(Object.assign({},s),{width:"100%",height:"100%",borderRadius:W+"px",border:t.borderSize&&!H?`${t.borderSize}px solid ${t.borderColor}`:"none",backgroundRepeat:"no-repeat",backgroundImage:`url(${r})`,transform:a,backgroundSize:`${Math.round(v)}px ${Math.round(j)}px`,backgroundPositionX:-Math.round(O)+"px",backgroundPositionY:-Math.round(z)+"px"})});return H?h("div",{style:{width:"100%",height:"100%",borderRadius:t.cornerRadius+"px",background:S(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},T):T},z=({element:t,type:e})=>{const o={"stroke-width":t.height,stroke:t.color,"stroke-linecap":"round","stroke-linejoin":"round",opacity:t.opacity},i=Object.assign(Object.assign({},o),{fill:t.color}),n=Object.assign(Object.assign({},o),{fill:"none"});return"arrow"===e?h("polyline",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},n)):"triangle"===e?h("polygon",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},i)):"bar"===e?h("polyline",Object.assign({points:`0,${2*-t.height} 0,${2*t.height}`},n)):"circle"===e?h("circle",Object.assign({cx:2*t.height,cy:0,r:2*t.height},i)):"square"===e?h("polygon",Object.assign({points:`0,${2*-t.height} ${4*t.height},${2*-t.height} ${4*t.height},${2*t.height} 0,${2*t.height}`},i)):null},H={image:O,svg:O,text:async({element:t,page:e,store:o})=>{const i=m.isGradient(t.fill),n=m.isGradient(t.stroke);if(t.curveEnabled){const e=v(t.text,{fontSize:t.fontSize,fontFamily:t.fontFamily}),o=f(e,{fontSize:t.fontSize,fontFamily:t.fontFamily}),r=Math.max(t.fontSize,...o.map(e=>{var o;return null!==(o=e.fontSize)&&void 0!==o?o:t.fontSize})),a=p(t.width,t.height,t.curvePower,r),s={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black",fontFamily:t.fontFamily,fontSize:t.fontSize},l=y(o,s);let d=`\n <svg xmlns="http://www.w3.org/2000/svg" width="${t.width}" height="${t.height}" style="display: block;">\n <defs>\n <path id="curve-${t.id}" d="${a}" fill="none" />`;if(i){const e=`curve-fill-grad-${t.id}`;d+=u(t.fill,e)}if(n&&t.strokeWidth){const e=`curve-stroke-grad-${t.id}`;d+=u(t.stroke,e)}d+=`</defs>\n <text\n font-family="'${t.fontFamily}'"\n font-size="${t.fontSize}"\n font-weight="${t.fontWeight}"\n font-style="${t.fontStyle}"\n fill="${i?`url(#curve-fill-grad-${t.id})`:t.fill}"\n text-anchor="middle"\n dominant-baseline="central"\n letter-spacing="${t.letterSpacing*r}"${t.textDecoration?` text-decoration="${t.textDecoration}"`:""}${t.strokeWidth?` stroke="${n?`url(#curve-stroke-grad-${t.id})`:t.stroke}" stroke-width="${t.strokeWidth}" paint-order="stroke fill"`:""}>\n <textPath href="#curve-${t.id}" startOffset="50%">${l}</textPath>\n </text>\n </svg>`;const c=t.backgroundPadding*(t.fontSize*t.lineHeight),g=t.backgroundEnabled&&h("div",{style:{position:"absolute",top:-c/2+"px",left:-c/2+"px",width:t.width+c+"px",height:t.height+c+"px",backgroundColor:t.backgroundColor,opacity:t.backgroundOpacity,borderRadius:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)+"px"}}),b=h("div",{style:{width:"100%",height:"100%",position:"absolute",top:0,left:0},innerHTML:d});return h("div",{style:{position:"relative",width:"100%",height:"100%"}},g,b)}const a=t=>({backgroundImage:t,backgroundSize:"100% 100%",backgroundRepeat:"repeat",WebkitBackgroundClip:"text",MozBackgroundClip:"text",backgroundClip:"text",WebkitTextFillColor:"transparent",MozTextFillColor:"transparent",color:"transparent"}),s="middle"===t.verticalAlign?{top:"50%",transform:"translateY(-50%)"}:"bottom"===t.verticalAlign?{bottom:0}:{top:0};let l=Object.assign(Object.assign({left:0},s),i?a(t.fill):{}),d=null;if(t.backgroundEnabled){if(t.legacyBackground){const e=t.backgroundPadding*(t.fontSize*t.lineHeight);d=h("div",{style:{position:"absolute",top:-e/2+"px",left:-e/2+"px",display:"block",width:t.width+e+"px",height:t.height+e+"px",backgroundColor:t.backgroundColor,opacity:t.backgroundOpacity,borderRadius:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)+"px"}})}else{const e=k(t);let o=[];try{o=w(e)}catch(H){o=[]}if(o.length){const i=t.backgroundPadding*(t.fontSize*t.lineHeight*.5),n=t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5),r=x({rects:o,padding:i,cornerRadius:n});if(r){let n=0;try{const{height:o}=$(e);"middle"===t.verticalAlign?n=(t.height-o)/2:"bottom"===t.verticalAlign&&(n=t.height-o)}catch(W){}const a=Math.min(...o.map(t=>t.top)),s=Math.max(...o.map(t=>t.bottom)),l=Math.min(...o.map(t=>t.left)),c=l-i,p=a-i,g=Math.max(...o.map(t=>t.right))-l+2*i,f=s-a+2*i;d=h("svg",{xmlns:"http://www.w3.org/2000/svg",width:g,height:f,viewBox:`${c} ${p} ${g} ${f}`,style:{position:"absolute",top:n+p+"px",left:c+"px",opacity:t.backgroundOpacity,pointerEvents:"none"},innerHTML:`<path d="${r}" fill="${t.backgroundColor}" />`})}}}}else{d=null}const c=/<[a-z][\s\S]*>/i.test(t.text),g=c?v(t.text,{fontSize:t.fontSize,fontFamily:t.fontFamily}):t.text.split("\n").join("<br />");if(t.strokeWidth&&(n||i&&!n)){const e={position:"absolute",width:t.width+"px",whiteSpace:"pre-wrap",overflowWrap:"break-word",fontSize:t.fontSize+"px",textAlign:t.align,fontFamily:`'${t.fontFamily}'`,textDecoration:t.textDecoration||"none",textDecorationColor:t.textDecoration?t.fill:void 0,textTransform:t.textTransform||"none",lineHeight:t.lineHeight,letterSpacing:t.letterSpacing*t.fontSize+"px",fontStyle:t.fontStyle,fontWeight:t.fontWeight},o=n?Object.assign(Object.assign(Object.assign({},e),a(t.stroke)),{WebkitTextStroke:`${t.strokeWidth}px transparent`}):Object.assign(Object.assign({},e),{color:"transparent",WebkitTextStroke:`${t.strokeWidth}px ${t.stroke}`}),l=i?Object.assign(Object.assign({},e),a(t.fill)):Object.assign(Object.assign({},e),{color:t.fill}),p="el-"+t.id,f=c?`<style>#${p} {${r}}</style>`:"",b=h("div",{style:Object.assign(Object.assign({},o),{position:"absolute",top:0,left:0,pointerEvents:"none"}),"aria-hidden":"true",innerHTML:c?`${f}${g}`:g}),m=h("div",Object.assign(Object.assign({style:Object.assign(Object.assign({},l),{position:"relative"})},c?{id:p}:{}),{innerHTML:c?`${f}${g}`:g}));return h("div",{style:{position:"relative",width:"100%",height:"100%"}},d,h("div",{style:Object.assign({position:"absolute",width:t.width+"px",left:0},s)},b,m))}const b=Object.assign(Object.assign({},l),{position:"absolute",width:t.width+"px",color:t.fill,whiteSpace:"pre-wrap",overflowWrap:"break-word",fontSize:t.fontSize+"px",textAlign:t.align,fontFamily:`'${t.fontFamily}'`,textDecoration:t.textDecoration||"none",textDecorationColor:t.textDecoration?t.fill:void 0,textTransform:t.textTransform||"none",lineHeight:t.lineHeight,letterSpacing:t.letterSpacing*t.fontSize+"px",fontStyle:t.fontStyle,fontWeight:t.fontWeight,WebkitTextStroke:t.strokeWidth?`${t.strokeWidth}px ${t.stroke}`:void 0,paintOrder:t.strokeWidth?"stroke fill":void 0}),j="el-"+t.id,S=c?{id:j}:{},O=`<style>#${j} {${r}}</style>`,z=h("div",Object.assign(Object.assign({style:b},S),{innerHTML:c?`${O}${g}`:g}));return h("div",{style:{position:"relative",width:"100%",height:"100%"}},d,z)},line:async({element:t,page:e,store:o})=>h("svg",{style:{width:"100%",height:"100%",contain:"layout style size",overflow:"visible"}},h("line",{x1:0,y1:t.height/2,x2:t.width,y2:t.height/2,stroke:t.color,"stroke-width":t.height,"stroke-dasharray":t.dash&&t.dash.length?t.dash.map(e=>e*t.height).join(" "):void 0}),h("g",{transform:`translate(0 ${t.height/2})`},z({element:t,type:t.startHead})),h("g",{transform:`translate(${t.width} ${t.height/2}) rotate(180)`},z({element:t,type:t.endHead}))),figure:async({element:t,page:e,store:o,elementHook:i})=>{let r=n(t);if(t.strokeWidth&&m.isGradient(t.stroke)){const e=`figure-stroke-grad-${t.id}`,o=u(t.stroke,e);r=r.replace(new RegExp(`stroke="${t.stroke.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"`,"g"),`stroke="url(#${e})"`),r=r.replace("</defs>",`${o}</defs>`)}if(m.isGradient(t.fill)){const e=`figure-fill-grad-${t.id}`,o=u(t.fill,e);r=r.replace(new RegExp(`fill="${t.fill.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"`,"g"),`fill="url(#${e})"`),r=r.replace("</defs>",`${o}</defs>`)}const a=h("div",{innerHTML:r});return i&&i({dom:a,element:t})||a},group:async({element:t,page:e,store:o,elementHook:i})=>{const n=await Promise.all(t.children.map(t=>W({element:t,page:e,store:o,elementHook:i}))),r=h("div",{style:{transformOrigin:"top left",opacity:t.opacity}},...n);return i&&i({dom:r,element:t})||r},video:async({element:t,page:e,store:o,elementHook:i})=>{const{cropX:n,cropY:r,cropWidth:a,cropHeight:s}=t,d=await l(t.src),c=d.width*a,p=d.height*s,g=t.width/t.height;let f,b;g>=c/p?(f=c,b=c/g):(f=p*g,b=p);const u=f/a,y=b/s,k=n*d.width,x=r*d.height,w=Math.max(t.width/d.width,t.height/d.height),$={position:"absolute",width:`${Math.round(u*w)}px`,height:`${Math.round(y*w)}px`,left:-Math.round(k*w)+"px",top:-Math.round(x*w)+"px",objectFit:"fill"},v=`video-${t.id}`,j=t.borderSize&&m.isGradient(t.borderColor),O=j?Math.max(0,t.cornerRadius-t.borderSize):t.cornerRadius,z=h("div",{style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",borderRadius:O+"px",border:t.borderSize&&!j?`${t.borderSize}px solid ${t.borderColor}`:"none"}},h("video",{id:v,src:t.src,style:$,controls:!0,playsInline:!0,muted:!0,volume:t.volume}));if(j){const e=h("div",{style:{width:"100%",height:"100%",borderRadius:t.cornerRadius+"px",background:S(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},z);return i&&i({dom:e,element:t})||e}return i&&i({dom:z,element:t})||z},gif:O,table:async({element:t})=>{const e=t.rows,o=t.cols,i=t.colWidths,n=t.rowHeights,r=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],a=(t.cells||[]).map(e=>{if(!e){return e}const o=Object.assign({},e);for(const i of r){void 0===o[i]&&(o[i]=t[i])}return o}),s=[];for(let d=0;d<e;d++){const e=[];for(let i=0;i<o;i++){const r=a[d*o+i];if(!r||r.mergedInto){continue}const s=r.cellPadding||4,l=r.colSpan||1,c=r.rowSpan||1,p=e=>{var o,i,n,a,s;const l=null===(o=r.borders)||void 0===o?void 0:o[e];return`${null!==(i=null==l?void 0:l.width)&&void 0!==i?i:t.borderWidth}px ${null!==(a=null!==(n=null==l?void 0:l.style)&&void 0!==n?n:t.borderStyle)&&void 0!==a?a:"solid"} ${null!==(s=null==l?void 0:l.color)&&void 0!==s?s:t.borderColor}`},f={style:{padding:s+"px",background:r.cellBackground||"transparent",fontSize:(r.fontSize||12)+"px",fontFamily:`'${r.fontFamily||"Roboto"}'`,fontWeight:r.fontWeight||"normal",fontStyle:r.fontStyle||"normal",color:r.fill||"black",textAlign:r.align||"left",verticalAlign:r.verticalAlign||"top",lineHeight:String(r.lineHeight||1.2),letterSpacing:r.letterSpacing?r.letterSpacing*(r.fontSize||12)+"px":void 0,textDecoration:r.textDecoration||"none",textTransform:r.textTransform||"none",borderTop:p("top"),borderRight:p("right"),borderBottom:p("bottom"),borderLeft:p("left"),overflow:"hidden",overflowWrap:"break-word",whiteSpace:"pre-wrap",height:n[d]*t.height+"px"}};l>1&&(f.colspan=String(l)),c>1&&(f.rowspan=String(c)),e.push(h("td",f,g(r.text||"")))}s.push(h("tr",{},...e))}const l=i.map(t=>h("col",{style:{width:100*t+"%"}}));return h("table",{style:{width:"100%",height:"100%",borderCollapse:"collapse",tableLayout:"fixed"}},h("colgroup",{},...l),h("tbody",{},...s))}};async function W({element:t,page:e,store:o,elementHook:i}){var n;let r=await H[t.type];if(r||(r=()=>h("div",{}),console.error(`HTML export does not support ${t.type} type...`)),!t.visible){return null}const l=await r({element:t,page:e,store:o}),d=[],c=[];if(t.blurEnabled&&d.push(`blur(${t.blurRadius/2}px)`),t.brightnessEnabled&&d.push(`brightness(${100*t.brightness+100}%)`),t.sepiaEnabled&&d.push("sepia()"),t.grayscaleEnabled&&d.push("grayscale()"),t.filters){for(const[g,f]of Object.entries(t.filters)){const t=s(a[g],f.intensity);t&&(d.push(t.filter),t.html&&c.push(t.html))}}if(t.shadowEnabled){const e=function(t,e){if(1===e){return t}const o=b.Util.colorToRGBA(t);return o?`rgba(${o.r}, ${o.g}, ${o.b}, ${o.a*e})`:t}(t.shadowColor,null!==(n=t.shadowOpacity)&&void 0!==n?n:1);d.push(`drop-shadow(${t.shadowOffsetX}px ${t.shadowOffsetY}px ${t.shadowBlur/2}px ${e})`)}const p=h("div",{id:t.id,style:{position:"absolute",left:t.x+"px",top:t.y+"px",width:t.width+"px",height:t.height+"px",transform:`rotate(${t.rotation}deg)`,transformOrigin:"top left",opacity:t.opacity,display:t.visible&&t.showInExport?"block":"none",filter:d.join(" ")||"none"}},l,...c);return i&&i({dom:p,element:t})||p}export async function jsonToDOM({json:t,elementHook:i}){const n=await Promise.all(t.pages.map(n=>async function({page:t,store:i,elementHook:n}){const r=[...t.children.filter(t=>!t.alwaysOnTop),...t.children.filter(t=>t.alwaysOnTop)],a=await Promise.all(r.map(e=>W({element:e,page:t,store:i,elementHook:n}))),s="auto"===t.width?i.width:t.width,l="auto"===t.height?i.height:t.height;let d={};if(t.background.indexOf("url")>=0||t.background.indexOf("http")>=0||t.background.indexOf(".jpg")>=0||t.background.indexOf(".png")>=0||t.background.indexOf(".jpeg")>=0){const{width:n,height:r}=await o(t.background),d=await O({element:Object.assign({x:0,y:0,width:s,height:l,src:t.background,cornerRadius:0},e({width:s,height:l},{width:n,height:r})),page:t,store:i});a.unshift(d)}else{d=m.isGradient(t.background)?Object.assign(Object.assign({},d),{backgroundImage:t.background}):Object.assign(Object.assign({},d),{backgroundColor:t.background})}return h("div",{className:"page",id:t.id,style:Object.assign(Object.assign({},d),{width:s+"px",height:l+"px",overflow:"hidden",position:"relative"})},...a)}({page:n,store:t,elementHook:i}))),r=[];c({children:t.pages},t=>{if(("text"===t.type||"tablecell"===t.type||"table"===t.type)&&(t.fontFamily&&-1===r.indexOf(t.fontFamily)&&r.push(t.fontFamily),t.text)){for(const e of j(t.text)){-1===r.indexOf(e)&&r.push(e)}}});const a=r.map(e=>{const o=t.fonts.find(t=>t.fontFamily===e);if(o){const t=(o.styles||(o.url?[{src:`url("${o.url}")`}]:[])).map(t=>`\n @font-face {\n font-family: '${o.fontFamily}';\n src: ${t.src};\n font-style: ${t.fontStyle||"normal"};\n font-weight: ${t.fontWeight||"normal"};\n font-display: swap;\n }`).join("\n");return h("style",{},t)}return h("link",{href:d(e),rel:"stylesheet"})});return h("div",{className:"design"},...a,...n)}const T=({dom:e})=>{if("string"==typeof e){return e}if(!e){return""}const o=e.props,{innerHTML:i}=o,n=t(o,["innerHTML"]),r=Object.keys(n).map(t=>"style"===t&&"object"==typeof n[t]?`style="${Object.keys(n[t]).filter(e=>null!=n[t][e]).map(e=>`${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}: ${n[t][e]}`).join("; ")}"`:((t,e)=>null==e||""===e?"":"object"==typeof e?`${t}="${Object.keys(e).map(t=>`${t.replace(/-([a-z])/g,t=>t[1].toUpperCase())}:${e[t]};`).join(" ")}"`:`${t}="${e}"`)(t,n[t])).filter(t=>t&&t.trim().length>0).join(" ");return`<${e.type} ${r}>${i||e.children.map(t=>T({dom:t})).join("")}</${e.type}>`};export async function jsonToHTML({json:t,elementHook:e}){const o=await jsonToDOM({json:t,elementHook:e});return T({dom:o})}
package/utils/to-pptx.js CHANGED
@@ -1 +1 @@
1
- import{loadImage as t,cropImage as e}from"./image.js";import*as a from"./svg.js";import{figureToSvg as o}from"./figure-to-svg.js";import{removeTags as i}from"./text.js";import{pxToUnit as n}from"./unit.js";import r from"konva";const s=t=>n({px:t,unit:"in",dpi:100}),d=t=>Math.round(100*(1-t)),c=t=>{const{dx:e,dy:a}=((t,e,a)=>{const o=(a%360+360)%360;if(0===o){return{dx:0,dy:0}}const i=o*Math.PI/180,n=t/2,r=e/2;return{dx:n*Math.cos(i)-r*Math.sin(i)-n,dy:n*Math.sin(i)+r*Math.cos(i)-r}})(t.width,t.height,t.rotation);return{x:s(t.x+e),y:s(t.y+a)}},h=t=>{if(!t){return"000000"}if(t.includes("gradient")){return console.warn("PPTX export: gradient fill is not supported, using black"),"000000"}if(/^[0-9a-fA-F]{6}$/.test(t)){return t.toLowerCase()}let e=r.Util.colorToRGBA(t);return!e&&/^[0-9a-fA-F]{3,6}$/.test(t)&&(e=r.Util.colorToRGBA("#"+t)),e?r.Util._rgbToHex(e.r,e.g,e.b).replace("#","").toLowerCase():t.replace("#","").toLowerCase()||"000000"};let l=null;export function getPptxGen(){return window.PptxGenJS?Promise.resolve(window.PptxGenJS):l||(l=new Promise(t=>{var e=document.createElement("script");e.onload=function(){t(window.PptxGenJS)},e.src="https://cdn.jsdelivr.net/gh/gitbrent/pptxgenjs/dist/pptxgen.bundle.js",document.head.appendChild(e)}),l)}const g=async({element:o,slide:i})=>{let{src:n}=o;if("svg"===o.type&&Object.keys(o.colorsReplace).length){const t=await a.urlToString(n);n=a.replaceColors(t,new Map(Object.entries(o.colorsReplace)))}const r=await t(n),l=r.width*o.cropWidth,g=r.height*o.cropHeight,p=o.width/o.height;let w,u;const f=l/g;"svg"===o.type?(w=l,u=g):p>=f?(w=l,u=l/p):(w=g*p,u=g);let m=await e(n,Object.assign(Object.assign({},o),{cropWidth:w/r.width,cropHeight:u/r.height}));(o.cornerRadius||o.borderSize)&&(m=await(async(e,{width:a,height:o,cornerRadius:i,borderSize:n,borderColor:r})=>{if(!i&&!n){return e}const s=await t(e),d=document.createElement("canvas");d.width=Math.max(1,Math.round(a)),d.height=Math.max(1,Math.round(o));const c=d.getContext("2d"),l=Math.max(0,i),g=d.width,p=d.height,w=(t=!1)=>{const e=Math.min(l,Math.min(g,p)/2);c.beginPath(),c.moveTo(e,0),c.lineTo(g-e,0),c.quadraticCurveTo(g,0,g,e),c.lineTo(g,p-e),c.quadraticCurveTo(g,p,g-e,p),c.lineTo(e,p),c.quadraticCurveTo(0,p,0,p-e),c.lineTo(0,e),c.quadraticCurveTo(0,0,e,0),c.closePath(),t&&n>0&&(c.lineWidth=n,c.strokeStyle="#"+h(r),c.stroke())};return w(!1),c.save(),c.clip(),c.drawImage(s,0,0,g,p),c.restore(),n>0&&w(!0),d.toDataURL("image/png")})(m,{width:o.width,height:o.height,cornerRadius:o.cornerRadius,borderSize:o.borderSize,borderColor:o.borderColor}));const b=Object.assign(Object.assign({},c(o)),{w:s(o.width),h:s(o.height),rotate:o.rotation,flipH:o.flipX,flipV:o.flipY,transparency:d(o.opacity)});if(o.shadowEnabled){const t=Math.hypot(o.shadowOffsetX,o.shadowOffsetY)/2,e=180*Math.atan2(o.shadowOffsetY,o.shadowOffsetX)/Math.PI;b.shadow={type:"outer",blur:o.shadowBlur/2,offset:t,angle:e,color:h(o.shadowColor),opacity:o.shadowOpacity}}await i.addImage(Object.assign({path:m},b))},p=t=>"arrow"===t?"arrow":"triangle"===t?"triangle":"circle"===t?"oval":"square"===t?"diamond":"none",w=t=>{if(t&&t.length){return t.length<=2?"dash":"dashDot"}},u={image:g,svg:g,gif:g,text:async({element:t,slide:e})=>{let a=i(t.text||"");"uppercase"===t.textTransform&&(a=a.toUpperCase());const o=Object.assign(Object.assign(Object.assign(Object.assign({},c(t)),{w:s(t.width),h:s(t.height),fontSize:Math.round(.75*t.fontSize),fontFace:t.fontFamily,color:h(t.fill),align:t.align,bold:"bold"===t.fontWeight,italic:"italic"===t.fontStyle}),"underline"===t.textDecoration?{underline:{style:"sng",color:h(t.fill)}}:{}),{lineSpacingMultiple:t.lineHeight,rotate:t.rotation,fit:"shrink",transparency:d(t.opacity),margin:0});if("middle"===t.verticalAlign?o.valign="middle":"bottom"===t.verticalAlign?o.valign="bottom":o.valign="top",t.letterSpacing&&(o.charSpacing=t.letterSpacing*o.fontSize),t.strokeWidth>0&&(o.outline={size:.75*t.strokeWidth,color:h(t.stroke)}),t.shadowEnabled){const e=.75*Math.hypot(t.shadowOffsetX,t.shadowOffsetY)/2,a=180*Math.atan2(t.shadowOffsetY,t.shadowOffsetX)/Math.PI;o.shadow={type:"outer",blur:.75*t.shadowBlur,offset:e,angle:a,color:h(t.shadowColor),opacity:t.shadowOpacity}}if(t.backgroundEnabled){o.fill={color:h(t.backgroundColor)};const e=t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5);o.rectRadius=s(e);const a=t.backgroundPadding*(t.fontSize*t.lineHeight);o.margin=Math.max(0,Math.round(.75*a))}await e.addText(a,o)},line:async({element:t,slide:e})=>{const a=Object.assign(Object.assign({},c(t)),{w:s(t.width),h:s(t.height),line:{color:h(t.color),width:t.height,beginArrowType:p(t.startHead),endArrowType:p(t.endHead),dashType:w(t.dash),transparency:d(t.opacity)},rotate:t.rotation,transparency:d(t.opacity)});await e.addShape("line",a)},figure:async({element:e,slide:a})=>{const i=o(e),n=await(async(e,a,o)=>{const i="data:image/svg+xml;base64,"+btoa(e),n=await t(i),r=document.createElement("canvas");return r.width=Math.max(1,Math.round(a)),r.height=Math.max(1,Math.round(o)),r.getContext("2d").drawImage(n,0,0,r.width,r.height),r.toDataURL("image/png")})(i,e.width,e.height),r=Object.assign(Object.assign({},c(e)),{w:s(e.width),h:s(e.height),rotate:e.rotation,transparency:d(e.opacity)});await a.addImage(Object.assign({path:n},r))},group:async({element:t,slide:e})=>{for(const a of t.children||[]){await f({element:a,slide:e})}},video:async({element:t,slide:e})=>{const a=Object.assign(Object.assign({},c(t)),{w:s(t.width),h:s(t.height),rotate:t.rotation});await e.addMedia(Object.assign({type:"video",path:t.src},a))}},f=async({element:t,slide:e})=>{if(!t.visible||!t.showInExport){return}const a=u[t.type];a?await a({element:t,slide:e}):console.warn(`PPTX export doesn't support ${t.type} type`)};export async function jsonToPPTX({json:t}){const e=new(await getPptxGen());e.defineLayout({name:"CUSTOM",width:s(t.width),height:s(t.height)}),e.layout="CUSTOM";for(const a of t.pages){const t=e.addSlide();if(/\.(jpg|jpeg|png|gif)$/i.test(a.background)||a.background.startsWith("data:image")||a.background.startsWith("http")){await t.addImage({path:a.background,x:0,y:0,w:e.width,h:e.height,sizing:{type:"contain"}})}else{const e=r.Util.colorToRGBA(a.background),o=r.Util._rgbToHex(e.r,e.g,e.b).replace("#","");t.background={color:o}}for(const e of a.children){await f({element:e,slide:t})}}return e.writeFile("test.pptx"),e}
1
+ import{loadImage as t,cropImage as e}from"./image.js";import*as a from"./svg.js";import{figureToSvg as o}from"./figure-to-svg.js";import{removeTags as i}from"./text.js";import{isBoldWeight as n}from"./rich-text-html.js";import{pxToUnit as r}from"./unit.js";import s from"konva";const d=t=>r({px:t,unit:"in",dpi:100}),c=t=>Math.round(100*(1-t)),h=t=>{const{dx:e,dy:a}=((t,e,a)=>{const o=(a%360+360)%360;if(0===o){return{dx:0,dy:0}}const i=o*Math.PI/180,n=t/2,r=e/2;return{dx:n*Math.cos(i)-r*Math.sin(i)-n,dy:n*Math.sin(i)+r*Math.cos(i)-r}})(t.width,t.height,t.rotation);return{x:d(t.x+e),y:d(t.y+a)}},l=t=>{if(!t){return"000000"}if(t.includes("gradient")){return console.warn("PPTX export: gradient fill is not supported, using black"),"000000"}if(/^[0-9a-fA-F]{6}$/.test(t)){return t.toLowerCase()}let e=s.Util.colorToRGBA(t);return!e&&/^[0-9a-fA-F]{3,6}$/.test(t)&&(e=s.Util.colorToRGBA("#"+t)),e?s.Util._rgbToHex(e.r,e.g,e.b).replace("#","").toLowerCase():t.replace("#","").toLowerCase()||"000000"};let g=null;export function getPptxGen(){return window.PptxGenJS?Promise.resolve(window.PptxGenJS):g||(g=new Promise(t=>{var e=document.createElement("script");e.onload=function(){t(window.PptxGenJS)},e.src="https://cdn.jsdelivr.net/gh/gitbrent/pptxgenjs/dist/pptxgen.bundle.js",document.head.appendChild(e)}),g)}const p=async({element:o,slide:i})=>{let{src:n}=o;if("svg"===o.type&&Object.keys(o.colorsReplace).length){const t=await a.urlToString(n);n=a.replaceColors(t,new Map(Object.entries(o.colorsReplace)))}const r=await t(n),s=r.width*o.cropWidth,g=r.height*o.cropHeight,p=o.width/o.height;let w,u;const f=s/g;"svg"===o.type?(w=s,u=g):p>=f?(w=s,u=s/p):(w=g*p,u=g);let m=await e(n,Object.assign(Object.assign({},o),{cropWidth:w/r.width,cropHeight:u/r.height}));(o.cornerRadius||o.borderSize)&&(m=await(async(e,{width:a,height:o,cornerRadius:i,borderSize:n,borderColor:r})=>{if(!i&&!n){return e}const s=await t(e),d=document.createElement("canvas");d.width=Math.max(1,Math.round(a)),d.height=Math.max(1,Math.round(o));const c=d.getContext("2d"),h=Math.max(0,i),g=d.width,p=d.height,w=(t=!1)=>{const e=Math.min(h,Math.min(g,p)/2);c.beginPath(),c.moveTo(e,0),c.lineTo(g-e,0),c.quadraticCurveTo(g,0,g,e),c.lineTo(g,p-e),c.quadraticCurveTo(g,p,g-e,p),c.lineTo(e,p),c.quadraticCurveTo(0,p,0,p-e),c.lineTo(0,e),c.quadraticCurveTo(0,0,e,0),c.closePath(),t&&n>0&&(c.lineWidth=n,c.strokeStyle="#"+l(r),c.stroke())};return w(!1),c.save(),c.clip(),c.drawImage(s,0,0,g,p),c.restore(),n>0&&w(!0),d.toDataURL("image/png")})(m,{width:o.width,height:o.height,cornerRadius:o.cornerRadius,borderSize:o.borderSize,borderColor:o.borderColor}));const b=Object.assign(Object.assign({},h(o)),{w:d(o.width),h:d(o.height),rotate:o.rotation,flipH:o.flipX,flipV:o.flipY,transparency:c(o.opacity)});if(o.shadowEnabled){const t=Math.hypot(o.shadowOffsetX,o.shadowOffsetY)/2,e=180*Math.atan2(o.shadowOffsetY,o.shadowOffsetX)/Math.PI;b.shadow={type:"outer",blur:o.shadowBlur/2,offset:t,angle:e,color:l(o.shadowColor),opacity:o.shadowOpacity}}await i.addImage(Object.assign({path:m},b))},w=t=>"arrow"===t?"arrow":"triangle"===t?"triangle":"circle"===t?"oval":"square"===t?"diamond":"none",u=t=>{if(t&&t.length){return t.length<=2?"dash":"dashDot"}},f={image:p,svg:p,gif:p,text:async({element:t,slide:e})=>{let a=i(t.text||"");"uppercase"===t.textTransform&&(a=a.toUpperCase());const o=Object.assign(Object.assign(Object.assign(Object.assign({},h(t)),{w:d(t.width),h:d(t.height),fontSize:Math.round(.75*t.fontSize),fontFace:t.fontFamily,color:l(t.fill),align:t.align,bold:n(t.fontWeight),italic:"italic"===t.fontStyle}),"underline"===t.textDecoration?{underline:{style:"sng",color:l(t.fill)}}:{}),{lineSpacingMultiple:t.lineHeight,rotate:t.rotation,fit:"shrink",transparency:c(t.opacity),margin:0});if("middle"===t.verticalAlign?o.valign="middle":"bottom"===t.verticalAlign?o.valign="bottom":o.valign="top",t.letterSpacing&&(o.charSpacing=t.letterSpacing*o.fontSize),t.strokeWidth>0&&(o.outline={size:.75*t.strokeWidth,color:l(t.stroke)}),t.shadowEnabled){const e=.75*Math.hypot(t.shadowOffsetX,t.shadowOffsetY)/2,a=180*Math.atan2(t.shadowOffsetY,t.shadowOffsetX)/Math.PI;o.shadow={type:"outer",blur:.75*t.shadowBlur,offset:e,angle:a,color:l(t.shadowColor),opacity:t.shadowOpacity}}if(t.backgroundEnabled){o.fill={color:l(t.backgroundColor)};const e=t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5);o.rectRadius=d(e);const a=t.backgroundPadding*(t.fontSize*t.lineHeight);o.margin=Math.max(0,Math.round(.75*a))}await e.addText(a,o)},line:async({element:t,slide:e})=>{const a=Object.assign(Object.assign({},h(t)),{w:d(t.width),h:d(t.height),line:{color:l(t.color),width:t.height,beginArrowType:w(t.startHead),endArrowType:w(t.endHead),dashType:u(t.dash),transparency:c(t.opacity)},rotate:t.rotation,transparency:c(t.opacity)});await e.addShape("line",a)},figure:async({element:e,slide:a})=>{const i=o(e),n=await(async(e,a,o)=>{const i="data:image/svg+xml;base64,"+btoa(e),n=await t(i),r=document.createElement("canvas");return r.width=Math.max(1,Math.round(a)),r.height=Math.max(1,Math.round(o)),r.getContext("2d").drawImage(n,0,0,r.width,r.height),r.toDataURL("image/png")})(i,e.width,e.height),r=Object.assign(Object.assign({},h(e)),{w:d(e.width),h:d(e.height),rotate:e.rotation,transparency:c(e.opacity)});await a.addImage(Object.assign({path:n},r))},group:async({element:t,slide:e})=>{for(const a of t.children||[]){await m({element:a,slide:e})}},video:async({element:t,slide:e})=>{const a=Object.assign(Object.assign({},h(t)),{w:d(t.width),h:d(t.height),rotate:t.rotation});await e.addMedia(Object.assign({type:"video",path:t.src},a))}},m=async({element:t,slide:e})=>{if(!t.visible||!t.showInExport){return}const a=f[t.type];a?await a({element:t,slide:e}):console.warn(`PPTX export doesn't support ${t.type} type`)};export async function jsonToPPTX({json:t}){const e=new(await getPptxGen());e.defineLayout({name:"CUSTOM",width:d(t.width),height:d(t.height)}),e.layout="CUSTOM";for(const a of t.pages){const t=e.addSlide();if(/\.(jpg|jpeg|png|gif)$/i.test(a.background)||a.background.startsWith("data:image")||a.background.startsWith("http")){await t.addImage({path:a.background,x:0,y:0,w:e.width,h:e.height,sizing:{type:"contain"}})}else{const e=s.Util.colorToRGBA(a.background),o=s.Util._rgbToHex(e.r,e.g,e.b).replace("#","");t.background={color:o}}for(const e of a.children){await m({element:e,slide:t})}}return e.writeFile("test.pptx"),e}
package/utils/to-svg.js CHANGED
@@ -1 +1 @@
1
- var t=this&&this.__rest||function(t,e){var n={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(t);i<o.length;i++){e.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(t,o[i])&&(n[o[i]]=t[o[i]])}}return n};import{cropImage as e,getCrop as n,loadImage as o}from"./image.js";import*as i from"./svg.js";import{figureToSvg as r}from"./figure-to-svg.js";import{Effects as l,shapeFilterToCSS as s}from"./filters.js";import{removeTags as a,parseHtmlToSegments as h}from"./text.js";import{segmentsToTspans as c}from"./text-html.js";import{xmlEscape as d}from"./xml.js";import{getCurvePath as f}from"../canvas/text-element.js";import*as g from"./gradient.js";import{normalizeRichTextHtml as p,extractFontFamiliesFromHtml as u}from"./rich-text-html.js";import{bulletMarkerPosition as m,numberMarkerPosition as y}from"./list-marker-geometry.js";import{generateBackgroundShapeFromRects as x,textLinesToRects as w}from"./background-shape.js";export const forEveryNode=(t,e)=>{if(t.children){for(const n of t.children){if(!0===e(n)){break}forEveryNode(n,e)}}if(t.cells){for(const n of t.cells){if(!0===e(n)){break}}}};const k=(t,e,...n)=>({type:t,props:e,children:n||[]});function b(t,e){if(!g.isGradient(t)){return null}const{stops:n,rotation:o}=g.parseColor(t),i=o*Math.PI/180,r=.5-.5*Math.sin(i),l=.5+.5*Math.cos(i),s=.5+.5*Math.sin(i),a=.5-.5*Math.cos(i),h=n.map(({offset:t,color:e})=>k("stop",{offset:100*t+"%","stop-color":e}));return k("linearGradient",{id:e,x1:100*r+"%",y1:100*l+"%",x2:100*s+"%",y2:100*a+"%"},...h)}export function fixRatio(t){var e=(new DOMParser).parseFromString(t,"image/svg+xml");return e.documentElement.setAttribute("preserveAspectRatio","none"),(new XMLSerializer).serializeToString(e)}const $=async t=>{try{const e=await fetch(t);if("undefined"!=typeof Buffer){const t=await e.arrayBuffer(),n=Buffer.from(t).toString("base64");return`data:${e.headers.get("content-type")||"image/png"};base64,${n}`}{const t=await e.blob();return new Promise((e,n)=>{const o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=n,o.readAsDataURL(t)})}}catch(e){return console.error("Error converting URL to data URL:",e),t}},v=async({element:t,page:e,store:n})=>{let{src:r}=t;if("svg"===t.type){const e=await i.urlToString(r);r=i.replaceColors(e,new Map(Object.entries(t.colorsReplace)))}else{r=await $(r)}let l,s,a,h,c="";if(t.flipX||t.flipY){const e=t.flipX?-1:1,n=t.flipY?-1:1,o=t.width/2,i=t.height/2;c=`translate(${o}, ${i}) scale(${e}, ${n}) translate(${-o}, ${-i})`}t.clipSrc&&(l=`clip-img-mask-${t.id}`,s=await $(t.clipSrc)),t.maskSrc&&(a=`mask-img-${t.id}`,h=await $(t.maskSrc));const d=await o(r),f=d.width*t.cropWidth,p=d.height*t.cropHeight,u=t.width/t.height;let m,y;const x=f/p,w="boolean"==typeof t.stretchEnabled&&t.stretchEnabled||"svg"===t.type;w?(m=f,y=p):u>=x?(m=f,y=f/u):(m=p*u,y=p);const v=m/d.width,S=y/d.height,j=m/y>t.width/t.height?t.height/y:t.width/m,O=w?t.width/m:j,H=w?t.height/y:j,z=m*O/v,W=y*H/S;let M=t.cropX*d.width*O,E=t.cropY*d.height*H;t.flipX&&(M=(1-t.cropX-t.cropWidth)*d.width*O),t.flipY&&(E=(1-t.cropY-t.cropHeight)*d.height*H);const F=`clip-${t.id}`,T=t.cornerRadius||0,L=r.replace(/&/g,"&amp;"),C={x:-M,y:-E,width:z,height:W,preserveAspectRatio:"none","clip-path":`url(#${F})`},A=[k("clipPath",{id:F},k("rect",{x:0,y:0,width:t.width,height:t.height,rx:T||void 0,ry:T||void 0}))];l&&s&&A.push(k("mask",{id:l,maskUnits:"userSpaceOnUse","mask-type":"alpha"},k("image",{href:s.replace(/&/g,"&amp;"),x:0,y:0,width:t.width,height:t.height,preserveAspectRatio:"none"}))),a&&A.push(k("mask",{id:a,maskUnits:"userSpaceOnUse","mask-type":"alpha"},k("image",Object.assign({href:L},C))));let B=L;const R={};a&&h&&(B=h.replace(/&/g,"&amp;"),R.mask=`url(#${a})`);const P={};l&&(P.mask=`url(#${l})`);const D=t.borderSize||0,N=D>0&&g.isGradient(t.borderColor),U=N?`border-grad-${t.id}`:null;if(N){const e=b(t.borderColor,U);e&&A.push(e)}const G=D>0?k("rect",{x:D/2,y:D/2,width:Math.max(0,t.width-D),height:Math.max(0,t.height-D),fill:"none",stroke:N?`url(#${U})`:t.borderColor,"stroke-width":D,rx:Math.max(0,T-D)||void 0,ry:Math.max(0,T-D)||void 0}):null,I=k("g",{},k("defs",{},...A),k("image",Object.assign(Object.assign({href:B},C),R)),G);return k("g",P,c?k("g",{transform:c},I):I)},S=({element:t,type:e})=>{const n={"stroke-width":t.height,stroke:t.color,"stroke-linecap":"round","stroke-linejoin":"round"},o=Object.assign(Object.assign({},n),{fill:t.color}),i=Object.assign(Object.assign({},n),{fill:"none"});return"arrow"===e?k("polyline",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},i)):"triangle"===e?k("polygon",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},o)):"bar"===e?k("polyline",Object.assign({points:`0,${2*-t.height} 0,${2*t.height}`},i)):"circle"===e?k("circle",Object.assign({cx:2*t.height,cy:0,r:2*t.height},o)):"square"===e?k("polygon",Object.assign({points:`0,${2*-t.height} ${4*t.height},${2*-t.height} ${4*t.height},${2*t.height} 0,${2*t.height}`},o)):null},j={image:v,svg:v,text:async({element:t,page:e,store:n})=>{const o=g.isGradient(t.fill),i=g.isGradient(t.stroke);if(t.curveEnabled){const e=p(t.text,{fontSize:t.fontSize,fontFamily:t.fontFamily}),n=h(e,{fontSize:t.fontSize,fontFamily:t.fontFamily}),r=Math.max(t.fontSize,...n.map(e=>{var n;return null!==(n=e.fontSize)&&void 0!==n?n:t.fontSize})),l=f(t.width,t.height,t.curvePower,r),s=z(t.id||"temp"),a=`curve-path-${s}`,d={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black",fontFamily:t.fontFamily,fontSize:t.fontSize},g=c(n,d),u=c(n,d,{omitColors:!0}),m=t.backgroundPadding*(t.fontSize*t.lineHeight*.5),y=t.backgroundEnabled?k("rect",{x:-m,y:-m,width:t.width+2*m,height:t.height+2*m,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5),ry:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)}):null,x=[k("path",{id:a,d:l,fill:"none"})],w=t.strokeWidth&&(i||o&&!i);if(o){const e=`curve-fill-grad-${s}`,n=b(t.fill,e);n&&x.push(n)}if(i&&t.strokeWidth){const e=`curve-stroke-grad-${s}`,n=b(t.stroke,e);n&&x.push(n)}if(w){const e={"font-size":t.fontSize+"px","text-anchor":"middle","dominant-baseline":"central","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration||void 0,"letter-spacing":t.letterSpacing*r},n=i?`url(#curve-stroke-grad-${s})`:t.stroke,l=k("text",Object.assign(Object.assign({},e),{fill:n,"stroke-width":t.strokeWidth,stroke:n}),k("textPath",{href:`#${a}`,startOffset:"50%",innerHTML:u})),h=o?`url(#curve-fill-grad-${s})`:t.fill,c=k("text",Object.assign(Object.assign({},e),{fill:h}),k("textPath",{href:`#${a}`,startOffset:"50%",innerHTML:g}));return k("g",{},y,k("defs",{},...x),l,c)}return k("g",{},y,k("defs",{},...x),k("text",{fill:o?`url(#curve-fill-grad-${s})`:t.fill,"font-size":t.fontSize+"px","text-anchor":"middle","dominant-baseline":"central","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration||void 0,"letter-spacing":t.letterSpacing*r,"stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?i?`url(#curve-stroke-grad-${s})`:t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0},k("textPath",{href:`#${a}`,startOffset:"50%",innerHTML:g})))}let r=null;const l=()=>(r||(r=document.createElement("canvas").getContext("2d")),r),s=(t,e,n,o,i,r=0)=>{const s=l();return s.font=`${i} ${o} ${e}px ${n}`,s.measureText(t).width+Math.max(0,(t?t.length:0)-1)*r*e},a=(e,n,o)=>{let i=n;null!=e.fontSize&&e.fontSize!==t.fontSize&&t.fontSize>0&&(i=e.fontSize*(n/t.fontSize));const r=e.fontFamily||t.fontFamily,l=e.bold?"bold":t.fontWeight||"normal",a=e.italic?"italic":t.fontStyle||"normal";return s(e.text,i,r,l,a,o)},u=/<[a-z][\s\S]*>/i.test(t.text);let $=t.text;!u&&$.includes("\n")&&($=$.split("\n").map(t=>`<p>${t}</p>`).join(""));const v=p($,{fontSize:t.fontSize,fontFamily:t.fontFamily}),S={fontSize:t.fontSize,fontFamily:t.fontFamily},j=[],O=(new DOMParser).parseFromString(v,"text/html"),H=O.body.querySelectorAll("p");H.length>0?H.forEach((t,e)=>{const n=t.innerHTML,o=h(n,S);j.push(...o),e<H.length-1&&j.push({text:"\n"})}):j.push(...h(v,S)),"uppercase"===t.textTransform&&j.forEach(t=>{"\n"!==t.text&&(t.text=t.text.toUpperCase())});const W=t=>{const e=[];let n=[];for(const o of t){if("\n"===o.text){n.length>0&&(e.push(n),n=[]),e.push([Object.assign(Object.assign({},o),{text:"\n"})]);continue}const t=o.text.split(/( )/);for(const i of t){""!==i&&(" "===i?(n.length>0&&(e.push(n),n=[]),e.push([Object.assign(Object.assign({},o),{text:" "})])):n.push(Object.assign(Object.assign({},o),{text:i})))}}return n.length>0&&e.push(n),e},M=(t,e,n,o)=>{const i=[[]];let r=0;for(const l of t){if(1===l.length&&"\n"===l[0].text){i.push([]),r=0;continue}const t=l.reduce((t,e)=>t+a(e,n,o),0);1!==l.length||" "!==l[0].text?(r+t>e+.5&&i[i.length-1].length>0&&(i.push([]),r=0),i[i.length-1].push(...l),r+=t):r+t<=e+.5&&(i[i.length-1].push(...l),r+=t)}return i},E=(t,e,n)=>t.reduce((t,o)=>t+a(o,e,n),0),F=(t,e)=>1===e?t:t.map(t=>t.map(t=>t.fontSize?Object.assign(Object.assign({},t),{fontSize:Math.round(t.fontSize*e*1e3)/1e3}):t));if(O.body.querySelector("ul, ol")){const e=[],n=2.1,r=e=>{const n=e.cloneNode(!0);n.querySelectorAll("ul, ol").forEach(t=>t.remove());const o=h(n.innerHTML,S);return"uppercase"===t.textTransform&&o.forEach(t=>{"\n"!==t.text&&(t.text=t.text.toUpperCase())}),o},a=(t,n)=>{for(const o of Array.from(t.children)){const t=o.tagName.toLowerCase();if("ul"===t||"ol"===t){const i="ol"===t;let l=parseInt(o.getAttribute("start")||"1",10)||1;for(const t of Array.from(o.children)){if("li"!==t.tagName.toLowerCase()){continue}const o=t.getAttribute("value");o&&!Number.isNaN(parseInt(o,10))&&(l=parseInt(o,10));const s=i?{text:`${l}.`,isOrdered:!0}:{text:"•",isOrdered:!1};e.push({segments:r(t),depth:n+1,marker:s}),i&&(l+=1),a(t,n+1)}}else{"p"===t||"div"===t?e.push({segments:r(o),depth:0,marker:null}):e.push({segments:h(o.outerHTML,S),depth:0,marker:null})}}};a(O.body,0);const f=o=>{const i=[],r=[];for(const l of e){const e=l.depth*n*o,s=Math.max(1,t.width-e);(0===l.segments.length?[[]]:M(W(l.segments),s,o,t.letterSpacing)).forEach((t,n)=>{i.push(t),r.push({indent:e,marker:0===n?l.marker:null})})}return{L:i,M:r}};let g=t.fontSize,p=[],u=[];for(;;){const e=f(g);p=e.L,u=e.M;const n=Math.max(0,...p.map((e,n)=>u[n].indent+E(e,g,t.letterSpacing))),o=p.length*g*t.lineHeight;if(n<=t.width&&(!t.height||o<=t.height)){break}if(g-=1,g<4){break}}p=F(p,g/t.fontSize);const w=g*t.lineHeight,$=p.length*w;let v=0;"middle"===t.verticalAlign?v=(t.height-$)/2:"bottom"===t.verticalAlign&&(v=t.height-$);const j=g+v,H={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black",fontFamily:t.fontFamily,fontSize:g},z=t=>{let e=t.length;for(;e>0&&""===t[e-1].text.trim();){e--}return t.slice(0,e)},T=l(),L=t.fontWeight||"normal",C=t.fontStyle||"normal";T.font=`${C} ${L} ${g}px ${t.fontFamily}`;const A=T.measureText(" ").width,B=u.map((e,n)=>{var o,i,r,l,a;if(!e.marker){return null}const h=j+n*w;let c;if(e.marker.isOrdered){const n=s(e.marker.text,g,t.fontFamily,L,C,t.letterSpacing);c=y(e.indent,h,{markerWidth:n,spaceWidth:A})}else{const t=T.measureText(e.marker.text);c=m(e.indent,h,{ascent:null!==(i=null!==(o=t.fontBoundingBoxAscent)&&void 0!==o?o:t.actualBoundingBoxAscent)&&void 0!==i?i:.8*g,inkRight:null!==(r=t.actualBoundingBoxRight)&&void 0!==r?r:0,inkAscent:null!==(l=t.actualBoundingBoxAscent)&&void 0!==l?l:0,inkDescent:null!==(a=t.actualBoundingBoxDescent)&&void 0!==a?a:0})}return k("tspan",{x:c.x,y:c.y,"letter-spacing":e.marker.isOrdered?t.letterSpacing*g+"px":void 0,innerHTML:d(e.marker.text)})}),R=t=>{const e=[];return p.forEach((n,o)=>{const i=z(n);i.length>0&&e.push(k("tspan",{x:u[o].indent,y:j+o*w,innerHTML:c(i,H,{omitColors:t})})),B[o]&&e.push(B[o])}),e};let P=null;if(t.backgroundEnabled){const e=t.backgroundPadding*(g*t.lineHeight*.5),n=t.backgroundCornerRadius*(g*t.lineHeight*.5);if(t.legacyBackground){P=k("rect",{x:-e,y:-e,width:t.width+2*e,height:t.height+2*e,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:n,ry:n})}else{const o=p.map((e,n)=>{const o=e.length?E(e,g,t.letterSpacing):0,i=n*w;return{left:u[n].indent,right:u[n].indent+o,top:i,bottom:i+w}}).filter(t=>t.right>t.left),i=x({rects:o,padding:e,cornerRadius:n});i&&(P=k("path",{d:i,fill:t.backgroundColor,opacity:t.backgroundOpacity,transform:v?`translate(0,${v})`:void 0}))}}const D=[];if(o){const e=b(t.fill,`text-fill-grad-${t.id}`);e&&D.push(e)}if(i&&t.strokeWidth){const e=b(t.stroke,`text-stroke-grad-${t.id}`);e&&D.push(e)}const N=t.strokeWidth&&(i||o&&!i),U={"font-size":g+"px","text-anchor":"start","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"letter-spacing":t.letterSpacing*g+"px"};if(N){const e=R(!0),n=i?`url(#text-stroke-grad-${t.id})`:t.stroke,r=k("text",Object.assign(Object.assign({},U),{fill:n,"stroke-width":t.strokeWidth,stroke:n}),...e.map(t=>k("tspan",t.props,t.props.innerHTML))),l=o?`url(#text-fill-grad-${t.id})`:t.fill,s=o?e:R(!1),a=k("text",Object.assign(Object.assign({},U),{fill:l}),...s.map(t=>k("tspan",t.props,t.props.innerHTML)));return k("g",{},P,D.length>0?k("defs",{},...D):null,r,a)}return k("g",{},P,D.length>0?k("defs",{},...D):null,k("text",Object.assign(Object.assign({},U),{fill:o?`url(#text-fill-grad-${t.id})`:t.fill,"stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0}),...R(!1)))}let T=t.fontSize;const L=W(j);let C=[];for(;;){C=M(L,t.width,T,t.letterSpacing);const e=Math.max(...C.map(e=>E(e,T,t.letterSpacing)),0),n=C.length*T*t.lineHeight;if(e<=t.width&&n<=t.height){break}if(T-=1,T<4){break}}C=F(C,T/t.fontSize);const A=T*t.lineHeight,B=C.length*A;let R=T;"middle"===t.verticalAlign?R=(t.height-B)/2+T:"bottom"===t.verticalAlign&&(R=t.height-B+T);const P="center"===t.align?"middle":"right"===t.align?"end":"start",D={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black",fontFamily:t.fontFamily,fontSize:T},N="center"===t.align?t.width/2:"right"===t.align?t.width:0,U=t=>{let e=t.length;for(;e>0&&""===t[e-1].text.trim();){e--}return t.slice(0,e)},G=C.map((t,e)=>{const n=U(t),o=0===n.length?"​":c(n,D);return k("tspan",{x:N,dy:0===e?0:A,innerHTML:o})}),I=t.backgroundPadding*(T*t.lineHeight*.5),X=t.backgroundCornerRadius*(T*t.lineHeight*.5);let Y=null;if(t.backgroundEnabled){if(t.legacyBackground){Y=k("rect",{x:-I,y:-I,width:t.width+2*I,height:t.height+2*I,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:X,ry:X})}else{const e=w({lines:C.map(e=>({width:0===e.length?0:E(e,T,t.letterSpacing)})),lineHeight:A,width:t.width,align:"justify"===t.align?"justify":t.align});let n=0;"middle"===t.verticalAlign?n=(t.height-C.length*A)/2:"bottom"===t.verticalAlign&&(n=t.height-C.length*A);const o=x({rects:e,padding:I,cornerRadius:X});o&&(Y=k("path",{d:o,fill:t.backgroundColor,opacity:t.backgroundOpacity,transform:n?`translate(0,${n})`:void 0}))}}const q=[],V=t.strokeWidth&&(i||o&&!i);if(o){const e=`text-fill-grad-${t.id}`,n=b(t.fill,e);n&&q.push(n)}if(i&&t.strokeWidth){const e=`text-stroke-grad-${t.id}`,n=b(t.stroke,e);n&&q.push(n)}if(V){const e=C.map((t,e)=>{const n=U(t),o=c(n,D,{omitColors:!0});return k("tspan",{x:N,dy:0===e?0:A,innerHTML:o})}),n={y:R,"font-size":T+"px","text-anchor":P,"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"letter-spacing":t.letterSpacing*T+"px"},r=i?`url(#text-stroke-grad-${t.id})`:t.stroke,l=k("text",Object.assign(Object.assign({},n),{fill:r,"stroke-width":t.strokeWidth,stroke:r}),...e.map(t=>k("tspan",t.props,t.props.innerHTML))),s=o?`url(#text-fill-grad-${t.id})`:t.fill,a=o?e:G,h=k("text",Object.assign(Object.assign({},n),{fill:s}),...a.map(t=>k("tspan",t.props,t.props.innerHTML)));return k("g",{},Y,q.length>0?k("defs",{},...q):null,l,h)}return k("g",{},Y,q.length>0?k("defs",{},...q):null,k("text",{fill:o?`url(#text-fill-grad-${t.id})`:t.fill,y:R,"font-size":T+"px","text-anchor":P,"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"letter-spacing":t.letterSpacing*T+"px","stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0},...G))},line:async({element:t,page:e,store:n})=>k("g",{},k("line",{x1:0,y1:t.height/2,x2:t.width,y2:t.height/2,stroke:t.color,"stroke-width":t.height,"stroke-dasharray":t.dash&&t.dash.length?t.dash.map(e=>e*t.height).join(" "):void 0}),k("g",{transform:`translate(0 ${t.height/2})`},S({element:t,type:t.startHead})),k("g",{transform:`translate(${t.width} ${t.height/2}) rotate(180)`},S({element:t,type:t.endHead}))),figure:async({element:t,page:e,store:n,elementHook:o})=>{let i=function(t){let e=t.replace(/<svg[^>]*>/,"");return e=e.replace(/<\/svg>/,""),e}(r(t));const l=[];if(t.strokeWidth&&g.isGradient(t.stroke)){const e=`figure-stroke-grad-${t.id}`,n=b(t.stroke,e);if(n){l.push(n);const o=t.stroke.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`stroke="${o}"`,"g"),`stroke="url(#${e})"`)}}if(g.isGradient(t.fill)){const e=`figure-fill-grad-${t.id}`,n=b(t.fill,e);if(n){l.push(n);const o=t.fill.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`fill="${o}"`,"g"),`fill="url(#${e})"`)}}if(l.length>0){const e=k("g",{},k("defs",{},...l),k("g",{innerHTML:i}));return o&&o({dom:e,element:t})||e}const s=k("g",{innerHTML:i});return o&&o({dom:s,element:t})||s},group:async({element:t,page:e,store:n,elementHook:o})=>{const i=await Promise.all(t.children.map(t=>O({element:t,page:e,store:n,elementHook:o}))),r=k("g",{style:{"transform-origin":"top left"}},...i);return o&&o({dom:r,element:t})||r},gif:v,table:async({element:t})=>{t.rows;const e=t.cols,n=t.colWidths,o=t.rowHeights,i=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],r=(t.cells||[]).map((n,o)=>{const r=Object.assign(Object.assign({},n),{row:Math.floor(o/e),col:o%e});for(const e of i){void 0===r[e]&&(r[e]=t[e])}return r}),l=[],s=(e,i,r,l)=>{let s=0;for(let o=0;o<i;o++){s+=n[o]*t.width}let a=0;for(let n=0;n<e;n++){a+=o[n]*t.height}let h=0;for(let o=i;o<i+l;o++){h+=(n[o]||0)*t.width}let c=0;for(let n=e;n<e+r;n++){c+=(o[n]||0)*t.height}return{x:s,y:a,width:h,height:c}};for(const a of r){if(!a.mergedInto&&a.cellBackground&&"transparent"!==a.cellBackground){s(a.row,a.col,a.colSpan||1,a.colSpan||1);const{x:t,y:e,width:n,height:o}=s(a.row,a.col,a.rowSpan||1,a.colSpan||1);l.push(k("rect",{x:t,y:e,width:n,height:o,fill:a.cellBackground}))}}const h=(t,e)=>"dashed"===t?`${4*e},${2*e}`:"dotted"===t?`${e},${e}`:void 0,c=(e,n)=>{var o,i,r,l,s;const a=null===(o=e.borders)||void 0===o?void 0:o[n];return{width:null!==(i=null==a?void 0:a.width)&&void 0!==i?i:t.borderWidth,style:null!==(l=null!==(r=null==a?void 0:a.style)&&void 0!==r?r:t.borderStyle)&&void 0!==l?l:"solid",color:null!==(s=null==a?void 0:a.color)&&void 0!==s?s:t.borderColor}};for(const a of r){if(a.mergedInto){continue}const t=s(a.row,a.col,a.rowSpan||1,a.colSpan||1);if(0===a.row){const e=c(a,"top");"none"!==e.style&&e.width>0&&l.push(k("line",{x1:t.x,y1:t.y+e.width/2,x2:t.x+t.width,y2:t.y+e.width/2,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}if(0===a.col){const e=c(a,"left");"none"!==e.style&&e.width>0&&l.push(k("line",{x1:t.x+e.width/2,y1:t.y,x2:t.x+e.width/2,y2:t.y+t.height,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}{const e=c(a,"bottom");"none"!==e.style&&e.width>0&&l.push(k("line",{x1:t.x,y1:t.y+t.height-e.width/2,x2:t.x+t.width,y2:t.y+t.height-e.width/2,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}{const e=c(a,"right");"none"!==e.style&&e.width>0&&l.push(k("line",{x1:t.x+t.width-e.width/2,y1:t.y,x2:t.x+t.width-e.width/2,y2:t.y+t.height,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}}for(const f of r){if(f.mergedInto){continue}let e=a(f.text||"");if(!e){continue}"uppercase"===f.textTransform&&(e=e.toUpperCase());const i=f.cellPadding||4;let r=0;for(let o=0;o<f.col;o++){r+=n[o]*t.width}let s=0;for(let n=0;n<f.row;n++){s+=o[n]*t.height}const h=n[f.col]*t.width,c=o[f.row]*t.height,g=f.fontSize||12,p=f.align||"left";let u=r+i,m="start";"center"===p?(u=r+h/2,m="middle"):"right"===p&&(u=r+h-i,m="end");let y=s+i+g;const x=f.verticalAlign||"top";"middle"===x?y=s+c/2+g/3:"bottom"===x&&(y=s+c-i),l.push(k("text",{x:u,y,"font-size":g,"font-family":f.fontFamily||"Roboto","font-weight":f.fontWeight||"normal","font-style":f.fontStyle||"normal",fill:f.fill||"black","text-anchor":m,"text-decoration":f.textDecoration||"none","letter-spacing":f.letterSpacing?f.letterSpacing*g+"px":void 0},d(e)))}return k("g",{},...l)}};async function O({element:t,page:e,store:n,elementHook:o}){var i;let r=await j[t.type];r||(r=()=>k("g",{}),console.error(`SVG export does not support ${t.type} type...`));const a=await r({element:t,page:e,store:n}),h=[],c=[];if(t.blurEnabled&&h.push(`blur(${t.blurRadius/2}px)`),t.brightnessEnabled&&h.push(`brightness(${100*t.brightness+100}%)`),t.sepiaEnabled&&h.push("sepia()"),t.grayscaleEnabled&&h.push("grayscale()"),t.shadowEnabled&&h.push(`drop-shadow(${t.shadowOffsetX}px ${t.shadowOffsetY}px ${t.shadowBlur}px ${t.shadowColor})`),t.filters){for(const[f,g]of Object.entries(t.filters)){const t=s(l[f],g.intensity);if(t&&(h.push(t.filter),t.html)){const e=t.html.replace(/<svg([^>]*)>/,"<g$1>").replace(/<\/svg>/,"</g>");c.push(e)}}}const d=k("g",{className:"element",id:t.id,transform:"group"!==t.type?`translate(${t.x}, ${t.y}) rotate(${t.rotation})`:void 0,display:null===(i=t.visible)||void 0===i||i?void 0:"none",opacity:t.opacity,style:{"transform-origin":"top left",filter:h.join(" ")}},a,...c);return o&&o({dom:d,element:t})||d}async function H(t){try{const e=await fetch(t),n=e.headers.get("content-type")||"font/ttf",o=await e.arrayBuffer();return`data:${n};base64,${"undefined"!=typeof Buffer?Buffer.from(o).toString("base64"):function(t){const e=new Uint8Array(t);let n="";for(let o=0;o<e.length;o+=32768){const t=e.subarray(o,o+32768);n+=String.fromCharCode(...t)}if("undefined"!=typeof btoa){return btoa(n)}if("undefined"!=typeof Buffer){return Buffer.from(e).toString("base64")}throw new Error("No base64 encoder available in this environment")}(o)}`}catch(e){return console.error("Error embedding font:",e),t}}export async function jsonToDOM({json:t,elementHook:i,fontEmbedding:r="inline"}){const l=[];forEveryNode({children:t.pages},t=>{if(("text"===t.type||"tablecell"===t.type||"table"===t.type)&&(t.fontFamily&&-1===l.indexOf(t.fontFamily)&&l.push(t.fontFamily),t.text)){for(const e of u(t.text)){-1===l.indexOf(e)&&l.push(e)}}});const s="inline"===r?await async function(t,e){return await Promise.all(t.map(async t=>{var n,o;if("Arial"===t){return null}const i=e.find(e=>e.fontFamily===t);if(i){const e=i.styles||(i.url?[{src:`url("${i.url}")`,fontStyle:"normal",fontWeight:"normal"}]:[]),n=await Promise.all(e.map(async e=>{var n,o;const r=(null===(o=null===(n=e.src)||void 0===n?void 0:n.match(/url\("?(.*?)"?\)/))||void 0===o?void 0:o[1])||i.url,l=await H(r);return`@font-face {\n font-family: '${t}';\n font-style: ${e.fontStyle||"normal"};\n font-weight: ${e.fontWeight||"normal"};\n src: url(${l});\n}`}));return k("style",{},n.join("\n"))}{const e=`https://fonts.googleapis.com/css?family=${encodeURIComponent(t)}:bi,normal,i,b`;try{const i=await fetch(e),r=await i.text(),l=null===(o=null===(n=r.match(/url\((.*?)\)/g))||void 0===n?void 0:n.map(t=>t.replace(/url\((.*?)\)/,"$1")))||void 0===o?void 0:o.filter(t=>t.startsWith("https"));if(!(null==l?void 0:l.length)){throw new Error("No font URLs found")}const s=await Promise.all(l.map(async e=>{const n=await H(e),o=(r.match(/@font-face\s*\{[^}]*?\}/g)||[]).find(t=>t.includes(e))||"",i=o.match(/font-style:\s*(.*?)[;\s}]/),l=o.match(/font-weight:\s*(.*?)[;\s}]/),s=i?i[1].trim():"normal",a=l?l[1].trim():"normal";return`@font-face {\n font-family: '${t}';\n font-style: ${s};\n font-weight: ${a};\n src: url(${n});\n}`}));return k("style",{},s.join("\n"))}catch(r){return console.error("Error embedding Google Font:",r),k("defs",{},k("style",{type:"text/css",innerHTML:`@import url('${e}');`.replace(/&/g,"&amp;")}))}}}))}(l,t.fonts):[],a=await Promise.all(t.pages.map(r=>async function({page:t,store:i,elementHook:r}){const l=await Promise.all(t.children.map(e=>O({element:e,page:t,store:i,elementHook:r}))),s=t.background.indexOf("url")>=0||t.background.indexOf("http")>=0||t.background.indexOf(".jpg")>=0||t.background.indexOf(".png")>=0||t.background.indexOf(".jpeg")>=0;let a;if(s){const r=await o(t.background);a=await e(t.background,Object.assign({width:i.width,height:i.height,x:0,y:0},n({width:i.width,height:i.height},{width:r.width,height:r.height})))}return k("g",{className:"page",style:{}},s?k("image",{"xlink:href":a,x:0,y:0,width:i.width,height:i.height,preserveAspectRatio:"none"}):k("rect",{x:0,y:0,width:i.width,height:i.height,fill:s?void 0:t.background}),...l)}({page:r,store:t,elementHook:i})));return k("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",viewBox:`0 0 ${t.width} ${t.height}`,width:t.width,height:t.height},...s,...a)}function z(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}const W=({dom:e,nestLevel:n=0})=>{if("string"==typeof e){return e}if(!e){return""}const o=e.props,{innerHTML:i}=o,r=t(o,["innerHTML"]),l=Object.keys(r).map(t=>((t,e)=>"object"==typeof e?`${t}="${Object.keys(e).map(t=>`${t}:${e[t]};`).join(" ")}"`:null==e||""===e?"":`${t}="${z(String(e))}"`)(t,r[t])).filter(t=>t&&t.trim().length>0).join(" "),s=" ".repeat(n);return`${s}<${e.type}${l?" "+l:""}>${i||"\n"+e.children.map(t=>W({dom:t,nestLevel:n+1})).join("")}${s}</${e.type}>\n`};export async function jsonToSVG({json:t,elementHook:e,fontEmbedding:n="inline"}){const o=await jsonToDOM({json:t,elementHook:e,fontEmbedding:n});return W({dom:o})}
1
+ var t=this&&this.__rest||function(t,e){var n={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(o=Object.getOwnPropertySymbols(t);i<o.length;i++){e.indexOf(o[i])<0&&Object.prototype.propertyIsEnumerable.call(t,o[i])&&(n[o[i]]=t[o[i]])}}return n};import{cropImage as e,getCrop as n,loadImage as o}from"./image.js";import*as i from"./svg.js";import{figureToSvg as r}from"./figure-to-svg.js";import{Effects as l,shapeFilterToCSS as s}from"./filters.js";import{removeTags as a,parseHtmlToSegments as h}from"./text.js";import{segmentsToTspans as c}from"./text-html.js";import{xmlEscape as d}from"./xml.js";import{getCurvePath as f}from"../canvas/text-element.js";import*as g from"./gradient.js";import{normalizeRichTextHtml as p,extractFontFamiliesFromHtml as u}from"./rich-text-html.js";import{bulletMarkerPosition as m,numberMarkerPosition as y}from"./list-marker-geometry.js";import{generateBackgroundShapeFromRects as x,textLinesToRects as w}from"./background-shape.js";export const forEveryNode=(t,e)=>{if(t.children){for(const n of t.children){if(!0===e(n)){break}forEveryNode(n,e)}}if(t.cells){for(const n of t.cells){if(!0===e(n)){break}}}};const k=(t,e,...n)=>({type:t,props:e,children:n||[]});function b(t,e){if(!g.isGradient(t)){return null}const{stops:n,rotation:o}=g.parseColor(t),i=o*Math.PI/180,r=.5-.5*Math.sin(i),l=.5+.5*Math.cos(i),s=.5+.5*Math.sin(i),a=.5-.5*Math.cos(i),h=n.map(({offset:t,color:e})=>k("stop",{offset:100*t+"%","stop-color":e}));return k("linearGradient",{id:e,x1:100*r+"%",y1:100*l+"%",x2:100*s+"%",y2:100*a+"%"},...h)}export function fixRatio(t){var e=(new DOMParser).parseFromString(t,"image/svg+xml");return e.documentElement.setAttribute("preserveAspectRatio","none"),(new XMLSerializer).serializeToString(e)}const $=async t=>{try{const e=await fetch(t);if("undefined"!=typeof Buffer){const t=await e.arrayBuffer(),n=Buffer.from(t).toString("base64");return`data:${e.headers.get("content-type")||"image/png"};base64,${n}`}{const t=await e.blob();return new Promise((e,n)=>{const o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=n,o.readAsDataURL(t)})}}catch(e){return console.error("Error converting URL to data URL:",e),t}},v=async({element:t,page:e,store:n})=>{let{src:r}=t;if("svg"===t.type){const e=await i.urlToString(r);r=i.replaceColors(e,new Map(Object.entries(t.colorsReplace)))}else{r=await $(r)}let l,s,a,h,c="";if(t.flipX||t.flipY){const e=t.flipX?-1:1,n=t.flipY?-1:1,o=t.width/2,i=t.height/2;c=`translate(${o}, ${i}) scale(${e}, ${n}) translate(${-o}, ${-i})`}t.clipSrc&&(l=`clip-img-mask-${t.id}`,s=await $(t.clipSrc)),t.maskSrc&&(a=`mask-img-${t.id}`,h=await $(t.maskSrc));const d=await o(r),f=d.width*t.cropWidth,p=d.height*t.cropHeight,u=t.width/t.height;let m,y;const x=f/p,w="boolean"==typeof t.stretchEnabled&&t.stretchEnabled||"svg"===t.type;w?(m=f,y=p):u>=x?(m=f,y=f/u):(m=p*u,y=p);const v=m/d.width,S=y/d.height,O=m/y>t.width/t.height?t.height/y:t.width/m,j=w?t.width/m:O,H=w?t.height/y:O,z=m*j/v,W=y*H/S;let M=t.cropX*d.width*j,E=t.cropY*d.height*H;t.flipX&&(M=(1-t.cropX-t.cropWidth)*d.width*j),t.flipY&&(E=(1-t.cropY-t.cropHeight)*d.height*H);const F=`clip-${t.id}`,T=t.cornerRadius||0,L=r.replace(/&/g,"&amp;"),C={x:-M,y:-E,width:z,height:W,preserveAspectRatio:"none","clip-path":`url(#${F})`},A=[k("clipPath",{id:F},k("rect",{x:0,y:0,width:t.width,height:t.height,rx:T||void 0,ry:T||void 0}))];l&&s&&A.push(k("mask",{id:l,maskUnits:"userSpaceOnUse","mask-type":"alpha"},k("image",{href:s.replace(/&/g,"&amp;"),x:0,y:0,width:t.width,height:t.height,preserveAspectRatio:"none"}))),a&&A.push(k("mask",{id:a,maskUnits:"userSpaceOnUse","mask-type":"alpha"},k("image",Object.assign({href:L},C))));let B=L;const R={};a&&h&&(B=h.replace(/&/g,"&amp;"),R.mask=`url(#${a})`);const P={};l&&(P.mask=`url(#${l})`);const D=t.borderSize||0,N=D>0&&g.isGradient(t.borderColor),U=N?`border-grad-${t.id}`:null;if(N){const e=b(t.borderColor,U);e&&A.push(e)}const G=D>0?k("rect",{x:D/2,y:D/2,width:Math.max(0,t.width-D),height:Math.max(0,t.height-D),fill:"none",stroke:N?`url(#${U})`:t.borderColor,"stroke-width":D,rx:Math.max(0,T-D)||void 0,ry:Math.max(0,T-D)||void 0}):null,I=k("g",{},k("defs",{},...A),k("image",Object.assign(Object.assign({href:B},C),R)),G);return k("g",P,c?k("g",{transform:c},I):I)},S=({element:t,type:e})=>{const n={"stroke-width":t.height,stroke:t.color,"stroke-linecap":"round","stroke-linejoin":"round"},o=Object.assign(Object.assign({},n),{fill:t.color}),i=Object.assign(Object.assign({},n),{fill:"none"});return"arrow"===e?k("polyline",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},i)):"triangle"===e?k("polygon",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},o)):"bar"===e?k("polyline",Object.assign({points:`0,${2*-t.height} 0,${2*t.height}`},i)):"circle"===e?k("circle",Object.assign({cx:2*t.height,cy:0,r:2*t.height},o)):"square"===e?k("polygon",Object.assign({points:`0,${2*-t.height} ${4*t.height},${2*-t.height} ${4*t.height},${2*t.height} 0,${2*t.height}`},o)):null},O={image:v,svg:v,text:async({element:t,page:e,store:n})=>{const o=g.isGradient(t.fill),i=g.isGradient(t.stroke);if(t.curveEnabled){const e=p(t.text,{fontSize:t.fontSize,fontFamily:t.fontFamily}),n=h(e,{fontSize:t.fontSize,fontFamily:t.fontFamily}),r=Math.max(t.fontSize,...n.map(e=>{var n;return null!==(n=e.fontSize)&&void 0!==n?n:t.fontSize})),l=f(t.width,t.height,t.curvePower,r),s=z(t.id||"temp"),a=`curve-path-${s}`,d={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black",fontFamily:t.fontFamily,fontSize:t.fontSize},g=c(n,d),u=c(n,d,{omitColors:!0}),m=t.backgroundPadding*(t.fontSize*t.lineHeight*.5),y=t.backgroundEnabled?k("rect",{x:-m,y:-m,width:t.width+2*m,height:t.height+2*m,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5),ry:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)}):null,x=[k("path",{id:a,d:l,fill:"none"})],w=t.strokeWidth&&(i||o&&!i);if(o){const e=`curve-fill-grad-${s}`,n=b(t.fill,e);n&&x.push(n)}if(i&&t.strokeWidth){const e=`curve-stroke-grad-${s}`,n=b(t.stroke,e);n&&x.push(n)}if(w){const e={"font-size":t.fontSize+"px","text-anchor":"middle","dominant-baseline":"central","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration||void 0,"letter-spacing":t.letterSpacing*r},n=i?`url(#curve-stroke-grad-${s})`:t.stroke,l=k("text",Object.assign(Object.assign({},e),{fill:n,"stroke-width":t.strokeWidth,stroke:n}),k("textPath",{href:`#${a}`,startOffset:"50%",innerHTML:u})),h=o?`url(#curve-fill-grad-${s})`:t.fill,c=k("text",Object.assign(Object.assign({},e),{fill:h}),k("textPath",{href:`#${a}`,startOffset:"50%",innerHTML:g}));return k("g",{},y,k("defs",{},...x),l,c)}return k("g",{},y,k("defs",{},...x),k("text",{fill:o?`url(#curve-fill-grad-${s})`:t.fill,"font-size":t.fontSize+"px","text-anchor":"middle","dominant-baseline":"central","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration||void 0,"letter-spacing":t.letterSpacing*r,"stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?i?`url(#curve-stroke-grad-${s})`:t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0},k("textPath",{href:`#${a}`,startOffset:"50%",innerHTML:g})))}let r=null;const l=()=>(r||(r=document.createElement("canvas").getContext("2d")),r),s=(t,e,n,o,i,r=0)=>{const s=l();return s.font=`${i} ${o} ${e}px ${n}`,s.measureText(t).width+Math.max(0,(t?t.length:0)-1)*r*e},a=(e,n,o)=>{let i=n;null!=e.fontSize&&e.fontSize!==t.fontSize&&t.fontSize>0&&(i=e.fontSize*(n/t.fontSize));const r=e.fontFamily||t.fontFamily,l=e.bold?"bold":t.fontWeight||"normal",a=e.italic?"italic":t.fontStyle||"normal";return s(e.text,i,r,l,a,o)},u=/<[a-z][\s\S]*>/i.test(t.text);let $=t.text;!u&&$.includes("\n")&&($=$.split("\n").map(t=>`<p>${t}</p>`).join(""));const v=p($,{fontSize:t.fontSize,fontFamily:t.fontFamily}),S={fontSize:t.fontSize,fontFamily:t.fontFamily},O=[],j=(new DOMParser).parseFromString(v,"text/html"),H=j.body.querySelectorAll("p");H.length>0?H.forEach((t,e)=>{const n=t.innerHTML,o=h(n,S);O.push(...o),e<H.length-1&&O.push({text:"\n"})}):O.push(...h(v,S)),"uppercase"===t.textTransform&&O.forEach(t=>{"\n"!==t.text&&(t.text=t.text.toUpperCase())});const W=t=>{const e=[];let n=[];for(const o of t){if("\n"===o.text){n.length>0&&(e.push(n),n=[]),e.push([Object.assign(Object.assign({},o),{text:"\n"})]);continue}const t=o.text.split(/( )/);for(const i of t){""!==i&&(" "===i?(n.length>0&&(e.push(n),n=[]),e.push([Object.assign(Object.assign({},o),{text:" "})])):n.push(Object.assign(Object.assign({},o),{text:i})))}}return n.length>0&&e.push(n),e},M=(t,e,n,o)=>{const i=[[]];let r=0;for(const l of t){if(1===l.length&&"\n"===l[0].text){i.push([]),r=0;continue}const t=l.reduce((t,e)=>t+a(e,n,o),0);1!==l.length||" "!==l[0].text?(r+t>e+.5&&i[i.length-1].length>0&&(i.push([]),r=0),i[i.length-1].push(...l),r+=t):r+t<=e+.5&&(i[i.length-1].push(...l),r+=t)}return i},E=(t,e,n)=>t.reduce((t,o)=>t+a(o,e,n),0),F=(t,e)=>1===e?t:t.map(t=>t.map(t=>t.fontSize?Object.assign(Object.assign({},t),{fontSize:Math.round(t.fontSize*e*1e3)/1e3}):t));if(j.body.querySelector("ul, ol")){const e=[],n=2.1,r=e=>{const n=e.cloneNode(!0);n.querySelectorAll("ul, ol").forEach(t=>t.remove());const o=h(n.innerHTML,S);return"uppercase"===t.textTransform&&o.forEach(t=>{"\n"!==t.text&&(t.text=t.text.toUpperCase())}),o},a=(t,n)=>{for(const o of Array.from(t.children)){const t=o.tagName.toLowerCase();if("ul"===t||"ol"===t){const i="ol"===t;let l=parseInt(o.getAttribute("start")||"1",10)||1;for(const t of Array.from(o.children)){if("li"!==t.tagName.toLowerCase()){continue}const o=t.getAttribute("value");o&&!Number.isNaN(parseInt(o,10))&&(l=parseInt(o,10));const s=i?{text:`${l}.`,isOrdered:!0}:{text:"•",isOrdered:!1};e.push({segments:r(t),depth:n+1,marker:s}),i&&(l+=1),a(t,n+1)}}else{"p"===t||"div"===t?e.push({segments:r(o),depth:0,marker:null}):e.push({segments:h(o.outerHTML,S),depth:0,marker:null})}}};a(j.body,0);const f=o=>{const i=[],r=[];for(const l of e){const e=l.depth*n*o,s=Math.max(1,t.width-e);(0===l.segments.length?[[]]:M(W(l.segments),s,o,t.letterSpacing)).forEach((t,n)=>{i.push(t),r.push({indent:e,marker:0===n?l.marker:null})})}return{L:i,M:r}};let g=t.fontSize,p=[],u=[];for(;;){const e=f(g);p=e.L,u=e.M;const n=Math.max(0,...p.map((e,n)=>u[n].indent+E(e,g,t.letterSpacing))),o=p.length*g*t.lineHeight;if(n<=t.width&&(!t.height||o<=t.height)){break}if(g-=1,g<4){break}}p=F(p,g/t.fontSize);const w=g*t.lineHeight,$=p.length*w;let v=0;"middle"===t.verticalAlign?v=(t.height-$)/2:"bottom"===t.verticalAlign&&(v=t.height-$);const O=g+v,H={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black",fontFamily:t.fontFamily,fontSize:g},z=t=>{let e=t.length;for(;e>0&&""===t[e-1].text.trim();){e--}return t.slice(0,e)},T=l(),L=t.fontWeight||"normal",C=t.fontStyle||"normal";T.font=`${C} ${L} ${g}px ${t.fontFamily}`;const A=T.measureText(" ").width,B=u.map((e,n)=>{var o,i,r,l,a;if(!e.marker){return null}const h=O+n*w;let c;if(e.marker.isOrdered){const n=s(e.marker.text,g,t.fontFamily,L,C,t.letterSpacing);c=y(e.indent,h,{markerWidth:n,spaceWidth:A})}else{const t=T.measureText(e.marker.text);c=m(e.indent,h,{ascent:null!==(i=null!==(o=t.fontBoundingBoxAscent)&&void 0!==o?o:t.actualBoundingBoxAscent)&&void 0!==i?i:.8*g,inkRight:null!==(r=t.actualBoundingBoxRight)&&void 0!==r?r:0,inkAscent:null!==(l=t.actualBoundingBoxAscent)&&void 0!==l?l:0,inkDescent:null!==(a=t.actualBoundingBoxDescent)&&void 0!==a?a:0})}return k("tspan",{x:c.x,y:c.y,"letter-spacing":e.marker.isOrdered?t.letterSpacing*g+"px":void 0,innerHTML:d(e.marker.text)})}),R=t=>{const e=[];return p.forEach((n,o)=>{const i=z(n);i.length>0&&e.push(k("tspan",{x:u[o].indent,y:O+o*w,innerHTML:c(i,H,{omitColors:t})})),B[o]&&e.push(B[o])}),e};let P=null;if(t.backgroundEnabled){const e=t.backgroundPadding*(g*t.lineHeight*.5),n=t.backgroundCornerRadius*(g*t.lineHeight*.5);if(t.legacyBackground){P=k("rect",{x:-e,y:-e,width:t.width+2*e,height:t.height+2*e,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:n,ry:n})}else{const o=p.map((e,n)=>{const o=e.length?E(e,g,t.letterSpacing):0,i=n*w;return{left:u[n].indent,right:u[n].indent+o,top:i,bottom:i+w}}).filter(t=>t.right>t.left),i=x({rects:o,padding:e,cornerRadius:n});i&&(P=k("path",{d:i,fill:t.backgroundColor,opacity:t.backgroundOpacity,transform:v?`translate(0,${v})`:void 0}))}}const D=[];if(o){const e=b(t.fill,`text-fill-grad-${t.id}`);e&&D.push(e)}if(i&&t.strokeWidth){const e=b(t.stroke,`text-stroke-grad-${t.id}`);e&&D.push(e)}const N=t.strokeWidth&&(i||o&&!i),U={"font-size":g+"px","text-anchor":"start","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"letter-spacing":t.letterSpacing*g+"px"};if(N){const e=R(!0),n=i?`url(#text-stroke-grad-${t.id})`:t.stroke,r=k("text",Object.assign(Object.assign({},U),{fill:n,"stroke-width":t.strokeWidth,stroke:n}),...e.map(t=>k("tspan",t.props,t.props.innerHTML))),l=o?`url(#text-fill-grad-${t.id})`:t.fill,s=o?e:R(!1),a=k("text",Object.assign(Object.assign({},U),{fill:l}),...s.map(t=>k("tspan",t.props,t.props.innerHTML)));return k("g",{},P,D.length>0?k("defs",{},...D):null,r,a)}return k("g",{},P,D.length>0?k("defs",{},...D):null,k("text",Object.assign(Object.assign({},U),{fill:o?`url(#text-fill-grad-${t.id})`:t.fill,"stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0}),...R(!1)))}let T=t.fontSize;const L=W(O);let C=[];for(;;){C=M(L,t.width,T,t.letterSpacing);const e=Math.max(...C.map(e=>E(e,T,t.letterSpacing)),0),n=C.length*T*t.lineHeight;if(e<=t.width&&n<=t.height){break}if(T-=1,T<4){break}}C=F(C,T/t.fontSize);const A=T*t.lineHeight,B=C.length*A;let R=T;"middle"===t.verticalAlign?R=(t.height-B)/2+T:"bottom"===t.verticalAlign&&(R=t.height-B+T);const P="center"===t.align?"middle":"right"===t.align?"end":"start",D={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black",fontFamily:t.fontFamily,fontSize:T},N="center"===t.align?t.width/2:"right"===t.align?t.width:0,U=t=>{let e=t.length;for(;e>0&&""===t[e-1].text.trim();){e--}return t.slice(0,e)},G=C.map((t,e)=>{const n=U(t),o=0===n.length?"​":c(n,D);return k("tspan",{x:N,dy:0===e?0:A,innerHTML:o})}),I=t.backgroundPadding*(T*t.lineHeight*.5),X=t.backgroundCornerRadius*(T*t.lineHeight*.5);let Y=null;if(t.backgroundEnabled){if(t.legacyBackground){Y=k("rect",{x:-I,y:-I,width:t.width+2*I,height:t.height+2*I,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:X,ry:X})}else{const e=w({lines:C.map(e=>({width:0===e.length?0:E(e,T,t.letterSpacing)})),lineHeight:A,width:t.width,align:"justify"===t.align?"justify":t.align});let n=0;"middle"===t.verticalAlign?n=(t.height-C.length*A)/2:"bottom"===t.verticalAlign&&(n=t.height-C.length*A);const o=x({rects:e,padding:I,cornerRadius:X});o&&(Y=k("path",{d:o,fill:t.backgroundColor,opacity:t.backgroundOpacity,transform:n?`translate(0,${n})`:void 0}))}}const q=[],V=t.strokeWidth&&(i||o&&!i);if(o){const e=`text-fill-grad-${t.id}`,n=b(t.fill,e);n&&q.push(n)}if(i&&t.strokeWidth){const e=`text-stroke-grad-${t.id}`,n=b(t.stroke,e);n&&q.push(n)}if(V){const e=C.map((t,e)=>{const n=U(t),o=c(n,D,{omitColors:!0});return k("tspan",{x:N,dy:0===e?0:A,innerHTML:o})}),n={y:R,"font-size":T+"px","text-anchor":P,"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"letter-spacing":t.letterSpacing*T+"px"},r=i?`url(#text-stroke-grad-${t.id})`:t.stroke,l=k("text",Object.assign(Object.assign({},n),{fill:r,"stroke-width":t.strokeWidth,stroke:r}),...e.map(t=>k("tspan",t.props,t.props.innerHTML))),s=o?`url(#text-fill-grad-${t.id})`:t.fill,a=o?e:G,h=k("text",Object.assign(Object.assign({},n),{fill:s}),...a.map(t=>k("tspan",t.props,t.props.innerHTML)));return k("g",{},Y,q.length>0?k("defs",{},...q):null,l,h)}return k("g",{},Y,q.length>0?k("defs",{},...q):null,k("text",{fill:o?`url(#text-fill-grad-${t.id})`:t.fill,y:R,"font-size":T+"px","text-anchor":P,"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"letter-spacing":t.letterSpacing*T+"px","stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0},...G))},line:async({element:t,page:e,store:n})=>k("g",{},k("line",{x1:0,y1:t.height/2,x2:t.width,y2:t.height/2,stroke:t.color,"stroke-width":t.height,"stroke-dasharray":t.dash&&t.dash.length?t.dash.map(e=>e*t.height).join(" "):void 0}),k("g",{transform:`translate(0 ${t.height/2})`},S({element:t,type:t.startHead})),k("g",{transform:`translate(${t.width} ${t.height/2}) rotate(180)`},S({element:t,type:t.endHead}))),figure:async({element:t,page:e,store:n,elementHook:o})=>{let i=function(t){let e=t.replace(/<svg[^>]*>/,"");return e=e.replace(/<\/svg>/,""),e}(r(t));const l=[];if(t.strokeWidth&&g.isGradient(t.stroke)){const e=`figure-stroke-grad-${t.id}`,n=b(t.stroke,e);if(n){l.push(n);const o=t.stroke.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`stroke="${o}"`,"g"),`stroke="url(#${e})"`)}}if(g.isGradient(t.fill)){const e=`figure-fill-grad-${t.id}`,n=b(t.fill,e);if(n){l.push(n);const o=t.fill.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`fill="${o}"`,"g"),`fill="url(#${e})"`)}}if(l.length>0){const e=k("g",{},k("defs",{},...l),k("g",{innerHTML:i}));return o&&o({dom:e,element:t})||e}const s=k("g",{innerHTML:i});return o&&o({dom:s,element:t})||s},group:async({element:t,page:e,store:n,elementHook:o})=>{const i=await Promise.all(t.children.map(t=>j({element:t,page:e,store:n,elementHook:o}))),r=k("g",{style:{"transform-origin":"top left"}},...i);return o&&o({dom:r,element:t})||r},gif:v,table:async({element:t})=>{t.rows;const e=t.cols,n=t.colWidths,o=t.rowHeights,i=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],r=(t.cells||[]).map((n,o)=>{const r=Object.assign(Object.assign({},n),{row:Math.floor(o/e),col:o%e});for(const e of i){void 0===r[e]&&(r[e]=t[e])}return r}),l=[],s=(e,i,r,l)=>{let s=0;for(let o=0;o<i;o++){s+=n[o]*t.width}let a=0;for(let n=0;n<e;n++){a+=o[n]*t.height}let h=0;for(let o=i;o<i+l;o++){h+=(n[o]||0)*t.width}let c=0;for(let n=e;n<e+r;n++){c+=(o[n]||0)*t.height}return{x:s,y:a,width:h,height:c}};for(const a of r){if(!a.mergedInto&&a.cellBackground&&"transparent"!==a.cellBackground){s(a.row,a.col,a.colSpan||1,a.colSpan||1);const{x:t,y:e,width:n,height:o}=s(a.row,a.col,a.rowSpan||1,a.colSpan||1);l.push(k("rect",{x:t,y:e,width:n,height:o,fill:a.cellBackground}))}}const h=(t,e)=>"dashed"===t?`${4*e},${2*e}`:"dotted"===t?`${e},${e}`:void 0,c=(e,n)=>{var o,i,r,l,s;const a=null===(o=e.borders)||void 0===o?void 0:o[n];return{width:null!==(i=null==a?void 0:a.width)&&void 0!==i?i:t.borderWidth,style:null!==(l=null!==(r=null==a?void 0:a.style)&&void 0!==r?r:t.borderStyle)&&void 0!==l?l:"solid",color:null!==(s=null==a?void 0:a.color)&&void 0!==s?s:t.borderColor}};for(const a of r){if(a.mergedInto){continue}const t=s(a.row,a.col,a.rowSpan||1,a.colSpan||1);if(0===a.row){const e=c(a,"top");"none"!==e.style&&e.width>0&&l.push(k("line",{x1:t.x,y1:t.y+e.width/2,x2:t.x+t.width,y2:t.y+e.width/2,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}if(0===a.col){const e=c(a,"left");"none"!==e.style&&e.width>0&&l.push(k("line",{x1:t.x+e.width/2,y1:t.y,x2:t.x+e.width/2,y2:t.y+t.height,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}{const e=c(a,"bottom");"none"!==e.style&&e.width>0&&l.push(k("line",{x1:t.x,y1:t.y+t.height-e.width/2,x2:t.x+t.width,y2:t.y+t.height-e.width/2,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}{const e=c(a,"right");"none"!==e.style&&e.width>0&&l.push(k("line",{x1:t.x+t.width-e.width/2,y1:t.y,x2:t.x+t.width-e.width/2,y2:t.y+t.height,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}}for(const f of r){if(f.mergedInto){continue}let e=a(f.text||"");if(!e){continue}"uppercase"===f.textTransform&&(e=e.toUpperCase());const i=f.cellPadding||4;let r=0;for(let o=0;o<f.col;o++){r+=n[o]*t.width}let s=0;for(let n=0;n<f.row;n++){s+=o[n]*t.height}const h=n[f.col]*t.width,c=o[f.row]*t.height,g=f.fontSize||12,p=f.align||"left";let u=r+i,m="start";"center"===p?(u=r+h/2,m="middle"):"right"===p&&(u=r+h-i,m="end");let y=s+i+g;const x=f.verticalAlign||"top";"middle"===x?y=s+c/2+g/3:"bottom"===x&&(y=s+c-i),l.push(k("text",{x:u,y,"font-size":g,"font-family":f.fontFamily||"Roboto","font-weight":f.fontWeight||"normal","font-style":f.fontStyle||"normal",fill:f.fill||"black","text-anchor":m,"text-decoration":f.textDecoration||"none","letter-spacing":f.letterSpacing?f.letterSpacing*g+"px":void 0},d(e)))}return k("g",{},...l)}};async function j({element:t,page:e,store:n,elementHook:o}){var i;let r=await O[t.type];r||(r=()=>k("g",{}),console.error(`SVG export does not support ${t.type} type...`));const a=await r({element:t,page:e,store:n}),h=[],c=[];if(t.blurEnabled&&h.push(`blur(${t.blurRadius/2}px)`),t.brightnessEnabled&&h.push(`brightness(${100*t.brightness+100}%)`),t.sepiaEnabled&&h.push("sepia()"),t.grayscaleEnabled&&h.push("grayscale()"),t.shadowEnabled&&h.push(`drop-shadow(${t.shadowOffsetX}px ${t.shadowOffsetY}px ${t.shadowBlur}px ${t.shadowColor})`),t.filters){for(const[f,g]of Object.entries(t.filters)){const t=s(l[f],g.intensity);if(t&&(h.push(t.filter),t.html)){const e=t.html.replace(/<svg([^>]*)>/,"<g$1>").replace(/<\/svg>/,"</g>");c.push(e)}}}const d=k("g",{className:"element",id:t.id,transform:"group"!==t.type?`translate(${t.x}, ${t.y}) rotate(${t.rotation})`:void 0,display:null===(i=t.visible)||void 0===i||i?void 0:"none",opacity:t.opacity,style:{"transform-origin":"top left",filter:h.join(" ")}},a,...c);return o&&o({dom:d,element:t})||d}async function H(t){try{const e=await fetch(t),n=e.headers.get("content-type")||"font/ttf",o=await e.arrayBuffer();return`data:${n};base64,${"undefined"!=typeof Buffer?Buffer.from(o).toString("base64"):function(t){const e=new Uint8Array(t);let n="";for(let o=0;o<e.length;o+=32768){const t=e.subarray(o,o+32768);n+=String.fromCharCode(...t)}if("undefined"!=typeof btoa){return btoa(n)}if("undefined"!=typeof Buffer){return Buffer.from(e).toString("base64")}throw new Error("No base64 encoder available in this environment")}(o)}`}catch(e){return console.error("Error embedding font:",e),t}}export async function jsonToDOM({json:t,elementHook:i,fontEmbedding:r="inline"}){const l=[];forEveryNode({children:t.pages},t=>{if(("text"===t.type||"tablecell"===t.type||"table"===t.type)&&(t.fontFamily&&-1===l.indexOf(t.fontFamily)&&l.push(t.fontFamily),t.text)){for(const e of u(t.text)){-1===l.indexOf(e)&&l.push(e)}}});const s="inline"===r?await async function(t,e){return await Promise.all(t.map(async t=>{var n,o;if("Arial"===t){return null}const i=e.find(e=>e.fontFamily===t);if(i){const e=i.styles||(i.url?[{src:`url("${i.url}")`,fontStyle:"normal",fontWeight:"normal"}]:[]),n=await Promise.all(e.map(async e=>{var n,o;const r=(null===(o=null===(n=e.src)||void 0===n?void 0:n.match(/url\("?(.*?)"?\)/))||void 0===o?void 0:o[1])||i.url,l=await H(r);return`@font-face {\n font-family: '${t}';\n font-style: ${e.fontStyle||"normal"};\n font-weight: ${e.fontWeight||"normal"};\n src: url(${l});\n}`}));return k("style",{},n.join("\n"))}{const e=`https://fonts.googleapis.com/css?family=${encodeURIComponent(t)}:bi,normal,i,b`;try{const i=await fetch(e),r=await i.text(),l=null===(o=null===(n=r.match(/url\((.*?)\)/g))||void 0===n?void 0:n.map(t=>t.replace(/url\((.*?)\)/,"$1")))||void 0===o?void 0:o.filter(t=>t.startsWith("https"));if(!(null==l?void 0:l.length)){throw new Error("No font URLs found")}const s=await Promise.all(l.map(async e=>{const n=await H(e),o=(r.match(/@font-face\s*\{[^}]*?\}/g)||[]).find(t=>t.includes(e))||"",i=o.match(/font-style:\s*(.*?)[;\s}]/),l=o.match(/font-weight:\s*(.*?)[;\s}]/),s=i?i[1].trim():"normal",a=l?l[1].trim():"normal";return`@font-face {\n font-family: '${t}';\n font-style: ${s};\n font-weight: ${a};\n src: url(${n});\n}`}));return k("style",{},s.join("\n"))}catch(r){return console.error("Error embedding Google Font:",r),k("defs",{},k("style",{type:"text/css",innerHTML:`@import url('${e}');`.replace(/&/g,"&amp;")}))}}}))}(l,t.fonts):[],a=await Promise.all(t.pages.map(r=>async function({page:t,store:i,elementHook:r}){const l=[...t.children.filter(t=>!t.alwaysOnTop),...t.children.filter(t=>t.alwaysOnTop)],s=await Promise.all(l.map(e=>j({element:e,page:t,store:i,elementHook:r}))),a=t.background.indexOf("url")>=0||t.background.indexOf("http")>=0||t.background.indexOf(".jpg")>=0||t.background.indexOf(".png")>=0||t.background.indexOf(".jpeg")>=0;let h;if(a){const r=await o(t.background);h=await e(t.background,Object.assign({width:i.width,height:i.height,x:0,y:0},n({width:i.width,height:i.height},{width:r.width,height:r.height})))}return k("g",{className:"page",style:{}},a?k("image",{"xlink:href":h,x:0,y:0,width:i.width,height:i.height,preserveAspectRatio:"none"}):k("rect",{x:0,y:0,width:i.width,height:i.height,fill:a?void 0:t.background}),...s)}({page:r,store:t,elementHook:i})));return k("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",viewBox:`0 0 ${t.width} ${t.height}`,width:t.width,height:t.height},...s,...a)}function z(t){return String(t).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}const W=({dom:e,nestLevel:n=0})=>{if("string"==typeof e){return e}if(!e){return""}const o=e.props,{innerHTML:i}=o,r=t(o,["innerHTML"]),l=Object.keys(r).map(t=>((t,e)=>"object"==typeof e?`${t}="${Object.keys(e).map(t=>`${t}:${e[t]};`).join(" ")}"`:null==e||""===e?"":`${t}="${z(String(e))}"`)(t,r[t])).filter(t=>t&&t.trim().length>0).join(" "),s=" ".repeat(n);return`${s}<${e.type}${l?" "+l:""}>${i||"\n"+e.children.map(t=>W({dom:t,nestLevel:n+1})).join("")}${s}</${e.type}>\n`};export async function jsonToSVG({json:t,elementHook:e,fontEmbedding:n="inline"}){const o=await jsonToDOM({json:t,elementHook:e,fontEmbedding:n});return W({dom:o})}
@@ -1 +1 @@
1
- import*as e from"mobx";import{getAPI as o}from"./api.js";import{setRemoveBackgroundEnabled as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";export const setKey=e=>{s=e||""};let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const p=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let u=fetch;export const __=e=>{u=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await u(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"4.1.2"})});if(e.runInAction(()=>{a.value=r.headers.get("x-api-version")||""}),!n){return console.error("Polotno API is initialized without API key. It may lead to unexpected behavior and stop working. Please create API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1}),!1}if(200!==r.status){await new Promise(e=>setTimeout(e,3e3));continue}const s=await r.json();return s.is_valid||(console.error("Polotno API key is not valid. Please get new API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1})),s.is_paid||(console.log("%cPolotno Free Version. For development usage only. https://polotno.com/","background: rgb(0, 161, 255); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{0===i.value&&(i.value=2)})),s.is_domain_valid||console.log(p,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),t(s.remove_background_enabled),s.is_paid||!1}catch(r){await new Promise(e=>setTimeout(e,3e3))}}return console.error("Can not validate Polotno API key. Please report to anton@polotno.com immediately."),!0}export async function validateKey(e){await isKeyPaid(s)&&!e||r()}
1
+ import*as e from"mobx";import{getAPI as o}from"./api.js";import{setRemoveBackgroundEnabled as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";export const setKey=e=>{s=e||""};let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const p=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let u=fetch;export const __=e=>{u=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await u(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"4.2.0"})});if(e.runInAction(()=>{a.value=r.headers.get("x-api-version")||""}),!n){return console.error("Polotno API is initialized without API key. It may lead to unexpected behavior and stop working. Please create API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1}),!1}if(200!==r.status){await new Promise(e=>setTimeout(e,3e3));continue}const s=await r.json();return s.is_valid||(console.error("Polotno API key is not valid. Please get new API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1})),s.is_paid||(console.log("%cPolotno Free Version. For development usage only. https://polotno.com/","background: rgb(0, 161, 255); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{0===i.value&&(i.value=2)})),s.is_domain_valid||console.log(p,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),t(s.remove_background_enabled),s.is_paid||!1}catch(r){await new Promise(e=>setTimeout(e,3e3))}}return console.error("Can not validate Polotno API key. Please report to anton@polotno.com immediately."),!0}export async function validateKey(e){await isKeyPaid(s)&&!e||r()}