polotno 3.23.0 → 3.24.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 +1 @@
1
- import{jsx as e,jsxs as n}from"react/jsx-runtime";import{cn as l,firstSliderValue as a}from"../lib/utils.js";import{Slider as s}from"./slider.js";import{Switch as i}from"./switch.js";import{NumericInput as t}from"./numeric-input.js";function p({label:p,value:m,onChange:r,min:d,max:c,step:o=1,disabled:u,className:h,visible:f=!0,enabled:x,onEnabledChange:b,sliderMax:g,sliderValue:v,onCommit:N}){if(!f){return null}const j=e=>{let n=e;return"number"==typeof d&&(n=Math.max(d,n)),"number"==typeof c&&(n=Math.min(c,n)),n},y=e(t,{value:m,onValueChange:e=>r(j(e)),min:d,max:c,step:o,disabled:u,style:{width:64}}),C=e=>Number.isInteger(o)?Math.round(e):e,w=e(s,{value:[null!=v?v:m],onValueChange:e=>r(j(C(a(e)))),onValueCommitted:N?e=>N(j(C(a(e)))):void 0,min:d,max:null!=g?g:c,step:o,disabled:u});return n("div",b?{className:l("pn:py-1",h),children:[n("div",{className:"pn:flex pn:items-center pn:justify-between pn:gap-2 pn:py-1",children:[e("label",{className:"pn:text-sm pn:font-medium",children:p}),e(i,{checked:!!x,onCheckedChange:b,disabled:u})]}),x&&n("div",{className:"pn:mt-1.5 pn:flex pn:items-center pn:gap-2.5 pn:rounded-lg pn:bg-muted/60 pn:px-3 pn:py-2.5",children:[e("div",{className:"pn:flex-1",children:w}),y]})]}:{className:l("pn:flex pn:flex-col pn:gap-2 pn:py-2",h),children:[n("div",{className:"pn:flex pn:items-center pn:justify-between pn:gap-2",children:[e("label",{className:"pn:text-sm",children:p}),y]}),w]})}export{p as SliderField};
1
+ import{jsx as e,jsxs as n}from"react/jsx-runtime";import*as l from"react";import{cn as a,firstSliderValue as s}from"../lib/utils.js";import{Slider as i}from"./slider.js";import{Switch as t}from"./switch.js";import{NumericInput as p}from"./numeric-input.js";function m({label:m,value:r,onChange:d,min:o,max:c,step:u=1,disabled:h,className:b,visible:f=!0,enabled:x,onEnabledChange:g,sliderMax:v,sliderValue:y,onCommit:N}){const j=l.useId();if(!f){return null}const C=e=>{let n=e;return"number"==typeof o&&(n=Math.max(o,n)),"number"==typeof c&&(n=Math.min(c,n)),n},w=e(p,{value:r,onValueChange:e=>d(C(e)),min:o,max:c,step:u,disabled:h,style:{width:64}}),M=e=>Number.isInteger(u)?Math.round(e):e,V=e(i,{value:[null!=y?y:r],onValueChange:e=>d(C(M(s(e)))),onValueCommitted:N?e=>N(C(M(s(e)))):void 0,min:o,max:null!=v?v:c,step:u,disabled:h});return n("div",g?{className:a("pn:py-1",b),children:[n("div",{className:"pn:flex pn:items-center pn:justify-between pn:gap-2 pn:py-1",children:[e("label",{id:j,className:"pn:text-sm pn:font-medium",children:m}),e(t,{"aria-labelledby":j,checked:!!x,onCheckedChange:g,disabled:h})]}),x&&n("div",{className:"pn:mt-1.5 pn:flex pn:items-center pn:gap-2.5 pn:rounded-lg pn:bg-muted/60 pn:px-3 pn:py-2.5",children:[e("div",{className:"pn:flex-1",children:V}),w]})]}:{className:a("pn:flex pn:flex-col pn:gap-2 pn:py-2",b),children:[n("div",{className:"pn:flex pn:items-center pn:justify-between pn:gap-2",children:[e("label",{className:"pn:text-sm",children:m}),w]}),V]})}export{m as SliderField};
@@ -1 +1 @@
1
- var e=this&&this.__rest||function(e,r){var t={};for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&r.indexOf(n)<0&&(t[n]=e[n])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++){r.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(t[n[s]]=e[n[s]])}}return t};import{Fragment as r,jsx as t,jsxs as n}from"react/jsx-runtime";import{Effects as s,shapeFilterToCSS as l}from"@polotno/core/filters";import{cn as a}from"../lib/utils.js";export const EffectCard=({title:e,imageSrc:r,effect:s,onClick:l,active:o})=>{const i=f(s);return n("div",{className:"pn:flex pn:flex-col pn:gap-2 pn:cursor-pointer pn:flex-grow-0 pn:w-[calc(33%-16px)]",onClick:l,children:[n("div",{className:"pn:relative pn:h-[90px] pn:rounded-[10px] pn:box-border",children:[t("div",{"data-active":o?"true":void 0,className:a("pn:absolute pn:-left-1 pn:-top-1 pn:-bottom-1 pn:-right-1 pn:flex pn:rounded-[15px] pn:p-[2px] pn:transition-[border] pn:duration-200 pn:border-2 pn:border-transparent",o&&"pn:border-white")}),t(i,{src:r})]}),t("span",{className:"pn:text-center",children:e})]})};const o=r=>{var{className:n,style:s}=r,l=e(r,["className","style"]);return t("img",Object.assign({crossOrigin:"anonymous",className:a("pn:h-full pn:w-full pn:rounded-[10px] pn:object-cover",n),style:s},l))},i=e=>t(o,Object.assign({style:{filter:"sepia(1)"}},e)),c=e=>t(o,Object.assign({style:{filter:"grayscale(1)"}},e)),p=e=>{const r=l(s.warm);return t(o,Object.assign({style:{filter:null==r?void 0:r.filter}},e))},u=e=>{const a=l(s.cold),i=null==a?void 0:a.html,c=null==a?void 0:a.filter;return n(r,{children:[t("div",{style:{display:"none"},dangerouslySetInnerHTML:{__html:i||""}}),t(o,Object.assign({style:{filter:c}},e))]})},d=e=>{const r=l(s.natural);return t(o,Object.assign({style:{filter:null==r?void 0:r.filter}},e))},f=e=>{switch(e){case s.sepia:return i;case s.grayscale:return c;case s.warm:return p;case s.cold:return u;case s.natural:return d;default:return o}};
1
+ var e=this&&this.__rest||function(e,r){var t={};for(var n in e){Object.prototype.hasOwnProperty.call(e,n)&&r.indexOf(n)<0&&(t[n]=e[n])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var l=0;for(n=Object.getOwnPropertySymbols(e);l<n.length;l++){r.indexOf(n[l])<0&&Object.prototype.propertyIsEnumerable.call(e,n[l])&&(t[n[l]]=e[n[l]])}}return t};import{Fragment as r,jsx as t,jsxs as n}from"react/jsx-runtime";import{Effects as l,shapeFilterToCSS as s}from"@polotno/core/filters";import{cn as a}from"../lib/utils.js";export const EffectCard=({title:e,imageSrc:r,effect:l,onClick:s,active:o})=>{const i=f(l);return n("div",{role:"button",tabIndex:0,"aria-pressed":!!o,className:"pn:flex pn:flex-col pn:gap-2 pn:cursor-pointer pn:flex-grow-0 pn:w-[calc(33%-16px)]",onClick:s,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),null==s||s())},children:[n("div",{className:"pn:relative pn:h-[90px] pn:rounded-[10px] pn:box-border",children:[t("div",{"data-active":o?"true":void 0,className:a("pn:absolute pn:-left-1 pn:-top-1 pn:-bottom-1 pn:-right-1 pn:flex pn:rounded-[15px] pn:p-[2px] pn:transition-[border] pn:duration-200 pn:border-2 pn:border-transparent",o&&"pn:border-white")}),t(i,{src:r})]}),t("span",{className:"pn:text-center",children:e})]})};const o=r=>{var{className:n,style:l}=r,s=e(r,["className","style"]);return t("img",Object.assign({crossOrigin:"anonymous",className:a("pn:h-full pn:w-full pn:rounded-[10px] pn:object-cover",n),style:l},s))},i=e=>t(o,Object.assign({style:{filter:"sepia(1)"}},e)),p=e=>t(o,Object.assign({style:{filter:"grayscale(1)"}},e)),c=e=>{const r=s(l.warm);return t(o,Object.assign({style:{filter:null==r?void 0:r.filter}},e))},u=e=>{const a=s(l.cold),i=null==a?void 0:a.html,p=null==a?void 0:a.filter;return n(r,{children:[t("div",{style:{display:"none"},dangerouslySetInnerHTML:{__html:i||""}}),t(o,Object.assign({style:{filter:p}},e))]})},d=e=>{const r=s(l.natural);return t(o,Object.assign({style:{filter:null==r?void 0:r.filter}},e))},f=e=>{switch(e){case l.sepia:return i;case l.grayscale:return p;case l.warm:return c;case l.cold:return u;case l.natural:return d;default:return o}};
@@ -1 +1 @@
1
- import{jsx as e,jsxs as n}from"react/jsx-runtime";import t from"react";import{registerNextDomDrop as r}from"../canvas/page.js";import{t as l}from"../utils/l10n.js";import{cn as o}from"../lib/utils.js";import{Spinner as a}from"../primitives/spinner.js";const s=({url:t,credit:l,onSelect:s,crossOrigin:p,shadowEnabled:i,itemHeight:c,className:d,onLoad:u,alt:m,pending:g})=>{const h=null==i||i;return e("div",{role:"button",onClick:()=>{s()},className:"polotno-close-panel pn:group/img-wrap pn:p-[5px] pn:w-full pn:md:[&_.credit]:opacity-0 pn:md:hover:[&_.credit]:opacity-100 pn:[&_.credit]:opacity-100",children:n("div",{"data-shadowenabled":h,className:o("pn:relative pn:overflow-hidden pn:rounded-[5px]",h?"pn:shadow-[0_0_5px_rgba(16,22,26,0.3),0_0_0_1px_rgba(16,22,26,0.12)] pn:dark:shadow-[0_0_0_1px_rgba(255,255,255,0.16)]":""),children:[e("img",{className:o("pn:block pn:max-h-[300px] pn:min-h-[50px] pn:w-full pn:cursor-pointer pn:object-contain",d),style:{height:null!=c?c:"auto"},src:t,draggable:!0,loading:"lazy",crossOrigin:p,alt:m,onDragStart:()=>{r(({x:e,y:n},t,r)=>{s({x:e,y:n},t,r)})},onDragEnd:()=>{r(null)},onLoad:u}),g&&e("div",{className:"pn:absolute pn:inset-0 pn:flex pn:items-center pn:justify-center pn:bg-background/70",children:e(a,{className:"pn:size-5 pn:text-muted-foreground"})}),l&&e("div",{className:"credit pn:absolute pn:bottom-0 pn:left-0 pn:w-full pn:bg-gradient-to-b pn:from-transparent pn:via-black/40 pn:to-black/60 pn:p-[3px] pn:pt-[10px] pn:text-center pn:text-[10px] pn:text-white pn:[&_a]:text-white pn:[&_a]:underline",children:l})]})})};export const ImagesGrid=({images:r,onSelect:o,isLoading:p,getPreview:i,loadMore:c,getCredit:d,getAlt:u,getImageClassName:m,getIsLoading:g,rowsNumber:h,crossOrigin:f="anonymous",shadowEnabled:x,itemHeight:b,error:v,hideNoResults:w=!1})=>{const N=h||2,_=t.useRef(null),y=[];for(var j=0;j<N;j++){y.push((r||[]).filter((e,n)=>n%N===j))}const H=t.useRef(null),k=()=>{var e;const n=_.current,t=!!n&&n.scrollHeight>n.offsetHeight+5,l=r&&r.length,o=Array.from(null!==(e=null==n?void 0:n.querySelectorAll("img"))&&void 0!==e?e:[]).every(e=>e.complete);!t&&c&&!p&&l&&o&&(H.current||(H.current=window.setTimeout(()=>{H.current=null,c&&c()},100)))},S=()=>{k()};return t.useEffect(()=>(k(),()=>{null!==H.current&&window.clearTimeout(H.current),H.current=null}),[r&&r.length,p]),n("div",{onScroll:e=>{const n=e.target.scrollHeight-e.target.scrollTop-e.target.offsetHeight;c&&!p&&n<200&&c()},ref:_,className:"pn:h-full pn:overflow-auto",children:[y.map((n,t)=>e("div",{className:"pn:float-left",style:{width:100/N+"%"},children:n.map((n,t)=>e(s,{url:i(n),onSelect:(e,t,r)=>o(n,e,t,r),credit:d&&d(n),crossOrigin:f,shadowEnabled:x,itemHeight:b,className:m&&m(n),onLoad:S,alt:u&&u(n)||"",pending:null==g?void 0:g(n)},t))},t)),p&&e("div",{className:"pn:clear-both pn:flex pn:justify-center pn:p-[30px]",children:e(a,{className:"pn:size-5 pn:text-muted-foreground"})}),!p&&(!r||!r.length)&&!v&&!w&&e("p",{className:"pn:p-[30px] pn:text-center",children:l("sidePanel.noResults")}),v&&e("p",{className:"pn:clear-both pn:p-[30px] pn:text-center",children:l("sidePanel.error")})]})};
1
+ import{jsx as e,jsxs as n}from"react/jsx-runtime";import t from"react";import{registerNextDomDrop as r}from"../canvas/page.js";import{t as l}from"../utils/l10n.js";import{cn as a}from"../lib/utils.js";import{Spinner as o}from"../primitives/spinner.js";const s=({url:t,credit:l,onSelect:s,crossOrigin:p,shadowEnabled:i,itemHeight:c,className:d,onLoad:u,alt:m,pending:g})=>{const h=null==i||i;return e("div",{role:"button",tabIndex:0,onClick:()=>{s()},onKeyDown:e=>{e.target===e.currentTarget&&("Enter"!==e.key&&" "!==e.key||(e.preventDefault(),s()))},className:"polotno-close-panel pn:group/img-wrap pn:p-[5px] pn:w-full pn:md:[&_.credit]:opacity-0 pn:md:hover:[&_.credit]:opacity-100 pn:[&_.credit]:opacity-100",children:n("div",{"data-shadowenabled":h,className:a("pn:relative pn:overflow-hidden pn:rounded-[5px]",h?"pn:shadow-[0_0_5px_rgba(16,22,26,0.3),0_0_0_1px_rgba(16,22,26,0.12)] pn:dark:shadow-[0_0_0_1px_rgba(255,255,255,0.16)]":""),children:[e("img",{className:a("pn:block pn:max-h-[300px] pn:min-h-[50px] pn:w-full pn:cursor-pointer pn:object-contain",d),style:{height:null!=c?c:"auto"},src:t,draggable:!0,loading:"lazy",crossOrigin:p,alt:m,onDragStart:e=>{e.dataTransfer.setData("text/plain",t),r(({x:e,y:n},t,r)=>{s({x:e,y:n},t,r)})},onDragEnd:()=>{r(null)},onLoad:u}),g&&e("div",{className:"pn:absolute pn:inset-0 pn:flex pn:items-center pn:justify-center pn:bg-background/70",children:e(o,{className:"pn:size-5 pn:text-muted-foreground"})}),l&&e("div",{className:"credit pn:absolute pn:bottom-0 pn:left-0 pn:w-full pn:bg-gradient-to-b pn:from-transparent pn:via-black/40 pn:to-black/60 pn:p-[3px] pn:pt-[10px] pn:text-center pn:text-[10px] pn:text-white pn:[&_a]:text-white pn:[&_a]:underline",children:l})]})})};export const ImagesGrid=({images:r,onSelect:a,isLoading:p,getPreview:i,loadMore:c,getCredit:d,getAlt:u,getImageClassName:m,getIsLoading:g,rowsNumber:h,crossOrigin:f="anonymous",shadowEnabled:x,itemHeight:b,error:v,hideNoResults:w=!1})=>{const y=h||2,N=t.useRef(null),_=[];for(var j=0;j<y;j++){_.push((r||[]).filter((e,n)=>n%y===j))}const k=t.useRef(null),H=()=>{var e;const n=N.current,t=!!n&&n.scrollHeight>n.offsetHeight+5,l=r&&r.length,a=Array.from(null!==(e=null==n?void 0:n.querySelectorAll("img"))&&void 0!==e?e:[]).every(e=>e.complete);!t&&c&&!p&&l&&a&&(k.current||(k.current=window.setTimeout(()=>{k.current=null,c&&c()},100)))},E=()=>{H()};return t.useEffect(()=>(H(),()=>{null!==k.current&&window.clearTimeout(k.current),k.current=null}),[r&&r.length,p]),n("div",{onScroll:e=>{const n=e.target.scrollHeight-e.target.scrollTop-e.target.offsetHeight;c&&!p&&n<200&&c()},ref:N,className:"pn:h-full pn:overflow-auto",children:[_.map((n,t)=>e("div",{className:"pn:float-left",style:{width:100/y+"%"},children:n.map((n,t)=>e(s,{url:i(n),onSelect:(e,t,r)=>a(n,e,t,r),credit:d&&d(n),crossOrigin:f,shadowEnabled:x,itemHeight:b,className:m&&m(n),onLoad:E,alt:u&&u(n)||"",pending:null==g?void 0:g(n)},t))},t)),p&&e("div",{className:"pn:clear-both pn:flex pn:justify-center pn:p-[30px]",children:e(o,{className:"pn:size-5 pn:text-muted-foreground"})}),!p&&(!r||!r.length)&&!v&&!w&&e("p",{className:"pn:p-[30px] pn:text-center",children:l("sidePanel.noResults")}),v&&e("p",{className:"pn:clear-both pn:p-[30px] pn:text-center",children:l("sidePanel.error")})]})};
@@ -1 +1 @@
1
- import{jsx as e,jsxs as n}from"react/jsx-runtime";import t from"react";import{action as i,observable as l,reaction as o}from"mobx";import{observer as s}from"mobx-react-lite";import{Button as r}from"../primitives/button.js";import{Input as a}from"../primitives/input.js";import{ROLES as d}from"../model/store.js";import{unboundWrite as c}from"../model/node-model.js";import{t as m}from"../utils/l10n.js";import{isMobile as p}from"../utils/screen.js";import{ReactSortable as h}from"react-sortablejs";import{removeTags as u}from"@polotno/core/text";import{PolotnoIcon as g}from"../icons/registry.js";import{cn as f}from"../lib/utils.js";import{PanelScrollArea as v}from"../primitives/panel-scroll-area.js";import{getLayerClickSelection as x,getLayerRows as y}from"./layer-selection.js";import{getParentGroupId as b}from"../utils/selection.js";const E=(e,n)=>!!n.selectable||e.role===d.ADMIN,k=e=>e.stopPropagation(),j=s(({element:i,ctx:l})=>{var o;const{store:s,expandedIds:d}=l,p=s.selectedElements.indexOf(i)>=0,h="group"===i.type,v=null!==(o=i.filled.visible)&&void 0!==o?o:i.visible,x=h&&d.has(i.id),[y,b]=t.useState(!1),j=()=>b(!1),I=t.useRef(null),N=p&&1===s.selectedElements.length;t.useEffect(()=>{var e,n;N&&(null===(n=null===(e=I.current)||void 0===e?void 0:e.scrollIntoView)||void 0===n||n.call(e,{block:"nearest"}))},[N]);const P=()=>{s.highlightedElementId===i.id&&s.highlightElement(null)};t.useEffect(()=>P,[s,i.id]);const z=y?i.name:i.name||("text"in i?u(i.text):"")||`#${i.id}`;return n("div",{style:{display:E(s,i)?"auto":"none"},children:[e("div",{ref:I,"data-layer-id":i.id,onMouseDown:e=>{l.onRowMouseDown(i.id,e)},onPointerEnter:e=>{"mouse"===e.pointerType&&s.highlightElement(i.id)},onPointerLeave:P,className:f("pn:rounded-md pn:border pn:bg-card pn:p-[5px] pn:mx-[1px] pn:mb-[5px] pn:shadow-sm",p&&"selected pn:border-primary pn:bg-primary/10"),children:n("div",{className:"pn:flex pn:items-center pn:justify-between",children:[n("div",{className:"pn:flex pn:min-w-0 pn:flex-1 pn:items-center",style:{lineHeight:"30px"},children:[e("div",{className:"drag-handle",style:{display:"flex",justifyContent:"center",alignItems:"center",cursor:"move",height:"30px"},children:e(g,{name:"action.dragHandle",className:"pn:size-4"})}),e("div",{className:"pn:flex pn:size-5 pn:shrink-0 pn:items-center pn:justify-center",children:h?e(r,{variant:"ghost",size:"icon-sm",className:"pn:size-5","aria-expanded":x,onMouseDown:k,onClick:()=>l.toggleExpanded(i.id),children:e(g,{name:x?"ui.chevronDown":"ui.chevronRight",className:"pn:size-4"})}):null}),e("div",{style:{padding:"0 7px",opacity:.5,width:"60px"},children:m("sidePanel.layerTypes."+i.type)}),e("div",{className:"pn:min-w-0 pn:flex-1",children:e(a,{value:z,onFocus:()=>b(!0),onBlur:j,placeholder:m("sidePanel.namePlaceholder"),onChange:e=>{i.set({name:e.target.value})},onKeyDown:e=>{"Enter"!==e.key&&"Escape"!==e.key||(j(),e.target.blur())},className:"pn:h-7 pn:border-none pn:bg-transparent pn:dark:bg-transparent pn:px-1 pn:shadow-none pn:focus-visible:ring-1"})})]}),n("div",{className:"pn:flex pn:shrink-0",onMouseDown:k,children:[e(r,{variant:"ghost",size:"icon-sm",onClick:()=>{i.set(c(i,{visible:!v}))},children:e(g,v?{name:"action.visible"}:{name:"action.hidden"})}),e(r,{variant:"ghost",size:"icon-sm",onClick:()=>{i.set({draggable:i.locked,contentEditable:i.locked,styleEditable:i.locked,resizable:i.locked,removable:i.locked})},children:(null==i?void 0:i.locked)?e(g,{name:"action.lock"}):e(g,{name:"action.unlock"})}),e(r,{variant:"ghost",size:"icon-sm",disabled:!i.removable,onClick:()=>{s.deleteElements([i.id])},style:{marginLeft:"auto"},children:e(g,{name:"action.remove"})})]})]})}),x?e(w,{container:i,ctx:l}):null]})}),w=s(({container:n,ctx:t})=>{const{store:i}=t,l=n.children.slice().reverse(),o=l.map(e=>({id:e.id})),s=p(),r=n!==i.activePage;return e(h,{list:o,setList:e=>{const t=e.filter(e=>null!=e&&null!=e.id);t.forEach((e,l)=>{const o=t.length-l-1,s=i.getElementById(e.id);s&&n.children.indexOf(s)!==o&&n.setElementZIndex(s.id,o)})},group:n.id,direction:"horizontal",handle:s?".drag-handle":void 0,className:r?"pn:ml-4":void 0,children:l.map(n=>e(j,{element:n,ctx:t},n.id))})});export const LayersPanel=s(({store:s})=>{const r=s.activePage,[a]=t.useState(()=>l.map()),d=t.useRef(null);t.useEffect(()=>o(()=>{const e=[];return s.selectedElements.forEach(n=>{for(let t=n.parent;t&&"group"===t.type;t=t.parent){e.push(t.id)}}),e},i(e=>{e.forEach(e=>a.set(e,!0))}),{equals:(e,n)=>e.length===n.length&&e.every((e,t)=>e===n[t]),fireImmediately:!0}),[s,a]);const c=t.useMemo(()=>({store:s,expandedIds:a,toggleExpanded:i(e=>{a.delete(e)||a.set(e,!0)}),onRowMouseDown:(e,n)=>{const t=s.activePage;if(!t){return}const i=x({clickedId:e,selectedIds:s.selectedElementsIds,anchorId:d.current,rows:y(t,a,e=>E(s,e)),modifiers:n,getParentId:e=>b(s,e)});d.current=i.anchorId,s.selectElements(i.selectedIds)}}),[s,a]);return n(v,{children:[e("div",{style:{height:"40px",paddingTop:"5px"},children:m("sidePanel.layersTip")}),n("div",{children:[r&&0!==r.children.length?null:e("div",{children:m("sidePanel.noLayers")}),r?e(w,{container:r,ctx:c}):null]})]})});
1
+ import{jsx as e,jsxs as n}from"react/jsx-runtime";import t from"react";import{action as r,observable as i,reaction as l}from"mobx";import{observer as s}from"mobx-react-lite";import{Button as o}from"../primitives/button.js";import{Input as a}from"../primitives/input.js";import{ROLES as d}from"../model/store.js";import{unboundWrite as c}from"../model/node-model.js";import{t as p}from"../utils/l10n.js";import{isMobile as m}from"../utils/screen.js";import{ReactSortable as h}from"react-sortablejs";import{removeTags as u}from"@polotno/core/text";import{PolotnoIcon as f}from"../icons/registry.js";import{cn as g}from"../lib/utils.js";import{PanelScrollArea as v}from"../primitives/panel-scroll-area.js";import{getLayerClickSelection as x,getLayerRows as b}from"./layer-selection.js";import{getParentGroupId as y}from"../utils/selection.js";const k=(e,n)=>!!n.selectable||e.role===d.ADMIN,w=e=>e.stopPropagation(),E=s(({element:r,ctx:i})=>{var l;const{store:s,expandedIds:d}=i,m=s.selectedElements.indexOf(r)>=0,h="group"===r.type,v=null!==(l=r.filled.visible)&&void 0!==l?l:r.visible,x=h&&d.has(r.id),[b,y]=t.useState(!1),E=()=>y(!1),I=t.useRef(null),P=m&&1===s.selectedElements.length;t.useEffect(()=>{var e,n;P&&(null===(n=null===(e=I.current)||void 0===e?void 0:e.scrollIntoView)||void 0===n||n.call(e,{block:"nearest"}))},[P]);const N=()=>{s.highlightedElementId===r.id&&s.highlightElement(null)};t.useEffect(()=>N,[s,r.id]);const D=e=>{const n=r.parent;if(!n){return}const t=n.children;let i=t.indexOf(r)+e;for(;t[i]&&!k(s,t[i]);){i+=e}t[i]&&n.setElementZIndex(r.id,i)},z=b?r.name:r.name||("text"in r?u(r.text):"")||`#${r.id}`;return n("div",{style:{display:k(s,r)?"auto":"none"},children:[e("div",{ref:I,"data-layer-id":r.id,tabIndex:0,onMouseDown:e=>{i.onRowMouseDown(r.id,e)},onClick:e=>{e.currentTarget.matches(":focus-visible")||e.currentTarget.blur()},onKeyDown:e=>{if(e.target===e.currentTarget){switch(e.key){case"Enter":case" ":i.onRowMouseDown(r.id,e);break;case"ArrowUp":D(1);break;case"ArrowDown":D(-1);break;case"ArrowLeft":case"ArrowRight":break;default:return}e.preventDefault(),e.stopPropagation()}},onPointerEnter:e=>{"mouse"===e.pointerType&&s.highlightElement(r.id)},onPointerLeave:N,className:g("pn:rounded-md pn:border pn:bg-card pn:p-[5px] pn:mx-[1px] pn:mb-[5px] pn:shadow-sm",m&&"selected pn:border-primary pn:bg-primary/10"),children:n("div",{className:"pn:flex pn:items-center pn:justify-between",children:[n("div",{className:"pn:flex pn:min-w-0 pn:flex-1 pn:items-center",style:{lineHeight:"30px"},children:[e("div",{className:"drag-handle",style:{display:"flex",justifyContent:"center",alignItems:"center",cursor:"move",height:"30px"},children:e(f,{name:"action.dragHandle",className:"pn:size-4"})}),e("div",{className:"pn:flex pn:size-5 pn:shrink-0 pn:items-center pn:justify-center",children:h?e(o,{variant:"ghost",size:"icon-sm",className:"pn:size-5","aria-expanded":x,onMouseDown:w,onClick:()=>i.toggleExpanded(r.id),children:e(f,{name:x?"ui.chevronDown":"ui.chevronRight",className:"pn:size-4"})}):null}),e("div",{style:{padding:"0 7px",opacity:.5,width:"60px"},children:p("sidePanel.layerTypes."+r.type)}),e("div",{className:"pn:min-w-0 pn:flex-1",children:e(a,{value:z,onFocus:()=>y(!0),onBlur:E,placeholder:p("sidePanel.namePlaceholder"),onChange:e=>{r.set({name:e.target.value})},onKeyDown:e=>{"Enter"!==e.key&&"Escape"!==e.key||(E(),e.target.blur())},className:"pn:h-7 pn:border-none pn:bg-transparent pn:dark:bg-transparent pn:px-1 pn:shadow-none pn:focus-visible:ring-1"})})]}),n("div",{className:"pn:flex pn:shrink-0",onMouseDown:w,children:[e(o,{variant:"ghost",size:"icon-sm","aria-label":p("sidePanel.hideLayer"),"aria-pressed":!v,onClick:()=>{r.set(c(r,{visible:!v}))},children:e(f,v?{name:"action.visible"}:{name:"action.hidden"})}),e(o,{variant:"ghost",size:"icon-sm","aria-label":p("sidePanel.lockLayer"),"aria-pressed":!!r.locked,onClick:()=>{r.set({draggable:r.locked,contentEditable:r.locked,styleEditable:r.locked,resizable:r.locked,removable:r.locked})},children:(null==r?void 0:r.locked)?e(f,{name:"action.lock"}):e(f,{name:"action.unlock"})}),e(o,{variant:"ghost",size:"icon-sm","aria-label":p("sidePanel.deleteLayer"),disabled:!r.removable,onClick:()=>{s.deleteElements([r.id])},style:{marginLeft:"auto"},children:e(f,{name:"action.remove"})})]})]})}),x?e(j,{container:r,ctx:i}):null]})}),j=s(({container:n,ctx:t})=>{const{store:r}=t,i=n.children.slice().reverse(),l=i.map(e=>({id:e.id})),s=m(),o=n!==r.activePage;return e(h,{list:l,setList:e=>{const t=e.filter(e=>null!=e&&null!=e.id);t.forEach((e,i)=>{const l=t.length-i-1,s=r.getElementById(e.id);s&&n.children.indexOf(s)!==l&&n.setElementZIndex(s.id,l)})},group:n.id,direction:"horizontal",handle:s?".drag-handle":void 0,className:o?"pn:ml-4":void 0,children:i.map(n=>e(E,{element:n,ctx:t},n.id))})});export const LayersPanel=s(({store:s})=>{const o=s.activePage,[a]=t.useState(()=>i.map()),d=t.useRef(null);t.useEffect(()=>l(()=>{const e=[];return s.selectedElements.forEach(n=>{for(let t=n.parent;t&&"group"===t.type;t=t.parent){e.push(t.id)}}),e},r(e=>{e.forEach(e=>a.set(e,!0))}),{equals:(e,n)=>e.length===n.length&&e.every((e,t)=>e===n[t]),fireImmediately:!0}),[s,a]);const c=t.useMemo(()=>({store:s,expandedIds:a,toggleExpanded:r(e=>{a.delete(e)||a.set(e,!0)}),onRowMouseDown:(e,n)=>{const t=s.activePage;if(!t){return}const r=x({clickedId:e,selectedIds:s.selectedElementsIds,anchorId:d.current,rows:b(t,a,e=>k(s,e)),modifiers:n,getParentId:e=>y(s,e)});d.current=r.anchorId,s.selectElements(r.selectedIds)}}),[s,a]);return n(v,{children:[e("div",{style:{height:"40px",paddingTop:"5px"},children:p("sidePanel.layersTip")}),n("div",{children:[o&&0!==o.children.length?null:e("div",{children:p("sidePanel.noLayers")}),o?e(j,{container:o,ctx:c}):null]})]})});
@@ -1,3 +1 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { cn } from '../lib/utils.js';
3
- export const SectionTab = ({ children, name, onClick, active, iconSize, }) => (_jsxs("div", { role: "button", onClick: onClick, className: cn('polotno-side-panel-tab pn-section-tab pn:w-full pn:cursor-pointer pn:whitespace-pre pn:text-center pn:text-[12px]', 'pn:pt-[15px] pn:pl-[5px] pn:pr-[5px] pn:h-[72px]', 'pn:max-md:h-[54px] pn:max-md:pt-[9px] pn:max-md:min-w-[72px] pn:max-md:w-min', 'pn:pn-mobile:h-[54px] pn:pn-mobile:pt-[9px] pn:pn-mobile:min-w-[72px] pn:pn-mobile:w-min', 'pn:hover:bg-sidebar-accent pn:hover:text-sidebar-accent-foreground', active && 'active pn:bg-sidebar-accent pn:text-sidebar-accent-foreground'), children: [_jsx("div", { style: { fontSize: (iconSize || 14) + 'px' }, children: children }), _jsx("div", { style: { paddingTop: '5px' }, children: name })] }));
1
+ import{jsx as n,jsxs as e}from"react/jsx-runtime";import{cn as p}from"../lib/utils.js";export const SectionTab=({children:t,name:i,onClick:r,active:o,iconSize:a})=>e("div",{role:"button",tabIndex:0,onClick:r,onKeyDown:n=>{"Enter"!==n.key&&" "!==n.key||(n.preventDefault(),n.currentTarget.click())},className:p("polotno-side-panel-tab pn-section-tab pn:w-full pn:cursor-pointer pn:whitespace-pre pn:text-center pn:text-[12px]","pn:pt-[15px] pn:pl-[5px] pn:pr-[5px] pn:h-[72px]","pn:max-md:h-[54px] pn:max-md:pt-[9px] pn:max-md:min-w-[72px] pn:max-md:w-min","pn:pn-mobile:h-[54px] pn:pn-mobile:pt-[9px] pn:pn-mobile:min-w-[72px] pn:pn-mobile:w-min","pn:hover:bg-sidebar-accent pn:hover:text-sidebar-accent-foreground",o&&"active pn:bg-sidebar-accent pn:text-sidebar-accent-foreground"),children:[n("div",{style:{fontSize:(a||14)+"px"},children:t}),n("div",{style:{paddingTop:"5px"},children:i})]});
@@ -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 a,TooltipTrigger as s}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 f,extendToolbar as d}from"./element-container.js";import u 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{editorHtml as S}from"../canvas/rich-editor.js";import{FontMenu as F,fetcher as z,TextSpacing as j,TextFontSize as A,ALIGN_OPTIONS as C,VERTICAL_ALIGN_OPTIONS as N,VERTICAL_ALIGN_ICONS as w}from"./text-toolbar.js";import{cycleNext as E,usedFontFamilies as k}from"./toolbar-shared.js";import D from"swr";import{getFontsList as L,globalFonts as M,isGoogleFontChanged as P}from"../utils/fonts.js";import{getGoogleFontsListAPI as I}from"../utils/api.js";import{quillHtmlToModelText as R,listEffectiveFontFamilies as O,isBoldWeight as W}from"../utils/rich-text-html.js";import{patchTextFormat as B,decorationTokensToString as H,isDecorationActive as V}from"../utils/text-format.js";import{activeFor as _,useTextFormat as G,resolveSelectionScope as J,applyToLiveEditor as U,restoreEditorSelection as X}from"../utils/text-format-state.js";const $=u("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 a,TooltipTrigger as s}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 f,extendToolbar as d}from"./element-container.js";import u 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{editorHtml as F}from"../canvas/rich-editor.js";import{FontMenu as S,fetcher as z,TextSpacing as j,TextFontSize as A,ALIGN_OPTIONS as C,VERTICAL_ALIGN_OPTIONS as N,VERTICAL_ALIGN_ICONS as E}from"./text-toolbar.js";import{cycleNext as w,usedFontFamilies as k}from"./toolbar-shared.js";import D from"swr";import{getFontsList as L,globalFonts as M,isGoogleFontChanged as P}from"../utils/fonts.js";import{getGoogleFontsListAPI as I}from"../utils/api.js";import{quillHtmlToModelText as R,listEffectiveFontFamilies as O,isBoldWeight as B}from"../utils/rich-text-html.js";import{patchTextFormat as H,isDecorationActive as V,formatToggle as W}from"../utils/text-format.js";import{activeFor as _,useTextFormat as G,resolveSelectionScope as J,applyToLiveEditor as U,restoreEditorSelection as X}from"../utils/text-format-state.js";const $=u("div")`
2
2
  position: relative;
3
3
  display: inline-block;
4
4
 
@@ -25,4 +25,4 @@ import{jsx as t,jsxs as e}from"react/jsx-runtime";import o from"react";import{ob
25
25
  pointer-events: none;
26
26
  font-size: inherit;
27
27
  color: inherit;
28
- `;let K=null;const Q=()=>{b.pendingToolbarInteraction=!0,K&&clearTimeout(K),K=setTimeout(()=>{b.pendingToolbarInteraction=!1,K=null},100)},Y=t=>{var e;(!(e=t.target)||"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName&&"SELECT"!==e.tagName&&!e.isContentEditable)&&t.preventDefault(),Q()},Z=n(({store:e,isActive:o,toggle:n,icon:i,ariaLabel:l,tooltipContent:r})=>{const{format:a,applyTextFormat:s}=G(e);return t(c,{label:r||l||"",active:o(a),onMouseDown:t=>{t.preventDefault()},onClick:()=>n(a,s),children:i})});function tt(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),H(n)}const et=(t,e,o)=>e({textDecoration:tt(t,o)},{decorationTokens:[o]});export const TextBold=n(({store:e})=>t(Z,{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")}));const ot=n(({store:e})=>t("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:t(Z,{store:e,isActive:t=>"uppercase"===t.textTransform.value,toggle:(t,e)=>e({textTransform:"uppercase"===t.textTransform.value?"none":"uppercase"}),icon:t(i,{name:"text.uppercase",className:"pn:size-4"}),tooltipContent:h("toolbar.uppercase")})}));export const FontStyleGroup=n(({element:o,store:n,elements:m,components:p})=>{const f=(null==p?void 0:p.TextBold)||TextBold;return e("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:[t(f,{element:o,store:n}),t(Z,{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(Z,{store:n,isActive:t=>V(t,"underline"),toggle:(t,e)=>et(t,e,"underline"),icon:t(i,{name:"text.underline",className:"pn:size-4"}),tooltipContent:h("toolbar.underline")}),t(Z,{store:n,isActive:t=>V(t,"line-through"),toggle:(t,e)=>et(t,e,"line-through"),icon:t(i,{name:"text.strikethrough",className:"pn:size-4"}),tooltipContent:h("toolbar.strikethrough")}),t(c,{label:h("toolbar.textAlign"),onClick:()=>{const t=E(C,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(s,{render:t(l,{variant:"ghost",size:"icon-sm",onClick:()=>{const t=E(N,o.verticalAlign);n.history.transaction(()=>{m.forEach(e=>{e.set({verticalAlign:t})})})},"aria-label":h("toolbar.verticalAlign"),children:w[o.verticalAlign]})}),t(a,{children:h("toolbar.verticalAlign")})]}),t(c,{label:h("toolbar.listFormat"),onMouseDown:t=>{t.preventDefault()},onClick:()=>{const t=t=>t?"bullet"===t&&"ordered":"bullet",e=_(n);if(e){const o=e.instance,n=o.getSelection(!0)||e.lastSelection||{index:0,length:o.getLength()};return void o.format("list",t(o.getFormat(n).list))}const o=(({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:S(m[0])});try{const e=t(o.getFormat(0,o.getLength()).list);n.history.transaction(()=>{m.forEach((t,n)=>{n>0&&y(o,S(t)),o.formatLine(0,o.getLength(),"list",e),t.set({text:R(o.root.innerHTML,{fontSize:t.fontSize,fontFamily:t.fontFamily})})})})}finally{(t=>{t.root.parentElement.remove()})(o)}},children:"bullet"===(null!==(u=null===(d=_(n))||void 0===d?void 0:d.currentFormat)&&void 0!==u?u:{}).list?t(i,{name:"text.numberedList",className:"pn:size-5"}):t(i,{name:"text.bulletList",className:"pn:size-5"})})]});var d,u});export const FontColorInput=n(({element:e,store:o})=>{var n;const{format:i,applyTextFormat:l}=G(o);return t("div",{"data-polotno-keep-focus":!0,onMouseDown:Y,children:t(m,{value:null!==(n=i.fill.value)&&void 0!==n?n:e.fill,gradientEnabled:!0,onClose:()=>{const t=_(o);(null==t?void 0:t.lastSelection)&&X(t.instance,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,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 nt=L(),it=n(({elements:e,store:n})=>{var i;const{format:l,applyTextFormat:r}=G(n),a=!!_(n),s=l.fontFamily.mixed,c=s?Array.from(new Set(e.flatMap(t=>O(t.text,t.fontFamily)))).sort((t,e)=>t.localeCompare(e,void 0,{sensitivity:"base"})):void 0,[m,p]=o.useState(!1),{data:f,mutate:d}=D(m?I():null,z,{isPaused:()=>P(),fallbackData:[]});o.useEffect(()=>{d()},[P()]);const u=n.fonts.concat(M).map(t=>t.fontFamily).concat((null==f?void 0:f.length)&&!P()?f:nt),x=k(n),g=[...new Set(x.concat("_divider").concat(u))],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:s,mixedFonts:c,open:m,onOpenChange:p,onFontSelect:t=>r({fontFamily:t})});return a?t("div",{"data-polotno-keep-focus":!0,onMouseDown:Y,children:b}):b}),lt=n(({elements:o,store:n})=>{const{format:i}=G(n),l=!!_(n),r=i.fontSize.mixed,a=i.fontSize.value,s=o.map(t=>new Proxy(t,{get:(t,e)=>"fontSize"===e?null!=a?a:t.fontSize:"set"===e?e=>((t,e)=>{if(!e.fontSize){return void t.set(e)}const o=_(n);if(o){const{scope:t,isEmpty:n}=J(o.instance,o.lastSelection);if("partial"===t||"collapsed"===t&&n){return void U(o.instance,{fontSize:e.fontSize},o.lastSelection)}}const{attrsToSet:i}=B(t,{fontSize:e.fontSize});t.set(Object.assign(Object.assign({},e),i))})(t,e):Reflect.get(t,e)})),c=e($,{className:r?"polotno-mixed":"",children:[t(A,{elements:s,store:n}),r&&t(q,{className:"polotno-fs-mixed-overlay","aria-hidden":!0,children:"—"})]});return l?t("div",{"data-polotno-keep-focus":!0,onMouseDown:Q,children:c}):c});export const PROPS_MAP={TextFontFamily:it,TextFontSize:lt,TextFontVariant:FontStyleGroup,TextTransform:ot,TextFilters:p,TextFill:FontColorInput,TextSpacing:j,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(f,{items:r,itemRender:l=>{if("TextBold"===l){return null}const r=(null==o?void 0:o[l])||PROPS_MAP[l];return t(r,{element:i,elements:n,store:e,components:o},l)}})});
28
+ `;let K=null;const Q=()=>{b.pendingToolbarInteraction=!0,K&&clearTimeout(K),K=setTimeout(()=>{b.pendingToolbarInteraction=!1,K=null},100)},Y=t=>{var e;(!(e=t.target)||"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName&&"SELECT"!==e.tagName&&!e.isContentEditable)&&t.preventDefault(),Q()},Z=n(({store:e,isActive:o,toggle:n,icon:i,ariaLabel:l,tooltipContent:r})=>{const{format:a,applyTextFormat:s}=G(e);return t(c,{label:r||l||"",active:o(a),onMouseDown:t=>{t.preventDefault()},onClick:()=>n(a,s),children:i})}),tt=t=>(e,o)=>{const{attrs:n,opts:i}=W(e,t);o(n,i)};export const TextBold=n(({store:e})=>t(Z,{store:e,isActive:t=>B(t.fontWeight.value),toggle:tt("bold"),icon:t(i,{name:"text.bold",className:"pn:size-4"}),tooltipContent:h("toolbar.bold")}));const et=n(({store:e})=>t("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:t(Z,{store:e,isActive:t=>"uppercase"===t.textTransform.value,toggle:(t,e)=>e({textTransform:"uppercase"===t.textTransform.value?"none":"uppercase"}),icon:t(i,{name:"text.uppercase",className:"pn:size-4"}),tooltipContent:h("toolbar.uppercase")})}));export const FontStyleGroup=n(({element:o,store:n,elements:m,components:p})=>{const f=(null==p?void 0:p.TextBold)||TextBold;return e("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:[t(f,{element:o,store:n}),t(Z,{store:n,isActive:t=>"italic"===t.fontStyle.value,toggle:tt("italic"),icon:t(i,{name:"text.italic",className:"pn:size-4"}),tooltipContent:h("toolbar.italic")}),t(Z,{store:n,isActive:t=>V(t,"underline"),toggle:tt("underline"),icon:t(i,{name:"text.underline",className:"pn:size-4"}),tooltipContent:h("toolbar.underline")}),t(Z,{store:n,isActive:t=>V(t,"line-through"),toggle:tt("line-through"),icon:t(i,{name:"text.strikethrough",className:"pn:size-4"}),tooltipContent:h("toolbar.strikethrough")}),t(c,{label:h("toolbar.textAlign"),onClick:()=>{const t=w(C,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(s,{render:t(l,{variant:"ghost",size:"icon-sm",onClick:()=>{const t=w(N,o.verticalAlign);n.history.transaction(()=>{m.forEach(e=>{e.set({verticalAlign:t})})})},"aria-label":h("toolbar.verticalAlign"),children:E[o.verticalAlign]})}),t(a,{children:h("toolbar.verticalAlign")})]}),t(c,{label:h("toolbar.listFormat"),onMouseDown:t=>{t.preventDefault()},onClick:()=>{const t=t=>t?"bullet"===t&&"ordered":"bullet",e=_(n);if(e){const o=e.instance,n=o.getSelection(!0)||e.lastSelection||{index:0,length:o.getLength()};return void o.format("list",t(o.getFormat(n).list))}const o=(({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:F(m[0])});try{const e=t(o.getFormat(0,o.getLength()).list);n.history.transaction(()=>{m.forEach((t,n)=>{n>0&&y(o,F(t)),o.formatLine(0,o.getLength(),"list",e),t.set({text:R(o.root.innerHTML,{fontSize:t.fontSize,fontFamily:t.fontFamily})})})})}finally{(t=>{t.root.parentElement.remove()})(o)}},children:"bullet"===(null!==(u=null===(d=_(n))||void 0===d?void 0:d.currentFormat)&&void 0!==u?u:{}).list?t(i,{name:"text.numberedList",className:"pn:size-5"}):t(i,{name:"text.bulletList",className:"pn:size-5"})})]});var d,u});export const FontColorInput=n(({element:e,store:o})=>{var n;const{format:i,applyTextFormat:l}=G(o);return t("div",{"data-polotno-keep-focus":!0,onMouseDown:Y,children:t(m,{value:null!==(n=i.fill.value)&&void 0!==n?n:e.fill,gradientEnabled:!0,onClose:()=>{const t=_(o);(null==t?void 0:t.lastSelection)&&X(t.instance,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,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 ot=L(),nt=n(({elements:e,store:n})=>{var i;const{format:l,applyTextFormat:r}=G(n),a=!!_(n),s=l.fontFamily.mixed,c=s?Array.from(new Set(e.flatMap(t=>O(t.text,t.fontFamily)))).sort((t,e)=>t.localeCompare(e,void 0,{sensitivity:"base"})):void 0,[m,p]=o.useState(!1),{data:f,mutate:d}=D(m?I():null,z,{isPaused:()=>P(),fallbackData:[]});o.useEffect(()=>{d()},[P()]);const u=n.fonts.concat(M).map(t=>t.fontFamily).concat((null==f?void 0:f.length)&&!P()?f:ot),x=k(n),g=[...new Set(x.concat("_divider").concat(u))],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(S,{fonts:g,activeFont:v,activeFontLabel:h,store:n,mixed:s,mixedFonts:c,open:m,onOpenChange:p,onFontSelect:t=>r({fontFamily:t})});return a?t("div",{"data-polotno-keep-focus":!0,onMouseDown:Y,children:b}):b}),it=n(({elements:o,store:n})=>{const{format:i}=G(n),l=!!_(n),r=i.fontSize.mixed,a=i.fontSize.value,s=o.map(t=>new Proxy(t,{get:(t,e)=>"fontSize"===e?null!=a?a:t.fontSize:"set"===e?e=>((t,e)=>{if(!e.fontSize){return void t.set(e)}const o=_(n);if(o){const{scope:t,isEmpty:n}=J(o.instance,o.lastSelection);if("partial"===t||"collapsed"===t&&n){return void U(o.instance,{fontSize:e.fontSize},o.lastSelection)}}const{attrsToSet:i}=H(t,{fontSize:e.fontSize});t.set(Object.assign(Object.assign({},e),i))})(t,e):Reflect.get(t,e)})),c=e($,{className:r?"polotno-mixed":"",children:[t(A,{elements:s,store:n}),r&&t(q,{className:"polotno-fs-mixed-overlay","aria-hidden":!0,children:"—"})]});return l?t("div",{"data-polotno-keep-focus":!0,onMouseDown:Q,children:c}):c});export const PROPS_MAP={TextFontFamily:nt,TextFontSize:it,TextFontVariant:FontStyleGroup,TextTransform:et,TextFilters:p,TextFill:FontColorInput,TextSpacing:j,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(f,{items:r,itemRender:l=>{if("TextBold"===l){return null}const r=(null==o?void 0:o[l])||PROPS_MAP[l];return t(r,{element:i,elements:n,store:e,components:o},l)}})});
@@ -1 +1 @@
1
- import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{List as i}from"react-window";import r from"swr";import{PolotnoIcon as a}from"../icons/registry.js";import{getFontsList as l,globalFonts as s,isGoogleFontChanged as c}from"../utils/fonts.js";import{getGoogleFontImage as p,getGoogleFontsListAPI as m}from"../utils/api.js";import{t as d}from"../utils/l10n.js";import{flags as f}from"../utils/flags.js";import{Button as h}from"../primitives/button.js";import{NumberInput as u}from"../primitives/numeric-input.js";export{NumberInput}from"../primitives/numeric-input.js";import{InputGroup as x}from"../primitives/input-group.js";import{SliderField as g}from"../primitives/slider-field.js";import{CELL_PADDING_FIELDS as v,PaddingControl as b,TEXT_PADDING_FIELDS as y,cellPaddingSides as F,paddingAttrs as T}from"./padding-control.js";import{textPadding as N}from"@polotno/core/text-types";import{Popover as C,PopoverContent as S,PopoverTrigger as j}from"../primitives/popover.js";import{Tooltip as w,TooltipContent as z,TooltipTrigger as E}from"../primitives/tooltip.js";import{TooltipIconButton as D}from"../primitives/tooltip-icon-button.js";import{Separator as A}from"../primitives/separator.js";import{cn as k}from"../lib/utils.js";import{cycleNext as O,usedFontFamilies as I}from"./toolbar-shared.js";import{isBoldWeight as L}from"@polotno/core/rich-text-html";import{cssFontFamily as M}from"@polotno/core/fonts";import{ColorPicker as V}from"./color-picker.js";import _ from"./filters-picker.js";import{AnimationsPicker as P}from"./animations-picker.js";import{renderToolbarItems as R}from"./element-container.js";import{TextAiWrite as G}from"./text-ai-write.js";import{unboundWrite as H}from"../model/node-model.js";const B=l(),W=({fontFamily:t,handleClick:o,modifiers:i,store:r,isCustom:a})=>{const[l,s]=n.useState(!a);if(n.useEffect(()=>{l||r.loadFont(t)},[t,l]),"_divider"===t){return e("div",{style:{paddingTop:"10px"},children:e(A,{})})}const c=l?e("img",{src:p(t),alt:t,onError:()=>{s(!1)},className:"pn:h-5 pn:dark:invert"}):t;return e("button",{type:"button",onClick:o,disabled:i.disabled,"data-active":i.active||void 0,className:k("pn:flex pn:w-full pn:items-center pn:rounded-sm pn:px-2 pn:py-1.5 pn:text-left pn:text-sm pn:hover:bg-muted",i.active&&"pn:bg-muted"),style:{fontFamily:M(t)},children:c})},$=({index:t,style:n,filteredFonts:o,activeFont:i,onFontSelect:r,store:a})=>{const l=o[t];return e("div",{style:n,children:e(W,{fontFamily:l,modifiers:{active:i===l},handleClick:()=>r(l),store:a,isCustom:a.fonts.find(e=>e.fontFamily===l)||s.find(e=>e.fontFamily===l)},l)})},J=({onChange:o,defaultValue:i})=>{const r=n.useRef(null);return n.useEffect(()=>{r.current&&r.current.focus()},[]),t(x,{children:[e("span",{className:"pn:flex pn:items-center pn:pl-2 pn:pr-1 pn:text-muted-foreground",children:e(a,{name:"action.search",className:"pn:size-3.5 pn:shrink-0 pn:opacity-50"})}),e("input",{ref:r,"data-slot":"input-group-control",defaultValue:i,onChange:e=>o(e.target.value),className:"pn:h-full pn:w-full pn:flex-1 pn:border-0 pn:bg-transparent pn:px-2 pn:text-xs pn:outline-none pn:placeholder:text-muted-foreground"})]})};export const FontMenu=({store:o,fonts:r,activeFont:l,activeFontLabel:s,onFontSelect:c,mixed:p,mixedFonts:m,open:f,onOpenChange:u})=>{const[x,g]=n.useState(""),v=r.filter(e=>(null==e?void 0:e.toLowerCase().indexOf(x.toLowerCase()))>=0);return t(C,{open:f,onOpenChange:u,children:[t(w,{children:[e(E,{render:e(j,{render:t(h,{variant:"ghost",size:"sm",className:"pn:gap-1 pn:overflow-hidden pn:whitespace-nowrap",style:{fontFamily:p?void 0:M(l),fontStyle:p?"italic":void 0,color:p?"#5c7080":void 0},"aria-label":d("toolbar.fontFamily"),children:[e("span",{className:"pn:truncate",children:p?d("toolbar.fontFamilyMixed"):s}),e(a,{name:"ui.chevronDown",className:"pn:size-3 pn:shrink-0 pn:opacity-50"})]})})}),e(z,{children:p&&m&&m.length>0?`${d("toolbar.fontsInSelection")}: ${m.join(", ")}`:d("toolbar.fontFamily")})]}),e(S,{className:"pn:w-[230px] pn:p-2",align:"start",children:t("div",{children:[e(J,{onChange:e=>g(e),defaultValue:x}),e("div",{style:{paddingTop:"5px"},children:e(i,{style:{height:Math.min(400,30*v.length)+10,width:210},rowCount:v.length,rowHeight:30,rowComponent:$,rowProps:{filteredFonts:v,activeFont:l,onFontSelect:c,store:o}})})]})})]})};const q={};export const fetcher=e=>q[e]?Promise.resolve(q[e]):fetch(e).then(e=>e.json()).then(t=>(q[e]=t,t));export const TextFontFamily=o(({elements:t,store:o})=>{const[i,a]=n.useState(!1),{data:l,mutate:p}=r(i?m():null,fetcher,{isPaused:()=>c(),fallbackData:[]});n.useEffect(()=>{p()},[c()]);const d=o.fonts.concat(s).map(e=>e.fontFamily).concat((null==l?void 0:l.length)&&!c()?l:B);let f=t[0].fontFamily;f.length>15&&(f=f.slice(0,15)+"...");const h=I(o),u=[...new Set(h.concat("_divider").concat(d))];return e(FontMenu,{fonts:u,activeFont:t[0].fontFamily,activeFontLabel:f,store:o,open:i,onOpenChange:a,onFontSelect:e=>{o.history.transaction(()=>{t.forEach(t=>{t.set({fontFamily:e})})})}})});export const TextFontSize=o(({elements:o,store:i})=>{const[r,a]=n.useState(!1),[l,s]=n.useState(!1);return t(w,{open:!l&&r,onOpenChange:e=>{l||a(e)},children:[e(E,{render:e(u,{"aria-label":d("toolbar.fontSize"),onFocus:()=>s(!0),onBlur:()=>s(!1),onValueChange:e=>{i.history.transaction(()=>{o.forEach(t=>{t.set({fontSize:e,width:Math.max(e,t.width)})})})},value:Math.round(100*o[0].fontSize)/100,style:{width:"50px"},min:5,max:4*i.height})}),e(z,{children:d("toolbar.fontSize")})]})});export const ALIGN_OPTIONS=["left","center","right","justify"];export const VERTICAL_ALIGN_OPTIONS=["top","middle","bottom"];export const VERTICAL_ALIGN_ICONS={top:e(a,{name:"text.valignTop",className:"pn:size-4"}),middle:e(a,{name:"text.valignMiddle",className:"pn:size-4"}),bottom:e(a,{name:"text.valignBottom",className:"pn:size-4"})};export const TextFontVariant=o(({elements:n,store:o})=>{const i=n[0],r=L(i.fontWeight),l="italic"===i.fontStyle,s=i.textDecoration.indexOf("underline")>=0,c=i.textDecoration.indexOf("line-through")>=0;return t("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:[t(w,{children:[e(E,{render:e(h,{variant:"ghost",size:"icon-sm",onMouseDown:e=>{e.preventDefault()},onClick:()=>{const e=O(ALIGN_OPTIONS,i.align);o.history.transaction(()=>{n.forEach(t=>{t.set({align:e})})})},"aria-label":d("toolbar.textAlign"),children:"left"===i.align?e(a,{name:"text.alignLeft",className:"pn:size-4"}):"center"===i.align?e(a,{name:"text.alignCenter",className:"pn:size-4"}):"right"===i.align?e(a,{name:"text.alignRight",className:"pn:size-4"}):e(a,{name:"text.alignJustify",className:"pn:size-4"})})}),e(z,{children:d("toolbar.textAlign")})]}),f.textVerticalResizeEnabled&&t(w,{children:[e(E,{render:e(h,{variant:"ghost",size:"icon-sm",onMouseDown:e=>{e.preventDefault()},onClick:()=>{const e=O(VERTICAL_ALIGN_OPTIONS,i.verticalAlign);o.history.transaction(()=>{n.forEach(t=>{t.set({verticalAlign:e})})})},"aria-label":d("toolbar.verticalAlign"),children:VERTICAL_ALIGN_ICONS[i.verticalAlign]})}),e(z,{children:d("toolbar.verticalAlign")})]}),e(D,{label:d("toolbar.bold"),active:r,onMouseDown:e=>{e.preventDefault()},onClick:()=>{const e=L(i.fontWeight);o.history.transaction(()=>{n.forEach(t=>{t.set({fontWeight:e?"400":"700"})})})},children:e(a,{name:"text.bold",className:"pn:size-4"})}),e(D,{label:d("toolbar.italic"),active:l,onMouseDown:e=>{e.preventDefault()},onClick:()=>{const e="italic"===i.fontStyle;o.history.transaction(()=>{n.forEach(t=>{e?t.set({fontStyle:"normal"}):t.set({fontStyle:"italic"})})})},children:e(a,{name:"text.italic",className:"pn:size-4"})}),e(D,{label:d("toolbar.underline"),active:s,onMouseDown:e=>{e.preventDefault()},onClick:()=>{let e=i.textDecoration.split(" ");e.indexOf("underline")>=0?e=e.filter(e=>"underline"!==e):e.push("underline"),o.history.transaction(()=>{n.forEach(t=>{t.set({textDecoration:e.join(" ")})})})},children:e(a,{name:"text.underline",className:"pn:size-4"})}),e(D,{label:d("toolbar.strikethrough"),active:c,onMouseDown:e=>{e.preventDefault()},onClick:()=>{let e=i.textDecoration.split(" ");e.indexOf("line-through")>=0?e=e.filter(e=>"line-through"!==e):e.push("line-through"),o.history.transaction(()=>{n.forEach(t=>{t.set({textDecoration:e.join(" ")})})})},children:e(a,{name:"text.strikethrough",className:"pn:size-4"})})]})});export const TextTransform=o(({elements:t,store:n})=>{const o="uppercase"==t[0].textTransform;return e("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:e(D,{label:d("toolbar.uppercase"),active:o,onMouseDown:e=>{e.preventDefault()},onClick:()=>{n.history.transaction(()=>{t.forEach(e=>{e.set({textTransform:"uppercase"===e.textTransform?"none":"uppercase"})})})},children:e(a,{name:"text.uppercase",className:"pn:size-4"})})})});export const TextFill=o(({elements:t,store:n})=>{var o;return e(V,{value:null!==(o=t[0].filled.fill)&&void 0!==o?o:t[0].fill,gradientEnabled:!0,onChange:e=>n.history.transaction(()=>{t.forEach(t=>{t.set(H(t,{fill:e}))})}),store:n})});export const TextSpacing=o(({elements:n,store:o})=>{const i=n[0],r=i,l="tablecell"===i.type?{label:d("toolbar.cellPadding"),value:F(i),fields:v,disabled:!1}:{label:d("toolbar.textPadding"),value:N({paddingTop:r.paddingTop,paddingRight:r.paddingRight,paddingBottom:r.paddingBottom,paddingLeft:r.paddingLeft}),fields:y,disabled:!!r.curveEnabled},s=e=>{o.history.transaction(()=>{n.forEach(t=>{t.set(e)})})},c="number"==typeof i.lineHeight?100*i.lineHeight:120;return t(C,{children:[t(w,{children:[e(E,{render:e(j,{render:e(h,{variant:"ghost",size:"icon-sm","aria-label":d("toolbar.spacing"),children:e(a,{name:"text.spacing",className:"pn:size-5"})})})}),e(z,{children:d("toolbar.spacing")})]}),t(S,{align:"start",className:"pn:w-[270px] pn:p-[15px]",children:[e(g,{label:d("toolbar.lineHeight"),value:Math.round(c),onChange:e=>s({lineHeight:e/100}),min:50,max:250}),e(g,{label:d("toolbar.letterSpacing"),value:Math.round(100*i.letterSpacing),onChange:e=>s({letterSpacing:e/100}),min:-50,max:250}),e("div",{className:"pn:mt-2 pn:border-t pn:pt-2",children:e(b,{label:l.label,value:l.value,disabled:l.disabled,onChange:e=>s(T(e,l.fields))},i.id)})]})]})});export const TextFilters=_;export const TextAnimations=P;export const TextToolbar=o(({store:e,components:t})=>{const n=e.selectedElements;return R({type:"text",components:t,controlProps:{store:e,element:n[0],elements:n},controls:{TextFill,TextFontFamily,TextFontSize,TextFontVariant,TextSpacing,TextTransform,TextFilters:_,TextAnimations:f.animationsEnabled&&P,TextAiWrite:f.aiTextEnabled&&G}})});export default TextToolbar;
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{List as i}from"react-window";import r from"swr";import{PolotnoIcon as a}from"../icons/registry.js";import{getFontsList as l,globalFonts as s,isGoogleFontChanged as c}from"../utils/fonts.js";import{getGoogleFontImage as p,getGoogleFontsListAPI as m}from"../utils/api.js";import{t as d}from"../utils/l10n.js";import{flags as f}from"../utils/flags.js";import{Button as h}from"../primitives/button.js";import{NumberInput as u}from"../primitives/numeric-input.js";export{NumberInput}from"../primitives/numeric-input.js";import{InputGroup as x}from"../primitives/input-group.js";import{SliderField as g}from"../primitives/slider-field.js";import{CELL_PADDING_FIELDS as v,PaddingControl as b,TEXT_PADDING_FIELDS as y,cellPaddingSides as F,paddingAttrs as T}from"./padding-control.js";import{textPadding as N}from"@polotno/core/text-types";import{Popover as C,PopoverContent as S,PopoverTrigger as j}from"../primitives/popover.js";import{Tooltip as w,TooltipContent as z,TooltipTrigger as E}from"../primitives/tooltip.js";import{TooltipIconButton as D}from"../primitives/tooltip-icon-button.js";import{Separator as A}from"../primitives/separator.js";import{cn as k}from"../lib/utils.js";import{cycleNext as O,usedFontFamilies as I}from"./toolbar-shared.js";import{isBoldWeight as L}from"@polotno/core/rich-text-html";import{cssFontFamily as M}from"@polotno/core/fonts";import{ColorPicker as P}from"./color-picker.js";import V from"./filters-picker.js";import{AnimationsPicker as _}from"./animations-picker.js";import{renderToolbarItems as R}from"./element-container.js";import{TextAiWrite as G}from"./text-ai-write.js";import{unboundWrite as H}from"../model/node-model.js";const B=l(),W=({fontFamily:t,handleClick:o,modifiers:i,store:r,isCustom:a})=>{const[l,s]=n.useState(!a);if(n.useEffect(()=>{l||r.loadFont(t)},[t,l]),"_divider"===t){return e("div",{style:{paddingTop:"10px"},children:e(A,{})})}const c=l?e("img",{src:p(t),alt:t,onError:()=>{s(!1)},className:"pn:h-5 pn:dark:invert"}):t;return e("button",{type:"button",onClick:o,disabled:i.disabled,"data-active":i.active||void 0,"aria-pressed":!!i.active,className:k("pn:flex pn:w-full pn:items-center pn:rounded-sm pn:px-2 pn:py-1.5 pn:text-left pn:text-sm pn:hover:bg-muted",i.active&&"pn:bg-muted"),style:{fontFamily:M(t)},children:c})},$=({index:t,style:n,filteredFonts:o,activeFont:i,onFontSelect:r,store:a})=>{const l=o[t];return e("div",{style:n,children:e(W,{fontFamily:l,modifiers:{active:i===l},handleClick:()=>r(l),store:a,isCustom:a.fonts.find(e=>e.fontFamily===l)||s.find(e=>e.fontFamily===l)},l)})},J=({onChange:o,defaultValue:i})=>{const r=n.useRef(null);return n.useEffect(()=>{r.current&&r.current.focus()},[]),t(x,{children:[e("span",{className:"pn:flex pn:items-center pn:pl-2 pn:pr-1 pn:text-muted-foreground",children:e(a,{name:"action.search",className:"pn:size-3.5 pn:shrink-0 pn:opacity-50"})}),e("input",{ref:r,"data-slot":"input-group-control","aria-label":d("sidePanel.searchPlaceholder"),defaultValue:i,onChange:e=>o(e.target.value),className:"pn:h-full pn:w-full pn:flex-1 pn:border-0 pn:bg-transparent pn:px-2 pn:text-xs pn:outline-none pn:placeholder:text-muted-foreground"})]})};export const FontMenu=({store:o,fonts:r,activeFont:l,activeFontLabel:s,onFontSelect:c,mixed:p,mixedFonts:m,open:f,onOpenChange:u})=>{const[x,g]=n.useState(""),v=r.filter(e=>(null==e?void 0:e.toLowerCase().indexOf(x.toLowerCase()))>=0);return t(C,{open:f,onOpenChange:u,children:[t(w,{children:[e(E,{render:e(j,{render:t(h,{variant:"ghost",size:"sm",className:"pn:gap-1 pn:overflow-hidden pn:whitespace-nowrap",style:{fontFamily:p?void 0:M(l),fontStyle:p?"italic":void 0,color:p?"#5c7080":void 0},"aria-label":d("toolbar.fontFamily"),children:[e("span",{className:"pn:truncate",children:p?d("toolbar.fontFamilyMixed"):s}),e(a,{name:"ui.chevronDown",className:"pn:size-3 pn:shrink-0 pn:opacity-50"})]})})}),e(z,{children:p&&m&&m.length>0?`${d("toolbar.fontsInSelection")}: ${m.join(", ")}`:d("toolbar.fontFamily")})]}),e(S,{className:"pn:w-[230px] pn:p-2",align:"start","aria-label":d("toolbar.fontFamily"),children:t("div",{children:[e(J,{onChange:e=>g(e),defaultValue:x}),e("div",{style:{paddingTop:"5px"},children:e(i,{style:{height:Math.min(400,30*v.length)+10,width:210},rowCount:v.length,rowHeight:30,rowComponent:$,rowProps:{filteredFonts:v,activeFont:l,onFontSelect:c,store:o}})})]})})]})};const q={};export const fetcher=e=>q[e]?Promise.resolve(q[e]):fetch(e).then(e=>e.json()).then(t=>(q[e]=t,t));export const TextFontFamily=o(({elements:t,store:o})=>{const[i,a]=n.useState(!1),{data:l,mutate:p}=r(i?m():null,fetcher,{isPaused:()=>c(),fallbackData:[]});n.useEffect(()=>{p()},[c()]);const d=o.fonts.concat(s).map(e=>e.fontFamily).concat((null==l?void 0:l.length)&&!c()?l:B);let f=t[0].fontFamily;f.length>15&&(f=f.slice(0,15)+"...");const h=I(o),u=[...new Set(h.concat("_divider").concat(d))];return e(FontMenu,{fonts:u,activeFont:t[0].fontFamily,activeFontLabel:f,store:o,open:i,onOpenChange:a,onFontSelect:e=>{o.history.transaction(()=>{t.forEach(t=>{t.set({fontFamily:e})})})}})});export const TextFontSize=o(({elements:o,store:i})=>{const[r,a]=n.useState(!1),[l,s]=n.useState(!1);return t(w,{open:!l&&r,onOpenChange:e=>{l||a(e)},children:[e(E,{render:e(u,{"aria-label":d("toolbar.fontSize"),onFocus:()=>s(!0),onBlur:()=>s(!1),onValueChange:e=>{i.history.transaction(()=>{o.forEach(t=>{t.set({fontSize:e,width:Math.max(e,t.width)})})})},value:Math.round(100*o[0].fontSize)/100,style:{width:"50px"},min:5,max:4*i.height})}),e(z,{children:d("toolbar.fontSize")})]})});export const ALIGN_OPTIONS=["left","center","right","justify"];export const VERTICAL_ALIGN_OPTIONS=["top","middle","bottom"];export const VERTICAL_ALIGN_ICONS={top:e(a,{name:"text.valignTop",className:"pn:size-4"}),middle:e(a,{name:"text.valignMiddle",className:"pn:size-4"}),bottom:e(a,{name:"text.valignBottom",className:"pn:size-4"})};export const TextFontVariant=o(({elements:n,store:o})=>{const i=n[0],r=L(i.fontWeight),l="italic"===i.fontStyle,s=i.textDecoration.indexOf("underline")>=0,c=i.textDecoration.indexOf("line-through")>=0;return t("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:[t(w,{children:[e(E,{render:e(h,{variant:"ghost",size:"icon-sm",onMouseDown:e=>{e.preventDefault()},onClick:()=>{const e=O(ALIGN_OPTIONS,i.align);o.history.transaction(()=>{n.forEach(t=>{t.set({align:e})})})},"aria-label":d("toolbar.textAlign"),children:"left"===i.align?e(a,{name:"text.alignLeft",className:"pn:size-4"}):"center"===i.align?e(a,{name:"text.alignCenter",className:"pn:size-4"}):"right"===i.align?e(a,{name:"text.alignRight",className:"pn:size-4"}):e(a,{name:"text.alignJustify",className:"pn:size-4"})})}),e(z,{children:d("toolbar.textAlign")})]}),f.textVerticalResizeEnabled&&t(w,{children:[e(E,{render:e(h,{variant:"ghost",size:"icon-sm",disabled:!!i.curveEnabled,onMouseDown:e=>{e.preventDefault()},onClick:()=>{const e=O(VERTICAL_ALIGN_OPTIONS,i.verticalAlign);o.history.transaction(()=>{n.forEach(t=>{t.set({verticalAlign:e})})})},"aria-label":d("toolbar.verticalAlign"),children:VERTICAL_ALIGN_ICONS[i.verticalAlign]})}),e(z,{children:d("toolbar.verticalAlign")})]}),e(D,{label:d("toolbar.bold"),active:r,onMouseDown:e=>{e.preventDefault()},onClick:()=>{const e=L(i.fontWeight);o.history.transaction(()=>{n.forEach(t=>{t.set({fontWeight:e?"400":"700"})})})},children:e(a,{name:"text.bold",className:"pn:size-4"})}),e(D,{label:d("toolbar.italic"),active:l,onMouseDown:e=>{e.preventDefault()},onClick:()=>{const e="italic"===i.fontStyle;o.history.transaction(()=>{n.forEach(t=>{e?t.set({fontStyle:"normal"}):t.set({fontStyle:"italic"})})})},children:e(a,{name:"text.italic",className:"pn:size-4"})}),e(D,{label:d("toolbar.underline"),active:s,onMouseDown:e=>{e.preventDefault()},onClick:()=>{let e=i.textDecoration.split(" ");e.indexOf("underline")>=0?e=e.filter(e=>"underline"!==e):e.push("underline"),o.history.transaction(()=>{n.forEach(t=>{t.set({textDecoration:e.join(" ")})})})},children:e(a,{name:"text.underline",className:"pn:size-4"})}),e(D,{label:d("toolbar.strikethrough"),active:c,onMouseDown:e=>{e.preventDefault()},onClick:()=>{let e=i.textDecoration.split(" ");e.indexOf("line-through")>=0?e=e.filter(e=>"line-through"!==e):e.push("line-through"),o.history.transaction(()=>{n.forEach(t=>{t.set({textDecoration:e.join(" ")})})})},children:e(a,{name:"text.strikethrough",className:"pn:size-4"})})]})});export const TextTransform=o(({elements:t,store:n})=>{const o="uppercase"==t[0].textTransform;return e("div",{className:"pn:flex pn:items-center pn:gap-0.5",children:e(D,{label:d("toolbar.uppercase"),active:o,onMouseDown:e=>{e.preventDefault()},onClick:()=>{n.history.transaction(()=>{t.forEach(e=>{e.set({textTransform:"uppercase"===e.textTransform?"none":"uppercase"})})})},children:e(a,{name:"text.uppercase",className:"pn:size-4"})})})});export const TextFill=o(({elements:t,store:n})=>{var o;return e(P,{value:null!==(o=t[0].filled.fill)&&void 0!==o?o:t[0].fill,gradientEnabled:!0,onChange:e=>n.history.transaction(()=>{t.forEach(t=>{t.set(H(t,{fill:e}))})}),store:n})});export const TextSpacing=o(({elements:n,store:o})=>{const i=n[0],r=i,l="tablecell"===i.type?{label:d("toolbar.cellPadding"),value:F(i),fields:v,disabled:!1}:{label:d("toolbar.textPadding"),value:N({paddingTop:r.paddingTop,paddingRight:r.paddingRight,paddingBottom:r.paddingBottom,paddingLeft:r.paddingLeft}),fields:y,disabled:!!r.curveEnabled},s=e=>{o.history.transaction(()=>{n.forEach(t=>{t.set(e)})})},c="number"==typeof i.lineHeight?100*i.lineHeight:120;return t(C,{children:[t(w,{children:[e(E,{render:e(j,{render:e(h,{variant:"ghost",size:"icon-sm","aria-label":d("toolbar.spacing"),children:e(a,{name:"text.spacing",className:"pn:size-5"})})})}),e(z,{children:d("toolbar.spacing")})]}),t(S,{align:"start",className:"pn:w-[270px] pn:p-[15px]",children:[e(g,{label:d("toolbar.lineHeight"),value:Math.round(c),onChange:e=>s({lineHeight:e/100}),min:50,max:250}),e(g,{label:d("toolbar.letterSpacing"),value:Math.round(100*i.letterSpacing),onChange:e=>s({letterSpacing:e/100}),min:-50,max:250}),e("div",{className:"pn:mt-2 pn:border-t pn:pt-2",children:e(b,{label:l.label,value:l.value,disabled:l.disabled,onChange:e=>s(T(e,l.fields))},i.id)})]})]})});export const TextFilters=V;export const TextAnimations=_;export const TextToolbar=o(({store:e,components:t})=>{const n=e.selectedElements;return R({type:"text",components:t,controlProps:{store:e,element:n[0],elements:n},controls:{TextFill,TextFontFamily,TextFontSize,TextFontVariant,TextSpacing,TextTransform,TextFilters:V,TextAnimations:f.animationsEnabled&&_,TextAiWrite:f.aiTextEnabled&&G}})});export default TextToolbar;
@@ -0,0 +1,2 @@
1
+ export declare const isWebKit: () => boolean;
2
+ export declare const isFirefox: () => boolean;
@@ -0,0 +1,3 @@
1
+ const userAgent = () => typeof navigator === 'undefined' ? '' : navigator.userAgent;
2
+ export const isWebKit = () => /^((?!chrome|android).)*safari/i.test(userAgent());
3
+ export const isFirefox = () => /firefox/i.test(userAgent());
package/utils/fonts.js CHANGED
@@ -1 +1 @@
1
- import*as A from"mobx";import{triggerLoadError as t,getFontLoadTimeout as o}from"./loader.js";import{polotnoError as e}from"@polotno/core/errors";import{removeTags as n}from"@polotno/core/text";import{decodeBase64 as r}from"./base64.js";import{DEFAULT_RETRIES as s,retryDelayMs as i}from"@polotno/core/retry";import{getGoogleFontsUrl as c,getGoogleFontsVariants as a}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as l,googleFontVariantUrl as u,cssFontFamily as f,isFontKeyword as d,parseUnicodeRange as m,rangesCover as p,toNumericWeight as g}from"@polotno/core/fonts";export{setGoogleFontsVariants,getGoogleFontsVariants,getGoogleFontsUrl}from"@polotno/core/google-fonts-url";const h=["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"];let F=A.observable([...h]),y=A.observable({value:!1});export function isGoogleFontChanged(){return y.value}export function setGoogleFonts(A){if("default"===A){return F.replace([...h]),void(y.value=!1)}y.value=!0,F.splice(0,F.length),F.push(...A)}export function getFontsList(){return F}export const globalFonts=A.observable([]);export function addGlobalFont(A){globalFonts.push(A)}export function removeGlobalFont(A){const t=globalFonts.findIndex(t=>t.fontFamily===A);-1!==t&&globalFonts.splice(t,1)}export function replaceGlobalFonts(A){globalFonts.replace(A)}const w="BESbswy 0123456789 Il1Ww";function b(A){const t=function(A=""){const t=n(A).replace(/\s+/g," ").trim();return t?Array.from(t).slice(0,10).join(""):""}(A);return t?`${w} ${t}`:w}export function _getFontProbeTextForTesting(A){return b(A)}const x="PolotnoBlank";let B,$;function E(A,t,o,e){null!=$||($=document.createElement("canvas"));const n=$.getContext("2d");if(!n){return!1}const r=(A,e)=>{n.font=`${t} ${o} 40px ${A}`;const r=n.measureText(e);return r.width>0||r.actualBoundingBoxLeft+r.actualBoundingBoxRight>0};if(r(x,w)){return!1}const s=`${f(A)}, ${x}`;return e.some(A=>r(s,A))}export function measureFontDom(A,t="sans-serif",o="normal",e="normal",n=w){if("undefined"==typeof document||!document.body){return 0}const r=document.createElement("span");r.textContent=n,r.style.cssText=`\n position:absolute;\n visibility:hidden;\n white-space:nowrap;\n top:-9999px;\n left:-9999px;\n font:${o} ${e} 90px ${f(A)}, ${t};\n `,document.body.appendChild(r);const s=r.getBoundingClientRect().width;return r.remove(),s}const v={Arial:!0},G={};export const isFontLoaded=(A,t,o,e)=>{if(t&&o){const n=`${A}_${t}_${o}`;if(!v[n]){return!1}const r=textChars(e),s=G[n];return!![...r].every(A=>null==s?void 0:s.has(A))||function(A,t,o,e){if("undefined"==typeof document||!document.fonts){return!1}const n="italic"===t?"italic":"normal",r=g(o),s=Y(A),i=[...e].map(A=>A.codePointAt(0)),c=new Set;let a=!1;for(const u of document.fonts){if(Y(u.family)!==s){continue}if(a=!0,u.style!==n){continue}const[A,t=A]=u.weight.split(/\s+/).map(g);if(r<A||r>t){continue}const o=m(u.unicodeRange),e=i.filter(A=>p(o,A));if(e.length){if("loaded"!==u.status){return!1}e.forEach(A=>c.add(A))}}if(a){return i.every(A=>c.has(A))}try{return document.fonts.check(C(A,t,o),e)}catch(l){return!1}}(A,t,o,r)}return Object.keys(v).some(t=>t.startsWith(A+"_"))||!!v[A]};export function _setFontLoadedForTesting(A,t){t?v[A]=!0:delete v[A]}export async function loadFont(A,t,e,n){var r;const s=performance.now()+o();await loadFontFace(A,t,e,n);const i=textChars(n),c=()=>{var o,n;const r=null!==(o=G[n=`${A}_${t}_${e}`])&&void 0!==o?o:G[n]=new Set;for(const A of i){r.add(A)}};if(!i||!(null===(r=document.fonts)||void 0===r?void 0:r.load)){return c()}let a;await Promise.race([document.fonts.load(C(A,t,e),i).catch(()=>{}).then(c),new Promise(A=>{a=setTimeout(A,Math.max(0,s-performance.now()))})]),clearTimeout(a)}const C=(A,t,o)=>`${t} ${o} 16px ${f(A)}`;export function textChars(A){return[...new Set(n(null!=A?A:"").replace(/\s/g,""))].join("")}export async function loadFontFace(A,n,s,c){var a;const l=`${A}_${n}_${s}`;if(d(A)){return void P(l,A)}if(injectGoogleFontVariant(A,n,s),v[l]&&!N(A,n,s)){return}const u=!!(null===(a=document.fonts)||void 0===a?void 0:a.load),f=b(c),m=[...textChars(c)];await(null!=B||(B=(async()=>{if("undefined"==typeof FontFace){return}const A=new FontFace(x,r("AAEAAAAKAIAAAwAgT1MvMlHNUusAAACsAAAAYGNtYXAAIQA0AAABDAAAAChnbHlmAAAAAAAAATQAAAAKaGVhZF8WQOUAAAFAAAAANmhoZWEDIf87AAABeAAAACRobXR4AAAAAAAAAZwAAAAIbG9jYQAFAAAAAAGkAAAABm1heHAAAwAAAAABrAAAACBuYW1lCUoZTgAAAcwAAACMcG9zdAADAAAAAAJYAAAAIAAEAAABkAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQT0xPAEAAAP//AyD/OAAAAyAAyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAwAKAAAADAANAAAAAAAcAAAAAAAAAAEAAAAAABD//wAAAAEAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAABfDzz1AAMD6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAgAAAAAAAAABAAADIP84AAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAFAAAAAQAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQANgADAAEECQABABgAAAADAAEECQACAA4AGAADAAEECQAEABgAJgADAAEECQAGABgAPgBQAG8AbABvAHQAbgBvAEIAbABhAG4AawBSAGUAZwB1AGwAYQByAFAAbwBsAG8AdABuAG8AQgBsAGEAbgBrAFAAbwBsAG8AdABuAG8AQgBsAGEAbgBrAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="),{weight:"1 1000"});document.fonts.add(A),await A.load()})().catch(A=>{console.error("Polotno could not load its blank probe font: no font can be verified as ready.",A)})),B);const p=o()/60;for(let o=0;o<p;o++){const r=!N(A,n,s);let c=[];if(u){try{c=await document.fonts.load(C(A,n,s),f)}catch(g){}}const a=t=>E(A,n,s,t),d=c.length>0&&c.every(A=>"loaded"===A.status);if(r&&(a([f])||d&&a(m))){return void P(l,A)}if("missing"===D[A]){if(Q(A)){const o=`Font "${A}" not found: not registered and no matching Google Font.`;console.error(o),t(e("FONT_FAILED",o,{family:A,reason:"not-found"}))}return}if(A in T&&!T[A]&&"errored"===D[A]&&injectGoogleFont(A),R[A]&&U(A)){const n=_(A);if("wait"===n){await new Promise(A=>setTimeout(A,60));continue}if("spent"!==n){V(A);const t=i(n);await new Promise(A=>setTimeout(A,t)),o+=Math.ceil(t/60);continue}if(Q(A)){const o=`Failed to load font "${A}": its font file could not be fetched.`;console.error(o),t(e("FONT_FAILED",o,{family:A,reason:"fetch-failed"}))}return}await new Promise(A=>setTimeout(A,60))}console.warn(`Timeout for loading font "${A}". Looks like polotno can't load it. Is it a correct font family?`),t(e("FONT_FAILED",`Timeout for loading font "${A}"`,{family:A,reason:"timeout"}))}const T={},D={},I=new Set;function Q(A){return!I.has(A)&&(I.add(A),setTimeout(()=>I.delete(A),o()),!0)}function P(A,t){v[A]=!0,delete D[t],delete k[t]}const k={};function _(A){const t=k[A],e=!t||Date.now()-t.at>o()?0:t.spent;return e>=s-1?"spent":t&&e>0&&Date.now()-t.at<i(e)?"wait":(k[A]={spent:e+1,at:Date.now()},e+1)}const j={};function N(A,t,o){return"loading"===T[A]||"loading"===j[`${A}|${"italic"===t?1:0}|${parseInt(o,10)}`]}export function injectGoogleFontVariant(A,t,o){const e=parseInt(o,10);if(!Number.isFinite(e)){return}if(function(A){const t=new Set;for(const o of a().split(",")){const e=o.trim().match(/^(\d+)(italic|i)?$/);e&&!!e[2]===A&&t.add(parseInt(e[1],10))}return t}("italic"===t).has(e)){return}if(!(A in T)){return}const n="italic"===t,r=`${A}|${n?1:0}|${e}`;if(j[r]){return}j[r]="loading";const s=document.createElement("link");s.type="text/css",s.href=u(A,n,e),s.rel="stylesheet",s.onload=()=>{j[r]=!0},s.onerror=()=>{j[r]=!0,s.remove()},document.getElementsByTagName("head")[0].appendChild(s)}export function injectGoogleFont(A){if(T[A]||d(A)){return}const t=c(A),o=document.createElement("link");o.type="text/css",o.href=t,o.rel="stylesheet",o.onload=()=>{T[A]=!0},o.onerror=()=>{o.remove(),T[A]=!1,"errored"===D[A]?function(A){D[A]="probing",fetch(c(A),{mode:"no-cors"}).then(()=>{D[A]="missing"}).catch(()=>{delete D[A]})}(A):D[A]||(D[A]="errored")},document.getElementsByTagName("head")[0].appendChild(o),T[A]="loading"}const R={};let S;function O(){return S||(S=document.getElementById("polotno-font-style"),S||(S=document.createElement("style"),S.id="polotno-font-style",document.head.appendChild(S)),S)}function L(A){const t=A.fontFamily,o=l(A),e=O().sheet;return o.map(A=>{const o=e.insertRule(`\n @font-face{\n font-family:${f(t)};\n src:${A.src};\n font-style:${A.fontStyle};\n font-weight:${A.fontWeight};\n font-display:swap; /* optional but recommended */\n }`,e.cssRules.length);return e.cssRules[o]})}export function injectCustomFont(A){const t=A.fontFamily;if(!A.url&&!A.styles){return}const o=JSON.stringify(l(A)),e=R[t];if(e){if(e.src===o){return}M(e.rules),W(t)}delete D[t],R[t]={font:A,src:o,rules:L(A)}}function M(A){const t=O().sheet;for(const o of A){const A=Array.prototype.indexOf.call(t.cssRules,o);A>=0&&t.deleteRule(A)}}export function removeCustomFont(A){const t=R[A];t&&(M(t.rules),delete R[A],W(A))}function W(A){delete k[A];for(const t of Object.keys(v)){(t===A||t.startsWith(A+"_"))&&(delete v[t],delete G[t])}}function V(A){const t=R[A];t&&(M(t.rules),t.rules=L(t.font))}const Y=A=>A.trim().replace(/^["']|["']$/g,"").toLowerCase();function U(A){const t=document.fonts;if(!t||"function"!=typeof t.forEach){return!1}const o=Y(A);let e=!1;return t.forEach(A=>{"error"===A.status&&Y(A.family)===o&&(e=!0)}),e}
1
+ import*as A from"mobx";import{triggerLoadError as t,getFontLoadTimeout as o}from"./loader.js";import{polotnoError as e}from"@polotno/core/errors";import{removeTags as n}from"@polotno/core/text";import{decodeBase64 as r}from"./base64.js";import{DEFAULT_RETRIES as s,retryDelayMs as i}from"@polotno/core/retry";import{getGoogleFontsUrl as c,getGoogleFontsVariants as a}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as l,googleFontVariantUrl as u,cssFontFamily as f,isFontKeyword as d,parseUnicodeRange as m,rangesCover as p,toNumericWeight as g}from"@polotno/core/fonts";export{setGoogleFontsVariants,getGoogleFontsVariants,getGoogleFontsUrl}from"@polotno/core/google-fonts-url";const h=["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"];let F=A.observable([...h]),y=A.observable({value:!1});export function isGoogleFontChanged(){return y.value}export function setGoogleFonts(A){if("default"===A){return F.replace([...h]),void(y.value=!1)}y.value=!0,F.splice(0,F.length),F.push(...A)}export function getFontsList(){return F}export const globalFonts=A.observable([]);export function addGlobalFont(A){globalFonts.push(A)}export function removeGlobalFont(A){const t=globalFonts.findIndex(t=>t.fontFamily===A);-1!==t&&globalFonts.splice(t,1)}export function replaceGlobalFonts(A){globalFonts.replace(A)}const w="BESbswy 0123456789 Il1Ww";function b(A){const t=function(A=""){const t=n(A).replace(/\s+/g," ").trim();return t?Array.from(t).slice(0,10).join(""):""}(A);return t?`${w} ${t}`:w}export function _getFontProbeTextForTesting(A){return b(A)}const x="PolotnoBlank",B="PolotnoBlankSpace";let $,E;function v(A,t,o,e){null!=E||(E=document.createElement("canvas"));const n=E.getContext("2d");if(!n){return!1}const r=(A,e)=>{n.font=`${t} ${o} 40px ${A}`;const r=n.measureText(e);return r.width>0||r.actualBoundingBoxLeft+r.actualBoundingBoxRight>0};if(r(x,w)){return!1}const s=`${f(A)}, ${B}, ${x}`;return e.some(A=>r(s,A))}export function measureFontDom(A,t="sans-serif",o="normal",e="normal",n=w){if("undefined"==typeof document||!document.body){return 0}const r=document.createElement("span");r.textContent=n,r.style.cssText=`\n position:absolute;\n visibility:hidden;\n white-space:nowrap;\n top:-9999px;\n left:-9999px;\n font:${o} ${e} 90px ${f(A)}, ${t};\n `,document.body.appendChild(r);const s=r.getBoundingClientRect().width;return r.remove(),s}const G={Arial:!0},C={};export const isFontLoaded=(A,t,o,e)=>{if(t&&o){const n=`${A}_${t}_${o}`;if(!G[n]){return!1}const r=textChars(e),s=C[n];return!![...r].every(A=>null==s?void 0:s.has(A))||function(A,t,o,e){if("undefined"==typeof document||!document.fonts){return!1}const n="italic"===t?"italic":"normal",r=g(o),s=Y(A),i=[...e].map(A=>A.codePointAt(0)),c=new Set;let a=!1;for(const u of document.fonts){if(Y(u.family)!==s){continue}if(a=!0,u.style!==n){continue}const[A,t=A]=u.weight.split(/\s+/).map(g);if(r<A||r>t){continue}const o=m(u.unicodeRange),e=i.filter(A=>p(o,A));if(e.length){if("loaded"!==u.status){return!1}e.forEach(A=>c.add(A))}}if(a){return i.every(A=>c.has(A))}try{return document.fonts.check(T(A,t,o),e)}catch(l){return!1}}(A,t,o,r)}return Object.keys(G).some(t=>t.startsWith(A+"_"))||!!G[A]};export function _setFontLoadedForTesting(A,t){t?G[A]=!0:delete G[A]}export async function loadFont(A,t,e,n){var r;const s=performance.now()+o();await loadFontFace(A,t,e,n);const i=textChars(n),c=()=>{var o,n;const r=null!==(o=C[n=`${A}_${t}_${e}`])&&void 0!==o?o:C[n]=new Set;for(const A of i){r.add(A)}};if(!i||!(null===(r=document.fonts)||void 0===r?void 0:r.load)){return c()}let a;await Promise.race([document.fonts.load(T(A,t,e),i).catch(()=>{}).then(c),new Promise(A=>{a=setTimeout(A,Math.max(0,s-performance.now()))})]),clearTimeout(a)}const T=(A,t,o)=>`${t} ${o} 16px ${f(A)}`;export function textChars(A){return[...new Set(n(null!=A?A:"").replace(/\s/g,""))].join("")}export async function loadFontFace(A,n,s,c){var a;const l=`${A}_${n}_${s}`;if(d(A)){return void k(l,A)}if(injectGoogleFontVariant(A,n,s),G[l]&&!j(A,n,s)){return}const u=!!(null===(a=document.fonts)||void 0===a?void 0:a.load),f=b(c),m=[...textChars(c)];await(null!=$||($=(async()=>{if("undefined"==typeof FontFace){return}const A=r("AAEAAAAKAIAAAwAgT1MvMlHNUusAAACsAAAAYGNtYXAAIQA0AAABDAAAAChnbHlmAAAAAAAAATQAAAAKaGVhZF8WQOUAAAFAAAAANmhoZWEDIf87AAABeAAAACRobXR4AAAAAAAAAZwAAAAIbG9jYQAFAAAAAAGkAAAABm1heHAAAwAAAAABrAAAACBuYW1lCUoZTgAAAcwAAACMcG9zdAADAAAAAAJYAAAAIAAEAAABkAAFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQT0xPAEAAAP//AyD/OAAAAyAAyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAwAKAAAADAANAAAAAAAcAAAAAAAAAAEAAAAAABD//wAAAAEAAAAAAAAAAAAAAAAAAQAAAAEAAAAAAABfDzz1AAMD6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAgAAAAAAAAABAAADIP84AAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAFAAAAAQAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQANgADAAEECQABABgAAAADAAEECQACAA4AGAADAAEECQAEABgAJgADAAEECQAGABgAPgBQAG8AbABvAHQAbgBvAEIAbABhAG4AawBSAGUAZwB1AGwAYQByAFAAbwBsAG8AdABuAG8AQgBsAGEAbgBrAFAAbwBsAG8AdABuAG8AQgBsAGEAbgBrAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="),t=[new FontFace(x,A,{weight:"1 1000"}),new FontFace(B,A,{weight:"1 1000",unicodeRange:"U+20"})];t.forEach(A=>document.fonts.add(A)),await Promise.all(t.map(A=>A.load()))})().catch(A=>{console.error("Polotno could not load its blank probe font: no font can be verified as ready.",A)})),$);const p=o()/60;for(let o=0;o<p;o++){const r=!j(A,n,s);let c=[];if(u){try{c=await document.fonts.load(T(A,n,s),f)}catch(g){}}const a=t=>v(A,n,s,t),d=c.length>0&&c.every(A=>"loaded"===A.status);if(r&&(a([f])||d&&a(m))){return void k(l,A)}if("missing"===I[A]){if(Q(A)){const o=`Font "${A}" not found: not registered and no matching Google Font.`;console.error(o),t(e("FONT_FAILED",o,{family:A,reason:"not-found"}))}return}if(A in D&&!D[A]&&"errored"===I[A]&&injectGoogleFont(A),N[A]&&Z(A)){const n=S(A);if("wait"===n){await new Promise(A=>setTimeout(A,60));continue}if("spent"!==n){V(A);const t=i(n);await new Promise(A=>setTimeout(A,t)),o+=Math.ceil(t/60);continue}if(Q(A)){const o=`Failed to load font "${A}": its font file could not be fetched.`;console.error(o),t(e("FONT_FAILED",o,{family:A,reason:"fetch-failed"}))}return}await new Promise(A=>setTimeout(A,60))}console.warn(`Timeout for loading font "${A}". Looks like polotno can't load it. Is it a correct font family?`),t(e("FONT_FAILED",`Timeout for loading font "${A}"`,{family:A,reason:"timeout"}))}const D={},I={},P=new Set;function Q(A){return!P.has(A)&&(P.add(A),setTimeout(()=>P.delete(A),o()),!0)}function k(A,t){G[A]=!0,delete I[t],delete R[t]}const R={};function S(A){const t=R[A],e=!t||Date.now()-t.at>o()?0:t.spent;return e>=s-1?"spent":t&&e>0&&Date.now()-t.at<i(e)?"wait":(R[A]={spent:e+1,at:Date.now()},e+1)}const _={};function j(A,t,o){return"loading"===D[A]||"loading"===_[`${A}|${"italic"===t?1:0}|${parseInt(o,10)}`]}export function injectGoogleFontVariant(A,t,o){const e=parseInt(o,10);if(!Number.isFinite(e)){return}if(function(A){const t=new Set;for(const o of a().split(",")){const e=o.trim().match(/^(\d+)(italic|i)?$/);e&&!!e[2]===A&&t.add(parseInt(e[1],10))}return t}("italic"===t).has(e)){return}if(!(A in D)){return}const n="italic"===t,r=`${A}|${n?1:0}|${e}`;if(_[r]){return}_[r]="loading";const s=document.createElement("link");s.type="text/css",s.href=u(A,n,e),s.rel="stylesheet",s.onload=()=>{_[r]=!0},s.onerror=()=>{_[r]=!0,s.remove()},document.getElementsByTagName("head")[0].appendChild(s)}export function injectGoogleFont(A){if(D[A]||d(A)){return}const t=c(A),o=document.createElement("link");o.type="text/css",o.href=t,o.rel="stylesheet",o.onload=()=>{D[A]=!0},o.onerror=()=>{o.remove(),D[A]=!1,"errored"===I[A]?function(A){I[A]="probing",fetch(c(A),{mode:"no-cors"}).then(()=>{I[A]="missing"}).catch(()=>{delete I[A]})}(A):I[A]||(I[A]="errored")},document.getElementsByTagName("head")[0].appendChild(o),D[A]="loading"}const N={};let O;function L(){return O||(O=document.getElementById("polotno-font-style"),O||(O=document.createElement("style"),O.id="polotno-font-style",document.head.appendChild(O)),O)}function M(A){const t=A.fontFamily,o=l(A),e=L().sheet;return o.map(A=>{const o=e.insertRule(`\n @font-face{\n font-family:${f(t)};\n src:${A.src};\n font-style:${A.fontStyle};\n font-weight:${A.fontWeight};\n font-display:swap; /* optional but recommended */\n }`,e.cssRules.length);return e.cssRules[o]})}export function injectCustomFont(A){const t=A.fontFamily;if(!A.url&&!A.styles){return}const o=JSON.stringify(l(A)),e=N[t];if(e){if(e.src===o){return}W(e.rules),U(t)}delete I[t],N[t]={font:A,src:o,rules:M(A)}}function W(A){const t=L().sheet;for(const o of A){const A=Array.prototype.indexOf.call(t.cssRules,o);A>=0&&t.deleteRule(A)}}export function removeCustomFont(A){const t=N[A];t&&(W(t.rules),delete N[A],U(A))}function U(A){delete R[A];for(const t of Object.keys(G)){(t===A||t.startsWith(A+"_"))&&(delete G[t],delete C[t])}}function V(A){const t=N[A];t&&(W(t.rules),t.rules=M(t.font))}const Y=A=>A.trim().replace(/^["']|["']$/g,"").toLowerCase();function Z(A){const t=document.fonts;if(!t||"function"!=typeof t.forEach){return!1}const o=Y(A);let e=!1;return t.forEach(A=>{"error"===A.status&&Y(A.family)===o&&(e=!0)}),e}
@@ -1 +1 @@
1
- export*from"@polotno/core/measure-html";import{getGoogleFontsVariants as t}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as o,cssFontFamily as e,isFontKeyword as n}from"@polotno/core/fonts";import{fetchWithRetry as r}from"@polotno/core/retry";import{optimizeCss as s}from"./css-optimizer.js";import{resetStyle as i}from"@polotno/core/reset-style";import{getHiddenElement as l}from"@polotno/core/measure-html";import{parsePrimaryFontFamily as c}from"@polotno/core/rich-text-html";import{shrinkParagraphStrutForRaster as a}from"./rich-text-html.js";import{htmlToImage as f}from"./html-to-svg/index.js";const m=new Map;export const prerenderFont=async t=>{if(m.has(t)){return m.get(t)}const o=(async()=>{const o=`<div style="font-family: ${e(t)}; font-size: 100px;">${t}<strong>${t}</strong></div>`,n=document.createElement("div");n.innerHTML=o,n.style.visibility="hidden",n.style.position="absolute";const r=l();r.appendChild(n);const s="undefined"!=typeof navigator&&navigator.userAgent.includes("Firefox")?180:50;await new Promise(t=>setTimeout(t,s)),r.removeChild(n)})();return m.set(t,o),o};const p={},h=t=>{if(p[t]){return p[t]}const o=function(t){const o=[];for(let n=0;n<document.styleSheets.length;n++){const r=document.styleSheets[n];try{const e=r.cssRules;if(e){for(let n=0;n<e.length;n++){const r=e[n];r instanceof CSSFontFaceRule&&c(r.style.fontFamily)===t&&o.push(r)}}}catch(e){console.warn(`Could not access stylesheet: ${r.href}`,e)}}return o}(t),e=o.map(t=>({src:t.style.getPropertyValue("src"),fontStyle:t.style.getPropertyValue("font-style")||"normal",fontWeight:t.style.getPropertyValue("font-weight")||"normal"}));return p[t]=e,e},u=new Map;async function y(t,o){if(n(t)){return""}const e=`${t}|${o}`;if(u.has(e)){return u.get(e)}const s=`https://fonts.googleapis.com/css?family=${encodeURIComponent(t)}:${o}&display=swap`;try{const t=await r(s),o=await t.text();return u.set(e,o),o}catch(i){return u.set(e,""),""}}export async function htmlToCanvas({html:n,width:r,height:l,fontFamily:c,fontFamilies:m,padding:p,font:u,resolveFont:d,pixelRatio:g}){n=a(n);const w=(null==m?void 0:m.length)?[...new Set([c,...m])]:[c],v=await async function(n,r,s,i){const l=[...new Set(n.filter(Boolean))];let c="";for(const a of l){if("Arial"===a){continue}const n=a===r&&s||(null==i?void 0:i(a));if(n){(n.styles||n.url?o(n):h(a)).forEach(t=>{c+=`\n @font-face {\n font-family: ${e(a)};\n src: ${t.src};\n font-style: ${t.fontStyle||"normal"};\n font-weight: ${t.fontWeight||"normal"};\n }\n `})}else{const o=t();c+=await y(a,o)}}return c}(w,c,u,d);let $="";return v&&($=s(v,n)),f({html:`<div style="padding: ${p}px;" dir="auto">${n+=$+i}</div>`,width:r+2*p,height:l+2*p,cache:{maxEntries:100},pixelRatio:g})}
1
+ export*from"@polotno/core/measure-html";import{getGoogleFontsVariants as t}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as o,cssFontFamily as e,isFontKeyword as n}from"@polotno/core/fonts";import{fetchWithRetry as r}from"@polotno/core/retry";import{optimizeCss as s}from"./css-optimizer.js";import{resetStyle as i}from"@polotno/core/reset-style";import{getHiddenElement as l}from"@polotno/core/measure-html";import{parsePrimaryFontFamily as c}from"@polotno/core/rich-text-html";import{shrinkParagraphStrutForRaster as a}from"./rich-text-html.js";import{htmlToImage as f}from"./html-to-svg/index.js";import{isFirefox as m}from"./engine.js";const p=new Map;export const prerenderFont=async t=>{if(p.has(t)){return p.get(t)}const o=(async()=>{const o=`<div style="font-family: ${e(t)}; font-size: 100px;">${t}<strong>${t}</strong></div>`,n=document.createElement("div");n.innerHTML=o,n.style.visibility="hidden",n.style.position="absolute";const r=l();r.appendChild(n);const s=m()?180:50;await new Promise(t=>setTimeout(t,s)),r.removeChild(n)})();return p.set(t,o),o};const h={},u=t=>{if(h[t]){return h[t]}const o=function(t){const o=[];for(let n=0;n<document.styleSheets.length;n++){const r=document.styleSheets[n];try{const e=r.cssRules;if(e){for(let n=0;n<e.length;n++){const r=e[n];r instanceof CSSFontFaceRule&&c(r.style.fontFamily)===t&&o.push(r)}}}catch(e){console.warn(`Could not access stylesheet: ${r.href}`,e)}}return o}(t),e=o.map(t=>({src:t.style.getPropertyValue("src"),fontStyle:t.style.getPropertyValue("font-style")||"normal",fontWeight:t.style.getPropertyValue("font-weight")||"normal"}));return h[t]=e,e},y=new Map;async function d(t,o){if(n(t)){return""}const e=`${t}|${o}`;if(y.has(e)){return y.get(e)}const s=`https://fonts.googleapis.com/css?family=${encodeURIComponent(t)}:${o}&display=swap`;try{const t=await r(s),o=await t.text();return y.set(e,o),o}catch(i){return y.set(e,""),""}}export async function htmlToCanvas({html:n,width:r,height:l,fontFamily:c,fontFamilies:m,padding:p,font:h,resolveFont:y,pixelRatio:g}){n=a(n);const w=(null==m?void 0:m.length)?[...new Set([c,...m])]:[c],$=await async function(n,r,s,i){const l=[...new Set(n.filter(Boolean))];let c="";for(const a of l){if("Arial"===a){continue}const n=a===r&&s||(null==i?void 0:i(a));if(n){(n.styles||n.url?o(n):u(a)).forEach(t=>{c+=`\n @font-face {\n font-family: ${e(a)};\n src: ${t.src};\n font-style: ${t.fontStyle||"normal"};\n font-weight: ${t.fontWeight||"normal"};\n }\n `})}else{const o=t();c+=await d(a,o)}}return c}(w,c,h,y);let v="";return $&&(v=s($,n)),f({html:`<div style="padding: ${p}px;" dir="auto">${n+=v+i}</div>`,width:r+2*p,height:l+2*p,cache:{maxEntries:100},pixelRatio:g})}
package/utils/l10n.d.ts CHANGED
@@ -416,6 +416,9 @@ export declare const getTranslations: () => {
416
416
  layersTip: string;
417
417
  noLayers: string;
418
418
  namePlaceholder: string;
419
+ hideLayer: string;
420
+ lockLayer: string;
421
+ deleteLayer: string;
419
422
  useMagicResize: string;
420
423
  advanced: string;
421
424
  bleed: string;
package/utils/l10n.js CHANGED
@@ -1 +1 @@
1
- import{observable as e,action as o,toJS as a}from"mobx";const r=e({variables:{title:"Variables",element:"Selected element",name:"Variable name",label:"Label",add:"Add variable",required:"Required",default:"Default",enterValue:"Enter a value",empty:"Add a variable, then insert it into text or link it to a selected element.",settings:"Settings",delete:"Delete variable",yes:"Yes",no:"No",insert:"Insert variable",search:"Search or add a variable",noMatch:"No matching variables",nameRule:"Use letters, digits, _ and dots",nameTaken:"Already exists",visible:"Visible",src:"Source",fill:"Color",unbound:"Not linked",always:"Always",fit:"Scale",manual:"Crop",cover:"Fill",contain:"Fit",focus:"Focus",orphan:"Unused","mixed-types":"Mixed types"},imageEdit:{title:"AI edit",expand:"Expand",upscale:"Upscale",inpaint:"Generative fill",replace:"Replace",remove:"Remove",prompt:"Your prompt",promptPlaceholder:"Describe what should be there",expandPromptPlaceholder:"Describe the new area (optional)",replaceDescription:"Select an area on the image, then describe what you want to change.",replaceHint:"Describe what should replace the selection, such as “plain wall” or “open sky”.",removeDescription:"Select an object to remove. The surrounding image will fill the selected area.",expandDescription:"Drag the frame beyond the image edges to make room for new content.",cropDescription:"Drag the frame to crop the image.",upscaleDescription:"Increase the image resolution.",removeBackgroundDescription:"Remove the image background.",applyCrop:"Apply crop",generate:"Generate",clear:"Clear selection",resetFrame:"Reset frame",processing:"Generating…",loadingImage:"Loading image…",upscaling:"Upscaling…",removingBackground:"Removing background…",failed:"The image could not be edited. Please try again.",rasterFailed:"This device could not prepare the image. Try a smaller image.",selectRegion:"Drag on the image to select an area."},toolbar:{duration:"Duration",opacity:"Opacity",effects:"Effects",blur:"Blur",curvedText:"Curved text",curvePower:"Power",temperature:"Temperature",saturation:"Saturation",contrast:"Contrast",shadows:"Shadows",white:"White",black:"Black",vibrance:"Vibrance",textBackground:"Background",backgroundCornerRadius:"Corner radius",backgroundOpacity:"Opacity",backgroundPadding:"Spread",backgroundShape:"Shape",backgroundFill:"Fill",backgroundShapeLines:"Lines",backgroundShapeBox:"Box",textPadding:"Padding",paddingSides:"Independent sides",paddingTop:"Top",paddingRight:"Right",paddingBottom:"Bottom",paddingLeft:"Left",brightness:"Brightness",filters:"Filters",sepia:"Sepia",grayscale:"Grayscale",cold:"Cold",natural:"Natural",warm:"Warm",textStroke:"Text Stroke",textEffect:{none:"None",shadow:"Shadow",lift:"Lift",glow:"Glow",outline:"Outline",sticker:"Sticker",pop:"Pop",background:"Background"},blendMode:"Blending",blend:{"pass-through":"Pass Through",normal:"Normal",multiply:"Multiply",screen:"Screen",overlay:"Overlay",darken:"Darken",lighten:"Lighten","color-dodge":"Color Dodge","color-burn":"Color Burn","hard-light":"Hard Light","soft-light":"Soft Light",difference:"Difference",exclusion:"Exclusion",hue:"Hue",saturation:"Saturation",color:"Color",luminosity:"Luminosity"},strokeLineJoin:"Corners",joinRound:"Round",joinMiter:"Miter",joinBevel:"Bevel",shadow:"Drop shadow",border:"Border",cornerRadius:"Corner Radius",copyStyle:"Copy style",uppercase:"Uppercase",position:"Position",layering:"Layering",toForward:"To Front",up:"Forward",down:"Backward",toBottom:"To back",alignLeft:"Align left",alignCenter:"Align center",alignRight:"Align right",alignTop:"Align top",alignMiddle:"Align middle",alignBottom:"Align bottom",flip:"Flip",flipHorizontally:"Flip horizontally",flipVertically:"Flip vertically",fitToBackground:"Fit to page",fitToPage:"Fit to page",widthShort:"W",heightShort:"H",removeBackground:"Remove background",removeBackgroundTitle:"Remove background from image",cancelRemoveBackground:"Cancel",confirmRemoveBackground:"Confirm",crop:"Crop",cropDone:"Done",cropCancel:"Cancel",clip:"Apply mask",removeClip:"Remove mask",removeMask:"Remove mask",transparency:"Transparency",lockedDescription:"Object is locked. Unlock it to allow changes from canvas.",unlockedDescription:"Object is unlocked. Lock it to prevent changes from canvas.",removeElements:"Remove elements",duplicateElements:"Duplicate elements",download:"Download",saveAsImage:"Save as image",saveAsPDF:"Save as PDF",lineHeight:"Line height",letterSpacing:"Letter spacing",offsetX:"Offset X",offsetY:"Offset Y",color:"Color",selectable:"Selectable",draggable:"Draggable",removable:"Removable",resizable:"Resizable",contentEditable:"Can change content",styleEditable:"Can change style",alwaysOnTop:"Always on top",showInExport:"Show in export",ungroupElements:"Ungroup",groupElements:"Group",lineSize:"Line size",fade:"Fade",move:"Move",zoom:"Zoom",animate:"Animate",rotate:"Rotate",none:"None",bounce:"Bounce",blink:"Blink",count:"Count",pop:"Pop",rise:"Rise",flipAnimation:"Flip",growTurn:"Grow & turn",spinAnimation:"Spin",pulse:"Pulse",float:"Float",shake:"Shake",typewriter:"Typewriter",lineRise:"Line rise",wordRise:"Word rise",wordFade:"Word fade",letterPop:"Letter pop",wordBlur:"Word blur",wipe:"Wipe",glow:"Glow",lineWipe:"Line wipe",linePeek:"Line peek",letterWave:"Letter wave",kenBurns:"Ken Burns",strength:"Strength",spaceEvenly:"Space evenly",horizontalDistribution:"Horizontally",verticalDistribution:"Vertically",strokeWidth:"Stroke Width",strokeSettings:"Stroke settings",spacing:"Spacing",volume:"Volume",speed:"Speed",seconds:"sec",lineStyle:"Line style",lineStartHead:"Line start",lineEndHead:"Line end",textDirection:"Text direction",fontSize:"Font size",fontFamily:"Font family",fontFamilyMixed:"Mixed",fontsInSelection:"Fonts in selection",textAlign:"Text align",verticalAlign:"Vertical align",bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",cellBackground:"Cell background",tableBorderSettings:"Border settings",tableBorderColor:"Border color",tableBorderWidth:"Border width",tableBorderStyle:"Border style",borderModeAll:"All borders",borderModeOuter:"Outer borders",borderModeInner:"Inner borders",borderModeBottomOnly:"Bottom only",borderModeTopOnly:"Top only",borderModeLeftOnly:"Left only",borderModeRightOnly:"Right only",borderModeInnerHorizontal:"Inner horizontal",borderModeInnerVertical:"Inner vertical",tableStructure:"Table structure",tableRows:"Rows",tableColumns:"Columns",insertRowAbove:"Insert row above",insertRowBelow:"Insert row below",deleteRow:"Delete row",insertColumnLeft:"Insert column left",insertColumnRight:"Insert column right",deleteColumn:"Delete column",deleteRows:"Delete rows",deleteColumns:"Delete columns",distributeRowsEvenly:"Distribute rows evenly",distributeColumnsEvenly:"Distribute columns evenly",cellPadding:"Cell padding",listFormat:"List",colorPicker:{solid:"Solid",gradient:"Gradient",gradientType:"Gradient type",linear:"Linear",radial:"Radial",center:"Gradient center",centerX:"Center X",centerY:"Center Y",angle:"Angle",stops:"Gradient stops",stop:"Stop",addStop:"Add stop",removeStop:"Remove stop",reverse:"Reverse gradient",colors:"Colors",resetColors:"Reset",recolorAll:"Recolor all"},clipFade:{title:"Fade",preparing:"Preparing mask…",shape:"Shape",linear:"Linear",radial:"Radial",stopOpacity:"Stop opacity",stops:"Fade stops",stop:"Stop",start:"Fade start",end:"Fade end",center:"Fade center",radius:"Fade radius",reverse:"Reverse",removeStop:"Remove stop",addStop:"Add stop",reset:"Reset",hint:"Drag the handles on the image to position the fade."},aiText:{aiWrite:"AI write",rewrite:"Rewrite",shorten:"Shorten",continue:"Continue writing",proofread:"Proofread",tones:"Tones",friendly:"Friendly",professional:"Professional",humorous:"Humorous",formal:"Formal",customPrompt:"Custom prompt",generatedResult:"Generated result",cancel:"Cancel",generate:"Generate",back:"Back",tryAgain:"Try Again",insert:"Insert",promptPlaceholder:"Describe what you want to generate"}},workspace:{noPages:"There are no pages yet...",addPage:"Add page",removePage:"Remove page",duplicatePage:"Duplicate page",moveUp:"Move up",moveDown:"Move down",moveLeft:"Move left",moveRight:"Move right"},scale:{reset:"Reset"},error:{removeBackground:"Ops! Something went wrong. Background can not be removed."},sidePanel:{close:"Close",templates:"Templates",searchTemplatesWithSameSize:"Show templates with the same size",searchPlaceholder:"Search...",otherFormats:"Other formats",noResults:"No results",error:"Loading is failed...",text:"Text",uploadFont:"Upload font",myFonts:"My fonts",photos:"Photos",videos:"Videos",animations:"Animations",effects:"Effects",elements:"Elements",shapes:"Shapes",tables:"Tables",lines:"Lines",draw:"Draw",drawTool:"Tool",drawSelection:"Selection",drawBrush:"Brush",drawHighlighter:"Highlighter",upload:"Upload",uploadImage:"Add file",uploadTip:"Upload your assets",uploadUnsupported:"Skipped some files. You can add images, video, audio and Lottie animations.",uploadFailed:"Upload failed. Please try again.",background:"Background",resize:"Resize",layers:"Layers",animate:"Animate",animationEnter:"Enter",animationBoth:"Both",animationExit:"Exit",animationLoop:"Loop",animationGeneral:"General",animationTextPresets:"Text",animationDuration:"Duration (s)",animationRepeatEvery:"Repeat every (s)",animationStartAt:"Start at (s)",animationEndAt:"End at (s)",animationDirection:"Direction",animationDirections:{right:"Right",left:"Left",up:"Up",down:"Down","bottom-right":"Bottom right","bottom-left":"Bottom left","top-right":"Top right","top-left":"Top left",none:"None"},zoomIn:"Zoom In",zoomOut:"Zoom Out",layerTypes:{image:"Image",text:"Text",svg:"SVG",line:"Line",figure:"Figure",group:"Group"},layersTip:"Elements on your active page:",noLayers:"No elements on the page...",namePlaceholder:"Type element name...",useMagicResize:"Use magic resize",advanced:"Advanced",bleed:"Bleed",showBleed:"Show bleed",clipImage:"Mask image",width:"Width",height:"Height",units:"Units",magicResizeDescription:"Magic resize will automatically resize and move all elements on the canvas",headerText:"Header",createHeader:"Create header",subHeaderText:"Sub Header",createSubHeader:"Create sub header",bodyText:"Body text",createBody:"Create body text"},pagesTimeline:{pages:"Pages",removePage:"Remove page",addPage:"Add page",duplicatePage:"Duplicate page",removeAudio:"Remove audio",duplicateAudio:"Duplicate audio",renameAudio:"Rename audio",muteAudio:"Mute",unmuteAudio:"Unmute",volume:"Volume",speed:"Speed",rewind:"Rewind to start",editAsVideo:"Edit as video",editAsVideoHint:"On: preview the frame at the playhead — timed elements hide outside their range. Off: show all elements while editing."},contextMenu:{duplicate:"Duplicate",split:"Split at playhead",rename:"Rename",remove:"Remove",lock:"Lock",unlock:"Unlock",copy:"Copy",paste:"Paste",copyStyle:"Copy style",moveUp:"Move up",moveDown:"Move down",moveBack:"Move back",moveForward:"Move forward"}}),n=e=>e&&"object"==typeof e;function i(e,o){Object.keys(o).forEach(a=>{const r=e[a],l=o[a];n(l)&&n(r)?i(r,l):e[a]=l})}function l(e,o,a=""){Object.keys(o).forEach(r=>{const i=o[r],s=a?`${a}.${r}`:r;n(i)?n(e[r])?l(e[r],i,s):console.warn(`Missing nested translation object at '${s}'`):void 0===e[r]&&console.warn(`Missing translation '${s}'`)})}export const setTranslations=o((e,{validate:o=!1}={})=>{o&&l(e,r),i(r,e)});export const getTranslations=()=>a(r);const s={};export const t=e=>{const o=function(e,o){var a,r=o.split("."),n=e;for(a=0;a<r.length;++a){if(null==n[r[a]]){return}n=n[r[a]]}return n}(r,e);if(void 0!==o){return o}s[e]||(s[e]=!0,console.warn(`Missing translation '${e}'`));const a=e.split("."),n=a[a.length-1]||" ";return n.charAt(0).toUpperCase()+n.slice(1)};
1
+ import{observable as e,action as o,toJS as a}from"mobx";const r=e({variables:{title:"Variables",element:"Selected element",name:"Variable name",label:"Label",add:"Add variable",required:"Required",default:"Default",enterValue:"Enter a value",empty:"Add a variable, then insert it into text or link it to a selected element.",settings:"Settings",delete:"Delete variable",yes:"Yes",no:"No",insert:"Insert variable",search:"Search or add a variable",noMatch:"No matching variables",nameRule:"Use letters, digits, _ and dots",nameTaken:"Already exists",visible:"Visible",src:"Source",fill:"Color",unbound:"Not linked",always:"Always",fit:"Scale",manual:"Crop",cover:"Fill",contain:"Fit",focus:"Focus",orphan:"Unused","mixed-types":"Mixed types"},imageEdit:{title:"AI edit",expand:"Expand",upscale:"Upscale",inpaint:"Generative fill",replace:"Replace",remove:"Remove",prompt:"Your prompt",promptPlaceholder:"Describe what should be there",expandPromptPlaceholder:"Describe the new area (optional)",replaceDescription:"Select an area on the image, then describe what you want to change.",replaceHint:"Describe what should replace the selection, such as “plain wall” or “open sky”.",removeDescription:"Select an object to remove. The surrounding image will fill the selected area.",expandDescription:"Drag the frame beyond the image edges to make room for new content.",cropDescription:"Drag the frame to crop the image.",upscaleDescription:"Increase the image resolution.",removeBackgroundDescription:"Remove the image background.",applyCrop:"Apply crop",generate:"Generate",clear:"Clear selection",resetFrame:"Reset frame",processing:"Generating…",loadingImage:"Loading image…",upscaling:"Upscaling…",removingBackground:"Removing background…",failed:"The image could not be edited. Please try again.",rasterFailed:"This device could not prepare the image. Try a smaller image.",selectRegion:"Drag on the image to select an area."},toolbar:{duration:"Duration",opacity:"Opacity",effects:"Effects",blur:"Blur",curvedText:"Curved text",curvePower:"Power",temperature:"Temperature",saturation:"Saturation",contrast:"Contrast",shadows:"Shadows",white:"White",black:"Black",vibrance:"Vibrance",textBackground:"Background",backgroundCornerRadius:"Corner radius",backgroundOpacity:"Opacity",backgroundPadding:"Spread",backgroundShape:"Shape",backgroundFill:"Fill",backgroundShapeLines:"Lines",backgroundShapeBox:"Box",textPadding:"Padding",paddingSides:"Independent sides",paddingTop:"Top",paddingRight:"Right",paddingBottom:"Bottom",paddingLeft:"Left",brightness:"Brightness",filters:"Filters",sepia:"Sepia",grayscale:"Grayscale",cold:"Cold",natural:"Natural",warm:"Warm",textStroke:"Text Stroke",textEffect:{none:"None",shadow:"Shadow",lift:"Lift",glow:"Glow",outline:"Outline",sticker:"Sticker",pop:"Pop",background:"Background"},blendMode:"Blending",blend:{"pass-through":"Pass Through",normal:"Normal",multiply:"Multiply",screen:"Screen",overlay:"Overlay",darken:"Darken",lighten:"Lighten","color-dodge":"Color Dodge","color-burn":"Color Burn","hard-light":"Hard Light","soft-light":"Soft Light",difference:"Difference",exclusion:"Exclusion",hue:"Hue",saturation:"Saturation",color:"Color",luminosity:"Luminosity"},strokeLineJoin:"Corners",joinRound:"Round",joinMiter:"Miter",joinBevel:"Bevel",shadow:"Drop shadow",border:"Border",cornerRadius:"Corner Radius",copyStyle:"Copy style",uppercase:"Uppercase",position:"Position",layering:"Layering",toForward:"To Front",up:"Forward",down:"Backward",toBottom:"To back",alignLeft:"Align left",alignCenter:"Align center",alignRight:"Align right",alignTop:"Align top",alignMiddle:"Align middle",alignBottom:"Align bottom",flip:"Flip",flipHorizontally:"Flip horizontally",flipVertically:"Flip vertically",fitToBackground:"Fit to page",fitToPage:"Fit to page",widthShort:"W",heightShort:"H",removeBackground:"Remove background",removeBackgroundTitle:"Remove background from image",cancelRemoveBackground:"Cancel",confirmRemoveBackground:"Confirm",crop:"Crop",cropDone:"Done",cropCancel:"Cancel",clip:"Apply mask",removeClip:"Remove mask",removeMask:"Remove mask",transparency:"Transparency",lockedDescription:"Object is locked. Unlock it to allow changes from canvas.",unlockedDescription:"Object is unlocked. Lock it to prevent changes from canvas.",removeElements:"Remove elements",duplicateElements:"Duplicate elements",download:"Download",saveAsImage:"Save as image",saveAsPDF:"Save as PDF",lineHeight:"Line height",letterSpacing:"Letter spacing",offsetX:"Offset X",offsetY:"Offset Y",color:"Color",selectable:"Selectable",draggable:"Draggable",removable:"Removable",resizable:"Resizable",contentEditable:"Can change content",styleEditable:"Can change style",alwaysOnTop:"Always on top",showInExport:"Show in export",ungroupElements:"Ungroup",groupElements:"Group",lineSize:"Line size",fade:"Fade",move:"Move",zoom:"Zoom",animate:"Animate",rotate:"Rotate",none:"None",bounce:"Bounce",blink:"Blink",count:"Count",pop:"Pop",rise:"Rise",flipAnimation:"Flip",growTurn:"Grow & turn",spinAnimation:"Spin",pulse:"Pulse",float:"Float",shake:"Shake",typewriter:"Typewriter",lineRise:"Line rise",wordRise:"Word rise",wordFade:"Word fade",letterPop:"Letter pop",wordBlur:"Word blur",wipe:"Wipe",glow:"Glow",lineWipe:"Line wipe",linePeek:"Line peek",letterWave:"Letter wave",kenBurns:"Ken Burns",strength:"Strength",spaceEvenly:"Space evenly",horizontalDistribution:"Horizontally",verticalDistribution:"Vertically",strokeWidth:"Stroke Width",strokeSettings:"Stroke settings",spacing:"Spacing",volume:"Volume",speed:"Speed",seconds:"sec",lineStyle:"Line style",lineStartHead:"Line start",lineEndHead:"Line end",textDirection:"Text direction",fontSize:"Font size",fontFamily:"Font family",fontFamilyMixed:"Mixed",fontsInSelection:"Fonts in selection",textAlign:"Text align",verticalAlign:"Vertical align",bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",cellBackground:"Cell background",tableBorderSettings:"Border settings",tableBorderColor:"Border color",tableBorderWidth:"Border width",tableBorderStyle:"Border style",borderModeAll:"All borders",borderModeOuter:"Outer borders",borderModeInner:"Inner borders",borderModeBottomOnly:"Bottom only",borderModeTopOnly:"Top only",borderModeLeftOnly:"Left only",borderModeRightOnly:"Right only",borderModeInnerHorizontal:"Inner horizontal",borderModeInnerVertical:"Inner vertical",tableStructure:"Table structure",tableRows:"Rows",tableColumns:"Columns",insertRowAbove:"Insert row above",insertRowBelow:"Insert row below",deleteRow:"Delete row",insertColumnLeft:"Insert column left",insertColumnRight:"Insert column right",deleteColumn:"Delete column",deleteRows:"Delete rows",deleteColumns:"Delete columns",distributeRowsEvenly:"Distribute rows evenly",distributeColumnsEvenly:"Distribute columns evenly",cellPadding:"Cell padding",listFormat:"List",colorPicker:{solid:"Solid",gradient:"Gradient",gradientType:"Gradient type",linear:"Linear",radial:"Radial",center:"Gradient center",centerX:"Center X",centerY:"Center Y",angle:"Angle",stops:"Gradient stops",stop:"Stop",addStop:"Add stop",removeStop:"Remove stop",reverse:"Reverse gradient",colors:"Colors",resetColors:"Reset",recolorAll:"Recolor all"},clipFade:{title:"Fade",preparing:"Preparing mask…",shape:"Shape",linear:"Linear",radial:"Radial",stopOpacity:"Stop opacity",stops:"Fade stops",stop:"Stop",start:"Fade start",end:"Fade end",center:"Fade center",radius:"Fade radius",reverse:"Reverse",removeStop:"Remove stop",addStop:"Add stop",reset:"Reset",hint:"Drag the handles on the image to position the fade."},aiText:{aiWrite:"AI write",rewrite:"Rewrite",shorten:"Shorten",continue:"Continue writing",proofread:"Proofread",tones:"Tones",friendly:"Friendly",professional:"Professional",humorous:"Humorous",formal:"Formal",customPrompt:"Custom prompt",generatedResult:"Generated result",cancel:"Cancel",generate:"Generate",back:"Back",tryAgain:"Try Again",insert:"Insert",promptPlaceholder:"Describe what you want to generate"}},workspace:{noPages:"There are no pages yet...",addPage:"Add page",removePage:"Remove page",duplicatePage:"Duplicate page",moveUp:"Move up",moveDown:"Move down",moveLeft:"Move left",moveRight:"Move right"},scale:{reset:"Reset"},error:{removeBackground:"Ops! Something went wrong. Background can not be removed."},sidePanel:{close:"Close",templates:"Templates",searchTemplatesWithSameSize:"Show templates with the same size",searchPlaceholder:"Search...",otherFormats:"Other formats",noResults:"No results",error:"Loading is failed...",text:"Text",uploadFont:"Upload font",myFonts:"My fonts",photos:"Photos",videos:"Videos",animations:"Animations",effects:"Effects",elements:"Elements",shapes:"Shapes",tables:"Tables",lines:"Lines",draw:"Draw",drawTool:"Tool",drawSelection:"Selection",drawBrush:"Brush",drawHighlighter:"Highlighter",upload:"Upload",uploadImage:"Add file",uploadTip:"Upload your assets",uploadUnsupported:"Skipped some files. You can add images, video, audio and Lottie animations.",uploadFailed:"Upload failed. Please try again.",background:"Background",resize:"Resize",layers:"Layers",animate:"Animate",animationEnter:"Enter",animationBoth:"Both",animationExit:"Exit",animationLoop:"Loop",animationGeneral:"General",animationTextPresets:"Text",animationDuration:"Duration (s)",animationRepeatEvery:"Repeat every (s)",animationStartAt:"Start at (s)",animationEndAt:"End at (s)",animationDirection:"Direction",animationDirections:{right:"Right",left:"Left",up:"Up",down:"Down","bottom-right":"Bottom right","bottom-left":"Bottom left","top-right":"Top right","top-left":"Top left",none:"None"},zoomIn:"Zoom In",zoomOut:"Zoom Out",layerTypes:{image:"Image",text:"Text",svg:"SVG",line:"Line",figure:"Figure",group:"Group"},layersTip:"Elements on your active page:",noLayers:"No elements on the page...",namePlaceholder:"Type element name...",hideLayer:"Hide layer",lockLayer:"Lock layer",deleteLayer:"Delete layer",useMagicResize:"Use magic resize",advanced:"Advanced",bleed:"Bleed",showBleed:"Show bleed",clipImage:"Mask image",width:"Width",height:"Height",units:"Units",magicResizeDescription:"Magic resize will automatically resize and move all elements on the canvas",headerText:"Header",createHeader:"Create header",subHeaderText:"Sub Header",createSubHeader:"Create sub header",bodyText:"Body text",createBody:"Create body text"},pagesTimeline:{pages:"Pages",removePage:"Remove page",addPage:"Add page",duplicatePage:"Duplicate page",removeAudio:"Remove audio",duplicateAudio:"Duplicate audio",renameAudio:"Rename audio",muteAudio:"Mute",unmuteAudio:"Unmute",volume:"Volume",speed:"Speed",rewind:"Rewind to start",editAsVideo:"Edit as video",editAsVideoHint:"On: preview the frame at the playhead — timed elements hide outside their range. Off: show all elements while editing."},contextMenu:{duplicate:"Duplicate",split:"Split at playhead",rename:"Rename",remove:"Remove",lock:"Lock",unlock:"Unlock",copy:"Copy",paste:"Paste",copyStyle:"Copy style",moveUp:"Move up",moveDown:"Move down",moveBack:"Move back",moveForward:"Move forward"}}),n=e=>e&&"object"==typeof e;function i(e,o){Object.keys(o).forEach(a=>{const r=e[a],l=o[a];n(l)&&n(r)?i(r,l):e[a]=l})}function l(e,o,a=""){Object.keys(o).forEach(r=>{const i=o[r],s=a?`${a}.${r}`:r;n(i)?n(e[r])?l(e[r],i,s):console.warn(`Missing nested translation object at '${s}'`):void 0===e[r]&&console.warn(`Missing translation '${s}'`)})}export const setTranslations=o((e,{validate:o=!1}={})=>{o&&l(e,r),i(r,e)});export const getTranslations=()=>a(r);const s={};export const t=e=>{const o=function(e,o){var a,r=o.split("."),n=e;for(a=0;a<r.length;++a){if(null==n[r[a]]){return}n=n[r[a]]}return n}(r,e);if(void 0!==o){return o}s[e]||(s[e]=!0,console.warn(`Missing translation '${e}'`));const a=e.split("."),n=a[a.length-1]||" ";return n.charAt(0).toUpperCase()+n.slice(1)};
@@ -31,6 +31,11 @@ export type ApplyTextFormatOptions = {
31
31
  export declare function decorationTokensOf(value: string | undefined): Set<DecorationToken>;
32
32
  export declare function decorationTokensToString(tokens: Set<DecorationToken>): string;
33
33
  export declare function isDecorationActive(f: TextFormat, token: DecorationToken): boolean;
34
+ export type FormatToggle = 'bold' | 'italic' | DecorationToken;
35
+ export declare function formatToggle(f: TextFormat, toggle: FormatToggle): {
36
+ attrs: TextFormatAttrs;
37
+ opts?: ApplyTextFormatOptions;
38
+ };
34
39
  export declare const decorationToQuillKey: (t: DecorationToken) => 'underline' | 'strike';
35
40
  export interface TextFormatElement {
36
41
  type?: string;
@@ -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,qlClassToFontFamilyName as a,isClipGradientSpan as c,readNativeColor as f}from"./rich-text-html.js";export const FORMAT_KEYS=["fontSize","fontFamily","fill","fontWeight","fontStyle","textDecoration","textTransform"];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-"));return e&&a(e)||void 0}case"fill":return c(o)?f(o,"background-image")||o.style.backgroundImage:f(o,"color")||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;case"textTransform":return o.style.textTransform||void 0}}function u(t,e){return"fontWeight"===e?s(t.fontWeight):"textTransform"===e?t.textTransform||"none":t[e]}function d(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 a of FORMAT_KEYS){"textDecoration"===a||r.has(a)||(n[a]=u(o,a))}return n.textDecoration=decorationTokensToString(i),n}function h(t,e){return 0===t.length?{value:e,mixed:!1,values:void 0===e?[]:[e]}:1===t.length?{value:t[0],mixed:!1,values:t}:{value:void 0,mixed:!0,values:t}}function x(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]=u(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(d(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?u(t,o):void 0;n[o]=h(r,i)}return n}export function getTextFormat(t){return Array.isArray(t)?function(t){const e={};for(const o of FORMAT_KEYS){const n=[];for(const e of t){for(const t of e[o].values){n.includes(t)||n.push(t)}}e[o]=h(n,void 0)}return e}(t.map(x)):x(t)}function T(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");case"textTransform":return i(t,"text-transform")}}let g=!1;function m(t){return"string"!=typeof t||/^\d+$/.test(t.trim())||g||(g=!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,a={};let c=t.text||"";for(const f of r){if("textDecoration"===f){const o=decorationTokensOf(e.textDecoration),n=decorationTokensOf(t.textDecoration);for(const t of s){o.has(t)?n.add(t):n.delete(t),c=i(c,decorationToQuillKey(t))}a.textDecoration=decorationTokensToString(n);continue}a[f]="fontWeight"===f?String(m(e.fontWeight)):e[f],c=T(c,f)}return c!==(t.text||"")&&(a.text=c),{attrsToSet:a}}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 a of r){const t=a.store,e=s.get(t)||[];e.push(a),s.set(t,e)}for(const[a,c]of s){(null===(n=null==a?void 0:a.history)||void 0===n?void 0:n.transaction)?a.history.transaction(()=>c.forEach(i)):c.forEach(i)}}
1
+ import{parsePrimaryFontFamily as t,parseFontSizeToPx as e,parseHtmlRoot as o,stripInlineFontSizes as n,stripInlineFontFamilies as r,stripInlineFormat as i,toNumericWeight as s,qlClassToFontFamilyName as a,isClipGradientSpan as c,readNativeColor as f,isBoldWeight as l}from"./rich-text-html.js";export const FORMAT_KEYS=["fontSize","fontFamily","fill","fontWeight","fontStyle","textDecoration","textTransform"];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))}function u(t,e){const o="underline"===e?"line-through":"underline",n=new Set;return isDecorationActive(t,e)||n.add(e),isDecorationActive(t,o)&&n.add(o),decorationTokensToString(n)}export function formatToggle(t,e){return"bold"===e?{attrs:{fontWeight:l(t.fontWeight.value)?400:700}}:"italic"===e?{attrs:{fontStyle:"italic"===t.fontStyle.value?"normal":"italic"}}:{attrs:{textDecoration:u(t,e)},opts:{decorationTokens:[e]}}}export const decorationToQuillKey=t=>"underline"===t?"underline":"strike";function d(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-"));return e&&a(e)||void 0}case"fill":return c(o)?f(o,"background-image")||o.style.backgroundImage:f(o,"color")||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;case"textTransform":return o.style.textTransform||void 0}}function h(t,e){return"fontWeight"===e?s(t.fontWeight):"textTransform"===e?t.textTransform||"none":t[e]}function g(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=d(s,"textDecoration",o);if("string"==typeof t){for(const e of decorationTokensOf(t)){i.add(e)}}continue}if(r.has(t)){continue}const e=d(s,t,o);void 0!==e&&(n[t]=e,r.add(t))}s=s.parentElement}for(const a of FORMAT_KEYS){"textDecoration"===a||r.has(a)||(n[a]=h(o,a))}return n.textDecoration=decorationTokensToString(i),n}function T(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 x(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]=h(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(g(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?h(t,o):void 0;n[o]=T(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]=T(n,void 0)}return e}(t.map(x)):x(t)}function m(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");case"textTransform":return i(t,"text-transform")}}let y=!1;function v(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,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,a={};let c=t.text||"";for(const f of r){if("textDecoration"===f){const o=decorationTokensOf(e.textDecoration),n=decorationTokensOf(t.textDecoration);for(const t of s){o.has(t)?n.add(t):n.delete(t),c=i(c,decorationToQuillKey(t))}a.textDecoration=decorationTokensToString(n);continue}a[f]="fontWeight"===f?String(v(e.fontWeight)):e[f],c=m(c,f)}return c!==(t.text||"")&&(a.text=c),{attrsToSet:a}}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 a of r){const t=a.store,e=s.get(t)||[];e.push(a),s.set(t,e)}for(const[a,c]of s){(null===(n=null==a?void 0:a.history)||void 0===n?void 0:n.transaction)?a.history.transaction(()=>c.forEach(i)):c.forEach(i)}}
@@ -1 +1 @@
1
- import*as e from"mobx";import{NO_KEY_MESSAGE as o,NO_VALID_MESSAGE as t,NOT_PAID_MESSAGE as n,NOT_PAID_STYLE as a}from"@polotno/core/validate-key";import{getAPI as i}from"./api.js";import{removeBackgroundState as r}from"./flags.js";const s=e.observable({value:!1}),l=e.observable({value:"v1"});export const ___=()=>l.value;const c=e.observable({value:0});export const ____=()=>c.value;export const isCreditVisible=()=>s.value;const d=e.action(()=>{s.value=!0});let u="";export const getKey=()=>u||"";export const setKey=e=>{u=e||""};let p="undefined"!=typeof window?window.location.origin:"";const v="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,f="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===p&&v&&(p="headless"),"file://"===p&&f&&(p="electron");const m=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${p}" here: https://polotno.com/cabinet`;let g=fetch;export const __=e=>{g=e};export async function isKeyPaid(s){for(let u=0;u<5;u++){try{const d=await g(i()+"/validate-key",{method:"POST",body:JSON.stringify({key:s,sdkVersion:"3.23.0"})});if(e.runInAction(()=>{l.value=d.headers.get("x-api-version")||""}),!s){return console.error(o),e.runInAction(()=>{c.value=1}),!1}if(200!==d.status){await new Promise(e=>setTimeout(e,3e3));continue}const u=await d.json();return u.is_valid||(console.error(t),e.runInAction(()=>{c.value=1})),u.is_paid||(console.log(n,a),e.runInAction(()=>{0===c.value&&(c.value=2)})),u.is_domain_valid||console.log(m,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{r.defaultEnabled=u.remove_background_enabled}),u.is_paid||!1}catch(d){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(u)&&!e||d()}
1
+ import*as e from"mobx";import{NO_KEY_MESSAGE as o,NO_VALID_MESSAGE as t,NOT_PAID_MESSAGE as n,NOT_PAID_STYLE as a}from"@polotno/core/validate-key";import{getAPI as i}from"./api.js";import{removeBackgroundState as r}from"./flags.js";const s=e.observable({value:!1}),l=e.observable({value:"v1"});export const ___=()=>l.value;const c=e.observable({value:0});export const ____=()=>c.value;export const isCreditVisible=()=>s.value;const d=e.action(()=>{s.value=!0});let u="";export const getKey=()=>u||"";export const setKey=e=>{u=e||""};let p="undefined"!=typeof window?window.location.origin:"";const v="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,f="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===p&&v&&(p="headless"),"file://"===p&&f&&(p="electron");const m=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${p}" here: https://polotno.com/cabinet`;let g=fetch;export const __=e=>{g=e};export async function isKeyPaid(s){for(let u=0;u<5;u++){try{const d=await g(i()+"/validate-key",{method:"POST",body:JSON.stringify({key:s,sdkVersion:"3.24.0"})});if(e.runInAction(()=>{l.value=d.headers.get("x-api-version")||""}),!s){return console.error(o),e.runInAction(()=>{c.value=1}),!1}if(200!==d.status){await new Promise(e=>setTimeout(e,3e3));continue}const u=await d.json();return u.is_valid||(console.error(t),e.runInAction(()=>{c.value=1})),u.is_paid||(console.log(n,a),e.runInAction(()=>{0===c.value&&(c.value=2)})),u.is_domain_valid||console.log(m,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{r.defaultEnabled=u.remove_background_enabled}),u.is_paid||!1}catch(d){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(u)&&!e||d()}