polotno 4.4.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.
@@ -1,4 +1,4 @@
1
- import{jsx as t,jsxs as e}from"react/jsx-runtime";import o from"react";import{observer as n}from"mobx-react-lite";import{PolotnoIcon as i}from"../icons/registry.js";import{Button as l}from"../primitives/button.js";import{Tooltip as r,TooltipContent as s,TooltipTrigger as a}from"../primitives/tooltip.js";import{TooltipIconButton as c}from"../primitives/tooltip-icon-button.js";import{ColorPicker as m}from"./color-picker.js";import p from"./filters-picker.js";import{ElementContainer as u,extendToolbar as d}from"./element-container.js";import f from"../utils/styled.js";import{AnimationsPicker as x}from"./animations-picker.js";import{flags as g}from"../utils/flags.js";import{TextAiWrite as v}from"./text-ai-write.js";import{t as h}from"../utils/l10n.js";import{quillRef as b,createQuill as T,setQuillContent as y}from"../canvas/html-element.js";import{FontMenu as F,fetcher as S,TextSpacing as z,TextFontSize as j,TextTransform as C,ALIGN_OPTIONS as A,VERTICAL_ALIGN_OPTIONS as D,VERTICAL_ALIGN_ICONS as N}from"./text-toolbar.js";import{cycleNext as w}from"./toolbar-shared.js";import E from"swr";import{getFontsList as k,globalFonts as L,isGoogleFontChanged as I}from"../utils/fonts.js";import{getGoogleFontsListAPI as M}from"../utils/api.js";import{quillHtmlToModelText as B,listEffectiveFontFamilies as R,isBoldWeight as W}from"../utils/rich-text-html.js";import{patchTextFormat as O}from"../utils/text-format.js";import{useTextFormat as P,getActiveTextEditor as V,resolveSelectionScope as _,applyToLiveEditor as G}from"../utils/text-format-state.js";const H=f("div")`
1
+ import{jsx as t,jsxs as e}from"react/jsx-runtime";import o from"react";import{observer as n}from"mobx-react-lite";import{PolotnoIcon as i}from"../icons/registry.js";import{Button as l}from"../primitives/button.js";import{Tooltip as r,TooltipContent as s,TooltipTrigger as a}from"../primitives/tooltip.js";import{TooltipIconButton as c}from"../primitives/tooltip-icon-button.js";import{ColorPicker as m}from"./color-picker.js";import p from"./filters-picker.js";import{ElementContainer as d,extendToolbar as u}from"./element-container.js";import f from"../utils/styled.js";import{AnimationsPicker as x}from"./animations-picker.js";import{flags as g}from"../utils/flags.js";import{TextAiWrite as h}from"./text-ai-write.js";import{t as v}from"../utils/l10n.js";import{quillRef as b,createQuill as T,setQuillContent as y}from"../canvas/html-element.js";import{FontMenu as S,fetcher as F,TextSpacing as z,TextFontSize as j,TextTransform as C,ALIGN_OPTIONS as A,VERTICAL_ALIGN_OPTIONS as N,VERTICAL_ALIGN_ICONS as w}from"./text-toolbar.js";import{cycleNext as k}from"./toolbar-shared.js";import E from"swr";import{getFontsList as D,globalFonts as L,isGoogleFontChanged as I}from"../utils/fonts.js";import{getGoogleFontsListAPI as M}from"../utils/api.js";import{quillHtmlToModelText as R,listEffectiveFontFamilies as W,isBoldWeight as B}from"../utils/rich-text-html.js";import{patchTextFormat as O,decorationTokensToString as P,isDecorationActive as V}from"../utils/text-format.js";import{useTextFormat as _,getActiveTextEditor as G,resolveSelectionScope as H,applyToLiveEditor as J}from"../utils/text-format-state.js";const Q=f("div")`
2
2
  position: relative;
3
3
  display: inline-block;
4
4
 
@@ -8,7 +8,7 @@ import{jsx as t,jsxs as e}from"react/jsx-runtime";import o from"react";import{ob
8
8
  &.polotno-mixed:focus-within input {
9
9
  color: inherit !important;
10
10
  }
11
- `,J=f("span")`
11
+ `,U=f("span")`
12
12
  position: absolute;
13
13
  left: 11px;
14
14
  top: 0;
@@ -19,7 +19,7 @@ import{jsx as t,jsxs as e}from"react/jsx-runtime";import o from"react";import{ob
19
19
  font-size: inherit;
20
20
  color: inherit;
21
21
 
22
- ${H}:focus-within & {
22
+ ${Q}:focus-within & {
23
23
  display: none;
24
24
  }
25
- `,Q=t=>{const e=V();return!!e&&e.store===t&&!!e.instance};let U=null;const X=()=>{b.pendingToolbarInteraction=!0,U&&clearTimeout(U),U=setTimeout(()=>{b.pendingToolbarInteraction=!1,U=null},100)},$=t=>{var e;(!(e=t.target)||"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName&&"SELECT"!==e.tagName&&!e.isContentEditable)&&t.preventDefault(),X()},q=n(({store:e,isActive:o,toggle:n,icon:i,ariaLabel:l,tooltipContent:r})=>{const{format:s,applyTextFormat:a}=P(e);return t(c,{label:r||l||"",side:"bottom",active:o(s),onMouseDown:t=>{t.preventDefault()},onClick:()=>n(s,a),children:i})});function K(t,e){const o=t.textDecoration.value||"",n="underline"===e?"line-through":"underline";return[!o.split(/\s+/).includes(e)&&e,o.split(/\s+/).includes(n)&&n].filter(Boolean).join(" ")}export const TextBold=n(({store:e})=>t(q,{store:e,isActive:t=>W(t.fontWeight.value),toggle:(t,e)=>e({fontWeight:W(t.fontWeight.value)?400:700}),icon:t(i,{name:"text.bold",className:"pn:size-4"}),tooltipContent:h("toolbar.bold")}));export const FontStyleGroup=n(({element:o,store:n,elements:m,components:p})=>{const u=(null==p?void 0:p.TextBold)||TextBold;return e("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:[t(u,{element:o,store:n}),t(q,{store:n,isActive:t=>"italic"===t.fontStyle.value,toggle:(t,e)=>e({fontStyle:"italic"===t.fontStyle.value?"normal":"italic"}),icon:t(i,{name:"text.italic",className:"pn:size-4"}),tooltipContent:h("toolbar.italic")}),t(q,{store:n,isActive:t=>{var e;return!!(null===(e=t.textDecoration.value)||void 0===e?void 0:e.split(/\s+/).includes("underline"))},toggle:(t,e)=>e({textDecoration:K(t,"underline")}),icon:t(i,{name:"text.underline",className:"pn:size-4"}),tooltipContent:h("toolbar.underline")}),t(q,{store:n,isActive:t=>{var e;return!!(null===(e=t.textDecoration.value)||void 0===e?void 0:e.split(/\s+/).includes("line-through"))},toggle:(t,e)=>e({textDecoration:K(t,"line-through")}),icon:t(i,{name:"text.strikethrough",className:"pn:size-4"}),tooltipContent:h("toolbar.strikethrough")}),t(c,{label:h("toolbar.textAlign"),side:"bottom",onClick:()=>{const t=w(A,o.align);n.history.transaction(()=>{m.forEach(e=>{e.set({align:t})})})},children:"left"===o.align?t(i,{name:"text.alignLeft",className:"pn:size-4"}):"center"===o.align?t(i,{name:"text.alignCenter",className:"pn:size-4"}):"right"===o.align?t(i,{name:"text.alignRight",className:"pn:size-4"}):t(i,{name:"text.alignJustify",className:"pn:size-4"})}),g.textVerticalResizeEnabled&&e(r,{children:[t(a,{render:t(l,{variant:"ghost",size:"icon-sm",onClick:()=>{const t=w(D,o.verticalAlign);n.history.transaction(()=>{o.set({verticalAlign:t})})},"aria-label":h("toolbar.verticalAlign"),children:N[o.verticalAlign]})}),t(s,{side:"bottom",children:h("toolbar.verticalAlign")})]}),t(c,{label:h("toolbar.listFormat"),side:"bottom",onMouseDown:t=>{t.preventDefault()},onClick:()=>{var t;let e=window.__polotnoQuill;const n=!e;e=e||(({html:t})=>{const e=document.createElement("div");document.body.appendChild(e),e.style.display="none",e.style.whiteSpace="pre-wrap";const o=T(e);return y(o,t),o})({html:o.text}),n&&e.setSelection(0,e.getLength(),"api");const i=e.getSelection(!0)||(null===(t=V())||void 0===t?void 0:t.lastSelection)||{index:0,length:e.getLength()},l=e.getFormat(i);l.list?"bullet"===l.list?e.format("list","ordered"):e.format("list",!1):e.format("list","bullet"),n&&(o.set({text:B(e.root.innerHTML,{fontSize:o.fontSize,fontFamily:o.fontFamily})}),(t=>{t.root.parentElement.remove()})(e))},children:(()=>{const e=V();return"bullet"===(e&&e.store===n?e.currentFormat:{}).list?t(i,{name:"text.numberedList",className:"pn:size-5"}):t(i,{name:"text.bulletList",className:"pn:size-5"})})()})]})});export const FontColorInput=n(({element:e,store:o})=>{var n;const{format:i,applyTextFormat:l}=P(o);return t("div",{"data-polotno-keep-focus":!0,onMouseDown:$,children:t(m,{value:null!==(n=i.fill.value)&&void 0!==n?n:e.fill,gradientEnabled:!0,onClose:()=>{const t=V();(null==t?void 0:t.instance)&&t.lastSelection&&t.instance.setSelection(t.lastSelection)},onChange:t=>l({fill:t}),store:o})})});export const DirectionInput=n(({element:e})=>{const o="rtl"===e.dir,n=h("toolbar.textDirection");return t(c,{label:n,side:"bottom",onClick:()=>{e.set({dir:o?"ltr":"rtl"})},children:t(i,o?{name:"text.paragraph",className:"pn:size-5 pn:-scale-x-100"}:{name:"text.richText",className:"pn:size-5"})})});const Y=k(),Z={TextFontFamily:n(({elements:e,store:n})=>{var i;const{format:l,applyTextFormat:r}=P(n),s=Q(n),a=l.fontFamily.mixed,c=a?Array.from(new Set(e.flatMap(t=>R(t.text,t.fontFamily)))).sort((t,e)=>t.localeCompare(e,void 0,{sensitivity:"base"})):void 0,[m,p]=o.useState(!1),{data:u,mutate:d}=E(m?M():null,S,{isPaused:()=>I(),fallbackData:[]});o.useEffect(()=>{d()},[I()]);const f=n.fonts.concat(L).map(t=>t.fontFamily).concat((null==u?void 0:u.length)&&!I()?u:Y),x=[];n.find(t=>("text"===t.type&&x.push(t.fontFamily),!1));const g=[...new Set(x.concat("_divider").concat(f))],v=null!==(i=l.fontFamily.value)&&void 0!==i?i:e[0].fontFamily;let h=v;h.length>15&&(h=h.slice(0,15)+"...");const b=t(F,{fonts:g,activeFont:v,activeFontLabel:h,store:n,mixed:a,mixedFonts:c,open:m,onOpenChange:p,onFontSelect:t=>r({fontFamily:t})});return s?t("div",{"data-polotno-keep-focus":!0,onMouseDown:$,children:b}):b}),TextFontSize:n(({elements:o,store:n})=>{const{format:i}=P(n),l=Q(n),r=i.fontSize.mixed,s=i.fontSize.value,a=o.map(t=>new Proxy(t,{get:(t,e)=>"fontSize"===e?null!=s?s:t.fontSize:"set"===e?e=>((t,e)=>{if(!e.fontSize){return void t.set(e)}const o=V();if(o&&o.store===n&&o.instance){const{scope:t,isEmpty:n}=_(o.instance,o.lastSelection);if("partial"===t||"collapsed"===t&&n){return void G(o.instance,{fontSize:e.fontSize},o.lastSelection)}}const{attrsToSet:i}=O(t,{fontSize:e.fontSize});t.set(Object.assign(Object.assign({},e),i))})(t,e):Reflect.get(t,e)})),c=e(H,{className:r?"polotno-mixed":"",children:[t(j,{elements:a,store:n}),r&&t(J,{"aria-hidden":!0,children:"—"})]});return l?t("div",{"data-polotno-keep-focus":!0,onMouseDown:X,children:c}):c}),TextFontVariant:FontStyleGroup,TextTransform:C,TextFilters:p,TextFill:FontColorInput,TextSpacing:z,TextDirection:DirectionInput,TextAnimations:x,TextAiWrite:v};export const HtmlToolbar=n(({store:e,components:o})=>{const n=e.selectedElements,i=e.selectedElements[0],l=["TextFill","TextFontFamily","TextFontSize","TextFontVariant","TextSpacing","TextTransform","TextFilters",g.animationsEnabled&&"TextAnimations",g.aiTextEnabled&&"TextAiWrite"],r=d({type:"text",usedItems:l,components:o});return t(u,{items:r,itemRender:l=>{if("TextBold"===l){return null}const r=(null==o?void 0:o[l])||Z[l];return t(r,{element:i,elements:n,store:e,components:o},l)}})});
25
+ `,X=t=>{const e=G();return!!e&&e.store===t&&!!e.instance};let $=null;const q=()=>{b.pendingToolbarInteraction=!0,$&&clearTimeout($),$=setTimeout(()=>{b.pendingToolbarInteraction=!1,$=null},100)},K=t=>{var e;(!(e=t.target)||"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName&&"SELECT"!==e.tagName&&!e.isContentEditable)&&t.preventDefault(),q()},Y=n(({store:e,isActive:o,toggle:n,icon:i,ariaLabel:l,tooltipContent:r})=>{const{format:s,applyTextFormat:a}=_(e);return t(c,{label:r||l||"",side:"bottom",active:o(s),onMouseDown:t=>{t.preventDefault()},onClick:()=>n(s,a),children:i})});function Z(t,e){const o="underline"===e?"line-through":"underline",n=new Set;return V(t,e)||n.add(e),V(t,o)&&n.add(o),P(n)}const tt=(t,e,o)=>e({textDecoration:Z(t,o)},{decorationTokens:[o]});export const TextBold=n(({store:e})=>t(Y,{store:e,isActive:t=>B(t.fontWeight.value),toggle:(t,e)=>e({fontWeight:B(t.fontWeight.value)?400:700}),icon:t(i,{name:"text.bold",className:"pn:size-4"}),tooltipContent:v("toolbar.bold")}));export const FontStyleGroup=n(({element:o,store:n,elements:m,components:p})=>{const d=(null==p?void 0:p.TextBold)||TextBold;return e("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:[t(d,{element:o,store:n}),t(Y,{store:n,isActive:t=>"italic"===t.fontStyle.value,toggle:(t,e)=>e({fontStyle:"italic"===t.fontStyle.value?"normal":"italic"}),icon:t(i,{name:"text.italic",className:"pn:size-4"}),tooltipContent:v("toolbar.italic")}),t(Y,{store:n,isActive:t=>V(t,"underline"),toggle:(t,e)=>tt(t,e,"underline"),icon:t(i,{name:"text.underline",className:"pn:size-4"}),tooltipContent:v("toolbar.underline")}),t(Y,{store:n,isActive:t=>V(t,"line-through"),toggle:(t,e)=>tt(t,e,"line-through"),icon:t(i,{name:"text.strikethrough",className:"pn:size-4"}),tooltipContent:v("toolbar.strikethrough")}),t(c,{label:v("toolbar.textAlign"),side:"bottom",onClick:()=>{const t=k(A,o.align);n.history.transaction(()=>{m.forEach(e=>{e.set({align:t})})})},children:"left"===o.align?t(i,{name:"text.alignLeft",className:"pn:size-4"}):"center"===o.align?t(i,{name:"text.alignCenter",className:"pn:size-4"}):"right"===o.align?t(i,{name:"text.alignRight",className:"pn:size-4"}):t(i,{name:"text.alignJustify",className:"pn:size-4"})}),g.textVerticalResizeEnabled&&e(r,{children:[t(a,{render:t(l,{variant:"ghost",size:"icon-sm",onClick:()=>{const t=k(N,o.verticalAlign);n.history.transaction(()=>{o.set({verticalAlign:t})})},"aria-label":v("toolbar.verticalAlign"),children:w[o.verticalAlign]})}),t(s,{side:"bottom",children:v("toolbar.verticalAlign")})]}),t(c,{label:v("toolbar.listFormat"),side:"bottom",onMouseDown:t=>{t.preventDefault()},onClick:()=>{var t;let e=window.__polotnoQuill;const n=!e;e=e||(({html:t})=>{const e=document.createElement("div");document.body.appendChild(e),e.style.display="none",e.style.whiteSpace="pre-wrap";const o=T(e);return y(o,t),o})({html:o.text}),n&&e.setSelection(0,e.getLength(),"api");const i=e.getSelection(!0)||(null===(t=G())||void 0===t?void 0:t.lastSelection)||{index:0,length:e.getLength()},l=e.getFormat(i);l.list?"bullet"===l.list?e.format("list","ordered"):e.format("list",!1):e.format("list","bullet"),n&&(o.set({text:R(e.root.innerHTML,{fontSize:o.fontSize,fontFamily:o.fontFamily})}),(t=>{t.root.parentElement.remove()})(e))},children:(()=>{const e=G();return"bullet"===(e&&e.store===n?e.currentFormat:{}).list?t(i,{name:"text.numberedList",className:"pn:size-5"}):t(i,{name:"text.bulletList",className:"pn:size-5"})})()})]})});export const FontColorInput=n(({element:e,store:o})=>{var n;const{format:i,applyTextFormat:l}=_(o);return t("div",{"data-polotno-keep-focus":!0,onMouseDown:K,children:t(m,{value:null!==(n=i.fill.value)&&void 0!==n?n:e.fill,gradientEnabled:!0,onClose:()=>{const t=G();(null==t?void 0:t.instance)&&t.lastSelection&&t.instance.setSelection(t.lastSelection)},onChange:t=>l({fill:t}),store:o})})});export const DirectionInput=n(({element:e})=>{const o="rtl"===e.dir,n=v("toolbar.textDirection");return t(c,{label:n,side:"bottom",onClick:()=>{e.set({dir:o?"ltr":"rtl"})},children:t(i,o?{name:"text.paragraph",className:"pn:size-5 pn:-scale-x-100"}:{name:"text.richText",className:"pn:size-5"})})});const et=D(),ot={TextFontFamily:n(({elements:e,store:n})=>{var i;const{format:l,applyTextFormat:r}=_(n),s=X(n),a=l.fontFamily.mixed,c=a?Array.from(new Set(e.flatMap(t=>W(t.text,t.fontFamily)))).sort((t,e)=>t.localeCompare(e,void 0,{sensitivity:"base"})):void 0,[m,p]=o.useState(!1),{data:d,mutate:u}=E(m?M():null,F,{isPaused:()=>I(),fallbackData:[]});o.useEffect(()=>{u()},[I()]);const f=n.fonts.concat(L).map(t=>t.fontFamily).concat((null==d?void 0:d.length)&&!I()?d:et),x=[];n.find(t=>("text"===t.type&&x.push(t.fontFamily),!1));const g=[...new Set(x.concat("_divider").concat(f))],h=null!==(i=l.fontFamily.value)&&void 0!==i?i:e[0].fontFamily;let v=h;v.length>15&&(v=v.slice(0,15)+"...");const b=t(S,{fonts:g,activeFont:h,activeFontLabel:v,store:n,mixed:a,mixedFonts:c,open:m,onOpenChange:p,onFontSelect:t=>r({fontFamily:t})});return s?t("div",{"data-polotno-keep-focus":!0,onMouseDown:K,children:b}):b}),TextFontSize:n(({elements:o,store:n})=>{const{format:i}=_(n),l=X(n),r=i.fontSize.mixed,s=i.fontSize.value,a=o.map(t=>new Proxy(t,{get:(t,e)=>"fontSize"===e?null!=s?s:t.fontSize:"set"===e?e=>((t,e)=>{if(!e.fontSize){return void t.set(e)}const o=G();if(o&&o.store===n&&o.instance){const{scope:t,isEmpty:n}=H(o.instance,o.lastSelection);if("partial"===t||"collapsed"===t&&n){return void J(o.instance,{fontSize:e.fontSize},o.lastSelection)}}const{attrsToSet:i}=O(t,{fontSize:e.fontSize});t.set(Object.assign(Object.assign({},e),i))})(t,e):Reflect.get(t,e)})),c=e(Q,{className:r?"polotno-mixed":"",children:[t(j,{elements:a,store:n}),r&&t(U,{"aria-hidden":!0,children:"—"})]});return l?t("div",{"data-polotno-keep-focus":!0,onMouseDown:q,children:c}):c}),TextFontVariant:FontStyleGroup,TextTransform:C,TextFilters:p,TextFill:FontColorInput,TextSpacing:z,TextDirection:DirectionInput,TextAnimations:x,TextAiWrite:h};export const HtmlToolbar=n(({store:e,components:o})=>{const n=e.selectedElements,i=e.selectedElements[0],l=["TextFill","TextFontFamily","TextFontSize","TextFontVariant","TextSpacing","TextTransform","TextFilters",g.animationsEnabled&&"TextAnimations",g.aiTextEnabled&&"TextAiWrite"],r=u({type:"text",usedItems:l,components:o});return t(d,{items:r,itemRender:l=>{if("TextBold"===l){return null}const r=(null==o?void 0:o[l])||ot[l];return t(r,{element:i,elements:n,store:e,components:o},l)}})});
package/utils/fonts.d.ts CHANGED
@@ -12,6 +12,7 @@ export declare function measureFontDom(fontName: string, fallback?: string, font
12
12
  export declare const isFontLoaded: (fontName: string, fontStyle?: string, fontWeight?: string) => boolean;
13
13
  export declare function _setFontLoadedForTesting(key: string, value: boolean): void;
14
14
  export declare function loadFont(fontName: string, fontStyle: string, fontWeight: string, sampleText?: string): Promise<void>;
15
+ export declare function injectGoogleFontVariant(fontName: string, fontStyle: string, fontWeight: string): void;
15
16
  export declare function injectGoogleFont(fontName: string): void;
16
17
  export type FONT = {
17
18
  fontFamily: string;
package/utils/fonts.js CHANGED
@@ -1 +1 @@
1
- import*as t from"mobx";import{triggerLoadError as o,getFontLoadTimeout as n}from"./loader.js";import{polotnoError as e}from"@polotno/core/errors";import{removeTags as r}from"@polotno/core/text";import{getGoogleFontsUrl as s}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as a}from"@polotno/core/fonts";export{setGoogleFontsVariants,getGoogleFontsVariants,getGoogleFontsUrl}from"@polotno/core/google-fonts-url";let i=t.observable(["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"]),l=t.observable({value:!1});export function isGoogleFontChanged(){return l.value}export function setGoogleFonts(t){"default"!==t?(l.value=!0,i.splice(0,i.length),i.push(...t)):l.value=!1}export function getFontsList(){return i}export const globalFonts=t.observable([]);export function addGlobalFont(t){globalFonts.push(t)}export function removeGlobalFont(t){const o=globalFonts.findIndex(o=>o.fontFamily===t);-1!==o&&globalFonts.splice(o,1)}export function replaceGlobalFonts(t){globalFonts.replace(t)}const c="BESbswy 0123456789 Il1Ww",u=["sans-serif","serif","monospace"];function f(t){const o=function(t=""){const o=r(t).replace(/\s+/g," ").trim();return o?Array.from(o).slice(0,10).join(""):""}(t);return o?`${c} ${o}`:c}export function _getFontProbeTextForTesting(t){return f(t)}let d;function m(t){return{width:t.width,actualBoundingBoxLeft:t.actualBoundingBoxLeft||0,actualBoundingBoxRight:t.actualBoundingBoxRight||0,actualBoundingBoxAscent:t.actualBoundingBoxAscent||0,actualBoundingBoxDescent:t.actualBoundingBoxDescent||0}}function p(t="sans-serif",o="normal",n="normal",e=c){d||(d=document.createElement("canvas"));const r=d.getContext("2d");return r.font=`${o} ${n} 40px ${t}`,m(r.measureText(e))}function g(t,o,n,e,r){return u.some(s=>{const a=function(t,o="sans-serif",n="normal",e="normal",r=c){d||(d=document.createElement("canvas"));const s=d.getContext("2d");return s.font=`${n} ${e} 40px '${t}', ${o}`,m(s.measureText(r))}(t,s,o,n,e);return function(t,o,n=.01){return Math.abs(t.width-o.width)>n||Math.abs(t.actualBoundingBoxLeft-o.actualBoundingBoxLeft)>n||Math.abs(t.actualBoundingBoxRight-o.actualBoundingBoxRight)>n||Math.abs(t.actualBoundingBoxAscent-o.actualBoundingBoxAscent)>n||Math.abs(t.actualBoundingBoxDescent-o.actualBoundingBoxDescent)>n}(a,r[s])})}export function measureFontDom(t,o="sans-serif",n="normal",e="normal",r=c){if("undefined"==typeof document||!document.body){return 0}const s=document.createElement("span");s.textContent=r,s.style.cssText=`\n position:absolute;\n visibility:hidden;\n white-space:nowrap;\n top:-9999px;\n left:-9999px;\n font:${n} ${e} 90px '${t}', ${o};\n `,document.body.appendChild(s);const a=s.getBoundingClientRect().width;return s.remove(),a}const x={Arial:!0};export const isFontLoaded=(t,o,n)=>o&&n?!!x[`${t}_${o}_${n}`]:Object.keys(x).some(o=>o.startsWith(t+"_"))||!!x[t];export function _setFontLoadedForTesting(t,o){o?x[t]=!0:delete x[t]}export async function loadFont(t,r,s,a){var i;const l=`${t}_${r}_${s}`;if(x[l]){return}const c=!!(null===(i=document.fonts)||void 0===i?void 0:i.load),u=f(a),d={"sans-serif":p("sans-serif",r,s,u),serif:p("serif",r,s,u),monospace:p("monospace",r,s,u)};if(c){try{if(await document.fonts.load(`${r} ${s} 16px '${t}'`,u),g(t,r,s,u,d)){return void b(l,t)}}catch(y){}}const m=Math.min(6e3,n())/60;for(let n=0;n<m;n++){if("missing"===B[t]){if(!F.has(t)){F.add(t),setTimeout(()=>F.delete(t),$);const n=`Font "${t}" not found: not registered and no matching Google Font.`;console.error(n),o(e("FONT_FAILED",n,{family:t,reason:"not-found"}))}return}if(t in h&&!h[t]&&"errored"===B[t]&&injectGoogleFont(t),c){try{await document.fonts.load(`${r} ${s} 16px '${t}'`,u)}catch(v){}}if(g(t,r,s,u,d)){return void b(l,t)}await new Promise(t=>setTimeout(t,60))}console.warn(`Timeout for loading font "${t}". Looks like polotno can't load it. Is it a correct font family?`),o(e("FONT_FAILED",`Timeout for loading font "${t}"`,{family:t,reason:"timeout"}))}const h={},B={},F=new Set,$=500;function b(t,o){x[t]=!0,delete B[o]}export function injectGoogleFont(t){if(h[t]){return}const o=s(t),n=document.createElement("link");n.type="text/css",n.href=o,n.rel="stylesheet",n.onerror=()=>{n.remove(),h[t]=!1,"errored"===B[t]?function(t){B[t]="probing",fetch(s(t),{mode:"no-cors"}).then(()=>{B[t]="missing"}).catch(()=>{delete B[t]})}(t):B[t]||(B[t]="errored")},document.getElementsByTagName("head")[0].appendChild(n),h[t]=!0}const y={};let v;export function injectCustomFont(t){const o=t.fontFamily;if(y[o]){return}if(!t.url&&!t.styles){return}delete B[o];const n=a(t),e=(v||(v=document.getElementById("polotno-font-style"),v||(v=document.createElement("style"),v.id="polotno-font-style",document.head.appendChild(v)),v)).sheet;n.forEach(t=>{e.insertRule(`\n @font-face{\n font-family:'${o}';\n src:${t.src};\n font-style:${t.fontStyle};\n font-weight:${t.fontWeight};\n font-display:swap; /* optional but recommended */\n }`,e.cssRules.length)}),y[t.fontFamily]=!0}
1
+ import*as t from"mobx";import{triggerLoadError as o,getFontLoadTimeout as n}from"./loader.js";import{polotnoError as e}from"@polotno/core/errors";import{removeTags as r}from"@polotno/core/text";import{getGoogleFontsUrl as s,getGoogleFontsVariants as a}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as i,googleFontVariantUrl as c}from"@polotno/core/fonts";export{setGoogleFontsVariants,getGoogleFontsVariants,getGoogleFontsUrl}from"@polotno/core/google-fonts-url";let l=t.observable(["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"]),u=t.observable({value:!1});export function isGoogleFontChanged(){return u.value}export function setGoogleFonts(t){"default"!==t?(u.value=!0,l.splice(0,l.length),l.push(...t)):u.value=!1}export function getFontsList(){return l}export const globalFonts=t.observable([]);export function addGlobalFont(t){globalFonts.push(t)}export function removeGlobalFont(t){const o=globalFonts.findIndex(o=>o.fontFamily===t);-1!==o&&globalFonts.splice(o,1)}export function replaceGlobalFonts(t){globalFonts.replace(t)}const f="BESbswy 0123456789 Il1Ww",d=["sans-serif","serif","monospace"];function m(t){const o=function(t=""){const o=r(t).replace(/\s+/g," ").trim();return o?Array.from(o).slice(0,10).join(""):""}(t);return o?`${f} ${o}`:f}export function _getFontProbeTextForTesting(t){return m(t)}let p;function g(t){return{width:t.width,actualBoundingBoxLeft:t.actualBoundingBoxLeft||0,actualBoundingBoxRight:t.actualBoundingBoxRight||0,actualBoundingBoxAscent:t.actualBoundingBoxAscent||0,actualBoundingBoxDescent:t.actualBoundingBoxDescent||0}}function x(t="sans-serif",o="normal",n="normal",e=f){p||(p=document.createElement("canvas"));const r=p.getContext("2d");return r.font=`${o} ${n} 40px ${t}`,g(r.measureText(e))}function h(t,o,n,e,r){return d.some(s=>{const a=function(t,o="sans-serif",n="normal",e="normal",r=f){p||(p=document.createElement("canvas"));const s=p.getContext("2d");return s.font=`${n} ${e} 40px '${t}', ${o}`,g(s.measureText(r))}(t,s,o,n,e);return function(t,o,n=.01){return Math.abs(t.width-o.width)>n||Math.abs(t.actualBoundingBoxLeft-o.actualBoundingBoxLeft)>n||Math.abs(t.actualBoundingBoxRight-o.actualBoundingBoxRight)>n||Math.abs(t.actualBoundingBoxAscent-o.actualBoundingBoxAscent)>n||Math.abs(t.actualBoundingBoxDescent-o.actualBoundingBoxDescent)>n}(a,r[s])})}export function measureFontDom(t,o="sans-serif",n="normal",e="normal",r=f){if("undefined"==typeof document||!document.body){return 0}const s=document.createElement("span");s.textContent=r,s.style.cssText=`\n position:absolute;\n visibility:hidden;\n white-space:nowrap;\n top:-9999px;\n left:-9999px;\n font:${n} ${e} 90px '${t}', ${o};\n `,document.body.appendChild(s);const a=s.getBoundingClientRect().width;return s.remove(),a}const B={Arial:!0};export const isFontLoaded=(t,o,n)=>o&&n?!!B[`${t}_${o}_${n}`]:Object.keys(B).some(o=>o.startsWith(t+"_"))||!!B[t];export function _setFontLoadedForTesting(t,o){o?B[t]=!0:delete B[t]}export async function loadFont(t,r,s,a){var i;const c=`${t}_${r}_${s}`;if(B[c]){return}injectGoogleFontVariant(t,r,s);const l=!!(null===(i=document.fonts)||void 0===i?void 0:i.load),u=m(a),f={"sans-serif":x("sans-serif",r,s,u),serif:x("serif",r,s,u),monospace:x("monospace",r,s,u)};if(l){try{if(await document.fonts.load(`${r} ${s} 16px '${t}'`,u),h(t,r,s,u,f)){return void v(c,t)}}catch(p){}}const d=Math.min(6e3,n())/60;for(let n=0;n<d;n++){if("missing"===$[t]){if(!b.has(t)){b.add(t),setTimeout(()=>b.delete(t),y);const n=`Font "${t}" not found: not registered and no matching Google Font.`;console.error(n),o(e("FONT_FAILED",n,{family:t,reason:"not-found"}))}return}if(t in F&&!F[t]&&"errored"===$[t]&&injectGoogleFont(t),l){try{await document.fonts.load(`${r} ${s} 16px '${t}'`,u)}catch(g){}}if(h(t,r,s,u,f)){return void v(c,t)}await new Promise(t=>setTimeout(t,60))}console.warn(`Timeout for loading font "${t}". Looks like polotno can't load it. Is it a correct font family?`),o(e("FONT_FAILED",`Timeout for loading font "${t}"`,{family:t,reason:"timeout"}))}const F={},$={},b=new Set,y=500;function v(t,o){B[t]=!0,delete $[o]}const w={};export function injectGoogleFontVariant(t,o,n){const e=parseInt(n,10);if(!Number.isFinite(e)){return}if(function(t){const o=new Set;for(const n of a().split(",")){const e=n.trim().match(/^(\d+)(italic|i)?$/);e&&!!e[2]===t&&o.add(parseInt(e[1],10))}return o}("italic"===o).has(e)){return}if(!(t in F)){return}const r="italic"===o,s=`${t}|${r?1:0}|${e}`;if(w[s]){return}w[s]=!0;const i=document.createElement("link");i.type="text/css",i.href=c(t,r,e),i.rel="stylesheet",i.onerror=()=>{i.remove()},document.getElementsByTagName("head")[0].appendChild(i)}export function injectGoogleFont(t){if(F[t]){return}const o=s(t),n=document.createElement("link");n.type="text/css",n.href=o,n.rel="stylesheet",n.onerror=()=>{n.remove(),F[t]=!1,"errored"===$[t]?function(t){$[t]="probing",fetch(s(t),{mode:"no-cors"}).then(()=>{$[t]="missing"}).catch(()=>{delete $[t]})}(t):$[t]||($[t]="errored")},document.getElementsByTagName("head")[0].appendChild(n),F[t]=!0}const G={};let T;export function injectCustomFont(t){const o=t.fontFamily;if(G[o]){return}if(!t.url&&!t.styles){return}delete $[o];const n=i(t),e=(T||(T=document.getElementById("polotno-font-style"),T||(T=document.createElement("style"),T.id="polotno-font-style",document.head.appendChild(T)),T)).sheet;n.forEach(t=>{e.insertRule(`\n @font-face{\n font-family:'${o}';\n src:${t.src};\n font-style:${t.fontStyle};\n font-weight:${t.fontWeight};\n font-display:swap; /* optional but recommended */\n }`,e.cssRules.length)}),G[t.fontFamily]=!0}
@@ -1 +1 @@
1
- export{clearFontCache,prefetchFonts}from"./font-inliner.js";export{extractStyleTags}from"./css-extractor.js";export{htmlToImage,clearImageCache}from"./render-cache.js";import{parseHtmlDocument as t}from"@polotno/core/platform";import{LRUCache as e}from"./lru-cache.js";import{inlineFontsInCss as o}from"./font-inliner.js";import{htmlToXhtml as r}from"./xhtml.js";import{buildSvg as n}from"./svg-builder.js";import{extractStyleTags as c}from"./css-extractor.js";import{clearFontCache as i}from"./font-inliner.js";import{clearImageCache as a}from"./render-cache.js";let l;async function s({html:e,css:i="",width:a,height:l,pixelRatio:s=1}){const m=c(e),h=[i,m.css].filter(Boolean).join("\n"),f=function(e){const o=t(e).body.textContent||"",r=new Set;for(let t=0;t<o.length;t++){const e=o.codePointAt(t);r.add(e),e>65535&&t++}return r}(m.html),p=await o(h,f),x=r(m.html);return n({xhtml:x,css:p,width:a,height:l,pixelRatio:s})}export async function htmlToSvg(t){var o,r,n,c;if(t.cache){const i=(c="object"==typeof t.cache&&null!==(o=t.cache.maxEntries)&&void 0!==o?o:50,l?l.maxEntries!==c&&l.resize(c):l=new e(c),l),a=`${t.html}\0${null!==(r=t.css)&&void 0!==r?r:""}\0${t.width}\0${t.height}\0${null!==(n=t.pixelRatio)&&void 0!==n?n:1}`,m=i.get(a);if(m){return m}const h=await s(t);return i.set(a,h),h}return s(t)}export function clearSvgCache(){l&&l.clear()}export function clearAllCaches(){i(),clearSvgCache(),a()}
1
+ export{clearFontCache,prefetchFonts}from"./font-inliner.js";export{extractStyleTags}from"./css-extractor.js";export{htmlToImage,clearImageCache}from"./render-cache.js";import{parseHtmlDocument as t}from"@polotno/core/platform";import{LRUCache as e}from"../lru-cache.js";import{inlineFontsInCss as o}from"./font-inliner.js";import{htmlToXhtml as r}from"./xhtml.js";import{buildSvg as n}from"./svg-builder.js";import{extractStyleTags as c}from"./css-extractor.js";import{clearFontCache as i}from"./font-inliner.js";import{clearImageCache as a}from"./render-cache.js";let l;async function s({html:e,css:i="",width:a,height:l,pixelRatio:s=1}){const m=c(e),h=[i,m.css].filter(Boolean).join("\n"),f=function(e){const o=t(e).body.textContent||"",r=new Set;for(let t=0;t<o.length;t++){const e=o.codePointAt(t);r.add(e),e>65535&&t++}return r}(m.html),p=await o(h,f),x=r(m.html);return n({xhtml:x,css:p,width:a,height:l,pixelRatio:s})}export async function htmlToSvg(t){var o,r,n,c;if(t.cache){const i=(c="object"==typeof t.cache&&null!==(o=t.cache.maxEntries)&&void 0!==o?o:50,l?l.maxEntries!==c&&l.resize(c):l=new e(c),l),a=`${t.html}\0${null!==(r=t.css)&&void 0!==r?r:""}\0${t.width}\0${t.height}\0${null!==(n=t.pixelRatio)&&void 0!==n?n:1}`,m=i.get(a);if(m){return m}const h=await s(t);return i.set(a,h),h}return s(t)}export function clearSvgCache(){l&&l.clear()}export function clearAllCaches(){i(),clearSvgCache(),a()}
@@ -1 +1 @@
1
- import{platform as e}from"@polotno/core/platform";import{LRUCache as t}from"./lru-cache.js";import{htmlToSvg as o}from"./index.js";let a;function n(e,t){"close"in t.image&&"function"==typeof t.image.close&&t.image.close()}async function i(t){const o="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(t),a=e.createElement("img");return a.src=o,await new Promise((e,t)=>{a.onload=()=>e(),a.onerror=()=>t(new Error("Failed to load SVG as image"))}),{image:a}}export async function htmlToImage(e){var r;const c=!!e.cache,m="object"==typeof e.cache&&null!==(r=e.cache.maxEntries)&&void 0!==r?r:50;if(c){const r=function(e){return a?a.maxEntries!==e&&a.resize(e):a=new t(e),a}(m),c=function(e){var t,o;return`${e.html}\0${null!==(t=e.css)&&void 0!==t?t:""}\0${e.width}\0${e.height}\0${null!==(o=e.pixelRatio)&&void 0!==o?o:1}`}(e),l=r.get(c);if(l){return l.image}const s=await o(e),u=await i(s);return r.setWithEviction(c,u,n),u.image}const l=await o(e);return(await i(l)).image}export function clearImageCache(){a&&(a.forEach(e=>n(0,e)),a.clear())}
1
+ import{platform as e}from"@polotno/core/platform";import{LRUCache as t}from"../lru-cache.js";import{htmlToSvg as o}from"./index.js";let a;function n(e,t){"close"in t.image&&"function"==typeof t.image.close&&t.image.close()}async function i(t){const o="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(t),a=e.createElement("img");return a.src=o,await new Promise((e,t)=>{a.onload=()=>e(),a.onerror=()=>t(new Error("Failed to load SVG as image"))}),{image:a}}export async function htmlToImage(e){var r;const c=!!e.cache,m="object"==typeof e.cache&&null!==(r=e.cache.maxEntries)&&void 0!==r?r:50;if(c){const r=function(e){return a?a.maxEntries!==e&&a.resize(e):a=new t(e),a}(m),c=function(e){var t,o;return`${e.html}\0${null!==(t=e.css)&&void 0!==t?t:""}\0${e.width}\0${e.height}\0${null!==(o=e.pixelRatio)&&void 0!==o?o:1}`}(e),l=r.get(c);if(l){return l.image}const s=await o(e),u=await i(s);return r.setWithEviction(c,u,n),u.image}const l=await o(e);return(await i(l)).image}export function clearImageCache(){a&&(a.forEach(e=>n(0,e)),a.clear())}
package/utils/math.d.ts CHANGED
@@ -16,6 +16,12 @@ export declare function getClientRect(element: Shape): {
16
16
  maxX: number;
17
17
  maxY: number;
18
18
  };
19
+ export type Point = {
20
+ x: number;
21
+ y: number;
22
+ };
23
+ export declare function getCorners(shape: Shape): Point[];
24
+ export declare function polygonsIntersect(a: Point[], b: Point[]): boolean;
19
25
  export declare function getTotalClientRect(elements: Shape[]): {
20
26
  x: number;
21
27
  y: number;
package/utils/math.js CHANGED
@@ -1 +1 @@
1
- export function degToRad(t){return t/180*Math.PI}function t(t,n,a,e,o){const i=Math.sqrt(a*a+e*e);return o+=Math.atan2(e,a),{x:t+i*Math.cos(o),y:n+i*Math.sin(o)}}export function getClientRect(n){const{x:a,y:e,width:o,height:i}=n,h=degToRad(n.rotation),x=t(a,e,0,0,h),r=t(a,e,o,0,h),m=t(a,e,o,i,h),c=t(a,e,0,i,h),M=Math.min(x.x,r.x,m.x,c.x),s=Math.min(x.y,r.y,m.y,c.y),y=Math.max(x.x,r.x,m.x,c.x),u=Math.max(x.y,r.y,m.y,c.y);return{x:M,y:s,width:y-M,height:u-s,minX:M,minY:s,maxX:y,maxY:u}}export function getTotalClientRect(t){const n=t.map(t=>getClientRect(t)),a=Math.min(...n.map(t=>t.minX)),e=Math.min(...n.map(t=>t.minY)),o=Math.max(...n.map(t=>t.maxX)),i=Math.max(...n.map(t=>t.maxY));return{x:a,y:e,width:o-a,height:i-e,minX:a,minY:e,maxX:o,maxY:i}}export function getCenter(t){const n=degToRad(t.rotation||0);return{x:t.x+t.width/2*Math.cos(n)+t.height/2*Math.sin(-n),y:t.y+t.height/2*Math.cos(n)+t.width/2*Math.sin(n)}}export function rotateAroundPoint(t,n,a){const e=degToRad(n),o=a.x+(t.x-a.x)*Math.cos(e)-(t.y-a.y)*Math.sin(e),i=a.y+(t.x-a.x)*Math.sin(e)+(t.y-a.y)*Math.cos(e);return Object.assign(Object.assign({},t),{rotation:t.rotation+n,x:o,y:i})}export function rotateAroundCenter(t,n){return rotateAroundPoint(t,n,getCenter(t))}
1
+ export function degToRad(t){return t/180*Math.PI}function t(t,n,o,e,a){const r=Math.sqrt(o*o+e*e);return a+=Math.atan2(e,o),{x:t+r*Math.cos(a),y:n+r*Math.sin(a)}}export function getClientRect(t){const[n,o,e,a]=getCorners(t),r=Math.min(n.x,o.x,e.x,a.x),i=Math.min(n.y,o.y,e.y,a.y),x=Math.max(n.x,o.x,e.x,a.x),h=Math.max(n.y,o.y,e.y,a.y);return{x:r,y:i,width:x-r,height:h-i,minX:r,minY:i,maxX:x,maxY:h}}export function getCorners(n){const{x:o,y:e,width:a,height:r}=n,i=degToRad(n.rotation);return[t(o,e,0,0,i),t(o,e,a,0,i),t(o,e,a,r,i),t(o,e,0,r,i)]}export function polygonsIntersect(t,n){const o=(t,n)=>{let o=1/0,e=-1/0;for(const a of t){const t=a.x*n.x+a.y*n.y;t<o&&(o=t),t>e&&(e=t)}return[o,e]};for(const e of[t,n]){for(let a=0;a<e.length;a++){const r=e[a],i=e[(a+1)%e.length],x={x:i.y-r.y,y:r.x-i.x},[h,c]=o(t,x),[s,y]=o(n,x);if(c<s||y<h){return!1}}}return!0}export function getTotalClientRect(t){const n=t.map(t=>getClientRect(t)),o=Math.min(...n.map(t=>t.minX)),e=Math.min(...n.map(t=>t.minY)),a=Math.max(...n.map(t=>t.maxX)),r=Math.max(...n.map(t=>t.maxY));return{x:o,y:e,width:a-o,height:r-e,minX:o,minY:e,maxX:a,maxY:r}}export function getCenter(t){const n=degToRad(t.rotation||0);return{x:t.x+t.width/2*Math.cos(n)+t.height/2*Math.sin(-n),y:t.y+t.height/2*Math.cos(n)+t.width/2*Math.sin(n)}}export function rotateAroundPoint(t,n,o){const e=degToRad(n),a=o.x+(t.x-o.x)*Math.cos(e)-(t.y-o.y)*Math.sin(e),r=o.y+(t.x-o.x)*Math.sin(e)+(t.y-o.y)*Math.cos(e);return Object.assign(Object.assign({},t),{rotation:t.rotation+n,x:a,y:r})}export function rotateAroundCenter(t,n){return rotateAroundPoint(t,n,getCenter(t))}
package/utils/px.d.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  export declare const roundEnabledPx: (value: number) => number;
2
2
  export declare const isCornerAnchor: (anchor: string) => boolean;
3
+ export declare const textMinResizeWidth: (startWidth: number, fontSize: number) => number;
4
+ export declare const textMinWidthIsMeasured: (element: {
5
+ curveEnabled?: boolean;
6
+ letterSpacing?: number;
7
+ text: string;
8
+ }) => boolean;
3
9
  type BoxStyleSource = {
4
10
  cornerRadius?: number;
5
11
  shadowBlur: number;
package/utils/px.js CHANGED
@@ -1 +1 @@
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 s=0;for(r=Object.getOwnPropertySymbols(t);s<r.length;s++){o.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(e[r[s]]=t[r[s]])}}return e};export const roundEnabledPx=t=>t>0?Math.max(1,Math.round(t)):0;export const isCornerAnchor=t=>!(t.includes("middle")||t.includes("center"));export const scaledBoxStyleAttrs=(t,o)=>{var e;return{cornerRadius:(null!==(e=t.cornerRadius)&&void 0!==e?e:0)*o,shadowBlur:t.shadowBlur*o,shadowOffsetX:t.shadowOffsetX*o,shadowOffsetY:t.shadowOffsetY*o}};export const roundedBoxStyleAttrs=t=>{var o;return{cornerRadius:roundEnabledPx(null!==(o=t.cornerRadius)&&void 0!==o?o:0),shadowBlur:Math.round(t.shadowBlur),shadowOffsetX:Math.round(t.shadowOffsetX),shadowOffsetY:Math.round(t.shadowOffsetY)}};export const scaledFontSizeAttrs=(t,o)=>{const e=t.fontSize>0?o/t.fontSize:1;return{fontSize:o,strokeWidth:t.strokeWidth*e,shadowBlur:t.shadowBlur*e,shadowOffsetX:t.shadowOffsetX*e,shadowOffsetY:t.shadowOffsetY*e}};export const roundedFontSizeAttrs=(t,o)=>{const e=scaledFontSizeAttrs(t,o);return{fontSize:Math.round(e.fontSize),strokeWidth:roundEnabledPx(e.strokeWidth),shadowBlur:Math.round(e.shadowBlur),shadowOffsetX:Math.round(e.shadowOffsetX),shadowOffsetY:Math.round(e.shadowOffsetY)}};export const roundedTextDecorationAttrs=o=>{const e=roundedFontSizeAttrs(o,o.fontSize),{fontSize:r}=e;return t(e,["fontSize"])};
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 s=0;for(r=Object.getOwnPropertySymbols(t);s<r.length;s++){o.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(e[r[s]]=t[r[s]])}}return e};import{htmlInflatesMinContentWidth as o}from"./rich-text-html.js";export const roundEnabledPx=t=>t>0?Math.max(1,Math.round(t)):0;export const isCornerAnchor=t=>!(t.includes("middle")||t.includes("center"));export const textMinResizeWidth=(t,o)=>t<o?1:o;export const textMinWidthIsMeasured=t=>{var e;return!!t.curveEnabled||(null!==(e=t.letterSpacing)&&void 0!==e?e:0)>0||o(t.text)};export const scaledBoxStyleAttrs=(t,o)=>{var e;return{cornerRadius:(null!==(e=t.cornerRadius)&&void 0!==e?e:0)*o,shadowBlur:t.shadowBlur*o,shadowOffsetX:t.shadowOffsetX*o,shadowOffsetY:t.shadowOffsetY*o}};export const roundedBoxStyleAttrs=t=>{var o;return{cornerRadius:roundEnabledPx(null!==(o=t.cornerRadius)&&void 0!==o?o:0),shadowBlur:Math.round(t.shadowBlur),shadowOffsetX:Math.round(t.shadowOffsetX),shadowOffsetY:Math.round(t.shadowOffsetY)}};export const scaledFontSizeAttrs=(t,o)=>{const e=t.fontSize>0?o/t.fontSize:1;return{fontSize:o,strokeWidth:t.strokeWidth*e,shadowBlur:t.shadowBlur*e,shadowOffsetX:t.shadowOffsetX*e,shadowOffsetY:t.shadowOffsetY*e}};export const roundedFontSizeAttrs=(t,o)=>{const e=scaledFontSizeAttrs(t,o);return{fontSize:Math.round(e.fontSize),strokeWidth:roundEnabledPx(e.strokeWidth),shadowBlur:Math.round(e.shadowBlur),shadowOffsetX:Math.round(e.shadowOffsetX),shadowOffsetY:Math.round(e.shadowOffsetY)}};export const roundedTextDecorationAttrs=o=>{const e=roundedFontSizeAttrs(o,o.fontSize),{fontSize:r}=e;return t(e,["fontSize"])};
@@ -1,4 +1,5 @@
1
1
  export * from '@polotno/core/rich-text-html';
2
+ export declare function htmlInflatesMinContentWidth(html: string): boolean;
2
3
  export declare function quillHtmlToModelText(html: string, defaults: {
3
4
  fontSize: number;
4
5
  fontFamily: string;
@@ -1 +1 @@
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";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",a=new Map,u=(t,e,o)=>{const n=r(t)||t||s,i=`${n}\0${e}\0${o}`;a.has(i)||a.set(i,{family:n,weight:e,style:o})};if(u(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="",a="",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")),a||(y.style.fontStyle?a=y.style.fontStyle:"EM"!==y.tagName&&"I"!==y.tagName||(a="italic")),y=y.parentElement}u(t||s,n||c,a||f)}e=t.nextNode()}}}return[...a.values()]}const c={bold:["STRONG","B"],italic:["EM","I"],underline:["U"],strike:["S","DEL"]},f={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=c[o]||[],a=f[o];for(const t of s){let e;for(;e=l.querySelector(t);){const t=e.parentNode;a&&a(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(a){for(const t of Array.from(l.querySelectorAll("[style]"))){a(t),(null===(i=t.getAttribute("style"))||void 0===i?void 0:i.trim())||t.removeAttribute("style")}}return e(l),l.innerHTML}const a=Symbol("unset");export function isQuillFormatMixed(t,e){var r;let o=a;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===a){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}
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}
@@ -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"@polotno/core/rich-text-html";import{isGradient as r}from"@polotno/core/gradient";import{getTextFormat as l,applyTextFormat as c,FORMAT_KEYS as a}from"./text-format.js";const s=e.observable({active:null},{},{deep:!1});export function getActiveTextEditor(){return s.active}export function setActiveTextEditor(t){e.runInAction(()=>{s.active=Object.assign(Object.assign({},t),{currentFormat:{},mixedFormats:{},lastSelection:null})})}export function updateActiveTextFormat(t,o,n){e.runInAction(()=>{s.active&&(s.active=Object.assign(Object.assign({},s.active),{currentFormat:t,mixedFormats:o,lastSelection:n||s.active.lastSelection}))})}export function clearActiveTextEditor(t){e.runInAction(()=>{var e;t&&(null===(e=s.active)||void 0===e?void 0:e.instance)!==t||(s.active=null)})}const f={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=>f[t])));function u(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":{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 a){if(f[i].some(t=>!0===e[t])){n[i]={value:void 0,mixed:!0,values:[]}}else{const e=u(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&&(r(String(t.fill))?e.push(["color",!1],["gradient",t.fill]):e.push(["gradient",!1],["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 p(t){return((null==t?void 0:t.selectedElements)||[]).filter(t=>"text"===t.type)}function m(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=m(t),o=p(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=>function(t,e){const o=m(t);if(!o){return void c(p(t),e)}const{scope:n,sel:i,isEmpty:r}=resolveSelectionScope(o.instance,o.lastSelection);"full"===n||"collapsed"===n&&!r?c([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"@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}
@@ -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 {};
@@ -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 a,guessFontFamilyFromQlClass as c}from"./rich-text-html.js";export const FORMAT_KEYS=["fontSize","fontFamily","fill","fontWeight","fontStyle","textDecoration"];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=a[e]||c(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;let i=t.parentElement;for(;i&&i!==e;){for(const t of FORMAT_KEYS){if(r.has(t)){continue}const e=l(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]=f(o,s))}return n}function g(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]=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]=g(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]=g(n,void 0)}return e}(t.map(d)):d(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 y=!1;function m(t){return"string"!=typeof t||/^\d+$/.test(t.trim())||y||(y=!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(m(e.fontWeight)):e[i]}let r=t.text||"";for(const i of o){r=h(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,a]of i){(null===(o=null==s?void 0:s.history)||void 0===o?void 0:o.transaction)?s.history.transaction(()=>a.forEach(r)):a.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"];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)}}
@@ -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.4.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()}
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.5.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()}