polotno 4.3.0 → 4.5.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.
- package/blueprint/toolbar/text-toolbar.js +2 -2
- package/blueprint.polotno.css +297 -297
- package/canvas/apply-filters.d.ts +1 -2
- package/canvas/apply-filters.js +1 -1
- package/canvas/figure-element.js +1 -1
- package/canvas/gif-element.js +1 -1
- package/canvas/hotkeys.js +1 -1
- package/canvas/html-element.js +1 -1
- package/canvas/image-element.js +1 -1
- package/canvas/line-element.js +1 -1
- package/canvas/page.js +1 -1
- package/canvas/quill-font-formats.js +1 -1
- package/canvas/render-tag-element.d.ts +2 -2
- package/canvas/render-tag-element.js +1 -1
- package/canvas/rich-editor.d.ts +17 -2
- package/canvas/rich-editor.js +28 -5
- package/canvas/text-element/fit-font-size.d.ts +3 -6
- package/canvas/text-element/fit-font-size.js +1 -1
- package/canvas/text-element.d.ts +2 -2
- package/canvas/text-element.js +1 -1
- package/canvas/tooltip.js +1 -1
- package/canvas/use-color.js +1 -1
- package/canvas/use-mediabunny-video.js +1 -1
- package/canvas/video-element.d.ts +1 -1
- package/canvas/video-element.js +1 -1
- package/model/group-model.d.ts +1 -2
- package/model/group-model.js +1 -1
- package/model/page-model.js +1 -1
- package/model/store.js +1 -1
- package/model/table-model.js +1 -1
- package/package.json +34 -48
- package/polotno.bundle.js +242 -225
- package/primitives/slider-field.d.ts +2 -1
- package/primitives/slider-field.js +1 -1
- package/primitives/slider.js +1 -1
- package/primitives/tabs.d.ts +1 -1
- package/side-panel/ai-images-panel.js +1 -1
- package/side-panel/draw-panel.js +1 -1
- package/side-panel/effect-card.d.ts +1 -1
- package/side-panel/effect-card.js +1 -1
- package/side-panel/effects-panel.js +1 -1
- package/side-panel/image-clip-panel.js +1 -1
- package/side-panel/layers-panel.js +1 -1
- package/side-panel/select-gif.js +1 -1
- package/side-panel/select-image.js +1 -1
- package/side-panel/select-svg.js +1 -1
- package/side-panel/select-video.js +1 -1
- package/toolbar/color-picker.js +1 -1
- package/toolbar/figure-toolbar.js +1 -1
- package/toolbar/html-toolbar.js +4 -4
- package/toolbar/image-toolbar.js +1 -1
- package/toolbar/svg-toolbar.js +1 -1
- package/toolbar/text-toolbar.js +1 -1
- package/toolbar/video-toolbar.js +1 -1
- package/ui.css +1 -1
- package/utils/background-shape.d.ts +1 -21
- package/utils/background-shape.js +1 -1
- package/utils/clipboard.js +1 -1
- package/utils/css-optimizer.js +1 -1
- package/utils/deprecation.d.ts +1 -0
- package/utils/deprecation.js +7 -0
- package/utils/errors.d.ts +3 -6
- package/utils/errors.js +1 -1
- package/utils/figure-to-svg.d.ts +1 -650
- package/utils/figure-to-svg.js +1 -1
- package/utils/filters.d.ts +1 -19
- package/utils/filters.js +1 -1
- package/utils/flags.d.ts +2 -1
- package/utils/fonts.d.ts +2 -3
- package/utils/fonts.js +1 -1
- package/utils/from-svg.js +1 -1
- package/utils/gradient.d.ts +1 -8
- package/utils/gradient.js +1 -1
- package/utils/html-to-svg/font-inliner.js +1 -1
- package/utils/html-to-svg/index.js +1 -1
- package/utils/html-to-svg/render-cache.js +1 -1
- package/utils/html-to-svg/xhtml.js +1 -1
- package/utils/html.js +1 -1
- package/utils/html2canvas.d.ts +1 -10
- package/utils/html2canvas.js +1 -1
- package/utils/image.d.ts +1 -14
- package/utils/image.js +1 -1
- package/utils/list-marker-geometry.d.ts +1 -14
- package/utils/list-marker-geometry.js +1 -1
- package/utils/loader.d.ts +1 -1
- package/utils/loader.js +1 -1
- package/utils/luma.js +1 -1
- package/utils/math.d.ts +6 -0
- package/utils/math.js +1 -1
- package/utils/measure-text.js +1 -1
- package/utils/path-to-svg.js +1 -1
- package/utils/px.d.ts +54 -0
- package/utils/px.js +1 -0
- package/utils/reset-style.d.ts +1 -2
- package/utils/reset-style.js +1 -1
- package/utils/rich-text-html.d.ts +4 -16
- package/utils/rich-text-html.js +1 -1
- package/utils/svg.d.ts +2 -12
- package/utils/svg.js +2 -1
- package/utils/text-format-state.d.ts +4 -4
- package/utils/text-format-state.js +1 -1
- package/utils/text-format.d.ts +11 -2
- package/utils/text-format.js +1 -1
- package/utils/text-html.d.ts +3 -35
- package/utils/text-html.js +1 -1
- package/utils/text-types.d.ts +1 -48
- package/utils/text-types.js +1 -1
- package/utils/text.d.ts +1 -16
- package/utils/text.js +1 -1
- package/utils/to-html.d.ts +6 -17
- package/utils/to-html.js +1 -1
- package/utils/to-pptx.js +1 -1
- package/utils/to-svg.d.ts +6 -17
- package/utils/to-svg.js +1 -1
- package/utils/use-svg-colors.d.ts +1 -0
- package/utils/use-svg-colors.js +1 -0
- package/utils/validate-key.js +1 -1
- package/utils/video.d.ts +1 -7
- package/utils/video.js +1 -1
- package/utils/xml.d.ts +1 -1
- package/utils/xml.js +1 -7
- /package/utils/{html-to-svg/lru-cache.d.ts → lru-cache.d.ts} +0 -0
- /package/utils/{html-to-svg/lru-cache.js → lru-cache.js} +0 -0
|
@@ -1,19 +1,10 @@
|
|
|
1
|
-
export
|
|
2
|
-
export declare
|
|
3
|
-
export declare function
|
|
4
|
-
export declare function parsePrimaryFontFamily(css: string): string | null;
|
|
5
|
-
export declare function parseFontSizeToPx(css: string | undefined, baseFontPx: number): number | undefined;
|
|
6
|
-
export declare function toNumericWeight(value: string | number | null | undefined): number;
|
|
7
|
-
export declare function isBoldWeight(value: string | number | null | undefined): boolean;
|
|
8
|
-
export declare function parseHtmlRoot(html: string): HTMLElement | null;
|
|
9
|
-
export interface RichTextDefaults {
|
|
1
|
+
export * from '@polotno/core/rich-text-html';
|
|
2
|
+
export declare function htmlInflatesMinContentWidth(html: string): boolean;
|
|
3
|
+
export declare function quillHtmlToModelText(html: string, defaults: {
|
|
10
4
|
fontSize: number;
|
|
11
5
|
fontFamily: string;
|
|
12
|
-
}
|
|
13
|
-
export declare function cleanupInlineWrappers(root: HTMLElement): void;
|
|
14
|
-
export declare function normalizeRichTextHtml(html: string, defaults: RichTextDefaults): string;
|
|
6
|
+
}): string;
|
|
15
7
|
export declare function shrinkParagraphStrutForRaster(html: string): string;
|
|
16
|
-
export declare function extractFontFamiliesFromHtml(html: string): string[];
|
|
17
8
|
export interface FontSpec {
|
|
18
9
|
family: string;
|
|
19
10
|
weight: string;
|
|
@@ -24,7 +15,6 @@ export declare function extractFontSpecsFromHtml(html: string, defaults: {
|
|
|
24
15
|
fontWeight: string | number;
|
|
25
16
|
fontStyle: string;
|
|
26
17
|
}): FontSpec[];
|
|
27
|
-
export declare function scaleRichTextFontSizesInHtml(html: string, factor: number): string;
|
|
28
18
|
export declare function stripInlineFormat(html: string, format: string): string;
|
|
29
19
|
interface QuillDeltaLike {
|
|
30
20
|
ops: Array<{
|
|
@@ -36,6 +26,4 @@ export declare function isQuillFormatMixed(delta: QuillDeltaLike, key: string):
|
|
|
36
26
|
export declare function stripInlineFontSizes(html: string): string;
|
|
37
27
|
export declare function stripInlineFontFamilies(html: string): string;
|
|
38
28
|
export declare function hasMultipleDistinctInlineFontSizes(html: string): boolean;
|
|
39
|
-
export declare function hasAnyInlineFontSize(html: string): boolean;
|
|
40
29
|
export declare function listEffectiveFontFamilies(html: string, baseFamily: string): string[];
|
|
41
|
-
export {};
|
package/utils/rich-text-html.js
CHANGED
|
@@ -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(/"/g,'"').replace(/&/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}
|
|
1
|
+
export*from"@polotno/core/rich-text-html";import{parseHtmlRoot as t,cleanupInlineWrappers as e,parsePrimaryFontFamily as r,toNumericWeight as o,extractFontFamiliesFromHtml as n,QUILL_FONT_CLASS_TO_FAMILY as i,guessFontFamilyFromQlClass as l,normalizeRichTextHtml as s}from"@polotno/core/rich-text-html";import{LRUCache as c}from"./lru-cache.js";const f=new c(500);export function htmlInflatesMinContentWidth(e){if(!e||!e.includes("<")){return!1}let r=f.get(e);if(void 0===r){r=!1;const o=t(e);if(o){if(o.querySelector("ol, ul")){r=!0}else{for(const t of o.querySelectorAll("[style]")){if(t.style.fontSize||t.style.letterSpacing){r=!0;break}}}}f.set(e,r)}return r}export function quillHtmlToModelText(t,e){return s(function(t){const e=(t||"").trim();if("<p><br></p>"===e||"<p></p>"===e){return""}if(e.startsWith("<p>")&&e.endsWith("</p>")){const t=e.slice(3,-4);if(!/(<\/?(p|div|h[1-6]|ul|ol|li|table|thead|tbody|tr|td|blockquote)\b)/i.test(t)){return t}}return t}(t),e)}export function shrinkParagraphStrutForRaster(e){var r;if(!e||!e.includes("<p")){return e}const o=t(e);if(!o){return e}for(const t of Array.from(o.querySelectorAll("p"))){let e=!1;const n=[],i=o.ownerDocument.createTreeWalker(t,NodeFilter.SHOW_TEXT);let l=i.nextNode();for(;l;){if((l.textContent||"").length>0){let o=l.parentElement,i=null;for(;o&&o!==t;){const t=null===(r=o.style)||void 0===r?void 0:r.fontSize;if(t){const e=parseFloat(t);if(!Number.isNaN(e)){i=e;break}}o=o.parentElement}if(null==i){e=!0;break}n.push(i)}l=i.nextNode()}!e&&n.length>0&&(t.style.fontSize=`${Math.min(...n)}px`)}return o.innerHTML}export function extractFontSpecsFromHtml(e,n){const s=r(n.fontFamily)||n.fontFamily,c=String(o(n.fontWeight)),f="italic"===n.fontStyle?"italic":"normal",u=new Map,a=(t,e,o)=>{const n=r(t)||t||s,i=`${n}\0${e}\0${o}`;u.has(i)||u.set(i,{family:n,weight:e,style:o})};if(a(s,c,f),e&&e.includes("<")){const r=t(e);if(r){const t=r.ownerDocument.createTreeWalker(r,NodeFilter.SHOW_TEXT);let e=t.nextNode();for(;e;){if((e.textContent||"").trim().length>0){let t="",n="",u="",y=e.parentElement;for(;y&&y!==r;){if(!t){if(y.style.fontFamily){t=y.style.fontFamily}else{const e=(y.getAttribute("class")||"").split(/\s+/).find(t=>t.startsWith("ql-font-"));e&&(t=i[e]||l(e))}}n||(y.style.fontWeight?n=String(o(y.style.fontWeight)):"STRONG"!==y.tagName&&"B"!==y.tagName||(n="700")),u||(y.style.fontStyle?u=y.style.fontStyle:"EM"!==y.tagName&&"I"!==y.tagName||(u="italic")),y=y.parentElement}a(t||s,n||c,u||f)}e=t.nextNode()}}}return[...u.values()]}const u={bold:["STRONG","B"],italic:["EM","I"],underline:["U"],strike:["S","DEL"]},a={bold:t=>t.style.removeProperty("font-weight"),italic:t=>t.style.removeProperty("font-style"),color:t=>{!function(t){if("text"===(t.style.getPropertyValue("-webkit-background-clip")||t.style.getPropertyValue("background-clip"))&&t.style.backgroundImage.includes("gradient")){for(const e of["background-image","background-size","-webkit-background-clip","background-clip","-webkit-text-fill-color"]){t.style.removeProperty(e)}}}(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(r,o){var n,i;if(!r||!r.includes("<")){return r}const l=t(r);if(!l){return r}const s=u[o]||[],c=a[o];for(const t of s){let e;for(;e=l.querySelector(t);){const t=e.parentNode;c&&c(e);const r=null===(n=e.getAttribute("style"))||void 0===n?void 0:n.trim();if(r){const o=l.ownerDocument.createElement("span");for(o.setAttribute("style",r);e.firstChild;){o.appendChild(e.firstChild)}t.insertBefore(o,e)}else{for(;e.firstChild;){t.insertBefore(e.firstChild,e)}}t.removeChild(e)}}if(c){for(const t of Array.from(l.querySelectorAll("[style]"))){c(t),(null===(i=t.getAttribute("style"))||void 0===i?void 0:i.trim())||t.removeAttribute("style")}}return e(l),l.innerHTML}const y=Symbol("unset");export function isQuillFormatMixed(t,e){var r;let o=y;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===y){o=t}else if(t!==o){return!0}}return!1}export function stripInlineFontSizes(r){var o;if(!r||!r.includes("font-size")){return r}const n=t(r);if(!n){return r}const i=n.querySelectorAll("[style]");for(let t=0;t<i.length;t++){const e=i[t];e.style.fontSize&&(e.style.removeProperty("font-size"),(null===(o=e.getAttribute("style"))||void 0===o?void 0:o.trim())||e.removeAttribute("style"))}return e(n),n.innerHTML}export function stripInlineFontFamilies(r){var o;if(!r||!r.includes("font-family")&&!r.includes("ql-font-")){return r}const n=t(r);if(!n){return r}for(const t of Array.from(n.querySelectorAll("[style]"))){t.style.fontFamily&&(t.style.removeProperty("font-family"),(null===(o=t.getAttribute("style"))||void 0===o?void 0:o.trim())||t.removeAttribute("style"))}for(const t of Array.from(n.querySelectorAll("[class]"))){const e=t.getAttribute("class")||"",r=e.split(/\s+/).filter(t=>t&&!t.startsWith("ql-font-"));r.length!==e.split(/\s+/).filter(Boolean).length&&(r.length?t.setAttribute("class",r.join(" ")):t.removeAttribute("class"))}return e(n),n.innerHTML}export function hasMultipleDistinctInlineFontSizes(e){if(!e||!e.includes("<")){return!1}const r=t(e);if(!r){return!1}const o=new Set;for(const t of r.querySelectorAll("[style]")){const e=t.style.fontSize;if(e){const t=e.match(/^(\d+(?:\.\d+)?)px$/i);if(t&&(o.add(parseFloat(t[1])),o.size>1)){return!0}}}return!1}export function listEffectiveFontFamilies(t,e){const o=[],i=e?r(e)||e:"";i&&o.push(i);for(const c of n(t||"")){const t=r(c)||c;t&&o.push(t)}const l=new Set,s=[];for(const r of o){l.has(r)||(l.add(r),s.push(r))}return s.sort((t,e)=>t.localeCompare(e,void 0,{sensitivity:"base"})),s}
|
package/utils/svg.d.ts
CHANGED
|
@@ -1,12 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
3
|
-
export declare function getColors(svgString: any): string[];
|
|
4
|
-
export declare function svgToURL(s: any): string;
|
|
5
|
-
export declare function getSvgSize(url: string): Promise<{
|
|
6
|
-
width: number;
|
|
7
|
-
height: number;
|
|
8
|
-
}>;
|
|
9
|
-
export declare function fixSize(svgString: string): string;
|
|
10
|
-
export declare const sameColors: (color1: any, color2: any) => boolean | undefined;
|
|
11
|
-
export declare function replaceColors(svgString: string, replaceMap: Map<string, string>): string;
|
|
12
|
-
export declare const useSvgColors: (src: string) => string[];
|
|
1
|
+
export * from '@polotno/core/svg';
|
|
2
|
+
export { useSvgColors } from './use-svg-colors.js';
|
package/utils/svg.js
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export * from '@polotno/core/svg';
|
|
2
|
+
export { useSvgColors } from './use-svg-colors.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { TextFormat, TextFormatAttrs } from './text-format.js';
|
|
1
|
+
import { TextFormat, TextFormatAttrs, ApplyTextFormatOptions } from './text-format.js';
|
|
2
2
|
type QuillFormat = Record<string, any>;
|
|
3
3
|
type QuillMixed = Record<string, boolean>;
|
|
4
4
|
export interface ActiveTextEditor {
|
|
@@ -33,10 +33,10 @@ export interface TextDefaults {
|
|
|
33
33
|
}
|
|
34
34
|
export declare const ALL_QUILL_MIXED_KEYS: string[];
|
|
35
35
|
export declare function quillToTextFormat(fmt: QuillFormat, mixed: QuillMixed, defaults: TextDefaults): TextFormat;
|
|
36
|
-
export declare function attrsToQuillOps(attrs: TextFormatAttrs): Array<[string, any]>;
|
|
36
|
+
export declare function attrsToQuillOps(attrs: TextFormatAttrs, opts?: ApplyTextFormatOptions): Array<[string, any]>;
|
|
37
37
|
export type TextFormatState = {
|
|
38
38
|
format: TextFormat;
|
|
39
|
-
applyTextFormat: (attrs: TextFormatAttrs) => void;
|
|
39
|
+
applyTextFormat: (attrs: TextFormatAttrs, opts?: ApplyTextFormatOptions) => void;
|
|
40
40
|
enabled: boolean;
|
|
41
41
|
};
|
|
42
42
|
export declare function resolveSelectionScope(quill: any, fallbackSelection: {
|
|
@@ -53,7 +53,7 @@ export declare function resolveSelectionScope(quill: any, fallbackSelection: {
|
|
|
53
53
|
export declare function applyToLiveEditor(quill: any, attrs: TextFormatAttrs, fallbackSelection?: {
|
|
54
54
|
index: number;
|
|
55
55
|
length: number;
|
|
56
|
-
} | null): void;
|
|
56
|
+
} | null, opts?: ApplyTextFormatOptions): void;
|
|
57
57
|
export declare function getTextFormatState(store: any): TextFormatState;
|
|
58
58
|
export declare function observeTextFormatState(store: any, cb: (state: TextFormatState) => void): () => void;
|
|
59
59
|
export declare function useTextFormat(store: any): TextFormatState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as t from"react";import*as e from"mobx";import{parsePrimaryFontFamily as o,parseFontSizeToPx as n,toNumericWeight as i}from"
|
|
1
|
+
import*as t from"react";import*as e from"mobx";import{parsePrimaryFontFamily as o,parseFontSizeToPx as n,toNumericWeight as i}from"@polotno/core/rich-text-html";import{isGradient as r}from"@polotno/core/gradient";import{getTextFormat as l,applyTextFormat as c,FORMAT_KEYS as a,DECORATION_TOKENS as s,decorationTokensOf as f,decorationTokensToString as u,decorationToQuillKey as d}from"./text-format.js";const m=e.observable({active:null},{},{deep:!1});export function getActiveTextEditor(){return m.active}export function setActiveTextEditor(t){e.runInAction(()=>{m.active=Object.assign(Object.assign({},t),{currentFormat:{},mixedFormats:{},lastSelection:null})})}export function updateActiveTextFormat(t,o,n){e.runInAction(()=>{m.active&&(m.active=Object.assign(Object.assign({},m.active),{currentFormat:t,mixedFormats:o,lastSelection:n||m.active.lastSelection}))})}export function clearActiveTextEditor(t){e.runInAction(()=>{var e;t&&(null===(e=m.active)||void 0===e?void 0:e.instance)!==t||(m.active=null)})}const p={fontSize:["size"],fontFamily:["font"],fill:["color","gradient"],fontWeight:["font-weight"],fontStyle:["italic"],textDecoration:["underline","strike"]};export const ALL_QUILL_MIXED_KEYS=Array.from(new Set(a.flatMap(t=>p[t])));function x(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 e.gradient||(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":return u(f(r.textDecoration))}}function v(t,e,o){const n=f(o.textDecoration),i=(o,i)=>n.has(o)?"on":e[i]?"mixed":t[i]?"on":"off",r=function(t,e){const o=t=>"on"===t?[!0]:"off"===t?[!1]:[!0,!1],n=[];for(const i of o(t)){for(const t of o(e)){const e=new Set;i&&e.add("underline"),t&&e.add("line-through"),n.push(u(e))}}return n}(i("underline","underline"),i("line-through","strike"));return{value:1===r.length?r[0]:void 0,mixed:r.length>1,values:r}}export function quillToTextFormat(t,e,o){const n={};for(const i of a){if("textDecoration"!==i){if(p[i].some(t=>!0===e[t])){n[i]={value:void 0,mixed:!0,values:[]}}else{const e=x(i,t,o);n[i]={value:e,mixed:!1,values:[e]}}}else{n.textDecoration=v(t,e,o)}}return n}export function attrsToQuillOps(t,e){var o;const n=[];if(void 0!==t.fontFamily&&n.push(["font",t.fontFamily]),void 0!==t.fontSize&&n.push(["size",`${t.fontSize}px`]),void 0!==t.fill&&(r(String(t.fill))?n.push(["color",!1],["gradient",t.fill]):n.push(["gradient",!1],["color",t.fill])),void 0!==t.fontWeight&&n.push(["font-weight",String(i(t.fontWeight))]),void 0!==t.fontStyle&&n.push(["italic","italic"===t.fontStyle]),void 0!==t.textDecoration){const i=null!==(o=null==e?void 0:e.decorationTokens)&&void 0!==o?o:s,r=f(t.textDecoration);for(const t of s){i.includes(t)&&n.push([d(t),r.has(t)])}}return n}function g(t){return((null==t?void 0:t.selectedElements)||[]).filter(t=>"text"===t.type)}function h(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,n){const i=attrsToQuillOps(e,n);if(!i.length){return}const{scope:r,sel:l}=resolveSelectionScope(t,null!=o?o:null);for(const[c,a]of i){"collapsed"===r?t.format(c,a,"user"):t.formatText(l.index,l.length,c,a,"user")}}function S(t,e){const o="function"==typeof t.getLength?t.getLength():0;t.formatText(0,o,e,!0,"api")}export function getTextFormatState(t){const e=h(t),o=g(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}):l(o),enabled:n,applyTextFormat:(e,o)=>function(t,e,o){const n=h(t);if(!n){return void c(g(t),e,o)}const{scope:i,sel:r,isEmpty:l}=resolveSelectionScope(n.instance,n.lastSelection);"full"===i||"collapsed"===i&&!l?c([n.element],e,o):function(t,e,o,n){var i,r;const l=t.instance,c=t.element;let a=!1;if(n.length>0){if(void 0!==e.fontStyle&&"italic"!==e.fontStyle&&"italic"===c.fontStyle&&(S(l,"italic"),c.set({fontStyle:"normal"}),a=!0),void 0!==e.textDecoration){const t=null!==(i=null==o?void 0:o.decorationTokens)&&void 0!==i?i:s,n=f(e.textDecoration),r=f(c.textDecoration),m=t.filter(t=>!n.has(t)&&r.has(t));for(const e of m){S(l,d(e)),r.delete(e)}m.length&&(c.set({textDecoration:u(r)}),a=!0)}a&&"function"==typeof(null===(r=l.history)||void 0===r?void 0:r.clear)&&l.history.clear()}applyToLiveEditor(l,e,n,o)}(n,e,o,r)}(t,e,o)}}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}
|
package/utils/text-format.d.ts
CHANGED
|
@@ -21,6 +21,15 @@ export type TextFormatAttrs = Partial<{
|
|
|
21
21
|
fontStyle: string;
|
|
22
22
|
textDecoration: string;
|
|
23
23
|
}>;
|
|
24
|
+
export type DecorationToken = 'underline' | 'line-through';
|
|
25
|
+
export declare const DECORATION_TOKENS: DecorationToken[];
|
|
26
|
+
export type ApplyTextFormatOptions = {
|
|
27
|
+
decorationTokens?: DecorationToken[];
|
|
28
|
+
};
|
|
29
|
+
export declare function decorationTokensOf(value: string | undefined): Set<DecorationToken>;
|
|
30
|
+
export declare function decorationTokensToString(tokens: Set<DecorationToken>): string;
|
|
31
|
+
export declare function isDecorationActive(f: TextFormat, token: DecorationToken): boolean;
|
|
32
|
+
export declare const decorationToQuillKey: (t: DecorationToken) => "underline" | "strike";
|
|
24
33
|
export interface TextFormatElement {
|
|
25
34
|
type?: string;
|
|
26
35
|
text: string;
|
|
@@ -39,8 +48,8 @@ export interface TextFormatElement {
|
|
|
39
48
|
}
|
|
40
49
|
type Target = TextFormatElement | TextFormatElement[];
|
|
41
50
|
export declare function getTextFormat(target: Target): TextFormat;
|
|
42
|
-
export declare function patchTextFormat(element: TextFormatElement, attrs: TextFormatAttrs): {
|
|
51
|
+
export declare function patchTextFormat(element: TextFormatElement, attrs: TextFormatAttrs, opts?: ApplyTextFormatOptions): {
|
|
43
52
|
attrsToSet: Record<string, any>;
|
|
44
53
|
};
|
|
45
|
-
export declare function applyTextFormat(target: Target, attrs: TextFormatAttrs): void;
|
|
54
|
+
export declare function applyTextFormat(target: Target, attrs: TextFormatAttrs, opts?: ApplyTextFormatOptions): void;
|
|
46
55
|
export {};
|
package/utils/text-format.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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
|
|
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"];export const DECORATION_TOKENS=["underline","line-through"];export function decorationTokensOf(t){const e=new Set;for(const o of(t||"").split(/\s+/)){"underline"!==o&&"line-through"!==o||e.add(o)}return e}export function decorationTokensToString(t){return DECORATION_TOKENS.filter(e=>t.has(e)).join(" ")}export function isDecorationActive(t,e){const o=t.textDecoration.values;return o.length>0&&o.every(t=>decorationTokensOf(t).has(e))}export const decorationToQuillKey=t=>"underline"===t?"underline":"strike";function l(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"text"===(o.style.getPropertyValue("-webkit-background-clip")||o.style.getPropertyValue("background-clip"))&&o.style.backgroundImage.includes("gradient")?o.style.backgroundImage: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 f(t,e){return"fontWeight"===e?s(t.fontWeight):t[e]}function u(t,e,o){const n={},r=new Set,i=decorationTokensOf(o.textDecoration);let s=t.parentElement;for(;s&&s!==e;){for(const t of FORMAT_KEYS){if("textDecoration"===t){const t=l(s,"textDecoration",o);if("string"==typeof t){for(const e of decorationTokensOf(t)){i.add(e)}}continue}if(r.has(t)){continue}const e=l(s,t,o);void 0!==e&&(n[t]=e,r.add(t))}s=s.parentElement}for(const c of FORMAT_KEYS){"textDecoration"===c||r.has(c)||(n[c]=f(o,c))}return n.textDecoration=decorationTokensToString(i),n}function d(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 g(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]=f(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?f(t,o):void 0;n[o]=d(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]=d(n,void 0)}return e}(t.map(g)):g(t)}function h(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 x=!1;function y(t){return"string"!=typeof t||/^\d+$/.test(t.trim())||x||(x=!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,o){var n;const r=FORMAT_KEYS.filter(t=>void 0!==e[t]);if(0===r.length){return{attrsToSet:{}}}const s=null!==(n=null==o?void 0:o.decorationTokens)&&void 0!==n?n:DECORATION_TOKENS,c={};let a=t.text||"";for(const l of r){if("textDecoration"===l){const o=decorationTokensOf(e.textDecoration),n=decorationTokensOf(t.textDecoration);for(const t of s){o.has(t)?n.add(t):n.delete(t),a=i(a,decorationToQuillKey(t))}c.textDecoration=decorationTokensToString(n);continue}c[l]="fontWeight"===l?String(y(e.fontWeight)):e[l],a=h(a,l)}return a!==(t.text||"")&&(c.text=a),{attrsToSet:c}}export function applyTextFormat(t,e,o){var n;const r=Array.isArray(t)?t:[t];if(0===r.length){return}const i=t=>{const{attrsToSet:n}=patchTextFormat(t,e,o);Object.keys(n).length&&t.set(n)};if(1===r.length){return void i(r[0])}const s=new Map;for(const c of r){const t=c.store,e=s.get(t)||[];e.push(c),s.set(t,e)}for(const[c,a]of s){(null===(n=null==c?void 0:c.history)||void 0===n?void 0:n.transaction)?c.history.transaction(()=>a.forEach(i)):a.forEach(i)}}
|
package/utils/text-html.d.ts
CHANGED
|
@@ -1,35 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
import {
|
|
3
|
-
export declare
|
|
4
|
-
export declare function normalizeStrokeLineJoin(join?: string): 'round' | 'miter' | 'bevel';
|
|
5
|
-
export declare function getCurvePath(width: number, height: number, power: number, absLineHeight: number): string;
|
|
6
|
-
export declare function createSVGGradientDef(gradientColor: string, id: string, width?: number, height?: number): string;
|
|
7
|
-
export declare function getCurveTextDimensions(element: TextElementLike, precomputed?: {
|
|
8
|
-
normalizedText: string;
|
|
9
|
-
segments: StyledSegment[];
|
|
10
|
-
}): {
|
|
11
|
-
width: number;
|
|
12
|
-
height: number;
|
|
13
|
-
};
|
|
14
|
-
export declare function getCurveTextHeight(element: TextElementLike): number;
|
|
15
|
-
export declare function segmentsToTspans(segments: StyledSegment[], defaults: {
|
|
16
|
-
fontWeight: string;
|
|
17
|
-
fontStyle: string;
|
|
18
|
-
fill: string;
|
|
19
|
-
fontFamily: string;
|
|
20
|
-
fontSize: number;
|
|
21
|
-
}, options?: {
|
|
22
|
-
omitColors?: boolean;
|
|
23
|
-
}): string;
|
|
24
|
-
export interface GetHtmlOptions {
|
|
25
|
-
fontFamily?: string;
|
|
26
|
-
color?: string;
|
|
27
|
-
forEditor?: boolean;
|
|
28
|
-
}
|
|
29
|
-
export declare function getQuillEditorHtml(element: TextElementLike, fontFamilyOverride?: string): string;
|
|
30
|
-
export declare function getHtml(element: TextElementLike, { fontFamily, color, forEditor }?: GetHtmlOptions): string;
|
|
31
|
-
export declare function resolveLineHeight({ fontFamily, fontSize, lineHeight, }: {
|
|
32
|
-
fontFamily: string;
|
|
33
|
-
fontSize: number;
|
|
34
|
-
lineHeight: number | string;
|
|
35
|
-
}): number;
|
|
1
|
+
export * from '@polotno/core/text-html';
|
|
2
|
+
import { getHtml as baseGetHtml, type GetHtmlOptions } from '@polotno/core/text-html';
|
|
3
|
+
export declare const getHtml: (element: Parameters<typeof baseGetHtml>[0], options?: GetHtmlOptions) => string;
|
package/utils/text-html.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"konva";import*as e from"./gradient.js";import{removeTags as n,sanitizeHtml as o,parseHtmlToSegments as i}from"./text.js";import{flags as r}from"./flags.js";import{xmlEscape as l}from"./xml.js";import{applyTextDefaults as a}from"./text-types.js";import{normalizeRichTextHtml as s}from"./rich-text-html.js";function f(t){var e="֑-߿יִ-﷽ﹰ-ﻼ";return new RegExp("^[^"+e+"]*?["+e+"]").test(t)}export function getDir(t){return function(t){t=t.replace(/\s/g,"");let e=0;for(var n=0;n<t.length;n++){f(t[n])&&(e+=1)}return e>t.length/2}(t)?"rtl":"ltr"}export function normalizeStrokeLineJoin(t){return"miter"===t||"bevel"===t?t:"round"}export function getCurvePath(t,e,n,o){const i=Math.max(-.9999,Math.min(.9999,n));if(Math.abs(i)<1e-4){return`M 0 ${e/2} L ${t} ${e/2}`}const r=5*o/(2*Math.abs(i))-o,l=t/2;if(i>0){const t=2*r+o/2;return[`M ${l} ${t}`,`A ${r} ${r} 0 1 1 ${l} ${t-2*r}`,`A ${r} ${r} 0 1 1 ${l} ${t}`].join(" ")}{const t=-(2*r-Math.round(e))-o/2;return[`M ${l} ${t}`,`A ${r} ${r} 0 1 0 ${l} ${t+2*r}`,`A ${r} ${r} 0 1 0 ${l} ${t}`].join(" ")}}export function createSVGGradientDef(t,n,o,i){if(!e.isGradient(t)){return""}const{stops:r,rotation:l}=e.parseColor(t),a=l*Math.PI/180;return`<linearGradient id="${n}" x1="${100*(.5-.5*Math.sin(a))}%" y1="${100*(.5+.5*Math.cos(a))}%" x2="${100*(.5+.5*Math.sin(a))}%" y2="${100*(.5-.5*Math.cos(a))}%">${r.map(({offset:t,color:e})=>`<stop offset="${100*t}%" stop-color="${e}" />`).join("")}</linearGradient>`}let c=null;function h(){return c||(c=document.createElement("canvas").getContext("2d")),c}export function getCurveTextDimensions(e,o){var r,l,f,c,$,d;const u=e.a?e.a:e,m=a(e),g=null!==(r=u.fontSize)&&void 0!==r?r:m.fontSize,p=null!==(l=null==o?void 0:o.normalizedText)&&void 0!==l?l:s(m.text,{fontSize:g,fontFamily:m.fontFamily}),x=null!==(f=null==o?void 0:o.segments)&&void 0!==f?f:i(p,{fontSize:g,fontFamily:m.fontFamily}),y=Math.max(g,...x.map(t=>{var e;return null!==(e=t.fontSize)&&void 0!==e?e:g})),k=n(p),v=function(t,e,n,o,i,r){if(!t.some(t=>t.fontFamily&&t.fontFamily!==n)||e.length<=1){return 0}const l=function(t,e,n,o,i){var r;const l=h();let a=0;for(const s of t){const t=s.fontFamily||e,f=s.bold?"bold":n,c=s.italic?"italic":o,h=null!==(r=s.fontSize)&&void 0!==r?r:i,$=t.replace(/'/g,"");l.font=`${c} ${f} ${h}px '${$}'`,a+=l.measureText(s.text).width}return a}(t,n,o,i,r),a=h();a.font=`${i} ${o} ${r}px '${n}'`;const s=l-a.measureText(e).width;return s<=0?0:s/(e.length-1)}(x,k,m.fontFamily,m.fontWeight||"normal",m.fontStyle||"normal",y),S=null!==(c=u.width)&&void 0!==c?c:m.width,w=new t.TextPath({data:getCurvePath(S,null!==(d=null!==($=u.height)&&void 0!==$?$:m.height)&&void 0!==d?d:0,m.curvePower,y),align:"center",textBaseline:"middle",text:k,fontSize:y,fontFamily:m.fontFamily,fontWeight:m.fontWeight,fontStyle:m.fontStyle,letterSpacing:m.letterSpacing*y+v,fill:m.fill}),b=w.getSelfRect();return w.destroy(),{width:b.width||S,height:b.height||y}}export function getCurveTextHeight(t){return getCurveTextDimensions(t).height}export function segmentsToTspans(t,e,n){return t.map(t=>{var o;const i=[];t.bold&&"bold"!==e.fontWeight&&i.push('font-weight="bold"'),t.italic&&"italic"!==e.fontStyle&&i.push('font-style="italic"');const r=[];t.underline&&r.push("underline"),t.strike&&r.push("line-through"),r.length&&i.push(`text-decoration="${r.join(" ")}"`),!(null==n?void 0:n.omitColors)&&t.color&&t.color!==e.fill&&i.push(`fill="${l(t.color)}"`);const a=t.fontFamily||e.fontFamily;a!==e.fontFamily&&i.push(`font-family="${l(a)}"`);const s=null!==(o=t.fontSize)&&void 0!==o?o:e.fontSize;s!==e.fontSize&&i.push(`font-size="${s}"`);const f=l(t.text);return 0===i.length?f:`<tspan ${i.join(" ")}>${f}</tspan>`}).join("")}export function getQuillEditorHtml(t,e){const n=a(t),i=e||n.fontFamily,r=s(n.text,{fontSize:n.fontSize,fontFamily:i});return o(r).replace(/\n/g,"<br/>")}export function getHtml(t,{fontFamily:f="",color:c="black",forEditor:h=!1}={}){const $=a(t),d=f||$.fontFamily,u=s($.text,{fontSize:$.fontSize,fontFamily:d}),m=e.isGradient($.fill),g=e.isGradient($.stroke)&&!!$.strokeWidth,p="ellipsis"===r.textOverflow&&!h&&!$.curveEnabled&&!!$.height,x=(()=>{if(!p){return[]}const t=Math.max(1,Math.round($.height)),e="number"==typeof $.lineHeight?$.lineHeight:1.2,n=Math.max(1,e*$.fontSize),o=Math.max(1,Math.floor(t/n));return[`max-height: ${t}px`,"overflow: hidden","display: -webkit-box","-webkit-box-orient: vertical",`-webkit-line-clamp: ${o}`,`line-clamp: ${o}`]})(),y=t=>`\n background-image: ${t};\n background-size: 100% 100%;\n background-repeat: repeat;\n -webkit-background-clip: text;\n -moz-background-clip: text;\n background-clip: text;\n -webkit-text-fill-color: transparent;\n color: transparent\n `.trim();let k=`color: ${c||$.fill}`,v="";g&&$.strokeWidth?(k=`color: ${c||$.fill}; ${y($.stroke)}`,v=`-webkit-text-stroke: ${$.strokeWidth}px transparent`):m&&(k=y($.fill));const S=["white-space: pre-wrap","overflow-wrap: break-word",`width: ${Math.round($.width||100)}px`,...x,k,`font-size: ${$.fontSize}px`,`font-family: '${d}'`,`text-align: ${$.align}`,`text-transform: ${$.textTransform}`,$.textDecoration?`text-decoration: ${$.textDecoration}; text-decoration-color: ${c||$.fill}; text-decoration-layer: over`:"",$.lineHeight?`line-height: ${$.lineHeight}`:"",$.letterSpacing?`letter-spacing: ${$.letterSpacing}em`:"",$.fontStyle?`font-style: ${$.fontStyle}`:"",$.fontWeight?`font-weight: ${$.fontWeight}`:"",v||($.strokeWidth?`-webkit-text-stroke: ${$.strokeWidth}px ${$.stroke}`:""),$.strokeWidth&&!g?"paint-order: stroke fill":"",$.strokeWidth?`stroke-linejoin: ${normalizeStrokeLineJoin($.strokeLineJoin)}`:""].filter(Boolean).join("; ");if($.curveEnabled&&!h){const e=i(u,{fontSize:$.fontSize,fontFamily:d}),n=getCurveTextDimensions(t,{normalizedText:u,segments:e}),o=Math.round(n.width),r=n.height,a=Math.max($.fontSize,...e.map(t=>{var e;return null!==(e=t.fontSize)&&void 0!==e?e:$.fontSize})),s=getCurvePath(o,r,$.curvePower,a),f={fontWeight:$.fontWeight||"normal",fontStyle:$.fontStyle||"normal",fill:c||$.fill||"black",fontFamily:d,fontSize:$.fontSize},h=segmentsToTspans(e,f),p=segmentsToTspans(e,f,{omitColors:!0}),x=l($.id||"temp"),y=`curve-${x}`,k=$.strokeWidth&&(g||m&&!g);let v=`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${r}" overflow="visible">\n <defs>\n <path id="${y}" d="${s}" fill="none" />`;if(m){const t=`curve-fill-grad-${x}`;v+=createSVGGradientDef($.fill,t,o,r)}if(g&&$.strokeWidth){const t=`curve-stroke-grad-${x}`;v+=createSVGGradientDef($.stroke,t,o,r)}v+="</defs>";const S=l(d),w=l($.fontWeight||"normal"),b=l($.fontStyle||"normal");if(k){const t=`\n font-family="'${S}'"\n font-size="${$.fontSize}"\n font-weight="${w}"\n font-style="${b}"\n text-anchor="middle"\n dominant-baseline="central"\n letter-spacing="${$.letterSpacing*a}"${$.textDecoration?` text-decoration="${$.textDecoration}"`:""}`,e=g?`url(#curve-stroke-grad-${x})`:$.stroke;v+=`\n <text ${t} fill="${e}" stroke="${e}" stroke-width="${$.strokeWidth}" stroke-linejoin="${normalizeStrokeLineJoin($.strokeLineJoin)}">\n <textPath href="#${y}" startOffset="50%">${p}</textPath>\n </text>`,v+=`\n <text ${t} fill="${m?`url(#curve-fill-grad-${x})`:c}">\n <textPath href="#${y}" startOffset="50%">${h}</textPath>\n </text>`}else{const t=m?`url(#curve-fill-grad-${x})`:c,e=g?`url(#curve-stroke-grad-${x})`:$.stroke;v+=`\n <text\n font-family="'${S}'"\n font-size="${$.fontSize}"\n font-weight="${w}"\n font-style="${b}"\n fill="${t}"\n text-anchor="middle"\n dominant-baseline="central"\n letter-spacing="${$.letterSpacing*a}"${$.textDecoration?` text-decoration="${$.textDecoration}"`:""}${$.strokeWidth?` stroke="${e}" stroke-width="${$.strokeWidth}" stroke-linejoin="${normalizeStrokeLineJoin($.strokeLineJoin)}" paint-order="stroke fill"`:""}>\n <textPath href="#${y}" startOffset="50%">${h}</textPath>\n </text>`}return v+="</svg>",v}if($.strokeWidth&&(g||m&&!g)&&!h){const t=o(u).replace(/\n/g,"<br/>"),e=Math.round($.width||100),i=["white-space: pre-wrap","overflow-wrap: break-word",`width: ${e}px`,...x,`font-size: ${$.fontSize}px`,`font-family: '${d}'`,`text-align: ${$.align}`,`text-transform: ${$.textTransform}`,$.textDecoration?`text-decoration: ${$.textDecoration}; text-decoration-color: ${c||$.fill}; text-decoration-layer: over`:"",$.lineHeight?`line-height: ${$.lineHeight}`:"",$.letterSpacing?`letter-spacing: ${$.letterSpacing}em`:"",$.fontStyle?`font-style: ${$.fontStyle}`:"",$.fontWeight?`font-weight: ${$.fontWeight}`:""].filter(Boolean).join("; ");let r;r=g?`${i}; ${y($.stroke)}; -webkit-text-stroke: ${$.strokeWidth}px transparent`:`${i}; color: transparent; -webkit-text-stroke: ${$.strokeWidth}px ${$.stroke}`;const l=`${i}; ${m?y($.fill):`color: ${c||$.fill}`}`;let a="";if(m||g){const t=[];g&&$.strokeWidth&&t.push(`.stroke-layer li, .stroke-layer li::before { ${y($.stroke)}; }`),m&&t.push(`.fill-layer li, .fill-layer li::before { ${y($.fill)}; }`),t.length&&(a=`<style>${t.join("\n")}</style>`)}return`\n <div style="position: relative; width: ${e}px;">\n <div class="stroke-layer" style="${r}; position: absolute; top: 0; left: 0; pointer-events: none;" aria-hidden="true">${t}</div>\n <div class="fill-layer" style="${l}; position: relative;" contentEditable dir="${getDir(n(u))}">${t}</div>\n </div>\n ${a}\n `}let w="";return m&&!g&&(w=`<style>\n li, li::before {\n ${y($.fill)};\n }\n </style>`),`<div style="${S}" contentEditable dir="${getDir(n(u))}">${o(u).replace(/\n/g,"<br/>")}</div>${w}`}export function resolveLineHeight({fontFamily:t,fontSize:e,lineHeight:n}){if("number"==typeof n){return n}const o=document.createElement("div");o.style.fontFamily=t,o.style.fontSize=e+"px",o.style.lineHeight=n,o.innerText="Test text",document.body.appendChild(o);try{return o.offsetHeight/e}finally{document.body.removeChild(o)}}
|
|
1
|
+
export*from"@polotno/core/text-html";import{getHtml as t}from"@polotno/core/text-html";import{flags as o}from"./flags.js";export const getHtml=(e,r={})=>t(e,Object.assign({textOverflow:o.textOverflow},r));
|
package/utils/text-types.d.ts
CHANGED
|
@@ -1,48 +1 @@
|
|
|
1
|
-
export
|
|
2
|
-
id?: string;
|
|
3
|
-
text: string;
|
|
4
|
-
width: number;
|
|
5
|
-
height?: number;
|
|
6
|
-
fontSize?: number;
|
|
7
|
-
fontFamily?: string;
|
|
8
|
-
fontWeight?: string;
|
|
9
|
-
fontStyle?: string;
|
|
10
|
-
lineHeight?: number | string;
|
|
11
|
-
letterSpacing?: number;
|
|
12
|
-
textTransform?: string;
|
|
13
|
-
textDecoration?: string;
|
|
14
|
-
align?: string;
|
|
15
|
-
fill?: string;
|
|
16
|
-
stroke?: string;
|
|
17
|
-
strokeWidth?: number;
|
|
18
|
-
strokeLineJoin?: string;
|
|
19
|
-
curveEnabled?: boolean;
|
|
20
|
-
curvePower?: number;
|
|
21
|
-
a?: {
|
|
22
|
-
width?: number;
|
|
23
|
-
height?: number;
|
|
24
|
-
fontSize?: number;
|
|
25
|
-
opacity?: number;
|
|
26
|
-
rotation?: number;
|
|
27
|
-
x?: number;
|
|
28
|
-
y?: number;
|
|
29
|
-
};
|
|
30
|
-
}
|
|
31
|
-
export declare const TEXT_DEFAULTS: {
|
|
32
|
-
readonly fontSize: 14;
|
|
33
|
-
readonly fontFamily: "Roboto";
|
|
34
|
-
readonly fontWeight: "normal";
|
|
35
|
-
readonly fontStyle: "normal";
|
|
36
|
-
readonly lineHeight: 1.2;
|
|
37
|
-
readonly letterSpacing: 0;
|
|
38
|
-
readonly textTransform: "none";
|
|
39
|
-
readonly textDecoration: "";
|
|
40
|
-
readonly align: "center";
|
|
41
|
-
readonly fill: "black";
|
|
42
|
-
readonly stroke: "black";
|
|
43
|
-
readonly strokeWidth: 0;
|
|
44
|
-
readonly strokeLineJoin: "round";
|
|
45
|
-
readonly curveEnabled: false;
|
|
46
|
-
readonly curvePower: 0.5;
|
|
47
|
-
};
|
|
48
|
-
export declare function applyTextDefaults<T extends Partial<TextElementLike>>(element: T): T & typeof TEXT_DEFAULTS;
|
|
1
|
+
export * from '@polotno/core/text-types';
|
package/utils/text-types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export
|
|
1
|
+
export * from '@polotno/core/text-types';
|
package/utils/text.d.ts
CHANGED
|
@@ -1,16 +1 @@
|
|
|
1
|
-
export
|
|
2
|
-
export interface StyledSegment {
|
|
3
|
-
text: string;
|
|
4
|
-
bold?: boolean;
|
|
5
|
-
italic?: boolean;
|
|
6
|
-
color?: string;
|
|
7
|
-
underline?: boolean;
|
|
8
|
-
strike?: boolean;
|
|
9
|
-
fontFamily?: string;
|
|
10
|
-
fontSize?: number;
|
|
11
|
-
}
|
|
12
|
-
export declare function parseHtmlToSegments(html: string, defaults?: {
|
|
13
|
-
fontSize: number;
|
|
14
|
-
fontFamily: string;
|
|
15
|
-
}): StyledSegment[];
|
|
16
|
-
export declare function sanitizeHtml(html: string): string;
|
|
1
|
+
export * from '@polotno/core/text';
|
package/utils/text.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
export * from '@polotno/core/text';
|
package/utils/to-html.d.ts
CHANGED
|
@@ -1,18 +1,7 @@
|
|
|
1
|
-
export
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
children: any[];
|
|
5
|
-
};
|
|
6
|
-
export declare function fixRatio(svgString: any): string;
|
|
7
|
-
export declare function jsonToDOM({ json, elementHook }: {
|
|
8
|
-
json: any;
|
|
9
|
-
elementHook: any;
|
|
10
|
-
}): Promise<{
|
|
11
|
-
type: any;
|
|
12
|
-
props: any;
|
|
13
|
-
children: any[];
|
|
14
|
-
}>;
|
|
15
|
-
export declare function jsonToHTML({ json, elementHook }: {
|
|
1
|
+
export * from '@polotno/html-export';
|
|
2
|
+
import { type RenderAttrs } from '@polotno/html-export';
|
|
3
|
+
export type JsonToHTMLOptions = RenderAttrs & {
|
|
16
4
|
json: any;
|
|
17
|
-
|
|
18
|
-
}
|
|
5
|
+
};
|
|
6
|
+
export declare const jsonToDOM: ({ json, ...attrs }: JsonToHTMLOptions) => Promise<import("@polotno/core/vnode").VNode>;
|
|
7
|
+
export declare const jsonToHTML: ({ json, ...attrs }: JsonToHTMLOptions) => Promise<string>;
|
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{getElementBlurRadius as l}from"../canvas/apply-filters.js";import{getVideoSize as d}from"./video.js";import{getGoogleFontsUrl as c}from"./fonts.js";import{forEveryNode as p}from"../model/group-model.js";import{getCurvePath as g}from"../canvas/text-element.js";import{removeTags as f,parseHtmlToSegments as m}from"./text.js";import b from"konva";import*as u from"./gradient.js";import{createSVGGradientDef as y,segmentsToTspans as k,getHtml as x,normalizeStrokeLineJoin as w}from"./text-html.js";import{generateBackgroundShapeFromRects as $}from"./background-shape.js";import{detectLineRects as v,detectSize as j}from"./html2canvas.js";import{normalizeRichTextHtml as S,extractFontFamiliesFromHtml as O}from"./rich-text-html.js";export const h=(t,e,...o)=>({type:t,props:e,children:o||[]});function z(t){return u.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 H=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 m=d/c,b="svg"===t.type||t.stretchEnabled;b?(g=d,f=c):p>=m?(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=b?t.width/g:x,$=b?t.height/f:x,v=g*w/y,j=f*$/k;let S=t.cropX*w*l.width,O=t.cropY*$*l.height;t.flipX&&(S=(1-t.cropX-t.cropWidth)*w*l.width),t.flipY&&(O=(1-t.cropY-t.cropHeight)*$*l.height);const H=t.borderSize&&u.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(S)+"px",backgroundPositionY:-Math.round(O)+"px"})});return H?h("div",{style:{width:"100%",height:"100%",borderRadius:t.cornerRadius+"px",background:z(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},T):T},W=({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},T={image:H,svg:H,text:async({element:t,page:e,store:o})=>{const i=u.isGradient(t.fill),n=u.isGradient(t.stroke);if(t.curveEnabled){const e=S(t.text,{fontSize:t.fontSize,fontFamily:t.fontFamily}),o=m(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=k(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+=y(t.fill,e)}if(n&&t.strokeWidth){const e=`curve-stroke-grad-${t.id}`;d+=y(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}" stroke-linejoin="${w(t.strokeLineJoin)}" 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"}}),f=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,f)}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=x(t);let o=[];try{o=v(e)}catch(W){o=[]}if(o.length){const i=t.backgroundPadding*(t.fontSize*t.lineHeight*.5),n=t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5),r=$({rects:o,padding:i,cornerRadius:n});if(r){let n=0;try{const{height:o}=j(e);"middle"===t.verticalAlign?n=(t.height-o)/2:"bottom"===t.verticalAlign&&(n=t.height-o)}catch(T){}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),p=c?S(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>`:"",m=h("div",{style:Object.assign(Object.assign({},o),{position:"absolute",top:0,left:0,pointerEvents:"none"}),"aria-hidden":"true",innerHTML:c?`${f}${p}`:p}),b=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)},m,b))}const f=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}),b="el-"+t.id,O=c?{id:b}:{},z=`<style>#${b} {${r}}</style>`,H=h("div",Object.assign(Object.assign({style:f},O),{innerHTML:c?`${z}${p}`:p}));return h("div",{style:{position:"relative",width:"100%",height:"100%"}},d,H)},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})`},W({element:t,type:t.startHead})),h("g",{transform:`translate(${t.width} ${t.height/2}) rotate(180)`},W({element:t,type:t.endHead}))),figure:async({element:t,page:e,store:o,elementHook:i})=>{let r=n(t);if(t.strokeWidth&&u.isGradient(t.stroke)){const e=`figure-stroke-grad-${t.id}`,o=y(t.stroke,e);r=r.replace(new RegExp(`stroke="${t.stroke.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"`,"g"),`stroke="url(#${e})"`),r=r.replace("</defs>",`${o}</defs>`)}if(u.isGradient(t.fill)){const e=`figure-fill-grad-${t.id}`,o=y(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=>M({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,l=await d(t.src),c=l.width*a,p=l.height*s,g=t.width/t.height;let f,m;g>=c/p?(f=c,m=c/g):(f=p*g,m=p);const b=f/a,y=m/s,k=n*l.width,x=r*l.height,w=Math.max(t.width/l.width,t.height/l.height),$={position:"absolute",width:`${Math.round(b*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&&u.isGradient(t.borderColor),S=j?Math.max(0,t.cornerRadius-t.borderSize):t.cornerRadius,O=h("div",{style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",borderRadius:S+"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:z(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},O);return i&&i({dom:e,element:t})||e}return i&&i({dom:O,element:t})||O},gif:H,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}`},g={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&&(g.colspan=String(l)),c>1&&(g.rowspan=String(c)),e.push(h("td",g,f(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 M({element:t,page:e,store:o,elementHook:i}){var n;let r=await T[t.type];if(r||(r=()=>h("div",{}),console.error(`HTML export does not support ${t.type} type...`)),!t.visible){return null}const d=await r({element:t,page:e,store:o}),c=[],p=[];if(t.blurEnabled&&c.push(`blur(${l(t)/2}px)`),t.brightnessEnabled&&c.push(`brightness(${100*t.brightness+100}%)`),t.sepiaEnabled&&c.push("sepia()"),t.grayscaleEnabled&&c.push("grayscale()"),t.filters){for(const[l,f]of Object.entries(t.filters)){const t=s(a[l],f.intensity);t&&(c.push(t.filter),t.html&&p.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);c.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:c.join(" ")||"none"}},d,...p);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=[...t.children.filter(t=>!t.alwaysOnTop),...t.children.filter(t=>t.alwaysOnTop)],a=await Promise.all(r.map(e=>M({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 H({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=u.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=[];p({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 O(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:c(e),rel:"stylesheet"})});return h("div",{className:"design"},...a,...n)}const R=({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=>R({dom:t})).join("")}</${e.type}>`};export async function jsonToHTML({json:t,elementHook:e}){const o=await jsonToDOM({json:t,elementHook:e});return R({dom:o})}
|
|
1
|
+
var t=this&&this.__rest||function(t,o){var e={};for(var r in t){Object.prototype.hasOwnProperty.call(t,r)&&o.indexOf(r)<0&&(e[r]=t[r])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var l=0;for(r=Object.getOwnPropertySymbols(t);l<r.length;l++){o.indexOf(r[l])<0&&Object.prototype.propertyIsEnumerable.call(t,r[l])&&(e[r[l]]=t[r[l]])}}return e};export*from"@polotno/html-export";import{jsonToHTML as o,jsonToDOM as e}from"@polotno/html-export";import{flags as r}from"./flags.js";export const jsonToDOM=o=>{var{json:l}=o,n=t(o,["json"]);return e(l,Object.assign({textOverflow:r.textOverflow,textSplitAllowed:r.textSplitAllowed},n))};export const jsonToHTML=e=>{var{json:l}=e,n=t(e,["json"]);return o(l,Object.assign({textOverflow:r.textOverflow,textSplitAllowed:r.textSplitAllowed},n))};console.warn('"polotno/utils/to-html" is deprecated, use the "@polotno/html-export" package instead');
|
package/utils/to-pptx.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadImage as t,cropImage as e}from"
|
|
1
|
+
import{loadImage as t,cropImage as e}from"@polotno/core/image";import*as o from"@polotno/core/svg";import{figureToSvg as a}from"@polotno/core/figure-to-svg";import{removeTags as i}from"@polotno/core/text";import{isBoldWeight as n}from"@polotno/core/rich-text-html";import{pxToUnit as r}from"./unit.js";import s from"konva";console.warn('"polotno/utils/to-pptx" is deprecated, use the "@polotno/pptx-export" package instead');const d=t=>r({px:t,unit:"in",dpi:100}),c=t=>Math.round(100*(1-t)),l=t=>{const{dx:e,dy:o}=((t,e,o)=>{const a=(o%360+360)%360;if(0===a){return{dx:0,dy:0}}const i=a*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+o)}},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=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:a,slide:i})=>{let{src:n}=a;if("svg"===a.type&&Object.keys(a.colorsReplace).length){const t=await o.urlToString(n);n=o.replaceColors(t,new Map(Object.entries(a.colorsReplace)))}const r=await t(n),s=r.width*a.cropWidth,g=r.height*a.cropHeight,p=a.width/a.height;let w,u;const f=s/g;"svg"===a.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({},a),{cropWidth:w/r.width,cropHeight:u/r.height}));(a.cornerRadius||a.borderSize)&&(m=await(async(e,{width:o,height:a,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(o)),d.height=Math.max(1,Math.round(a));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:a.width,height:a.height,cornerRadius:a.cornerRadius,borderSize:a.borderSize,borderColor:a.borderColor}));const b=Object.assign(Object.assign({},l(a)),{w:d(a.width),h:d(a.height),rotate:a.rotation,flipH:a.flipX,flipV:a.flipY,transparency:c(a.opacity)});if(a.shadowEnabled){const t=Math.hypot(a.shadowOffsetX,a.shadowOffsetY)/2,e=180*Math.atan2(a.shadowOffsetY,a.shadowOffsetX)/Math.PI;b.shadow={type:"outer",blur:a.shadowBlur/2,offset:t,angle:e,color:h(a.shadowColor),opacity:a.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 o=i(t.text||"");"uppercase"===t.textTransform&&(o=o.toUpperCase());const a=Object.assign(Object.assign(Object.assign(Object.assign({},l(t)),{w:d(t.width),h:d(t.height),fontSize:Math.round(.75*t.fontSize),fontFace:t.fontFamily,color:h(t.fill),align:t.align,bold:n(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:c(t.opacity),margin:0});if("middle"===t.verticalAlign?a.valign="middle":"bottom"===t.verticalAlign?a.valign="bottom":a.valign="top",t.letterSpacing&&(a.charSpacing=t.letterSpacing*a.fontSize),t.strokeWidth>0&&(a.outline={size:.75*t.strokeWidth,color:h(t.stroke)}),t.shadowEnabled){const e=.75*Math.hypot(t.shadowOffsetX,t.shadowOffsetY)/2,o=180*Math.atan2(t.shadowOffsetY,t.shadowOffsetX)/Math.PI;a.shadow={type:"outer",blur:.75*t.shadowBlur,offset:e,angle:o,color:h(t.shadowColor),opacity:t.shadowOpacity}}if(t.backgroundEnabled){a.fill={color:h(t.backgroundColor)};const e=t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5);a.rectRadius=d(e);const o=t.backgroundPadding*(t.fontSize*t.lineHeight);a.margin=Math.max(0,Math.round(.75*o))}await e.addText(o,a)},line:async({element:t,slide:e})=>{const o=Object.assign(Object.assign({},l(t)),{w:d(t.width),h:d(t.height),line:{color:h(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",o)},figure:async({element:e,slide:o})=>{const i=a(e),n=await(async(e,o,a)=>{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(o)),r.height=Math.max(1,Math.round(a)),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({},l(e)),{w:d(e.width),h:d(e.height),rotate:e.rotation,transparency:c(e.opacity)});await o.addImage(Object.assign({path:n},r))},group:async({element:t,slide:e})=>{for(const o of t.children||[]){await m({element:o,slide:e})}},video:async({element:t,slide:e})=>{const o=Object.assign(Object.assign({},l(t)),{w:d(t.width),h:d(t.height),rotate:t.rotation});await e.addMedia(Object.assign({type:"video",path:t.src},o))}},m=async({element:t,slide:e})=>{if(!t.visible||!t.showInExport){return}const o=f[t.type];o?await o({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 o of t.pages){const t=e.addSlide();if(/\.(jpg|jpeg|png|gif)$/i.test(o.background)||o.background.startsWith("data:image")||o.background.startsWith("http")){await t.addImage({path:o.background,x:0,y:0,w:e.width,h:e.height,sizing:{type:"contain"}})}else{const e=s.Util.colorToRGBA(o.background),a=s.Util._rgbToHex(e.r,e.g,e.b).replace("#","");t.background={color:a}}for(const e of o.children){await m({element:e,slide:t})}}return e.writeFile("test.pptx"),e}
|
package/utils/to-svg.d.ts
CHANGED
|
@@ -1,18 +1,7 @@
|
|
|
1
|
-
export
|
|
2
|
-
type
|
|
3
|
-
|
|
4
|
-
props: Record<string, any>;
|
|
5
|
-
children: (VNode | string | null)[];
|
|
6
|
-
};
|
|
7
|
-
export declare function fixRatio(svgString: any): string;
|
|
8
|
-
export declare function jsonToDOM({ json, elementHook, fontEmbedding, }: {
|
|
9
|
-
json: any;
|
|
10
|
-
elementHook: any;
|
|
11
|
-
fontEmbedding?: string | undefined;
|
|
12
|
-
}): Promise<VNode>;
|
|
13
|
-
export declare function jsonToSVG({ json, elementHook, fontEmbedding, }: {
|
|
1
|
+
export * from '@polotno/svg-export';
|
|
2
|
+
import { type RenderAttrs } from '@polotno/svg-export';
|
|
3
|
+
export type JsonToSVGOptions = RenderAttrs & {
|
|
14
4
|
json: any;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
export {};
|
|
5
|
+
};
|
|
6
|
+
export declare const jsonToDOM: ({ json, ...attrs }: JsonToSVGOptions) => Promise<import("@polotno/core/vnode").VNode>;
|
|
7
|
+
export declare const jsonToSVG: ({ json, ...attrs }: JsonToSVGOptions) => Promise<string>;
|