polotno 4.5.2 → 4.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +22 -7
- package/README.md +1 -1
- package/blueprint/toolbar/image-toolbar.d.ts +2 -2
- package/blueprint/toolbar/sketch.js +1 -1
- package/blueprint.polotno.css +116 -116
- package/canvas/apply-filters.d.ts +1 -1
- package/canvas/audio.js +1 -1
- package/canvas/context-menu/context-menu.d.ts +2 -2
- package/canvas/figure-element.js +1 -1
- package/canvas/gif-element.js +1 -1
- package/canvas/html-element.js +1 -1
- package/canvas/image-element.d.ts +11 -0
- package/canvas/image-element.js +1 -1
- package/canvas/page-controls.d.ts +1 -1
- package/canvas/page.js +1 -1
- package/canvas/render-tag-element.js +1 -1
- package/canvas/rich-editor.d.ts +0 -4
- package/canvas/rich-editor.js +2 -2
- package/canvas/rules.d.ts +1 -1
- package/canvas/text-element.js +1 -1
- package/canvas/tooltip.d.ts +2 -2
- package/canvas/use-mediabunny-video.js +1 -1
- package/canvas/video-element.js +1 -1
- package/hooks/use-event.js +1 -1
- package/icons/registry.d.ts +1 -0
- package/icons/registry.js +1 -1
- package/model/audio-model.d.ts +2 -0
- package/model/audio-model.js +1 -1
- package/model/image-model.js +1 -1
- package/model/store.d.ts +3 -0
- package/model/store.js +1 -1
- package/package.json +30 -30
- package/pages-timeline/audio-track.d.ts +3 -2
- package/pages-timeline/audio-track.js +1 -1
- package/pages-timeline/audios.js +1 -1
- package/pages-timeline/current-time.js +1 -1
- package/pages-timeline/element-track.js +1 -1
- package/pages-timeline/index.d.ts +1 -1
- package/pages-timeline/index.js +1 -1
- package/pages-timeline/page-preview.js +1 -1
- package/pages-timeline/pages-timeline.js +1 -1
- package/pages-timeline/pages.js +1 -1
- package/pages-timeline/play-button.d.ts +1 -1
- package/pages-timeline/play-button.js +1 -1
- package/pages-timeline/time-ruler.js +1 -1
- package/pages-timeline/track-styles.d.ts +9 -0
- package/pages-timeline/track-styles.js +1 -1
- package/polotno.bundle.js +200 -201
- package/primitives/button-group.d.ts +2 -2
- package/primitives/button.d.ts +2 -2
- package/primitives/dialog.d.ts +2 -2
- package/primitives/dropdown-menu.d.ts +2 -2
- package/primitives/field-group.d.ts +1 -1
- package/primitives/field-row.d.ts +1 -1
- package/primitives/floating-control.js +2 -2
- package/primitives/index.d.ts +27 -27
- package/primitives/input-group.d.ts +2 -2
- package/primitives/input.d.ts +1 -1
- package/primitives/navbar.d.ts +5 -5
- package/primitives/numeric-input.d.ts +1 -1
- package/primitives/overflow-list.d.ts +1 -1
- package/primitives/panel-header.d.ts +1 -1
- package/primitives/popover.d.ts +2 -2
- package/primitives/portal-scope.d.ts +3 -3
- package/primitives/search-input.d.ts +1 -1
- package/primitives/select.d.ts +3 -3
- package/primitives/separator.d.ts +1 -1
- package/primitives/slider-field.d.ts +1 -1
- package/primitives/slider.d.ts +2 -2
- package/primitives/spinner.d.ts +1 -1
- package/primitives/switch.d.ts +1 -1
- package/primitives/tabs.d.ts +2 -2
- package/primitives/textarea.d.ts +1 -1
- package/primitives/toggle-group.d.ts +4 -4
- package/primitives/toggle.d.ts +3 -3
- package/primitives/tooltip-icon-button.d.ts +4 -4
- package/primitives/tooltip.d.ts +2 -2
- package/side-panel/background-panel.d.ts +2 -2
- package/side-panel/draw-panel.d.ts +2 -2
- package/side-panel/elements-panel.d.ts +2 -2
- package/side-panel/images-grid.js +1 -1
- package/side-panel/index.d.ts +35 -35
- package/side-panel/photos-panel.d.ts +1 -1
- package/side-panel/select-gif.d.ts +1 -1
- package/side-panel/side-panel.d.ts +5 -5
- package/side-panel/size-panel.d.ts +3 -3
- package/side-panel/tab-button.d.ts +1 -1
- package/side-panel/tab-button.js +2 -2
- package/side-panel/templates-panel.d.ts +2 -2
- package/side-panel/unsplash-credit.d.ts +1 -1
- package/side-panel/upload-panel.d.ts +3 -3
- package/side-panel/upload-panel.js +1 -1
- package/side-panel/videos-grid.js +1 -1
- package/themes/blueprint.css +1 -1
- package/themes/carbon.css +127 -128
- package/toolbar/download-button.d.ts +2 -2
- package/toolbar/element-container.d.ts +1 -1
- package/toolbar/filters-picker.d.ts +1 -1
- package/toolbar/group-toolbar.d.ts +2 -2
- package/toolbar/history-buttons.d.ts +1 -1
- package/toolbar/image-remove-background-button.d.ts +1 -1
- package/toolbar/image-toolbar.d.ts +1 -1
- package/toolbar/index.d.ts +34 -34
- package/toolbar/many-toolbar.d.ts +2 -2
- package/toolbar/opacity-picker.d.ts +1 -1
- package/toolbar/page-toolbar.d.ts +3 -3
- package/toolbar/toolbar.d.ts +3 -3
- package/toolbar/video-toolbar.js +1 -1
- package/toolbar/zoom-buttons.d.ts +1 -1
- package/ui-types.d.ts +8 -8
- package/ui.css +2 -2
- package/utils/array.js +1 -1
- package/utils/file.d.ts +3 -0
- package/utils/file.js +1 -1
- package/utils/html-to-svg/svg-builder.d.ts +1 -1
- package/utils/insert-file.d.ts +3 -2
- package/utils/insert-file.js +1 -1
- package/utils/l10n.d.ts +4 -0
- package/utils/l10n.js +1 -1
- package/utils/media.d.ts +6 -0
- package/utils/media.js +1 -0
- package/utils/pointer-drag.d.ts +13 -0
- package/utils/pointer-drag.js +1 -0
- package/utils/px.d.ts +2 -0
- package/utils/px.js +1 -1
- package/utils/text-format-state.js +1 -1
- package/utils/validate-key.js +1 -1
package/canvas/rules.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ type TopRulesProps = {
|
|
|
10
10
|
layout?: 'vertical' | 'horizontal';
|
|
11
11
|
renderOnlyActivePage?: boolean;
|
|
12
12
|
};
|
|
13
|
-
export declare const TopRules: (({ store, width, height, pageSizes, layout, renderOnlyActivePage }: TopRulesProps) => React.JSX.Element | null) & {
|
|
13
|
+
export declare const TopRules: (({ store, width, height, pageSizes, layout, renderOnlyActivePage, }: TopRulesProps) => React.JSX.Element | null) & {
|
|
14
14
|
displayName: string;
|
|
15
15
|
};
|
|
16
16
|
export {};
|
package/canvas/text-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as l,TextPath as s}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as p}from"@polotno/core/background-shape";import{useColor as m}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as v}from"../utils/loader.js";import{scaledFontSizeAttrs as y,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as b,textMinResizeWidth as E}from"../utils/px.js";import{isFontLoaded as z}from"../utils/fonts.js";import{flags as k}from"../utils/flags.js";import{removeTags as O}from"@polotno/core/text";import{getDir as R,getCurvePath as A,resolveLineHeight as F,normalizeStrokeLineJoin as M}from"@polotno/core/text-html";import{applyFilter as j}from"./apply-filters.js";import{useFadeIn as L}from"./use-fadein.js";import{isTouchDevice as T}from"../utils/screen.js";import{isAlive as C,getParent as H}from"mobx-state-tree";import{getLimitedFontSize as P}from"./text-element/max-font-size.js";import{getOptimalCaretColor as X}from"./text-element/caret-color.js";import{visiblePlaceholder as Y}from"./text-element/placeholder.js";import{hasMeasuredHeight as W,resolveTextBoxHeight as D}from"@polotno/core/text-types";let $;function B(){return $||($=document.getElementById("polotno-text-style"),$||($=document.createElement("style"),$.id="polotno-text-style",document.head.appendChild($)),$)}d._fixTextRendering=!0;const I={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"@polotno/core/text-html";const N=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[l,s]=n.useState(I),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=X(r);const e=`\n .polotno-input::placeholder {\n color: ${l.color};\n opacity: 0.6;\n }\n `,n=B();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(l)&&s(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize(),h=D(r.a,f);"middle"===r.verticalAlign&&(d=(h-f)/2),"bottom"===r.verticalAlign&&(d=h-f);const g=O(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:R(g),style:Object.assign(Object.assign(Object.assign({},I),l),{paddingTop:d+"px"}),value:g,onChange:t=>{const e=P({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},y(r,e)))},placeholder:Y(r.placeholder),onBlur:o})}),J=e=>t(c,{children:t(N,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=n.useRef(z(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(s.current=z(e,r,o),s.current){return}let n=!0;return(async()=>{s.current=!1,l();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,s.current=!0,l()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{s.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[s.current]),[s.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,l]=n.useReducer(t=>t+1,0),s=e.join("\0"),c=n.useRef(e.every(t=>z(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>z(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,l();const a=v(`text fonts ${s}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,l()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[s,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>F({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function _(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=O(e.text);let a=e.a.fontSize;t.height(void 0);const l=Math.round(2*e.a.fontSize)-1;for(let s=1;s<l;s++){const n=W(e.a)&&t.height()>e.a.height;let o=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),l=t.textArr.map(t=>t.text.toLowerCase()).join(";");const s=o.find(t=>!l.includes(t)||(l=l.replace(t,""),!1));if(!(n||s&&!r)){break}a-=.5,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),z=n.useRef(null),F=n.useRef(null),P=n.useRef(null),X=n.useRef([]),$=n.useRef(!0),[,B]=n.useReducer(t=>t+1,0),{editorEnabled:I,selectAll:N}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[V,q]=n.useState(!1),[U,Z]=n.useState(!1),G=n.useRef(o.a.height),K=n.useRef(0),Q=n.useRef(""),tt=n.useRef(0),et=o.isSelected,rt=usePrevious(et),{textVerticalResizeEnabled:nt}=k,ot=k.autoDeleteEmptyText,it=usePrevious(o.fontFamily),[at,lt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=z.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(at)&<(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=z.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{rt&&!et&&ot&&""===o.text&&o.removable&&!Y(o.placeholder)&&c.deleteElements([o.id])},[ot,o.placeholder,o.removable,o.text,et,rt]);const st=()=>{if(o.curveEnabled){const t=z.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=F.current;e&&j(e,o)}else{const t=z.current;t&&j(t,o)}};n.useLayoutEffect(()=>{if(!U){return u(o,()=>{st()})}}),n.useEffect(()=>{const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{$.current=!1;const t=X.current;t.length>0&&(X.current=[],t.forEach(t=>t()))},[]);let ct=O(o.text);"uppercase"===o.textTransform&&(ct=ct.toUpperCase());const[ut]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),dt=()=>{if(o.curveEnabled){const t=F.current;return t.getSelfRect().height||t.fontSize()}const t=z.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!ut){return}if("tablecell"===o.type){const{textOverflow:t}=k;if("resize"===t){const t=dt(),e=C(o)?H(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=z.current;if(t){const e=_(t,o,k.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=k,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{$.current?(X.current.push(i),B()):i()})};n?queueMicrotask(a):a()};if(!W(o)){const t=dt();return void r(()=>{W(o)||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||V){if("resize"===t){const t=dt();nt&&o.height<t&&!V&&r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0),nt||o.height===t||V||r(()=>{var e;C(o)&&o.set({height:t}),null===(e=z.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=z.current,n=o.curveEnabled?o.fontSize:_(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(y(o,n))},!1,!0)}const i=dt();o.height===i||nt||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(ut&&o.curveEnabled){const e=null===(t=F.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[ut,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=z.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),st())},[ut]);const ft=n.useRef(null),ht=n.useRef(o.width),gt=n.useRef(0),pt=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(gt.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),l=null!==(e=o[i])&&void 0!==e?e:o[0];let s=0;return"right"===r.align()?s=r.width()-l.width:"center"===r.align()&&(s=r.width()/2-l.width/2),a+Math.round((n.x-s)/l.width*l.text.length)}(t),o.toggleEditMode())},mt=Y(o.placeholder),xt=!ct&&mt?.6:o.a.opacity;L(z,xt);const wt=getLineHeight({fontLoaded:ut,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),vt=o.selectable||c.role===w.ADMIN,yt=m(o),St=m(o,o.stroke,"stroke"),bt=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,l=e+r,s=f(`M ${o} ${i} L ${a} ${i} L ${a} ${l} L ${o} ${l} Z`);return h(s,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*wt*.5),padding:o.backgroundPadding*(o.a.fontSize*wt*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=p({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(at)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*wt*.5),lineHeight:wt*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*wt*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,wt,o.backgroundPadding,o.a.width,o.align,at]),Et=T();let zt=0;if(!o.curveEnabled){const t=at.length*wt*o.a.fontSize,e=D(o.a,t);"middle"===o.verticalAlign?zt=(e-t)/2:"bottom"===o.verticalAlign&&(zt=e-t)}const kt=o.curveEnabled?A(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",Ot=ut?'"'+o.fontFamily+'"':it===o.fontFamily?"Arial":'"'+it+'"',Rt=R(ct);return r(e,{children:[t(a,{ref:P,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*xt,data:bt,fill:o.backgroundColor,offsetY:-zt}),t(a,{data:kt,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(s,Object.assign({ref:F,visible:o.curveEnabled,data:kt,text:ct||mt,listening:!1,align:"center",textBaseline:"middle",direction:Rt},yt,St,{strokeWidth:o.strokeWidth,lineJoin:M(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`"${o.fontFamily}", "${it}"`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:xt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(l,Object.assign({ref:z,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:W(o.a)?o.a.height:void 0,text:ct||mt,direction:Rt},yt,St,{lineJoin:M(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:Ot,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:Et?o.draggable&&et:o.draggable,preventDefault:!Et||et,opacity:o.curveEnabled?0:xt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===k.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:wt,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&vt,onDragStart:()=>{Z(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{Z(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:pt,onTap:pt,onTransformStart:()=>{var t,e;q(!0);const r=z.current;G.current=r.height(),ht.current=o.a.width,ft.current=r.position(),K.current=r.rotation(),tt.current=r.height();const n=null===(t=r.getStage())||void 0===t?void 0:t.findOne("Transformer");Q.current=null!==(e=null==n?void 0:n.getActiveAnchor())&&void 0!==e?e:""},onTransform:t=>{var e,r,n;const i=t.target;null===(e=P.current)||void 0===e||e.setAttrs({x:i.x(),y:i.y(),rotation:i.rotation(),scale:i.scale()});const a=(null===(r=i.getStage())||void 0===r?void 0:r.findOne("Transformer")).getActiveAnchor();if("middle-left"===a||"middle-right"===a){const t=i.scaleX(),e=i.width()*t,r=E(ht.current,o.a.fontSize);let n=e;e<r&&(n=r,ft.current&&i.position(ft.current)),i.width(n),i.scaleX(1),i.scaleY(1);let a=dt();if("ellipsis"===k.textOverflow){a=G.current}else{const t=Math.max(a,G.current);i.height(t),o.set({height:i.height()})}const l=k.textVerticalResizeEnabled?Math.max(a,G.current):dt();o.set({x:i.x(),width:i.width(),rotation:i.rotation(),height:l}),i.skewX(0),i.skewY(0),st()}if("top-center"===a||"bottom-center"===a){const e="resize"===k.textOverflow?dt():wt*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),ft.current){if("top-center"===Q.current){const r=K.current*Math.PI/180,n=tt.current-e;t.target.x(ft.current.x-n*Math.sin(r)),t.target.y(ft.current.y+n*Math.cos(r))}else{t.target.position(ft.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(K.current),t.target.skewX(0),t.target.skewY(0),tt.current=Math.max(e,r)}ft.current=t.target.position();const l=t.target.scaleX();null===(n=P.current)||void 0===n||n.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*l,width:t.target.width()*l,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*l,shadowBlur:o.shadowBlur*l,shadowOffsetX:o.shadowOffsetX*l,shadowOffsetY:o.shadowOffsetY*l,strokeWidth:o.strokeWidth*l})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set(Object.assign(Object.assign({},S(o,o.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*r})),null===(e=P.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),q(!1)}})),I&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(J,{textNodeRef:z,element:o,selectAll:N,cursorPosition:gt.current,onBlur:()=>{o.set(b(o)),o.toggleEditMode(!1)}})})]})});
|
|
1
|
+
import{jsx as t,Fragment as e,jsxs as r}from"react/jsx-runtime";import n from"react";import{observer as o}from"mobx-react-lite";import{Group as i,Path as a,Text as s,TextPath as l}from"react-konva";import{Html as c}from"react-konva-utils";import{nodeAutorun as u}from"../utils/mobx.js";import d from"konva";import{parsePath as f,roundCommands as h}from"svg-round-corners/lib/index.js";import{generateBackgroundShapeFromRects as g,textLinesToRects as p}from"@polotno/core/background-shape";import{useColor as m}from"./use-color.js";import{useWorkspaceStyle as x}from"./workspace-style.js";import{ROLES as w}from"../model/store.js";import{incrementLoader as v}from"../utils/loader.js";import{activeAnchorOf as y,scaledFontSizeAttrs as b,roundedFontSizeAttrs as S,roundedTextDecorationAttrs as E,textMinResizeWidth as z}from"../utils/px.js";import{isFontLoaded as k}from"../utils/fonts.js";import{flags as O}from"../utils/flags.js";import{removeTags as R}from"@polotno/core/text";import{getDir as F,getCurvePath as A,resolveLineHeight as M,normalizeStrokeLineJoin as j}from"@polotno/core/text-html";import{applyFilter as L}from"./apply-filters.js";import{useFadeIn as C}from"./use-fadein.js";import{isTouchDevice as T}from"../utils/screen.js";import{isAlive as H,getParent as P}from"mobx-state-tree";import{getLimitedFontSize as X}from"./text-element/max-font-size.js";import{getOptimalCaretColor as Y}from"./text-element/caret-color.js";import{visiblePlaceholder as W}from"./text-element/placeholder.js";import{hasMeasuredHeight as D,resolveTextBoxHeight as $}from"@polotno/core/text-types";let B;function I(){return B||(B=document.getElementById("polotno-text-style"),B||(B=document.createElement("style"),B.id="polotno-text-style",document.head.appendChild(B)),B)}d._fixTextRendering=!0;const N={border:"none",padding:"0px",overflow:"hidden",background:"none",outline:"none",resize:"none",overflowWrap:"break-word",whiteSpace:"pre-wrap",userSelect:"text",wordBreak:"normal",textTransform:"none"};export{getDir}from"@polotno/core/text-html";const J=o(({textNodeRef:e,element:r,onBlur:o,selectAll:i,cursorPosition:a})=>{const[s,l]=n.useState(N),c=e.current;n.useLayoutEffect(()=>{if(!c){return}const t={};t.width=c.width()-2*c.padding()+"px",t.height=c.height()-2*c.padding()+c.fontSize()*c.lineHeight()+"px",t.fontSize=c.fontSize()+"px",t.lineHeight=c.lineHeight()+.01,t.fontFamily=c.fontFamily(),t.textAlign=c.align(),t.color=c.fill(),t.fontWeight=r.fontWeight,t.fontStyle=r.fontStyle,t.letterSpacing=r.letterSpacing+"em",t.opacity=Math.max(r.a.opacity,.2),t.textTransform=r.textTransform,t.caretColor=Y(r);const e=`\n .polotno-input::placeholder {\n color: ${s.color};\n opacity: 0.6;\n }\n `,n=I();n.innerHTML="",n.appendChild(document.createTextNode(e)),JSON.stringify(t)!==JSON.stringify(s)&&l(t)});const u=n.useRef(null);if(n.useLayoutEffect(()=>{var t;const e=u.current;if(!e){return}null===(t=u.current)||void 0===t||t.focus({preventScroll:!0});const r=a||e.value.length;e.selectionStart=e.selectionEnd=r,i&&(null==e||e.select(),document.execCommand("selectAll",!1,void 0))},[]),n.useEffect(()=>{window.addEventListener("blur",o);const t=t=>{var e;(null===(e=u.current)||void 0===e?void 0:e.contains(t.target))||o()};return window.addEventListener("touchstart",t),()=>{window.removeEventListener("blur",o),window.removeEventListener("touchstart",t)}},[]),!c){return null}let d=0;const f=c.textArr.length*c.lineHeight()*c.fontSize(),h=$(r.a,f);"middle"===r.verticalAlign&&(d=(h-f)/2),"bottom"===r.verticalAlign&&(d=h-f);const g=R(r.text);return t("textarea",{className:"polotno-input",ref:u,dir:F(g),style:Object.assign(Object.assign(Object.assign({},N),s),{paddingTop:d+"px"}),value:g,onChange:t=>{const e=X({oldText:r.text,newText:t.target.value,element:r});r.set(Object.assign({text:t.target.value},b(r,e)))},placeholder:W(r.placeholder),onBlur:o})}),_=e=>t(c,{children:t(J,Object.assign({},e))});export const useFontLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=n.useRef(k(e,r,o)),c=n.useRef(null);return n.useLayoutEffect(()=>{if(l.current=k(e,r,o),l.current){return}let n=!0;return(async()=>{l.current=!1,s();const a=v(`text ${e}`);await t.loadFont(e,r,o,i),n?(c.current=a,l.current=!0,s()):a()})(),()=>{c.current&&(c.current(),c.current=null),n=!1}},[e,r,o]),n.useEffect(()=>{l.current&&setTimeout(()=>{c.current&&(c.current(),c.current=null)})},[l.current]),[l.current]};export const useFontFamiliesLoader=(t,e,r,o,i)=>{const[a,s]=n.useReducer(t=>t+1,0),l=e.join("\0"),c=n.useRef(e.every(t=>k(t,r,o))),u=n.useRef(null);return n.useLayoutEffect(()=>{if(c.current=e.every(t=>k(t,r,o)),c.current){return}let n=!0;return(async()=>{c.current=!1,s();const a=v(`text fonts ${l}`);await Promise.all(e.map(e=>t.loadFont(e,r,o,i))),n?(u.current=a,c.current=!0,s()):a()})(),()=>{u.current&&(u.current(),u.current=null),n=!1}},[l,r,o]),n.useEffect(()=>{c.current&&setTimeout(()=>{u.current&&(u.current(),u.current=null)})},[c.current]),[c.current]};export const getLineHeight=({fontLoaded:t,fontFamily:e,fontSize:r,lineHeight:o})=>n.useMemo(()=>M({fontFamily:e,fontSize:r,lineHeight:o}),[t,e,r,o]);export function usePrevious(t){const e=n.useRef(t),r=n.useRef(t);return n.useMemo(()=>{r.current=e.current,e.current=t},[t]),r.current}function V(t,e,r=!1){const n=t.fontSize(),o=t.height(),i=R(e.text);let a=e.a.fontSize;t.height(void 0);const s=Math.round(2*e.a.fontSize)-1;for(let l=1;l<s;l++){const n=D(e.a)&&t.height()>e.a.height;let o=i.split("\n").join(" ").split(/[\s-]+/).reduce((t,e)=>(e=e.toLowerCase(),/[\u3000-\u303F\u3040-\u309F\u30A0-\u30FF\uFF00-\uFFEF\u4E00-\u9FAF\uAC00-\uD7AF]/.test(e)?t.concat(e.split("")):t.concat(e)),[]),s=t.textArr.map(t=>t.text.toLowerCase()).join(";");const l=o.find(t=>!s.includes(t)||(s=s.replace(t,""),!1));if(!(n||l&&!r)){break}a-=.5,t.fontSize(a)}return t.fontSize(n),t.height(o),a}export{getCurvePath}from"@polotno/core/text-html";export const TextElement=o(({element:o,store:c})=>{const{textOverflowIndicatorStyle:d}=x(),k=n.useRef(null),M=n.useRef(null),X=n.useRef(null),Y=n.useRef([]),B=n.useRef(!0),[,I]=n.useReducer(t=>t+1,0),{editorEnabled:N,selectAll:J}=(t=>{const[e,r]=n.useState(!1),o=n.useRef(!1);return n.useEffect(()=>{var e=!0;return setTimeout(()=>{e&&(t._editModeEnabled&&(o.current=!0),r(!0),setTimeout(()=>{o.current=!1},50))},50),()=>{e=!1}},[]),{editorEnabled:e&&t._editModeEnabled,selectAll:o.current}})(o),[q,U]=n.useState(!1),[Z,G]=n.useState(!1),K=n.useRef(o.a.height),Q=n.useRef(0),tt=n.useRef(""),et=n.useRef(0),rt=o.isSelected,nt=usePrevious(rt),{textVerticalResizeEnabled:ot}=O,it=O.autoDeleteEmptyText,at=usePrevious(o.fontFamily),[st,lt]=n.useState([]);n.useEffect(()=>{var t,e;const r=null!==(e=null===(t=k.current)||void 0===t?void 0:t.textArr)&&void 0!==e?e:[];JSON.stringify(r)!==JSON.stringify(st)&<(r)}),n.useEffect(()=>{if(o.a.width||"tablecell"===o.type){return}const t=k.current;t.width(600),o.set({width:1.4*t.getTextWidth()})},[]),n.useEffect(()=>{nt&&!rt&&it&&""===o.text&&o.removable&&!W(o.placeholder)&&c.deleteElements([o.id])},[it,o.placeholder,o.removable,o.text,rt,nt]);const ct=()=>{if(o.curveEnabled){const t=k.current;null==t||t.clearCache(),null==t||t.setAttrs({filters:[]});const e=M.current;e&&L(e,o)}else{const t=k.current;t&&L(t,o)}};n.useLayoutEffect(()=>{if(!Z){return u(o,()=>{ct()})}}),n.useEffect(()=>{const t=Y.current;t.length>0&&(Y.current=[],t.forEach(t=>t()))}),n.useEffect(()=>()=>{B.current=!1;const t=Y.current;t.length>0&&(Y.current=[],t.forEach(t=>t()))},[]);let ut=R(o.text);"uppercase"===o.textTransform&&(ut=ut.toUpperCase());const[dt]=useFontLoader(c,o.fontFamily,o.fontStyle,o.fontWeight,o.text||o.placeholder),ft=()=>{if(o.curveEnabled){const t=M.current;return t.getSelfRect().height||t.fontSize()}const t=k.current.clone({height:void 0}),e=Math.ceil(t.fontSize()*t.lineHeight()*t.textArr.length+1);return t.destroy(),e};n.useLayoutEffect(()=>{if(!dt){return}if("tablecell"===o.type){const{textOverflow:t}=O;if("resize"===t){const t=ft(),e=H(o)?P(o,2):null;(null==e?void 0:e.setCellContentHeight)&&e.setCellContentHeight(o.id,t)}else if("change-font-size"===t){const t=k.current;if(t){const e=V(t,o,O.textSplitAllowed);e!==o.fontSize&&c.history.ignore(()=>{o.set({fontSize:e})})}}return}const{textOverflow:t,textSplitAllowed:e}=O,r=(t,e,r,n)=>{const i=v(`text ${o.id}`),a=()=>{c.history.ignore(t,e,r).then(()=>{B.current?(Y.current.push(i),I()):i()})};n?queueMicrotask(a):a()};if(!D(o)){const t=ft();return void r(()=>{D(o)||o.set({height:t})},void 0,void 0,!0)}if(!c.isPlaying){if("change-font-size"!==t||q){if("resize"===t){const t=ft();ot&&o.height<t&&!q&&r(()=>{var e;H(o)&&o.set({height:t}),null===(e=k.current)||void 0===e||e.height(t)},!1,!0),ot||o.height===t||q||r(()=>{var e;H(o)&&o.set({height:t}),null===(e=k.current)||void 0===e||e.height(t)},!1,!0)}}else{const t=k.current,n=o.curveEnabled?o.fontSize:V(t,o,e);if(n!==o.fontSize){return void r(()=>{o.set(b(o,n))},!1,!0)}const i=ft();o.height===i||ot||r(()=>{o.set({height:i})},!1,!0)}}}),n.useLayoutEffect(()=>{var t;if(dt&&o.curveEnabled){const e=null===(t=M.current)||void 0===t?void 0:t.getSelfRect().width;if(e){const t=e-o.a.width,r=o.a.rotation*Math.PI/180,n=-t/2*Math.cos(r),i=-t/2*Math.sin(r);o.set({width:e,x:o.a.x+n,y:o.a.y+i})}}},[dt,o.curveEnabled,o.curvePower,o.text,o.fontSize,o.fontFamily,o.fontWeight,o.fontStyle,o.letterSpacing]),n.useLayoutEffect(()=>{const t=k.current;t&&(t.width(t.width()+1e-8),t.width(t.width()-1e-8),t._setTextData(),ct())},[dt]);const ht=n.useRef(null),gt=n.useRef(o.width),pt=n.useRef(0),mt=t=>{t.evt.preventDefault();const e=c.selectedShapes.find(t=>t===o);e&&o.contentEditable&&(pt.current=function(t){var e;const r=t.target,n=function(t){var e=t.getAbsoluteTransform().copy();e.invert();var r=t.getStage().getPointerPosition();return e.point(r)}(r),o=r.textArr,i=Math.floor(n.y/(r.fontSize()*r.lineHeight())),a=o.slice(0,i).reduce((t,e)=>t+e.text.length,i),s=null!==(e=o[i])&&void 0!==e?e:o[0];let l=0;return"right"===r.align()?l=r.width()-s.width:"center"===r.align()&&(l=r.width()/2-s.width/2),a+Math.round((n.x-l)/s.width*s.text.length)}(t),o.toggleEditMode())},xt=W(o.placeholder),wt=!ut&&xt?.6:o.a.opacity;C(k,wt);const vt=getLineHeight({fontLoaded:dt,fontFamily:o.fontFamily,fontSize:o.a.fontSize,lineHeight:o.lineHeight}),yt=o.selectable||c.role===w.ADMIN,bt=m(o),St=m(o,o.stroke,"stroke"),Et=n.useMemo(()=>o.backgroundEnabled?o.curveEnabled?function({width:t,height:e,padding:r=0,cornerRadius:n=0}){const o=-r,i=-r,a=t+r,s=e+r,l=f(`M ${o} ${i} L ${a} ${i} L ${a} ${s} L ${o} ${s} Z`);return h(l,n).path}({width:o.a.width,height:o.a.height,cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*vt*.5),padding:o.backgroundPadding*(o.a.fontSize*vt*.5)}):function({lines:t,lineHeight:e,width:r,align:n="left",padding:o=0,cornerRadius:i=0}){const a=p({lines:t,lineHeight:e,width:r,align:n});return g({rects:a,padding:o,cornerRadius:i})}({lines:JSON.parse(JSON.stringify(st)),cornerRadius:o.backgroundCornerRadius*(o.a.fontSize*vt*.5),lineHeight:vt*o.a.fontSize,padding:o.backgroundPadding*(o.a.fontSize*vt*.5),width:o.a.width,align:o.align}):"",[o.backgroundEnabled,o.curveEnabled,o.backgroundCornerRadius,o.a.fontSize,o.a.height,vt,o.backgroundPadding,o.a.width,o.align,st]),zt=T();let kt=0;if(!o.curveEnabled){const t=st.length*vt*o.a.fontSize,e=$(o.a,t);"middle"===o.verticalAlign?kt=(e-t)/2:"bottom"===o.verticalAlign&&(kt=e-t)}const Ot=o.curveEnabled?A(o.a.width,o.a.height,o.curvePower,o.a.fontSize):"",Rt=dt?'"'+o.fontFamily+'"':at===o.fontFamily?"Arial":'"'+at+'"',Ft=F(ut);return r(e,{children:[t(a,{ref:X,x:o.a.x,y:o.a.y,rotation:o.a.rotation,hideInExport:!o.showInExport,listening:!1,visible:o.backgroundEnabled,opacity:o.backgroundOpacity*wt,data:Et,fill:o.backgroundColor,offsetY:-kt}),t(a,{data:Ot,stroke:d.stroke,strokeWidth:1,x:o.a.x,y:o.a.y,rotation:o.a.rotation,visible:!1}),t(l,Object.assign({ref:M,visible:o.curveEnabled,data:Ot,text:ut||xt,listening:!1,align:"center",textBaseline:"middle",direction:Ft},bt,St,{strokeWidth:o.strokeWidth,lineJoin:j(o.strokeLineJoin),fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:`"${o.fontFamily}", "${at}"`,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration.trim(),letterSpacing:o.letterSpacing*o.a.fontSize,x:o.a.x,y:o.a.y,rotation:o.a.rotation,opacity:o._editModeEnabled?.3:wt,hideInExport:!o.showInExport,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity})),t(s,Object.assign({ref:k,id:o.selectable?o.id:void 0,name:o.selectable?"element":"",hideInExport:!o.showInExport,editModeEnabled:o._editModeEnabled,x:o.a.x,y:o.a.y,rotation:o.a.rotation,width:o.a.width,height:D(o.a)?o.a.height:void 0,text:ut||xt,direction:Ft},bt,St,{lineJoin:j(o.strokeLineJoin),strokeWidth:o.strokeWidth,fillAfterStrokeEnabled:!0,fontSize:o.a.fontSize,fontFamily:Rt,fontStyle:o.fontStyle+" "+o.fontWeight,textDecoration:o.textDecoration,align:o.align,verticalAlign:o.verticalAlign,draggable:zt?o.draggable&&rt:o.draggable,preventDefault:!zt||rt,opacity:o.curveEnabled?0:wt,visible:!o._editModeEnabled,ellipsis:"ellipsis"===O.textOverflow,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,lineHeight:vt,letterSpacing:o.letterSpacing*o.a.fontSize,listening:!!o.selectable&&yt,onDragStart:()=>{G(!0)},onDragMove:t=>{o.set({x:t.target.x(),y:t.target.y()})},onDragEnd:t=>{G(!1),o.set({x:t.target.x(),y:t.target.y()})},onClick:mt,onTap:mt,onTransformStart:()=>{U(!0);const t=k.current;K.current=t.height(),gt.current=o.a.width,ht.current=t.position(),Q.current=t.rotation(),et.current=t.height(),tt.current=y(t)},onTransform:t=>{var e,r;const n=t.target;null===(e=X.current)||void 0===e||e.setAttrs({x:n.x(),y:n.y(),rotation:n.rotation(),scale:n.scale()});const i=tt.current;if("middle-left"===i||"middle-right"===i){const t=n.scaleX(),e=n.width()*t,r=z(gt.current,o.a.fontSize);let i=e;e<r&&(i=r,ht.current&&n.position(ht.current)),n.width(i),n.scaleX(1),n.scaleY(1);let a=ft();if("ellipsis"===O.textOverflow){a=K.current}else{const t=Math.max(a,K.current);n.height(t),o.set({height:n.height()})}const s=O.textVerticalResizeEnabled?Math.max(a,K.current):ft();o.set({x:n.x(),width:n.width(),rotation:n.rotation(),height:s}),n.skewX(0),n.skewY(0),ct()}if("top-center"===i||"bottom-center"===i){const e="resize"===O.textOverflow?ft():vt*o.a.fontSize,r=t.target.height()*t.target.scaleY();if(r<e){if(t.target.height(e),ht.current){if("top-center"===tt.current){const r=Q.current*Math.PI/180,n=et.current-e;t.target.x(ht.current.x-n*Math.sin(r)),t.target.y(ht.current.y+n*Math.cos(r))}else{t.target.position(ht.current)}}}else{t.target.height(r)}t.target.scaleY(1),t.target.scaleX(1),t.target.rotation(Q.current),t.target.skewX(0),t.target.skewY(0),et.current=Math.max(e,r)}ht.current=t.target.position();const a=t.target.scaleX();null===(r=X.current)||void 0===r||r.setAttrs({scaleX:1,scaleY:1}),t.target.scaleX(1),t.target.scaleY(1),o.set({fontSize:o.a.fontSize*a,width:t.target.width()*a,x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*a,shadowBlur:o.shadowBlur*a,shadowOffsetX:o.shadowOffsetX*a,shadowOffsetY:o.shadowOffsetY*a,strokeWidth:o.strokeWidth*a})},onTransformEnd:t=>{var e;const r=t.target.scaleX();t.target.scaleX(1),t.target.scaleY(1),o.set(Object.assign(Object.assign({},S(o,o.fontSize*r)),{width:Math.ceil(t.target.width()*r),x:t.target.x(),y:t.target.y(),rotation:t.target.rotation(),height:t.target.height()*r})),null===(e=X.current)||void 0===e||e.setAttrs({scaleX:1,scaleY:1}),U(!1)}})),N&&o.contentEditable&&t(i,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,children:t(_,{textNodeRef:k,element:o,selectAll:J,cursorPosition:pt.current,onBlur:()=>{o.set(E(o)),o.toggleEditMode(!1)}})})]})});
|
package/canvas/tooltip.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import React from
|
|
2
|
-
import type { StoreType, PageType } from
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import type { StoreType, PageType } from '../ui-types.js';
|
|
3
3
|
export declare const Tooltip: (({ store, page, components, stageRef, tooltipSafeArea, }: {
|
|
4
4
|
store: StoreType;
|
|
5
5
|
page: PageType;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{nodeAutorun as r}from"../utils/mobx.js";import{Input as t,UrlSource as n,BufferSource as u,CanvasSink as
|
|
1
|
+
import e from"react";import{nodeAutorun as r}from"../utils/mobx.js";import{Input as t,UrlSource as n,BufferSource as u,CanvasSink as i,ALL_FORMATS as a}from"mediabunny";import{incrementLoader as c,triggerLoadError as o}from"../utils/loader.js";import{polotnoError as s}from"@polotno/core/errors";import{getElementTimeRange as l,getVideoRestMs as d}from"../utils/timeline.js";import{decodeBase64 as m}from"../utils/base64.js";function f(e,r){const t=p(e);return t>0&&r>=e.timestamp&&r<e.timestamp+t}function p(e){var r;const t=null!==(r=e.duration)&&void 0!==r?r:0;return Number.isFinite(t)&&t>0?t:0}export const useMediabunnyVideo=(g,v,h)=>{const[w,y]=e.useState({input:null,videoSink:null,duration:0,isReady:!1,error:null});e.useRef(w).current=w;const b=e.useRef(0),T=e.useRef(null),R=e.useRef(null),k=e.useRef(null),E=e.useRef(null),S=e.useRef(null),$=e.useRef(null),O=e.useRef(!1),I=e.useRef(null),j=e.useRef([]),x=e.useRef(null),D=e.useRef(!1),[,F]=e.useReducer(e=>e+1,0);return e.useEffect(()=>{if(!h){return}let e=!0;const r=++b.current;let l=null;return(async()=>{try{if(!e||r!==b.current){return}l=c(`mediabunny init ${g.id}`);const o=await async function(e){if(function(e){return e.startsWith("data:")}(e)){const r=function(e){const r=e.indexOf(",");if(-1===r){throw new Error("Invalid data URL format")}return m(e.slice(r+1)).buffer}(e);return new u(r)}if(function(e){return e.startsWith("file://")}(e)){try{const r=await fetch(e),t=await r.arrayBuffer();return new u(t)}catch(r){throw new Error(`Failed to load file URL: ${e}. File URLs may not be supported in this environment. Error: ${r}`)}}return new n(e)}(g.src);if(!e||r!==b.current){return void(l&&(l(),l=null))}const d=new t({source:o,formats:a}),f=await d.computeDuration(),p=await d.getPrimaryVideoTrack();if(!p){throw s("VIDEO_FAILED","No video track found",{reason:"no-video-track"})}if(null===p.codec){throw s("VIDEO_FAILED","Unsupported video codec",{reason:"unsupported-codec"})}if(!await p.canDecode()){throw s("VIDEO_FAILED","Unable to decode the video track",{reason:"cannot-decode"})}const v=await p.canBeTransparent(),h=new i(p,{poolSize:5,fit:"contain",alpha:v});if(!e||r!==b.current){return d.dispose(),void(l&&(l(),l=null))}l&&(l(),l=null),y(e=>Object.assign(Object.assign({},e),{input:d,videoSink:h,duration:f,isReady:!0,error:null}))}catch(d){if(console.error("Failed to initialize mediabunny:",d),l&&(l(),l=null),e&&r===b.current){const e=`Failed to initialize mediabunny for video ${g.id}: ${d}`;o(s("VIDEO_FAILED",e,Object.assign({reason:"load"},null==d?void 0:d.details),d)),y(e=>Object.assign(Object.assign({},e),{error:String(d),isReady:!1}))}}})(),()=>{e=!1,l&&(l(),l=null)}},[g.src,h]),e.useEffect(()=>()=>{R.current&&(R.current.return(),R.current=null),T.current&&(T.current(),T.current=null),k.current=null,E.current=null,S.current=null,O.current=!1,I.current=null,j.current=[],x.current=null,D.current=!1,y({input:null,videoSink:null,duration:0,isReady:!1,error:null})},[h]),e.useEffect(()=>{if(!h||!w.isReady||!w.videoSink){return}const e=++b.current,t="string"==typeof g.src?g.src.slice(0,120):String(g.src),n=(e,r={},n="debug")=>{var u;let i="";try{i=JSON.stringify(Object.assign(Object.assign({},r),{timeCalc:$.current}))}catch(c){i=`[unserializable extras: ${String(c)}]`}const a=`mediabunny event=${e} elementId=${g.id} targetTime=${S.current} duration=${w.duration} lastFrameTimestamp=${null===(u=E.current)||void 0===u?void 0:u.timestamp} hasIterator=${Boolean(R.current)} prefetchSize=${j.current.length} srcHint=${t} extras=${i}`;"error"===n?console.error(a):"warn"===n?console.warn(a):console.debug(a)},u=e=>{const r=w.duration||0;return r&&Number.isFinite(r)?Math.max(0,Math.min(e,r)):e},i=e=>{let r=k.current;r&&r.width===e.canvas.width&&r.height===e.canvas.height||(r||(r=document.createElement("canvas"),k.current=r),r.width=e.canvas.width,r.height=e.canvas.height);const t=r.getContext("2d");t&&(t.clearRect(0,0,r.width,r.height),t.drawImage(e.canvas,0,0)),E.current={timestamp:e.timestamp,duration:p(e)}},a=e=>{const r=R.current;r&&(D.current||(D.current=!0,x.current=(async()=>{try{for(;j.current.length<4&&e===b.current;){const t=await r.next();if(e!==b.current){return}if(t.done||!t.value){break}j.current.push({timestamp:t.value.timestamp,frame:t.value})}}catch(t){}finally{D.current=!1,x.current=null}})()))},o=e=>{const r=j.current;let t=-1;for(let u=0;u<r.length&&!(r[u].timestamp>e);u++){t=u}if(-1===t){return null}const n=r[t];return t<r.length-1||f(n.frame,e)?(j.current=r.slice(t+1),n):null},s=()=>{j.current=[]},m=async(e,r,t=0)=>{const c=u(e),l=(e=>{const r=E.current;return!r||e<r.timestamp||e>r.timestamp+.5})(c)?"seek":"iterate";try{const t=w.videoSink,u=E.current;if(u&&f(u,c)){return void(S.current=e)}const d=o(c);if(d){return i(d.frame),S.current=e,a(r),void F()}if(x.current){await x.current;const t=o(c);if(t){return i(t.frame),S.current=e,a(r),void F()}}s();const m=()=>n("iterator_exhausted",{mode:l,requestedTargetTime:e,clampedTargetTime:c},"warn"),p=async e=>{R.current&&(await R.current.return(),R.current=null),s();const n=t.canvases(e);R.current=n;const u=await n.next();return r!==b.current?(await n.return(),R.current===n&&(R.current=null),"cancelled"):u.done||!u.value?"empty":(i(u.value),a(r),"drawn")};if("seek"===l){const e=await p(c);if("cancelled"===e){return}if("empty"===e){return void m()}}else{const e=R.current;if(!e){return}for(;r===b.current;){const t=await e.next();if(r!==b.current){break}if(t.done||!t.value){"empty"===await p(c)&&m();break}const n=t.value;if(i(n),f(n,c)||n.timestamp>=c){a(r);break}}}S.current=e,F()}catch(d){const u=d instanceof Error?{name:d.name,message:d.message,stack:d.stack}:{message:String(d)},i=d instanceof Error?`${d.name}: ${d.message}`:String(d),a=i.includes("Unsupported configuration")||i.includes("isConfigSupported")||i.includes("OperationError");if(n("frame_process_failed",{mode:l,requestedTargetTime:e,clampedTargetTime:c,unsupportedConfigAttempt:t,isUnsupportedConfig:a,error:u},"error"),a&&t<1){try{R.current&&(await R.current.return(),R.current=null),s(),x.current=null,D.current=!1,E.current=null,await m(e,r,t+1)}catch(p){}}}},y=r(g,()=>{const r=w.videoSink,t=w.duration;if(!r||!t){return}const n=g.startTime*t*1e3,i=t*(g.endTime-g.startTime)*1e3,{start:a}=l(g.animations,g.page.duration),o=d(v.currentTime,g.page.startTime,a,i,n,g.speed),s=o/1e3+1e-6,f=u(s);$.current={pageStartTime:g.page.startTime,storeCurrentTime:v.currentTime,offsetMs:n,durationMs:i,restMs:o,targetTime:s,clampedTargetTime:f,startTime:g.startTime,endTime:g.endTime,videoDuration:t},((e,r)=>{O.current?I.current=e:(O.current=!0,T.current||(T.current=c(`mediabunny video frame ${g.id}`)),(async()=>{let t=e;for(;null!==t&&r===b.current;){await m(t,r),t=I.current,I.current=null}T.current&&(T.current(),T.current=null),O.current=!1})())})(s,e)});return()=>{y(),b.current++,T.current&&(T.current(),T.current=null)}},[h,w.isReady,w.videoSink,w.duration,v,g]),h&&w.isReady?k.current:null};
|
package/canvas/video-element.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import i from"react";import{observer as o}from"mobx-react-lite";import{nodeAutorun as n}from"../utils/mobx.js";import{Arc as a,Group as d,Image as h,Rect as s,Text as l,Transformer as c}from"react-konva";import{ROLES as u}from"../model/store.js";import g from"use-image";import m from"konva";import{Portal as f}from"react-konva-utils";import{useWorkspaceStyle as p}from"./workspace-style.js";import{incrementLoader as v,triggerLoadError as w}from"../utils/loader.js";import{polotnoError as x}from"@polotno/core/errors";import{getCropRect as M}from"@polotno/core/image";import*as y from"@polotno/core/svg";import{flags as E}from"../utils/flags.js";import{roundEnabledPx as b,isCornerAnchor as L,scaledBoxStyleAttrs as T,roundedBoxStyleAttrs as C}from"../utils/px.js";import{useFilteredSource as S}from"./use-filtered-source.js";import{useEvent as R}from"../hooks/use-event.js";import{useFadeIn as I}from"./use-fadein.js";import{isTouchDevice as k}from"../utils/screen.js";import{useMediabunnyVideo as H}from"./use-mediabunny-video.js";import{getElementTimeRange as W,getVideoRestMs as X}from"../utils/timeline.js";function Y(){return document.createElement("canvas")}const O=new window.Image;O.src=y.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" fill="white"/>\n <path d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');const j=new window.Image;j.src=y.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useCornerRadiusAndCrop=(e,t,r,o,n=0,a=!1)=>{var d,h;const s=Math.floor(Math.max(e.width*o,1)),l=Math.floor(Math.max(e.height*o,1)),c=Math.min(n*o,s/2,l/2),u=Math.max(e.width/r.width,e.height/r.height)*o,g=(null===(d=e.page)||void 0===d?void 0:d._exportingOrRendering)&&E.imageDownScalingEnabled&&u<1&&!a,f=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,p=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height,v=0===r.x&&0===r.y&&r.width===f&&r.height===p,w=i.useMemo(()=>{if(t&&f&&p){return v&&0===c&&!g?void 0:Y()}},[t,c,g,v,f,p]),x=()=>{if(!w||!t){return}w.width=s,w.height=l;const e=w.getContext("2d");if(!e){return}c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(s-c,0),e.arc(s-c,c,c,3*Math.PI/2,0,!1),e.lineTo(s,l-c),e.arc(s-c,l-c,c,0,Math.PI/2,!1),e.lineTo(c,l),e.arc(c,l-c,c,Math.PI/2,Math.PI,!1),e.lineTo(0,c),e.arc(c,c,c,Math.PI,3*Math.PI/2,!1),e.clip());const i=g?function(e,t){var r,i;const o=Y(),n=e instanceof HTMLVideoElement?e.videoWidth:e.width,a=e instanceof HTMLVideoElement?e.videoHeight:e.height;o.width=n,o.height=a,null===(r=o.getContext("2d"))||void 0===r||r.drawImage(e,0,0,o.width,o.height);const d=function(e,t,r,i,o,n,a){for(var d=new ImageData(t,r),h=new Int32Array(e.data.buffer),s=e.width,l=new Int32Array(d.data.buffer),c=d.width,u=t/n,g=r/a,m=Math.round(1/u),f=Math.round(1/g),p=m*f,v=0;v<d.height;v++){for(var w=0;w<c;w++){for(var x=0+Math.round(w/u)+(0+Math.round(v/g))*s,M=0,y=0,E=0,b=0,L=0;L<f;L++){for(var T=0;T<m;T++){var C=h[x+T+L*s];M+=C<<24>>>24,y+=C<<16>>>24,E+=C<<8>>>24,b+=C>>>24}}M=Math.round(M/p),y=Math.round(y/p),E=Math.round(E/p),b=Math.round(b/p),l[w+v*c]=b<<24|E<<16|y<<8|M}}return d}(o.getContext("2d").getImageData(0,0,o.width,o.height),Math.floor(o.width*t),Math.floor(o.height*t),0,0,o.width,o.height);return o.width=Math.floor(o.width*t),o.height=Math.floor(o.height*t),null===(i=o.getContext("2d"))||void 0===i||i.putImageData(d,0,0),o}(t,u):t,o=g?{x:Math.floor(r.x*u),y:Math.floor(r.y*u),width:Math.floor(r.width*u),height:Math.floor(r.height*u)}:r;e.drawImage(i,o.x,o.y,o.width,o.height,0,0,w.width,w.height)};return i.useLayoutEffect(()=>{x()},[w,e.width,e.height,r.x,r.y,r.width,r.height,n,o,a,null===(h=e.page)||void 0===h?void 0:h._exportingOrRendering,g]),i.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&m.Util.releaseCanvas(w)},[w]),[w||t,x]};const A=Y(),P=o(({element:r})=>{const o=Math.min(30,r.width/4,r.height/4),n=i.useRef(null);i.useEffect(()=>{const e=n.current;if(!e){return}const t=new m.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:h}=p();return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(s,{width:r.width,height:r.height,fill:h.fill}),e(a,{ref:n,x:r.width/2,y:r.height/2,fill:h.textFill,outerRadius:Math.abs(o),innerRadius:Math.max(1,o-5),angle:270})]})}),_=o(({element:r})=>{const{mediaErrorStyle:i}=p(),o=Math.max(10,Math.min(30,r.width/25));return t(d,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(s,{width:r.width,height:r.height,fill:i.fill}),e(l,{text:"Can not load the video...",fontSize:o,width:r.width,height:r.height,align:"center",fill:i.textFill,verticalAlign:"middle",padding:5})]})});let V=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,d]=i.useState(0),h=i.useRef(void 0),s=i.useRef(void 0),l=i.useRef(void 0);return h.current===e&&s.current===t&&l.current===r||(o.current="loading",n.current=void 0,h.current=e,s.current=t,l.current=r),i.useLayoutEffect(function(){if(e){var i=document.createElement("video");return i.addEventListener("canplay",a),i.addEventListener("error",h),t&&(i.crossOrigin=t),r&&(i.referrerPolicy=r),i.src=e,i.load(),function(){i.removeEventListener("canplay",a),i.removeEventListener("error",h)}}function a(){o.current="loaded",n.current=i,n.current.currentTime=0,d(Math.random()),n.current.removeEventListener("canplay",a)}function h(e){var t;const r=4===i.readyState,a=i.buffered&&i.buffered.length>0&&i.buffered.end(i.buffered.length-1)/i.duration*100>=100;if(r&&a){return}const h=e.message||(null===(t=i.error)||void 0===t?void 0:t.message)||"Unknown error",s=new Error("Video failed to load: "+h);console.error(s),o.current="failed",n.current=void 0,d(Math.random())}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{V=e};function D(e){return e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const o=i.useRef(void 0),n=()=>{var e;null===(e=o.current)||void 0===e||e.call(o),o.current=void 0};i.useEffect(()=>n,[]),i.useLayoutEffect(()=>{const i=t.slice(0,200),a=`video with id ${r} url: ${i}`;"loading"!==e||o.current||(o.current=v(a)),"loading"!==e&&n(),"failed"===e&&w(x("VIDEO_FAILED",a,{src:i,elementId:r,reason:"load"}))},[e])};export const VideoElement=o(({element:o,store:a})=>{var l,p,w;const[x,E]=i.useState(!1),z=i.useRef(null),B=i.useRef(null),U=o.isSelected,[F,N]=i.useState(!1),[Z,$]=V(o.src,"anonymous"),[q,G]=i.useState(!1),J=a.activePage===o.page,K=(null===(l=o.page)||void 0===l?void 0:l._exportingOrRendering)&&"loaded"===$,Q=H(o,a,K);useLoader($,o.src,o.id),Z&&(Z.playsInline=!0);const ee=((e,t,r)=>{const o=i.useMemo(()=>{var i,o;const{flipX:n,flipY:a}=e,d="svg"===e.type||e.src.indexOf("data:image/svg+xml")>=0||e.src.indexOf(".svg")>=0,h=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(n||a||h&&d)){return t}if(!t){return null}const s=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,l=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!s||!l){return null}const c=Y();let u=1;"svg"===e.type&&(u=Math.max(e.width/s*r,e.height/l*r)),c.width=Math.max(s*u,1),c.height=Math.max(l*u,1);let g=n?-c.width:0,m=a?-c.height:0;return null===(i=c.getContext("2d"))||void 0===i||i.scale(n?-1:1,a?-1:1),null===(o=c.getContext("2d"))||void 0===o||o.drawImage(t,g,m,c.width,c.height),c},[e.flipX,e.flipY,t,e.width,e.height,r]);return i.useEffect(()=>()=>{o&&"CANVAS"===o.nodeName&&m.Util.releaseCanvas(o)},[o]),o})(o,Z,a._elementsPixelRatio),te=K&&Q||ee||A,[re=A,ie]=S(o,te);i.useEffect(()=>{Z&&a.history.ignore(()=>{o.set({duration:1e3*Z.duration})})},[Z]),i.useEffect(()=>{var e;if(!Z){return}const t=a.animatedElementsIds,r=(!t.length||t.includes(o.id))&&a.isPlaying;if(!J||!r&&!F){return void Z.pause()}F&&(Z.muted=!1,Z.currentTime=o.startTime*Z.duration,Z.play());const i=new m.Animation(()=>{ye()},null===(e=z.current)||void 0===e?void 0:e.getLayer());i.start();const n=()=>{N(!1),Z.currentTime=o.startTime*Z.duration},d=()=>{Z.currentTime>=o.endTime*Z.duration&&(Z.pause(),Z.currentTime=o.startTime*Z.duration,N(!1))};return Z.addEventListener("ended",n),Z.addEventListener("timeupdate",d),()=>{Z.pause(),i.stop(),Z.removeEventListener("ended",n),Z.removeEventListener("timeupdate",d)}},[Z,F,a.isPlaying,J]),i.useEffect(()=>{Z&&(Z.volume=o.volume)},[Z,o.volume]),i.useEffect(()=>{Z&&(Z.playbackRate=o.speed,Z.preservesPitch=!1)},[Z,o.speed]);const oe=i.useRef(null);i.useEffect(()=>{const e=n(o,()=>{var e,t;if(Z){if(K&&Q){return ye(),void a.currentTime}const r=a.animatedElementsIds;if(r.length&&!r.includes(o.id)){return}const i=a.activePage===o.page,n=a.currentTime>=o.page.startTime&&a.currentTime<o.page.startTime+o.page.duration,d=o.startTime*Z.duration*1e3,h=Z.duration*(o.endTime-o.startTime)*1e3,{start:s,end:l}=W(o.animations,o.page.duration),c=(a.currentTime||o.page.startTime)-o.page.startTime,u=n?X(a.currentTime,o.page.startTime,s,h,d,o.speed):0,g=u/1e3,m=n&&c>=s&&c<l;F||(Z.muted=!m,m&&a.isPlaying&&i?Z.paused?(Z.currentTime=g,Z.play()):Math.abs(1e3*Z.currentTime-u)>500&&(Z.currentTime=g):(Z.paused||Z.pause(),g!==Z.currentTime&&(Z.currentTime=g),!D(Z)&&!a.isPlaying&&!oe.current&&(oe.current=v(`video ${o.id}`)))),ye(),null===(t=null===(e=z.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),oe.current&&(oe.current(),oe.current=null)}},[a,Z,K,Q,F]),i.useEffect(()=>{var e,t;if(!Z){return}if(K){return null===(e=oe.current)||void 0===e||e.call(oe),void(oe.current=null)}const r=()=>{var e,t,r;!D(Z)&&(null===(e=o.page)||void 0===e?void 0:e._exportingOrRendering)||oe.current&&(ye(),null===(r=null===(t=z.current)||void 0===t?void 0:t.getLayer())||void 0===r||r.batchDraw(),oe.current(),oe.current=null)};let i;return(null===(t=o.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),Z.addEventListener("timeupdate",r),Z.addEventListener("canplay",r),()=>{clearInterval(i),Z.removeEventListener("timeupdate",r),Z.removeEventListener("canplay",r)}},[null===(p=o.page)||void 0===p?void 0:p._exportingOrRendering,Z,o.id,v,K]);let{cropX:ne,cropY:ae,cropWidth:de,cropHeight:he}=o;"loaded"!==$&&(ne=ae=0,de=he=1);const se=(le=re)instanceof HTMLVideoElement?le.videoWidth:(null==le?void 0:le.width)||0;var le;const ce=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(re),ue=M({type:o.type,cropX:ne,cropY:ae,cropWidth:de,cropHeight:he,width:o.width,height:o.height},{width:se,height:ce}),ge=ue.width,me=ue.height,fe="svg"===o.type,pe=null!==(w=o.cornerRadius)&&void 0!==w?w:0,[ve,we]=useCornerRadiusAndCrop(o,re,ue,a._elementsPixelRatio,pe,!0);let[xe,Me]=((e,t,r,o)=>{const n=(e=>{const[t,r]=i.useState(e);return i.useEffect(()=>{(async()=>{const i=await async function(e){if(!(e.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await y.urlToString(e),r=y.fixSize(t);return y.svgToURL(r)}(e);i!==t&&r(i)})()},[e]),t})(e.clipSrc||""),[a,d]=g(n,"anonymous"),h=e.clipSrc?d:"loaded";useLoader(h,e.clipSrc,e.id);const s=i.useMemo(()=>{if(t&&a){return Y()}},[t,a]);function l(){var i;if(!a){return}const o=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,n=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!t||!o||!n){return}if(!a||!a.width||!a.height){return}if(!s){return}const d=Y(),h=Math.max(e.width/a.width*r,e.height/a.height*r);d.width=a.width*h,d.height=a.height*h,null===(i=d.getContext("2d"))||void 0===i||i.drawImage(a,0,0,d.width,d.height),s.width=Math.max(o,1),s.height=Math.max(n,1);const l=s.getContext("2d");l&&(l.save(),l.drawImage(d,0,0,o,n),m.Util.releaseCanvas(d),l.globalCompositeOperation="source-in",l.drawImage(t,0,0,s.width,s.height),l.restore())}return i.useLayoutEffect(()=>{l()},[s,t,a,e.width,e.height,r,...o]),[e.clipSrc&&a?s:t,l]})(o,ve,a._elementsPixelRatio,[ue,pe,a._elementsPixelRatio]);const ye=R(()=>{var e,t;ie(),we(),Me(),null===(t=null===(e=z.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});i.useEffect(()=>{ye()});const Ee=Math.max(o.width/ge,o.height/me);i.useEffect(()=>{var e;if(!o._cropModeEnabled){return}const t=null===(e=z.current)||void 0===e?void 0:e.getStage();function r(e){o._cropModeEnabled&&e.target!==B.current&&o.toggleCropMode(!1)}function i(e){o._cropModeEnabled&&e.target.parentNode!==(null==t?void 0:t.content)&&o.toggleCropMode(!1)}return document.body.addEventListener("click",i),null==t||t.on("click",r),null==t||t.on("tap",r),()=>{document.body.removeEventListener("click",i),document.body.removeEventListener("touchstart",i),null==t||t.off("click",r),null==t||t.off("click",r)}},[o._cropModeEnabled]);const be=i.useRef(null),Le=i.useRef(null),Te=i.useRef(null);i.useLayoutEffect(()=>{o._cropModeEnabled&&(Le.current.nodes([be.current]),Te.current.nodes([B.current]))},[o._cropModeEnabled]);const Ce=e=>{Math.round(e.target.x())>0&&(e.target.x(0),e.target.scaleX(1)),Math.round(e.target.y())>0&&(e.target.y(0),e.target.scaleY(1));const t=e.target.width()*e.target.scaleX(),r=e.target.height()*e.target.scaleY(),i=Math.min(1,ge/t),n=Math.min(1,me/r),a=1-i,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/t)),h=1-n,s=Math.min(h,Math.max(0,Math.round(-e.target.y())/r));e.target.setAttrs({x:-d*se,y:-s*ce,scaleX:1,scaleY:1}),o.set({cropX:d,cropY:s,cropWidth:i,cropHeight:n})},Se=()=>{"svg"!==o.type&&o.contentEditable&&setTimeout(()=>{o.toggleCropMode(!0)})},Re="loading"===$,Ie="failed"===$,ke=!Re&&!Ie,He=i.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),We=ke?o.a.opacity:0;I(z,We);const Xe=o.selectable||a.role===u.ADMIN,Ye=k();return e(r,{children:t(d,{onMouseEnter:()=>G(!0),onMouseLeave:()=>G(!1),children:[Re&&e(P,{element:o}),Ie&&e(_,{element:o}),e(h,{ref:z,name:"element",id:o.id,image:xe,x:o.a.x,y:o.a.y,width:o.a.width||1,height:o.a.height||1,rotation:o.a.rotation,opacity:We,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,customCrop:ue,listening:Xe,draggable:Ye?o.draggable&&U:o.draggable,preventDefault:!Ye||U,hideInExport:!o.showInExport,onDragMove:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDblClick:Se,onDblTap:Se,onTransformStart:()=>{E(!0),He.current={cropX:o.cropX,cropY:o.cropY,cropWidth:o.cropWidth,cropHeight:o.cropHeight}},onTransform:e=>{var t,r;const i=e.currentTarget,n=Math.abs(i.scaleX()-1)<1e-7?1:i.scaleX(),a=Math.abs(i.scaleY()-1)<1e-7?1:i.scaleY();i.scaleX(1),i.scaleY(1);const d=null===(t=e.target.getStage())||void 0===t?void 0:t.findOne("Transformer"),h=1-ge/se,s=Math.min(h,Math.max(0,o.cropX)),l=1-me/ce,c=Math.min(l,Math.max(0,o.cropY)),u=L(null!==(r=d.getActiveAnchor())&&void 0!==r?r:""),g=!u&&n<1&&He.current.cropHeight>me/ce;let m=u?o.cropWidth:o.cropWidth*n;g&&(m=o.cropWidth);const f=!u&&a<1&&He.current.cropWidth>ge/se;let p=u?o.cropHeight:o.cropHeight*a;f&&(p=o.cropHeight),fe&&(m=o.cropWidth,p=o.cropHeight);const v=u?Math.min(n,a):1;o.set(Object.assign({cropX:s,cropY:c,x:i.x(),y:i.y(),width:i.width()*n,height:i.height()*a,rotation:e.target.rotation(),cropWidth:Math.min(m,1-s),cropHeight:Math.min(p,1-c)},1!==v&&Object.assign(Object.assign({},T(o,v)),{borderSize:o.borderSize*v})))},onTransformEnd:e=>{const t=e.currentTarget;o.set(Object.assign(Object.assign({width:t.width(),height:t.height(),x:t.x(),y:t.y(),rotation:e.target.rotation(),cropWidth:ge/se,cropHeight:me/ce},C(o)),{borderSize:b(o.borderSize)})),E(!1)}}),e(s,{x:o.a.x,y:o.a.y,width:Math.max(o.a.width-o.borderSize,0),height:Math.max(o.a.height-o.borderSize,0),opacity:We,offsetX:-o.borderSize/2,offsetY:-o.borderSize/2,stroke:o.borderColor,strokeWidth:o.borderSize,listening:!1,visible:!!o.borderSize,rotation:o.rotation,cornerRadius:Math.max(0,pe-o.borderSize),hideInExport:!o.showInExport}),!a.isPlaying&&e(h,{image:F?q||Ye?j:void 0:O,x:o.a.x,y:o.a.y,offsetX:-o.a.width/2+15/a.scale,offsetY:-o.a.height/2+15/a.scale,rotation:o.a.rotation,width:30/a.scale,height:30/a.scale,hideInExport:!0,onClick:()=>N(!F),onTap:()=>N(!F)}),o._cropModeEnabled&&t(f,{selector:".page-abs-container",enabled:!0,children:[e(s,{x:-window.innerWidth/a.scale,y:-window.innerWidth/a.scale,width:window.innerWidth/a.scale*3,height:window.innerWidth/a.scale*3,fill:"rgba(0,0,0,0.3)"}),e(h,{listening:!1,image:xe,x:o.a.x,y:o.a.y,width:o.a.width,height:o.a.height,rotation:o.a.rotation,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur}),t(d,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,scaleX:Ee,scaleY:Ee,children:[e(h,{image:re,ref:B,width:se,height:ce,opacity:.4,draggable:!0,x:-o.cropX*se,y:-o.cropY*ce,onDragMove:Ce,onTransform:Ce}),e(c,{ref:Te,anchorSize:20,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,rotateEnabled:!1,borderEnabled:!1,anchorCornerRadius:10,anchorStrokeWidth:2,borderStrokeWidth:2}),e(s,{width:ge,height:me,ref:be,listening:!1,onTransform:e=>{e.target.x()<-o.cropX*se-1e-9&&(e.target.x(-o.cropX*se),e.target.scaleX(1)),e.target.y()<-o.cropY*ce-1e-9&&(e.target.y(-o.cropY*ce),e.target.scaleY(1));const t=Math.min(1,Math.max(0,o.cropX+e.target.x()/se)),r=Math.min(1,Math.max(0,e.target.y()/ce+o.cropY)),i=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),a=Math.min(1-t,i/se),d=Math.min(1-r,n/ce),h=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),o.set({x:h.x,y:h.y,cropX:t,cropY:r,cropWidth:a,cropHeight:d,width:Math.min(i*Ee,se*(1-t)*Ee),height:Math.min(n*Ee,ce*(1-r)*Ee)})}}),e(c,{ref:Le,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,keepRatio:!1,rotateEnabled:!1,anchorFill:"rgb(240, 240, 240)",anchorStrokeWidth:2,borderStrokeWidth:2,visible:o.resizable})]})]})]})})});
|
|
1
|
+
import{jsx as e,jsxs as t,Fragment as r}from"react/jsx-runtime";import i from"react";import{observer as o}from"mobx-react-lite";import{isAlive as n}from"mobx-state-tree";import{nodeAutorun as a}from"../utils/mobx.js";import{Arc as d,Group as h,Image as s,Rect as l,Text as c,Transformer as u}from"react-konva";import{ROLES as g}from"../model/store.js";import m from"use-image";import f from"konva";import{Portal as p}from"react-konva-utils";import{useWorkspaceStyle as v}from"./workspace-style.js";import{incrementLoader as w,triggerLoadError as x}from"../utils/loader.js";import{polotnoError as M}from"@polotno/core/errors";import{getCropRect as y}from"@polotno/core/image";import*as E from"@polotno/core/svg";import{flags as b}from"../utils/flags.js";import{roundEnabledPx as L,activeAnchorOf as T,isCornerAnchor as C,scaledBoxStyleAttrs as R,roundedBoxStyleAttrs as S}from"../utils/px.js";import{useFilteredSource as I}from"./use-filtered-source.js";import{useEvent as k}from"../hooks/use-event.js";import{useFadeIn as H}from"./use-fadein.js";import{isTouchDevice as W}from"../utils/screen.js";import{createPlayGate as X,playMedia as Y}from"../utils/media.js";import{useMediabunnyVideo as O}from"./use-mediabunny-video.js";import{getElementTimeRange as j,getVideoRestMs as P}from"../utils/timeline.js";function A(){return document.createElement("canvas")}const _=new window.Image;_.src=E.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" fill="white"/>\n <path d="M4 5.49683V18.5032C4 20.05 5.68077 21.0113 7.01404 20.227L18.0694 13.7239C19.384 12.9506 19.384 11.0494 18.0694 10.2761L7.01404 3.77296C5.68077 2.98869 4 3.95 4 5.49683Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');const V=new window.Image;V.src=E.svgToURL('\n <svg width="800px" height="800px" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">\n <path opacity="0.6" d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" fill="white"/>\n <path opacity="0.6" d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" fill="white"/>\n <path d="M14 19L14 5C14 3.89543 14.8954 3 16 3L17 3C18.1046 3 19 3.89543 19 5L19 19C19 20.1046 18.1046 21 17 21L16 21C14.8954 21 14 20.1046 14 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n <path d="M10 19L10 5C10 3.89543 9.10457 3 8 3L7 3C5.89543 3 5 3.89543 5 5L5 19C5 20.1046 5.89543 21 7 21L8 21C9.10457 21 10 20.1046 10 19Z" stroke="#323232" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>\n </svg>\n');export const useCornerRadiusAndCrop=(e,t,r,o,n=0,a=!1)=>{var d,h;const s=Math.floor(Math.max(e.width*o,1)),l=Math.floor(Math.max(e.height*o,1)),c=Math.min(n*o,s/2,l/2),u=Math.max(e.width/r.width,e.height/r.height)*o,g=(null===(d=e.page)||void 0===d?void 0:d._exportingOrRendering)&&b.imageDownScalingEnabled&&u<1&&!a,m=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,p=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height,v=0===r.x&&0===r.y&&r.width===m&&r.height===p,w=i.useMemo(()=>{if(t&&m&&p){return v&&0===c&&!g?void 0:A()}},[t,c,g,v,m,p]),x=()=>{if(!w||!t){return}w.width=s,w.height=l;const e=w.getContext("2d");if(!e){return}c&&(e.beginPath(),e.moveTo(c,0),e.lineTo(s-c,0),e.arc(s-c,c,c,3*Math.PI/2,0,!1),e.lineTo(s,l-c),e.arc(s-c,l-c,c,0,Math.PI/2,!1),e.lineTo(c,l),e.arc(c,l-c,c,Math.PI/2,Math.PI,!1),e.lineTo(0,c),e.arc(c,c,c,Math.PI,3*Math.PI/2,!1),e.clip());const i=g?function(e,t){var r,i;const o=A(),n=e instanceof HTMLVideoElement?e.videoWidth:e.width,a=e instanceof HTMLVideoElement?e.videoHeight:e.height;o.width=n,o.height=a,null===(r=o.getContext("2d"))||void 0===r||r.drawImage(e,0,0,o.width,o.height);const d=function(e,t,r,i,o,n,a){for(var d=new ImageData(t,r),h=new Int32Array(e.data.buffer),s=e.width,l=new Int32Array(d.data.buffer),c=d.width,u=t/n,g=r/a,m=Math.round(1/u),f=Math.round(1/g),p=m*f,v=0;v<d.height;v++){for(var w=0;w<c;w++){for(var x=0+Math.round(w/u)+(0+Math.round(v/g))*s,M=0,y=0,E=0,b=0,L=0;L<f;L++){for(var T=0;T<m;T++){var C=h[x+T+L*s];M+=C<<24>>>24,y+=C<<16>>>24,E+=C<<8>>>24,b+=C>>>24}}M=Math.round(M/p),y=Math.round(y/p),E=Math.round(E/p),b=Math.round(b/p),l[w+v*c]=b<<24|E<<16|y<<8|M}}return d}(o.getContext("2d").getImageData(0,0,o.width,o.height),Math.floor(o.width*t),Math.floor(o.height*t),0,0,o.width,o.height);return o.width=Math.floor(o.width*t),o.height=Math.floor(o.height*t),null===(i=o.getContext("2d"))||void 0===i||i.putImageData(d,0,0),o}(t,u):t,o=g?{x:Math.floor(r.x*u),y:Math.floor(r.y*u),width:Math.floor(r.width*u),height:Math.floor(r.height*u)}:r;e.drawImage(i,o.x,o.y,o.width,o.height,0,0,w.width,w.height)};return i.useLayoutEffect(()=>{x()},[w,e.width,e.height,r.x,r.y,r.width,r.height,n,o,a,null===(h=e.page)||void 0===h?void 0:h._exportingOrRendering,g]),i.useEffect(()=>()=>{w&&"CANVAS"===w.nodeName&&f.Util.releaseCanvas(w)},[w]),[w||t,x]};const D=A(),z=o(({element:r})=>{const o=Math.min(30,r.width/4,r.height/4),n=i.useRef(null);i.useEffect(()=>{const e=n.current;if(!e){return}const t=new f.Animation(t=>{e.rotate(((null==t?void 0:t.timeDiff)||0)/2)},e.getLayer());return t.start(),()=>{t.stop()}});const{mediaLoadingStyle:a}=v();return t(h,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(l,{width:r.width,height:r.height,fill:a.fill}),e(d,{ref:n,x:r.width/2,y:r.height/2,fill:a.textFill,outerRadius:Math.abs(o),innerRadius:Math.max(1,o-5),angle:270})]})}),B=o(({element:r})=>{const{mediaErrorStyle:i}=v(),o=Math.max(10,Math.min(30,r.width/25));return t(h,{x:r.a.x,y:r.a.y,rotation:r.a.rotation,listening:!1,opacity:r.a.opacity,hideInExport:!r.showInExport,children:[e(l,{width:r.width,height:r.height,fill:i.fill}),e(c,{text:"Can not load the video...",fontSize:o,width:r.width,height:r.height,align:"center",fill:i.textFill,verticalAlign:"middle",padding:5})]})});let U=function(e,t,r){const o=i.useRef("loading"),n=i.useRef(void 0),[a,d]=i.useState(0),h=i.useRef(void 0),s=i.useRef(void 0),l=i.useRef(void 0);return h.current===e&&s.current===t&&l.current===r||(o.current="loading",n.current=void 0,h.current=e,s.current=t,l.current=r),i.useLayoutEffect(function(){if(e){var i=document.createElement("video");return i.addEventListener("canplay",a),i.addEventListener("error",h),t&&(i.crossOrigin=t),r&&(i.referrerPolicy=r),i.src=e,i.load(),function(){i.removeEventListener("canplay",a),i.removeEventListener("error",h)}}function a(){o.current="loaded",n.current=i,n.current.currentTime=0,d(Math.random()),n.current.removeEventListener("canplay",a)}function h(e){var t;const r=4===i.readyState,a=i.buffered&&i.buffered.length>0&&i.buffered.end(i.buffered.length-1)/i.duration*100>=100;if(r&&a){return}const h=e.message||(null===(t=i.error)||void 0===t?void 0:t.message)||"Unknown error",s=new Error("Video failed to load: "+h);console.error(s),o.current="failed",n.current=void 0,d(Math.random())}},[e,t,r]),[n.current,o.current]};export const setVideoLoaderHook=e=>{U=e};function F(e){return e.readyState>=HTMLMediaElement.HAVE_CURRENT_DATA}export const useLoader=(e,t,r)=>{const o=i.useRef(void 0),n=()=>{var e;null===(e=o.current)||void 0===e||e.call(o),o.current=void 0};i.useEffect(()=>n,[]),i.useLayoutEffect(()=>{const i=t.slice(0,200),a=`video with id ${r} url: ${i}`;"loading"!==e||o.current||(o.current=w(a)),"loading"!==e&&n(),"failed"===e&&x(M("VIDEO_FAILED",a,{src:i,elementId:r,reason:"load"}))},[e])};export const VideoElement=o(({element:o,store:d})=>{var c,v,x;const[M,b]=i.useState(!1),N=i.useRef(null),Z=i.useRef(null),$=o.isSelected,[q,G]=i.useState(!1),[J,K]=U(o.src,"anonymous"),[Q,ee]=i.useState(!1),te=d.activePage===o.page,re=(null===(c=o.page)||void 0===c?void 0:c._exportingOrRendering)&&"loaded"===K,ie=O(o,d,re);useLoader(K,o.src,o.id),J&&(J.playsInline=!0);const oe=((e,t,r)=>{const o=i.useMemo(()=>{var i,o;const{flipX:n,flipY:a}=e,d="svg"===e.type||e.src.indexOf("data:image/svg+xml")>=0||e.src.indexOf(".svg")>=0,h=navigator.userAgent.toLowerCase().indexOf("firefox")>-1;if(!(n||a||h&&d)){return t}if(!t){return null}const s=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,l=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!s||!l){return null}const c=A();let u=1;"svg"===e.type&&(u=Math.max(e.width/s*r,e.height/l*r)),c.width=Math.max(s*u,1),c.height=Math.max(l*u,1);let g=n?-c.width:0,m=a?-c.height:0;return null===(i=c.getContext("2d"))||void 0===i||i.scale(n?-1:1,a?-1:1),null===(o=c.getContext("2d"))||void 0===o||o.drawImage(t,g,m,c.width,c.height),c},[e.flipX,e.flipY,t,e.width,e.height,r]);return i.useEffect(()=>()=>{o&&"CANVAS"===o.nodeName&&f.Util.releaseCanvas(o)},[o]),o})(o,J,d._elementsPixelRatio),ne=re&&ie||oe||D,[ae=D,de]=I(o,ne);i.useEffect(()=>{J&&d.history.ignore(()=>{o.set({duration:1e3*J.duration})})},[J]);const he=i.useMemo(X,[J]);i.useEffect(()=>{var e;if(!J){return}const t=d.animatedElementsIds,r=(!t.length||t.includes(o.id))&&d.isPlaying;if(!te||!r&&!q){return void J.pause()}q&&(J.muted=!1,J.currentTime=o.startTime*J.duration,Y(J).then(e=>{"refused"===e&&G(!1)}));const i=new f.Animation(()=>{Ce()},null===(e=N.current)||void 0===e?void 0:e.getLayer());i.start();const n=()=>{G(!1),J.currentTime=o.startTime*J.duration},a=()=>{J.currentTime>=o.endTime*J.duration&&(J.pause(),J.currentTime=o.startTime*J.duration,G(!1))};return J.addEventListener("ended",n),J.addEventListener("timeupdate",a),()=>{J.pause(),i.stop(),J.removeEventListener("ended",n),J.removeEventListener("timeupdate",a)}},[J,q,d.isPlaying,te]),i.useEffect(()=>{J&&(J.volume=o.volume)},[J,o.volume]),i.useEffect(()=>{J&&(J.playbackRate=o.speed,J.preservesPitch=!1)},[J,o.speed]);const se=i.useRef(null);i.useEffect(()=>{const e=a(o,()=>{var e,t;if(J){if(re&&ie){return Ce(),void d.currentTime}const r=d.animatedElementsIds;if(r.length&&!r.includes(o.id)){return}const i=d.activePage===o.page,n=d.currentTime>=o.page.startTime&&d.currentTime<o.page.startTime+o.page.duration,a=o.startTime*J.duration*1e3,h=J.duration*(o.endTime-o.startTime)*1e3,{start:s,end:l}=j(o.animations,o.page.duration),c=(d.currentTime||o.page.startTime)-o.page.startTime,u=n?P(d.currentTime,o.page.startTime,s,h,a,o.speed):0,g=u/1e3,m=n&&c>=s&&c<l;q||(J.muted=!m,m&&d.isPlaying&&i?J.paused?(J.currentTime=g,he.play(J)):Math.abs(1e3*J.currentTime-u)>500&&(J.currentTime=g):(he.reset(),J.paused||J.pause(),g!==J.currentTime&&(J.currentTime=g),!F(J)&&!d.isPlaying&&!se.current&&(se.current=w(`video ${o.id}`)))),Ce(),null===(t=null===(e=N.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()}});return()=>{e(),se.current&&(se.current(),se.current=null)}},[d,J,re,ie,q]),i.useEffect(()=>{var e,t;if(!J){return}if(re){return null===(e=se.current)||void 0===e||e.call(se),void(se.current=null)}const r=()=>{var e,t,r;!F(J)&&(null===(e=o.page)||void 0===e?void 0:e._exportingOrRendering)||se.current&&(Ce(),null===(r=null===(t=N.current)||void 0===t?void 0:t.getLayer())||void 0===r||r.batchDraw(),se.current(),se.current=null)};let i;return(null===(t=o.page)||void 0===t?void 0:t._exportingOrRendering)&&(i=setInterval(r,20)),J.addEventListener("timeupdate",r),J.addEventListener("canplay",r),()=>{clearInterval(i),J.removeEventListener("timeupdate",r),J.removeEventListener("canplay",r)}},[null===(v=o.page)||void 0===v?void 0:v._exportingOrRendering,J,o.id,w,re]);let{cropX:le,cropY:ce,cropWidth:ue,cropHeight:ge}=o;"loaded"!==K&&(le=ce=0,ue=ge=1);const me=(fe=ae)instanceof HTMLVideoElement?fe.videoWidth:(null==fe?void 0:fe.width)||0;var fe;const pe=(e=>e instanceof HTMLVideoElement?e.videoHeight:(null==e?void 0:e.height)||0)(ae),ve=y({cropX:le,cropY:ce,cropWidth:ue,cropHeight:ge,width:o.width,height:o.height},{width:me,height:pe}),we=ve.width,xe=ve.height,Me="svg"===o.type,ye=null!==(x=o.cornerRadius)&&void 0!==x?x:0,[Ee,be]=useCornerRadiusAndCrop(o,ae,ve,d._elementsPixelRatio,ye,!0);let[Le,Te]=((e,t,r,o)=>{const n=(e=>{const[t,r]=i.useState(e);return i.useEffect(()=>{(async()=>{const i=await async function(e){if(!(e.indexOf("data:image/svg+xml")>=0||e.indexOf(".svg")>=0)){return e}const t=await E.urlToString(e),r=E.fixSize(t);return E.svgToURL(r)}(e);i!==t&&r(i)})()},[e]),t})(e.clipSrc||""),[a,d]=m(n,"anonymous"),h=e.clipSrc?d:"loaded";useLoader(h,e.clipSrc,e.id);const s=i.useMemo(()=>{if(t&&a){return A()}},[t,a]);function l(){var i;if(!a){return}const o=t instanceof HTMLVideoElement?t.videoWidth:null==t?void 0:t.width,n=t instanceof HTMLVideoElement?t.videoHeight:null==t?void 0:t.height;if(!t||!o||!n){return}if(!a||!a.width||!a.height){return}if(!s){return}const d=A(),h=Math.max(e.width/a.width*r,e.height/a.height*r);d.width=a.width*h,d.height=a.height*h,null===(i=d.getContext("2d"))||void 0===i||i.drawImage(a,0,0,d.width,d.height),s.width=Math.max(o,1),s.height=Math.max(n,1);const l=s.getContext("2d");l&&(l.save(),l.drawImage(d,0,0,o,n),f.Util.releaseCanvas(d),l.globalCompositeOperation="source-in",l.drawImage(t,0,0,s.width,s.height),l.restore())}return i.useLayoutEffect(()=>{l()},[s,t,a,e.width,e.height,r,...o]),[e.clipSrc&&a?s:t,l]})(o,Ee,d._elementsPixelRatio,[ve,ye,d._elementsPixelRatio]);const Ce=k(()=>{var e,t;de(),be(),Te(),null===(t=null===(e=N.current)||void 0===e?void 0:e.getLayer())||void 0===t||t.batchDraw()});i.useEffect(()=>{Ce()});const Re=Math.max(o.width/we,o.height/xe);i.useEffect(()=>{var e;if(!o._cropModeEnabled){return}const t=null===(e=N.current)||void 0===e?void 0:e.getStage();function r(e){o._cropModeEnabled&&e.target!==Z.current&&o.toggleCropMode(!1)}function i(e){o._cropModeEnabled&&e.target.parentNode!==(null==t?void 0:t.content)&&o.toggleCropMode(!1)}return document.body.addEventListener("click",i),null==t||t.on("click",r),null==t||t.on("tap",r),()=>{document.body.removeEventListener("click",i),document.body.removeEventListener("touchstart",i),null==t||t.off("click",r),null==t||t.off("click",r)}},[o._cropModeEnabled]);const Se=i.useRef(null),Ie=i.useRef(null),ke=i.useRef(null);i.useLayoutEffect(()=>{o._cropModeEnabled&&(Ie.current.nodes([Se.current]),ke.current.nodes([Z.current]))},[o._cropModeEnabled]);const He=e=>{Math.round(e.target.x())>0&&(e.target.x(0),e.target.scaleX(1)),Math.round(e.target.y())>0&&(e.target.y(0),e.target.scaleY(1));const t=e.target.width()*e.target.scaleX(),r=e.target.height()*e.target.scaleY(),i=Math.min(1,we/t),n=Math.min(1,xe/r),a=1-i,d=Math.min(a,Math.max(0,Math.round(-e.target.x())/t)),h=1-n,s=Math.min(h,Math.max(0,Math.round(-e.target.y())/r));e.target.setAttrs({x:-d*me,y:-s*pe,scaleX:1,scaleY:1}),o.set({cropX:d,cropY:s,cropWidth:i,cropHeight:n})},We=()=>{"svg"!==o.type&&o.contentEditable&&setTimeout(()=>{n(o)&&o.toggleCropMode(!0)})},Xe="loading"===K,Ye="failed"===K,Oe=!Xe&&!Ye,je=i.useRef({cropX:0,cropY:0,cropWidth:0,cropHeight:0}),Pe=i.useRef(!1),Ae=Oe?o.a.opacity:0;H(N,Ae);const _e=o.selectable||d.role===g.ADMIN,Ve=W();return e(r,{children:t(h,{onMouseEnter:()=>ee(!0),onMouseLeave:()=>ee(!1),children:[Xe&&e(z,{element:o}),Ye&&e(B,{element:o}),e(s,{ref:N,name:"element",id:o.id,image:Le,x:o.a.x,y:o.a.y,width:o.a.width||1,height:o.a.height||1,rotation:o.a.rotation,opacity:Ae,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur,shadowOffsetX:o.shadowOffsetX,shadowOffsetY:o.shadowOffsetY,shadowColor:o.shadowColor,shadowOpacity:o.shadowOpacity,customCrop:ve,listening:_e,draggable:Ve?o.draggable&&$:o.draggable,preventDefault:!Ve||$,hideInExport:!o.showInExport,onDragMove:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDragEnd:e=>{o.set({x:e.target.x(),y:e.target.y()})},onDblClick:We,onDblTap:We,onTransformStart:e=>{b(!0),Pe.current=C(T(e.target)),je.current={cropX:o.cropX,cropY:o.cropY,cropWidth:o.cropWidth,cropHeight:o.cropHeight}},onTransform:e=>{const t=e.currentTarget,r=Math.abs(t.scaleX()-1)<1e-7?1:t.scaleX(),i=Math.abs(t.scaleY()-1)<1e-7?1:t.scaleY();t.scaleX(1),t.scaleY(1);const n=1-we/me,a=Math.min(n,Math.max(0,o.cropX)),d=1-xe/pe,h=Math.min(d,Math.max(0,o.cropY)),s=Pe.current,l=!s&&r<1&&je.current.cropHeight>xe/pe;let c=s?o.cropWidth:o.cropWidth*r;l&&(c=o.cropWidth);const u=!s&&i<1&&je.current.cropWidth>we/me;let g=s?o.cropHeight:o.cropHeight*i;u&&(g=o.cropHeight),Me&&(c=o.cropWidth,g=o.cropHeight);const m=s?Math.min(r,i):1;o.set(Object.assign({cropX:a,cropY:h,x:t.x(),y:t.y(),width:t.width()*r,height:t.height()*i,rotation:e.target.rotation(),cropWidth:Math.min(c,1-a),cropHeight:Math.min(g,1-h)},1!==m&&Object.assign(Object.assign({},R(o,m)),{borderSize:o.borderSize*m})))},onTransformEnd:e=>{const t=e.currentTarget;o.set(Object.assign(Object.assign({width:t.width(),height:t.height(),x:t.x(),y:t.y(),rotation:e.target.rotation(),cropWidth:we/me,cropHeight:xe/pe},S(o)),{borderSize:L(o.borderSize)})),b(!1)}}),e(l,{x:o.a.x,y:o.a.y,width:Math.max(o.a.width-o.borderSize,0),height:Math.max(o.a.height-o.borderSize,0),opacity:Ae,offsetX:-o.borderSize/2,offsetY:-o.borderSize/2,stroke:o.borderColor,strokeWidth:o.borderSize,listening:!1,visible:!!o.borderSize,rotation:o.rotation,cornerRadius:Math.max(0,ye-o.borderSize),hideInExport:!o.showInExport}),!d.isPlaying&&e(s,{image:q?Q||Ve?V:void 0:_,x:o.a.x,y:o.a.y,offsetX:-o.a.width/2+15/d.scale,offsetY:-o.a.height/2+15/d.scale,rotation:o.a.rotation,width:30/d.scale,height:30/d.scale,hideInExport:!0,onClick:()=>G(!q),onTap:()=>G(!q)}),o._cropModeEnabled&&t(p,{selector:".page-abs-container",enabled:!0,children:[e(l,{x:-window.innerWidth/d.scale,y:-window.innerWidth/d.scale,width:window.innerWidth/d.scale*3,height:window.innerWidth/d.scale*3,fill:"rgba(0,0,0,0.3)"}),e(s,{listening:!1,image:Le,x:o.a.x,y:o.a.y,width:o.a.width,height:o.a.height,rotation:o.a.rotation,shadowEnabled:o.shadowEnabled,shadowBlur:o.shadowBlur}),t(h,{x:o.a.x,y:o.a.y,rotation:o.a.rotation,scaleX:Re,scaleY:Re,children:[e(s,{image:ae,ref:Z,width:me,height:pe,opacity:.4,draggable:!0,x:-o.cropX*me,y:-o.cropY*pe,onDragMove:He,onTransform:He}),e(u,{ref:ke,anchorSize:20,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,rotateEnabled:!1,borderEnabled:!1,anchorCornerRadius:10,anchorStrokeWidth:2,borderStrokeWidth:2}),e(l,{width:we,height:xe,ref:Se,listening:!1,onTransform:e=>{e.target.x()<-o.cropX*me-1e-9&&(e.target.x(-o.cropX*me),e.target.scaleX(1)),e.target.y()<-o.cropY*pe-1e-9&&(e.target.y(-o.cropY*pe),e.target.scaleY(1));const t=Math.min(1,Math.max(0,o.cropX+e.target.x()/me)),r=Math.min(1,Math.max(0,e.target.y()/pe+o.cropY)),i=e.target.width()*e.target.scaleX(),n=e.target.height()*e.target.scaleY(),a=Math.min(1-t,i/me),d=Math.min(1-r,n/pe),h=e.target.getAbsolutePosition(e.target.getParent().getParent());e.target.scale({x:1,y:1}),e.target.position({x:0,y:0}),o.set({x:h.x,y:h.y,cropX:t,cropY:r,cropWidth:a,cropHeight:d,width:Math.min(i*Re,me*(1-t)*Re),height:Math.min(n*Re,pe*(1-r)*Re)})}}),e(u,{ref:Ie,enabledAnchors:["top-left","top-right","bottom-left","bottom-right"],boundBoxFunc:(e,t)=>t.width<5||t.height<5?e:t,keepRatio:!1,rotateEnabled:!1,anchorFill:"rgb(240, 240, 240)",anchorStrokeWidth:2,borderStrokeWidth:2,visible:o.resizable})]})]})]})})});
|
package/hooks/use-event.js
CHANGED
package/icons/registry.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ export type IconComponent = ComponentType<{
|
|
|
5
5
|
declare const defaults: {
|
|
6
6
|
'action.duplicate': import("react").ForwardRefExoticComponent<Omit<import("lucide-react").LucideProps, "ref"> & import("react").RefAttributes<SVGSVGElement>>;
|
|
7
7
|
'action.split': import("react").ForwardRefExoticComponent<Omit<import("lucide-react").LucideProps, "ref"> & import("react").RefAttributes<SVGSVGElement>>;
|
|
8
|
+
'action.rename': import("react").ForwardRefExoticComponent<Omit<import("lucide-react").LucideProps, "ref"> & import("react").RefAttributes<SVGSVGElement>>;
|
|
8
9
|
'action.remove': import("react").ForwardRefExoticComponent<Omit<import("lucide-react").LucideProps, "ref"> & import("react").RefAttributes<SVGSVGElement>>;
|
|
9
10
|
'action.lock': import("react").ForwardRefExoticComponent<Omit<import("lucide-react").LucideProps, "ref"> & import("react").RefAttributes<SVGSVGElement>>;
|
|
10
11
|
'action.unlock': import("react").ForwardRefExoticComponent<Omit<import("lucide-react").LucideProps, "ref"> & import("react").RefAttributes<SVGSVGElement>>;
|
package/icons/registry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=this&&this.__rest||function(t,o){var e={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&o.indexOf(i)<0&&(e[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++){o.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(e[i[n]]=t[i[n]])}}return e};import{jsx as o}from"react/jsx-runtime";import{observable as e,action as i}from"mobx";import{observer as n}from"mobx-react-lite";import{AlignCenter as a,AlignCenterHorizontal as r,AlignCenterVertical as l,AlignEndHorizontal as s,AlignEndVertical as c,AlignHorizontalSpaceAround as p,AlignJustify as d,AlignLeft as m,AlignRight as g,AlignStartHorizontal as u,AlignStartVertical as b,AlignVerticalJustifyCenter as f,AlignVerticalJustifyEnd as x,AlignVerticalJustifyStart as y,AlignVerticalSpaceAround as h,ArrowDown as v,ArrowDownLeft as w,ArrowDownRight as P,ArrowLeft as z,ArrowLeftRight as O,ArrowRight as j,ArrowUp as k,ArrowUpDown as L,ArrowUpLeft as R,ArrowUpRight as T,Ban as I,Bold as B,CaseSensitive as C,Check as D,ChevronDown as H,ChevronLeft as M,ChevronRight as F,ChevronsDown as S,ChevronsUp as U,ChevronUp as V,CloudUpload as $,Contrast as _,Copy as E,CreditCard as J,Crop as W,Edit as Z,Eye as q,EyeOff as A,Files as G,FileText as K,GripVertical as N,HelpCircle as Q,Highlighter as X,Image as Y,Italic as tt,Layers as ot,LayoutTemplate as et,List as it,ListOrdered as nt,Lock as at,MousePointer as rt,MoreHorizontal as lt,PaintBucket as st,Palette as ct,Pause as pt,Pencil as dt,Pilcrow as mt,Pipette as gt,Play as ut,Plus as bt,Redo2 as ft,Scaling as xt,Scissors as yt,Search as ht,SkipBack as vt,Settings as wt,Shapes as Pt,Sparkles as zt,Strikethrough as Ot,TextCursorInput as jt,Timer as kt,Trash2 as Lt,Type as Rt,Underline as Tt,Undo2 as It,Unlock as Bt,Upload as Ct,Video as Dt,Volume2 as Ht,VolumeX as Mt,WandSparkles as Ft,WrapText as St,X as Ut,ZoomIn as Vt,ZoomOut as $t}from"lucide-react";import{Instagram as _t,Facebook as Et,Youtube as Jt,Linkedin as Wt,Twitter as Zt}from"./brand-icons.js";import{MoveIcon as qt,FadeIcon as At,ZoomIcon as Gt,RotateIcon as Kt,BlinkIcon as Nt,BounceIcon as Qt}from"./animation-icons.js";const Xt={"action.duplicate":E,"action.split":yt,"action.remove":Lt,"action.lock":at,"action.unlock":Bt,"action.undo":It,"action.redo":ft,"action.add":bt,"action.more":lt,"action.settings":wt,"action.search":ht,"action.close":Ut,"action.confirm":D,"action.none":I,"action.visible":q,"action.hidden":A,"action.dragHandle":N,"action.eyeDropper":gt,"action.unmuted":Ht,"action.muted":Mt,"action.help":Q,"ui.chevronUp":V,"ui.chevronDown":H,"ui.chevronLeft":M,"ui.chevronRight":F,"layering.menu":ot,"layering.up":V,"layering.down":H,"layering.top":U,"layering.bottom":S,"text.bold":B,"text.italic":tt,"text.underline":Tt,"text.strikethrough":Ot,"text.alignLeft":m,"text.alignCenter":a,"text.alignRight":g,"text.alignJustify":d,"text.valignTop":y,"text.valignMiddle":f,"text.valignBottom":x,"text.uppercase":C,"text.spacing":St,"text.bulletList":it,"text.numberedList":nt,"text.paragraph":mt,"text.richText":jt,"text.uploadFont":Ct,"position.alignLeft":b,"position.alignCenter":l,"position.alignRight":c,"position.alignTop":u,"position.alignMiddle":r,"position.alignBottom":s,"position.distributeVertical":h,"position.distributeHorizontal":p,"sidePanel.templates":et,"sidePanel.text":Rt,"sidePanel.photos":Y,"sidePanel.elements":Pt,"sidePanel.upload":$,"sidePanel.background":st,"sidePanel.pages":G,"sidePanel.layers":ot,"sidePanel.resize":xt,"sidePanel.draw":dt,"sidePanel.videos":Dt,"toolbar.opacity":_,"toolbar.filters":Ft,"toolbar.aiWrite":zt,"toolbar.duration":kt,"toolbar.trim":yt,"toolbar.flipHorizontal":O,"toolbar.flipVertical":L,"toolbar.zoomIn":Vt,"toolbar.zoomOut":$t,"toolbar.crop":W,"download.export":Ct,"download.image":Y,"download.pdf":K,"download.video":Dt,"draw.select":rt,"draw.brush":Z,"draw.highlighter":X,"background.colorPicker":ct,"pagesTimeline.play":ut,"pagesTimeline.pause":pt,"pagesTimeline.rewind":vt,"size.instagram":_t,"size.facebook":Et,"size.youtube":Jt,"size.linkedin":Wt,"size.twitter":Zt,"size.video":Dt,"size.print":K,"size.businessCard":J,"animation.directionRight":j,"animation.directionLeft":z,"animation.directionUp":k,"animation.directionDown":v,"animation.directionBottomRight":P,"animation.directionBottomLeft":w,"animation.directionTopRight":T,"animation.directionTopLeft":R,"animation.typeMove":qt,"animation.typeFade":At,"animation.typeZoom":Gt,"animation.typeRotate":Kt,"animation.typeBlink":Nt,"animation.typeBounce":Qt},Yt=e.map();export const setIcons=i(t=>{for(const o of Object.keys(t)){const e=t[o];null!=e&&("function"==typeof e||"object"==typeof e?Yt.set(o,e):console.warn(`polotno: setIcons('${o}') expects a React component, received ${typeof e}. Ignored.`))}});export const resetIcons=i(()=>Yt.clear());export const PolotnoIcon=n(e=>{var i,{name:n}=e,a=t(e,["name"]);const r=null!==(i=Yt.get(n))&&void 0!==i?i:Xt[n];return o(r,Object.assign({"data-pn-icon":""},a))});
|
|
1
|
+
var t=this&&this.__rest||function(t,o){var e={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&o.indexOf(i)<0&&(e[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++){o.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(e[i[n]]=t[i[n]])}}return e};import{jsx as o}from"react/jsx-runtime";import{observable as e,action as i}from"mobx";import{observer as n}from"mobx-react-lite";import{AlignCenter as a,AlignCenterHorizontal as r,AlignCenterVertical as l,AlignEndHorizontal as s,AlignEndVertical as c,AlignHorizontalSpaceAround as p,AlignJustify as d,AlignLeft as m,AlignRight as g,AlignStartHorizontal as u,AlignStartVertical as b,AlignVerticalJustifyCenter as f,AlignVerticalJustifyEnd as x,AlignVerticalJustifyStart as y,AlignVerticalSpaceAround as h,ArrowDown as v,ArrowDownLeft as w,ArrowDownRight as P,ArrowLeft as z,ArrowLeftRight as O,ArrowRight as j,ArrowUp as k,ArrowUpDown as L,ArrowUpLeft as R,ArrowUpRight as T,Ban as I,Bold as B,CaseSensitive as C,Check as D,ChevronDown as H,ChevronLeft as M,ChevronRight as F,ChevronsDown as S,ChevronsUp as U,ChevronUp as V,CloudUpload as $,Contrast as _,Copy as E,CreditCard as J,Crop as W,Edit as Z,Eye as q,EyeOff as A,Files as G,FileText as K,GripVertical as N,HelpCircle as Q,Highlighter as X,Image as Y,Italic as tt,Layers as ot,LayoutTemplate as et,List as it,ListOrdered as nt,Lock as at,MousePointer as rt,MoreHorizontal as lt,PaintBucket as st,Palette as ct,Pause as pt,Pencil as dt,Pilcrow as mt,Pipette as gt,Play as ut,Plus as bt,Redo2 as ft,Scaling as xt,Scissors as yt,Search as ht,SkipBack as vt,Settings as wt,Shapes as Pt,Sparkles as zt,Strikethrough as Ot,TextCursorInput as jt,Timer as kt,Trash2 as Lt,Type as Rt,Underline as Tt,Undo2 as It,Unlock as Bt,Upload as Ct,Video as Dt,Volume2 as Ht,VolumeX as Mt,WandSparkles as Ft,WrapText as St,X as Ut,ZoomIn as Vt,ZoomOut as $t}from"lucide-react";import{Instagram as _t,Facebook as Et,Youtube as Jt,Linkedin as Wt,Twitter as Zt}from"./brand-icons.js";import{MoveIcon as qt,FadeIcon as At,ZoomIcon as Gt,RotateIcon as Kt,BlinkIcon as Nt,BounceIcon as Qt}from"./animation-icons.js";const Xt={"action.duplicate":E,"action.split":yt,"action.rename":dt,"action.remove":Lt,"action.lock":at,"action.unlock":Bt,"action.undo":It,"action.redo":ft,"action.add":bt,"action.more":lt,"action.settings":wt,"action.search":ht,"action.close":Ut,"action.confirm":D,"action.none":I,"action.visible":q,"action.hidden":A,"action.dragHandle":N,"action.eyeDropper":gt,"action.unmuted":Ht,"action.muted":Mt,"action.help":Q,"ui.chevronUp":V,"ui.chevronDown":H,"ui.chevronLeft":M,"ui.chevronRight":F,"layering.menu":ot,"layering.up":V,"layering.down":H,"layering.top":U,"layering.bottom":S,"text.bold":B,"text.italic":tt,"text.underline":Tt,"text.strikethrough":Ot,"text.alignLeft":m,"text.alignCenter":a,"text.alignRight":g,"text.alignJustify":d,"text.valignTop":y,"text.valignMiddle":f,"text.valignBottom":x,"text.uppercase":C,"text.spacing":St,"text.bulletList":it,"text.numberedList":nt,"text.paragraph":mt,"text.richText":jt,"text.uploadFont":Ct,"position.alignLeft":b,"position.alignCenter":l,"position.alignRight":c,"position.alignTop":u,"position.alignMiddle":r,"position.alignBottom":s,"position.distributeVertical":h,"position.distributeHorizontal":p,"sidePanel.templates":et,"sidePanel.text":Rt,"sidePanel.photos":Y,"sidePanel.elements":Pt,"sidePanel.upload":$,"sidePanel.background":st,"sidePanel.pages":G,"sidePanel.layers":ot,"sidePanel.resize":xt,"sidePanel.draw":dt,"sidePanel.videos":Dt,"toolbar.opacity":_,"toolbar.filters":Ft,"toolbar.aiWrite":zt,"toolbar.duration":kt,"toolbar.trim":yt,"toolbar.flipHorizontal":O,"toolbar.flipVertical":L,"toolbar.zoomIn":Vt,"toolbar.zoomOut":$t,"toolbar.crop":W,"download.export":Ct,"download.image":Y,"download.pdf":K,"download.video":Dt,"draw.select":rt,"draw.brush":Z,"draw.highlighter":X,"background.colorPicker":ct,"pagesTimeline.play":ut,"pagesTimeline.pause":pt,"pagesTimeline.rewind":vt,"size.instagram":_t,"size.facebook":Et,"size.youtube":Jt,"size.linkedin":Wt,"size.twitter":Zt,"size.video":Dt,"size.print":K,"size.businessCard":J,"animation.directionRight":j,"animation.directionLeft":z,"animation.directionUp":k,"animation.directionDown":v,"animation.directionBottomRight":P,"animation.directionBottomLeft":w,"animation.directionTopRight":T,"animation.directionTopLeft":R,"animation.typeMove":qt,"animation.typeFade":At,"animation.typeZoom":Gt,"animation.typeRotate":Kt,"animation.typeBlink":Nt,"animation.typeBounce":Qt},Yt=e.map();export const setIcons=i(t=>{for(const o of Object.keys(t)){const e=t[o];null!=e&&("function"==typeof e||"object"==typeof e?Yt.set(o,e):console.warn(`polotno: setIcons('${o}') expects a React component, received ${typeof e}. Ignored.`))}});export const resetIcons=i(()=>Yt.clear());export const PolotnoIcon=n(e=>{var i,{name:n}=e,a=t(e,["name"]);const r=null!==(i=Yt.get(n))&&void 0!==i?i:Xt[n];return o(r,Object.assign({"data-pn-icon":""},a))});
|
package/model/audio-model.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Instance } from 'mobx-state-tree';
|
|
2
2
|
export declare const Audio: import("mobx-state-tree").IModelType<{
|
|
3
3
|
id: import("mobx-state-tree").ISimpleType<string>;
|
|
4
|
+
name: import("mobx-state-tree").IType<string | undefined, string, string>;
|
|
4
5
|
src: import("mobx-state-tree").IType<string | undefined, string, string>;
|
|
5
6
|
duration: import("mobx-state-tree").IType<number | undefined, number, number>;
|
|
6
7
|
startTime: import("mobx-state-tree").IType<number | undefined, number, number>;
|
|
@@ -14,6 +15,7 @@ export declare const Audio: import("mobx-state-tree").IModelType<{
|
|
|
14
15
|
} & {
|
|
15
16
|
toJSON(): {
|
|
16
17
|
id: string;
|
|
18
|
+
name: string;
|
|
17
19
|
src: string;
|
|
18
20
|
duration: number;
|
|
19
21
|
startTime: number;
|
package/model/audio-model.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{types as e,getSnapshot as t}from"mobx-state-tree";export const Audio=e.model("Audio",{id:e.identifier,src:"",duration:0,startTime:0,endTime:1,volume:1,delay:0,speed:1,custom:e.frozen()}).views(e=>({get visibleDuration(){return(e.endTime-e.startTime)*e.duration/e.speed}})).actions(e=>({toJSON:()=>Object.assign({},t(e))})).actions(e=>({set(t){Object.assign(e,t)}}));
|
|
1
|
+
import{types as e,getSnapshot as t}from"mobx-state-tree";export const Audio=e.model("Audio",{id:e.identifier,name:"",src:"",duration:0,startTime:0,endTime:1,volume:1,delay:0,speed:1,custom:e.frozen()}).views(e=>({get visibleDuration(){return(e.endTime-e.startTime)*e.duration/e.speed}})).actions(e=>({toJSON:()=>Object.assign({},t(e))})).actions(e=>({set(t){Object.assign(e,t)}}));
|
package/model/image-model.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{observable as e}from"mobx";import{Shape as o}from"./shape-model.js";export const ImageElement=o.named("Image").props({type:"image",width:100,height:100,src:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,cornerRadius:0,flipX:!1,flipY:!1,clipSrc:"",borderColor:"black",borderSize:0,keepRatio:!1,stretchEnabled:!1}).extend(o=>{const r=e.box(!1);let t=!1;return{views:{get _cropModeEnabled(){return r.get()}},actions:{toggleCropMode(e){const
|
|
1
|
+
import{observable as e}from"mobx";import{Shape as o}from"./shape-model.js";export const ImageElement=o.named("Image").props({type:"image",width:100,height:100,src:"",cropX:0,cropY:0,cropWidth:1,cropHeight:1,cornerRadius:0,flipX:!1,flipY:!1,clipSrc:"",borderColor:"black",borderSize:0,keepRatio:!1,stretchEnabled:!1}).extend(o=>{const r=e.box(!1);let t=!1;return{views:{get _cropModeEnabled(){return r.get()}},actions:{toggleCropMode(e){var n;const i=null!=e?e:!r.get();r.set(i);const s=null===(n=o.store)||void 0===n?void 0:n.history;s&&(i&&!t?(s.startTransaction(),t=!0):!i&&t&&(s.endTransaction(),t=!1))},beforeDestroy(){t&&(o.store.history.endTransaction(),t=!1)}}}});
|
package/model/store.d.ts
CHANGED
|
@@ -2022,6 +2022,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
|
|
|
2022
2022
|
}, {}, any, import("mobx-state-tree")._NotCustomized>>;
|
|
2023
2023
|
audios: import("mobx-state-tree").IArrayType<import("mobx-state-tree").IModelType<{
|
|
2024
2024
|
id: import("mobx-state-tree").ISimpleType<string>;
|
|
2025
|
+
name: import("mobx-state-tree").IType<string | undefined, string, string>;
|
|
2025
2026
|
src: import("mobx-state-tree").IType<string | undefined, string, string>;
|
|
2026
2027
|
duration: import("mobx-state-tree").IType<number | undefined, number, number>;
|
|
2027
2028
|
startTime: import("mobx-state-tree").IType<number | undefined, number, number>;
|
|
@@ -2035,6 +2036,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
|
|
|
2035
2036
|
} & {
|
|
2036
2037
|
toJSON(): {
|
|
2037
2038
|
id: string;
|
|
2039
|
+
name: string;
|
|
2038
2040
|
src: string;
|
|
2039
2041
|
duration: number;
|
|
2040
2042
|
startTime: number;
|
|
@@ -18219,6 +18221,7 @@ export declare const Store: import("mobx-state-tree").IModelType<{
|
|
|
18219
18221
|
pages: {}[];
|
|
18220
18222
|
audios: import("mobx-state-tree").ModelSnapshotType<{
|
|
18221
18223
|
id: import("mobx-state-tree").ISimpleType<string>;
|
|
18224
|
+
name: import("mobx-state-tree").IType<string | undefined, string, string>;
|
|
18222
18225
|
src: import("mobx-state-tree").IType<string | undefined, string, string>;
|
|
18223
18226
|
duration: import("mobx-state-tree").IType<number | undefined, number, number>;
|
|
18224
18227
|
startTime: import("mobx-state-tree").IType<number | undefined, number, number>;
|
package/model/store.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=this&&this.__rest||function(e,t){var i={};for(var o in e){Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(i[o]=e[o])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n<o.length;n++){t.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(e,o[n])&&(i[o[n]]=e[o[n]])}}return i};import{applySnapshot as t,cast as i,destroy as o,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m}from"@polotno/schema";import{downloadFile as u}from"../utils/download.js";import{getJsPDF as f}from"../utils/pdf.js";import{createGIF as h}from"../utils/gif-lib.js";import{validateKey as b,setKey as v}from"../utils/validate-key.js";import*as y from"../utils/fonts.js";import{flags as P}from"../utils/flags.js";import{addDpiMetadataToImage as w}from"../utils/image-dpi.js";import{nodeToCanvas as x}from"../utils/canvas.js";import{whenLoaded as E}from"../utils/loader.js";import{polotnoError as I}from"@polotno/core/errors";import{pxToUnit as T}from"../utils/unit.js";import{deepEqual as _}from"../utils/deep-equal.js";import{waitTillAvailable as S}from"../utils/wait.js";import{jsonToHTML as O}from"@polotno/html-export";import{jsonToSVG as k}from"@polotno/svg-export";import{warnOnceDeprecated as j}from"../utils/deprecation.js";import{Page as R}from"./page-model.js";import{forEveryChild as F,forEveryNode as A}from"./group-model.js";import{Audio as V}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(R),fonts:l.array(Font),audios:l.array(V),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:4,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return A({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return F({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const i of e.pages){if(t>=i.startTime&&t<i.startTime+i.duration){return i}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let i;return A({children:e.pages},e=>{if(!i&&t(e)){return i=e,!0}}),i},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const v={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:o=0,endTime:n=r.duration,repeat:a=!1}={}){o&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=o),r.animatedElementsIds=i(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>v.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&v.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const i=d||r.duration;r.currentTime>=i&&!g&&(r.currentTime=i),v.checkActivePage(),r.isPlaying&&r.currentTime<i?requestAnimationFrame(()=>v.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>v.seek())):v.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=i([])},stop(){v.pause(),r.currentTime=0,v.checkActivePage()},__(){r._validated||(b(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=R.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=i([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=i([e]))},selectPages(e){r._selectedPagesIds=i(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var i,o,n,a;return(null!==(o=null===(i=e.parent)||void 0===i?void 0:i.children.indexOf(e))&&void 0!==o?o:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=i(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,i){r.pages.forEach(o=>{o.setSize({width:e,height:t,useMagic:i,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const i=r.pages.find(t=>t.id===e);i&&(n(i),r.pages.remove(i),r.pages.splice(t,0,i))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);o(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),v.selectPages(n),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const o=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!o.length){return}const a=o[0].parent;if(!a){return}if(!o.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}o.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var i;if("group"===t.type){const o=null===(i=t.name)||void 0===i?void 0:i.match(/group-(\d+)/);if(o){const t=parseInt(o[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:o,type:"group"},t);return a.children.push(l),r.selectedElementsIds=i([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),o=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const i=t.children.indexOf(e);e.children.forEach(e=>{o.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(i,1)}}),r.selectedElementsIds=i(o)},deleteElements(e){const t=[];r.find(i=>(e.includes(i.id)&&t.push(i),!1)),t.forEach(e=>{o(e)}),r.selectedElementsIds=i(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=v.toJSON();return s(r,i=>{const o=v.toJSON();!_(e,o)&&(e=o,t(o))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:i,mimeType:o,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;i=i||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===i);if(!g){throw I("EXPORT_FAILED",`No page for export with id ${i}`,{reason:"page-not-found",pageId:i,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;p>r._elementsPixelRatio&&v.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const f=await S(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===i);return 0===e.length?null:e});if(!f){throw null==g||g.set({_forceMount:!1,_exporting:!1}),v.setElementsPixelRatio(u),I("EXPORT_FAILED",`Export is failed. Can not find stage for page ${i}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:i})}f.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${i}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const h=f[0];await v.waitLoading({_skipTimeout:a});const b=h.findOne(".page-container");if(!b){throw v.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1}),I("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:i})}const y=h.position();h.position({x:0,y:0}),h.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),b.find(".page-background").forEach(e=>e.shadowEnabled(!1)),b.find(".page-background").forEach(e=>e.strokeEnabled(!1)),b.find(".highlighter").forEach(e=>e.visible(!1));const P=b.findOne(".page-background-group"),w=P.clip();P.clip({x:null,y:null,width:null,height:null});const E=b.findOne(".elements-container"),T=E.clip();E.clip({x:null,y:null,width:null,height:null});const _=b.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));_.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const O=b.find(e=>e.getAttr("hideInExport"));O.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&b.find(".page-background").forEach(e=>e.hide());const k=n?g.computedBleed:m;let j=k.left,R=k.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(j=0,R=0):r.bleedVisible&&!n&&(j=-g.computedBleed.left,R=-g.computedBleed.top):(j=0,R=0));const F=g.computedWidth+k.left+k.right,A=g.computedHeight+k.top+k.bottom,V=b.scale();b.scale({x:1,y:1});const C=x(b,{x:b.x()-j,y:b.y()-R,width:F,height:A,pixelRatio:p,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});b.scale(V);const L=C._canvas;if("image/jpeg"===o){const e=L.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,L.width,L.height),e.restore()}return t&&b.find(".page-background").forEach(e=>e.show()),O.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),_.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".page-background").forEach(e=>e.shadowEnabled(!0)),b.find(".page-background").forEach(e=>e.strokeEnabled(!0)),h.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".highlighter").forEach(e=>e.visible(!0)),P.clip(w),E.clip(T),h.position(y),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),v.setElementsPixelRatio(u),L},async toDataURL(t={}){var{mimeType:i,quality:o,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await v._toCanvas(Object.assign({mimeType:i},s)),d=i||"image/png",p=l.toDataURL(d,o);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:w(p,d,g)},async toBlob(t={}){var{mimeType:i,quality:o}=t,n=e(t,["mimeType","quality"]);const a=await v._toCanvas(Object.assign({mimeType:i},n)),s=await new Promise(e=>{a.toBlob(e,i,o)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=(o.mimeType||"image/png").split("/")[1];u(await v.toDataURL(o),i||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,i=e.parallel||1,o=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await f(),d=e=>T({px:e,unit:o,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var y=new l({unit:o,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const P=((e,t)=>{const i=[];for(let o=0;o<e.length;o+=t){i.push(e.slice(o,o+t))}return i})(s,i);let w=0;for(const r of P){const t=r.map(async t=>{const i=e.includeBleed?t.computedBleed:m,o=t.computedWidth+i.left+i.right+2*p,s=t.computedHeight+i.top+i.bottom+2*p,r=d(o),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await v.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:o,heightPx:s,cb:i}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:i,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,i],t>i?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(o){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw I("EXPORT_FAILED","Invalid unit: "+o,{reason:"invalid-options",option:"unit",value:o})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:i*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),o=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-o,0,t-o,c),y.line(t,n,t-c,n),y.line(0,i-a,c,i-a),y.line(e,i,e,i-c),y.line(t,i-a,t-c,i-a),y.line(t-o,i,t-o,i-c)}y.addImage(e,c,c,t-2*c,i-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await v._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,i=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),o=r.pages.filter(e=>i.includes(e.id));if(!o.length){throw I("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=o[0],a=await h({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of o){const e=Math.max(1,Math.floor(l.duration/s));for(let i=0;i<e;i++){const e=l.startTime+i*s||1;v.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const o=await v._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(o.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return v.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);const n=await v.toGIFDataURL(o);u(n,i||"polotno.gif")},async toHTML({elementHook:e}={}){j("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=v.toJSON();return O(t,{elementHook:e,textOverflow:P.textOverflow,textSplitAllowed:P.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const i=await v.toHTML({elementHook:t}),o="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(i)));u(o,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:i="inline"}={fontEmbedding:"inline"}){var o;j("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=v.toJSON();t=t||(null===(o=n.pages[0])||void 0===o?void 0:o.id);const a=n.pages.find(e=>e.id===t);return k(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),{elementHook:e,fontEmbedding:i})},async saveAsSVG({fileName:e,elementHook:t,pageId:i,fontEmbedding:o="inline"}={}){const n=await v.toSVG({elementHook:t,pageId:i,fontEmbedding:o}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));u(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:i}=t,o=e(t,["fileName"]);(await v._toPDF(Object.assign({mimeType:"image/jpeg"},o))).save(i||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await E()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,i=!1){var o,n,s;const l="boolean"==typeof i?i:null!==(o=null==i?void 0:i.keepHistory)&&void 0!==o&&o,d="boolean"!=typeof i&&null!==(n=null==i?void 0:i.modernizeTextBackground)&&void 0!==n&&n,p=JSON.parse(JSON.stringify(e)),c=p.schemaVersion||0;c<1&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&A({children:p.pages},e=>{if("text"===e.type){const t=16,i=e.letterSpacing*t;e.letterSpacing=i/e.fontSize}}),c<2&&A({children:p.pages},e=>{e.filters&&Object.keys(e.filters).forEach(t=>{if(["warm","cold","natural"].includes(t)){return}const i=e.filters[t];i&&"number"==typeof i.intensity&&(i.intensity=i.intensity/100)})}),c<3&&(P.htmlRenderEnabled||P.renderTagTextEnabled)&&!d&&A({children:p.pages},e=>{"text"===e.type&&e.backgroundEnabled&&(e.legacyBackground=!0)}),delete p.schemaVersion;const g=r.activePage?r.pages.indexOf(r.activePage):0;let m=null===(s=p.pages[g]||p.pages[0])||void 0===s?void 0:s.id;p._activePageId=m,p._selectedPagesIds=[];const u=Object.assign({},a(r));Object.assign(u,p),u.history=l?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,u)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);v.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){v.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>o(e))},addAudio(e){const t=V.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,i,o){const n=r.fonts.find(t=>t.fontFamily===e)||y.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),y.injectCustomFont(n)):y.injectGoogleFont(e),t&&i&&!a.some(e=>e.fontStyle===t&&e.fontWeight===i)&&a.push({fontStyle:t,fontWeight:i}),Promise.all(a.map(t=>y.loadFont(e,t.fontStyle,t.fontWeight,o)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return v});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return v(e),Store.create({_forceShowCredit:t})}export default createStore;
|
|
1
|
+
var e=this&&this.__rest||function(e,t){var o={};for(var i in e){Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(o[i]=e[i])}if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(e);n<i.length;n++){t.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(e,i[n])&&(o[i[n]]=e[i[n]])}}return o};import{applySnapshot as t,cast as o,destroy as i,detach as n,getSnapshot as a,onSnapshot as s,setLivelinessChecking as r,types as l}from"mobx-state-tree";import{UndoManager as d}from"./history.js";import{nanoid as p}from"nanoid";import c from"konva";import{computed as g}from"mobx";import{ZERO_BLEED as m,migrateDesign as u,CURRENT_SCHEMA_VERSION as f}from"@polotno/schema";import{downloadFile as h}from"../utils/download.js";import{getJsPDF as v}from"../utils/pdf.js";import{createGIF as b}from"../utils/gif-lib.js";import{validateKey as y,setKey as P}from"../utils/validate-key.js";import*as w from"../utils/fonts.js";import{flags as x}from"../utils/flags.js";import{addDpiMetadataToImage as E}from"../utils/image-dpi.js";import{nodeToCanvas as I}from"../utils/canvas.js";import{whenLoaded as T}from"../utils/loader.js";import{polotnoError as _}from"@polotno/core/errors";import{pxToUnit as O}from"../utils/unit.js";import{deepEqual as S}from"../utils/deep-equal.js";import{waitTillAvailable as k}from"../utils/wait.js";import{jsonToHTML as j}from"@polotno/html-export";import{jsonToSVG as R}from"@polotno/svg-export";import{warnOnceDeprecated as F}from"../utils/deprecation.js";import{Page as A}from"./page-model.js";import{forEveryChild as V,forEveryNode as C}from"./group-model.js";import{Audio as L}from"./audio-model.js";r("ignore");export const Font=l.model("Font",{fontFamily:l.string,url:l.optional(l.string,""),styles:l.frozen()}).preProcessSnapshot(e=>Object.assign(Object.assign({},e),{fontFamily:e.fontFamily||e.name}));export const ROLES={ADMIN:"admin",VIEWER:"viewer"};export const Store=l.model("Store",{role:"",pages:l.array(A),fonts:l.array(Font),audios:l.array(L),width:1080,height:1080,currentTime:0,isPlaying:!1,scale:1,scaleToFit:1,unit:l.optional(l.enumeration("UnitType",["pt","mm","cm","in","px"]),"px"),dpi:72,schemaVersion:f,bleedVisible:!1,rulesVisible:!1,distanceGuidesVisible:!1,timingPreview:l.optional(l.enumeration("TimingPreview",["all","playhead"]),"all"),openedSidePanel:"",previousOpenedSidePanel:"",custom:l.frozen(),tool:l.optional(l.enumeration("Tool",["selection","draw","pan","text","eraser"]),"selection"),toolOptions:l.optional(l.model({brushType:l.optional(l.enumeration("BrushType",["brush","highlighter"]),"brush"),strokeWidth:l.optional(l.number,5),stroke:l.optional(l.string,"#000000"),opacity:l.optional(l.number,1)}),{}),selectedElementsIds:l.array(l.string),animatedElementsIds:l.array(l.string),history:l.optional(d,{targetPath:"../pages"}),_elementsPixelRatio:Math.min(2,"undefined"!=typeof window&&window.devicePixelRatio||1),_activePageId:"",_selectedPagesIds:l.array(l.string),_forceShowCredit:!1,_validated:!1}).views(e=>{const t=g(()=>{const t={};return C({children:e.pages},e=>(t[e.id]=e,!1)),t},{keepAlive:!0});return{get _idsMap(){return t.get()}}}).views(e=>({get _bleedVisible(){return console.warn("store._bleedVisible is deprecated. Please use store.bleedVisible instead."),e.bleedVisible},get selectedElements(){return e.selectedElementsIds.map(t=>e._idsMap[t]).filter(e=>!!e)},get children(){return e.pages},get selectedShapes(){const e=[];return V({children:this.selectedElements},t=>{"group"!==t.type&&e.push(t)}),e},get activePage(){return e.pages.slice().find(t=>t.id===e._activePageId)||(e.pages.length?e.pages[0]:null)},get selectedPages(){return e._selectedPagesIds.map(t=>e.pages.find(e=>e.id===t))},get duration(){let t=0;return e.pages.forEach(e=>{t+=e.duration}),t},pageAtTime(t){for(const o of e.pages){if(t>=o.startTime&&t<o.startTime+o.duration){return o}}return e.pages.length&&t>=this.duration?e.pages[e.pages.length-1]:null},get effectiveTime(){if(e.isPlaying){return e.currentTime}const t=this.activePage;return t&&this.pageAtTime(e.currentTime)!==t?t.startTime:e.currentTime},get playheadAccurate(){return e.isPlaying||"playhead"===e.timingPreview},get isEditingPaused(){var t;return!e.isPlaying&&!(null===(t=this.activePage)||void 0===t?void 0:t._exportingOrRendering)},get _hasCroppedImages(){return this.find(e=>"image"===e.type&&e._cropModeEnabled)},find(t){let o;return C({children:e.pages},e=>{if(!o&&t(e)){return o=e,!0}}),o},getElementById:t=>e._idsMap[t]})).actions(r=>{let l=0,d=null,g=!1;const f={afterCreate(){r.history.canUndo},setCurrentTime(e){r.currentTime=e},_togglePlaying(e=!r.isPlaying){r.isPlaying=e},play({animatedElementsIds:e=[],startTime:t=0,currentTime:i=0,endTime:n=r.duration,repeat:a=!1}={}){i&&(console.warn("currentTime property of store.play() is deprecated. Please use startTime instead."),t=i),r.animatedElementsIds=o(e),r.currentTime=t,r.isPlaying=!0,l=Date.now(),d=n,g=a,requestAnimationFrame(()=>f.seek())},checkActivePage(){const e=r.pageAtTime(r.currentTime);e&&f.selectPage(e.id)},seek(){if(!r.isPlaying){return}const e=Date.now(),t=e-l;l=e,r.currentTime+=t;const o=d||r.duration;r.currentTime>=o&&!g&&(r.currentTime=o),f.checkActivePage(),r.isPlaying&&r.currentTime<o?requestAnimationFrame(()=>f.seek()):r.isPlaying&&g?(r.currentTime=0,requestAnimationFrame(()=>f.seek())):f.pause()},pause(){r.isPlaying=!1,r.animatedElementsIds=o([])},stop(){f.pause(),r.currentTime=0,f.checkActivePage()},__(){r._validated||(y(r._forceShowCredit),r._validated=!0)},set(e){Object.assign(r,e)},setUnit({unit:e,dpi:t}){r.unit=e||r.unit,r.dpi=t||r.dpi},setRole(e){r.role=e},setTool(e){r.tool=e},setToolOptions(e){Object.assign(r.toolOptions,e)},addPage(e){const t=A.create(Object.assign({id:p(10)},e));return r.pages.push(t),r._activePageId=t.id,r._selectedPagesIds=o([]),t},selectPage(e){r._activePageId=e,1===r._selectedPagesIds.length&&(r._selectedPagesIds=o([e]))},selectPages(e){r._selectedPagesIds=o(e),1===r._selectedPagesIds.length&&(r._activePageId=r._selectedPagesIds[0])},selectElements(e){const t=e.map(e=>r.getElementById(e)).filter(e=>!!e);t.sort((e,t)=>{var o,i,n,a;return(null!==(i=null===(o=e.parent)||void 0===o?void 0:o.children.indexOf(e))&&void 0!==i?i:0)-(null!==(a=null===(n=t.parent)||void 0===n?void 0:n.children.indexOf(t))&&void 0!==a?a:0)}),r.selectedElementsIds=o(t.map(e=>e.id))},toggleBleed(e){r.bleedVisible=null!=e?e:!r.bleedVisible},toggleRulers(e){r.rulesVisible=null!=e?e:!r.rulesVisible},setTimingPreview(e){r.timingPreview=e},toggleDistanceGuides(e){r.distanceGuidesVisible=null!=e?e:!r.distanceGuidesVisible},openSidePanel(e){r.openedSidePanel!==e&&(r.previousOpenedSidePanel=r.openedSidePanel,r.openedSidePanel=e)},restoreSidePanel(){const e=r.previousOpenedSidePanel;e&&e!==r.openedSidePanel?r.openedSidePanel=e:r.openedSidePanel="photos"},setScale(e){r.scale=e},_setScaleToFit(e){r.scaleToFit=e},setElementsPixelRatio(e){r._elementsPixelRatio=e},setSize(e,t,o){r.pages.forEach(i=>{i.setSize({width:e,height:t,useMagic:o,softChange:!0})}),r.width=e,r.height=t},setPageZIndex(e,t){const o=r.pages.find(t=>t.id===e);o&&(n(o),r.pages.remove(o),r.pages.splice(t,0,o))},deletePages(e){const t=r.pages.indexOf(r.activePage);e.forEach(e=>{const t=r.pages.find(t=>t.id===e);i(t)});const n=r._selectedPagesIds.filter(e=>r.pages.some(t=>t.id===e)),a=Math.min(r.pages.length-1,t),s=r.pages[a];s&&(r._activePageId=s.id),f.selectPages(n),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},groupElements(e,t={}){const i=e.map(e=>r.getElementById(e)).filter(e=>!!e);if(!i.length){return}const a=i[0].parent;if(!a){return}if(!i.every(e=>e.parent===a)){return void console.warn("store.groupElements: refusing to group elements that do not share a parent. Pass ids whose elements all live under the same page or the same group.")}i.forEach(e=>n(e));const s=a.children.reduce((e,t)=>{var o;if("group"===t.type){const i=null===(o=t.name)||void 0===o?void 0:o.match(/group-(\d+)/);if(i){const t=parseInt(i[1],10);return Math.max(e,t)}}return e},0),l=Object.assign({id:p(10),name:`group-${s+1}`,children:i,type:"group"},t);return a.children.push(l),r.selectedElementsIds=o([l.id]),a.children.find(e=>e.id===l.id)},ungroupElements(e){const t=e.map(e=>r.getElementById(e)),i=[];t.forEach(e=>{if(e&&"group"===e.type){const t=e.parent;if(!t){return}const o=t.children.indexOf(e);e.children.forEach(e=>{i.push(e.id)}),e.children.slice().forEach(e=>{n(e),t.children.push(e)}),t.children.splice(o,1)}}),r.selectedElementsIds=o(i)},deleteElements(e){const t=[];r.find(o=>(e.includes(o.id)&&t.push(o),!1)),t.forEach(e=>{i(e)}),r.selectedElementsIds=o(r.selectedElementsIds.filter(e=>r.getElementById(e)))},on(e,t){if("change"===e){let e=f.toJSON();return s(r,o=>{const i=f.toJSON();!S(e,i)&&(e=i,t(i))})}},async _toCanvas({pixelRatio:e,ignoreBackground:t,pageId:o,mimeType:i,includeBleed:n,_skipTimeout:a,quickMode:s=!1,_exportCanvases:l}={}){var d;const p=e||1;o=o||(null===(d=r.pages[0])||void 0===d?void 0:d.id);const g=r.pages.find(e=>e.id===o);if(!g){throw _("EXPORT_FAILED",`No page for export with id ${o}`,{reason:"page-not-found",pageId:o,availablePageIds:r.pages.map(e=>e.id)})}const u=r._elementsPixelRatio;p>r._elementsPixelRatio&&f.setElementsPixelRatio(p),s?null==g||g.set({_forceMount:!0}):null==g||g.set({_exporting:!0});const h=await k(()=>{const e=c.stages.filter(e=>e.getAttr("pageId")===o);return 0===e.length?null:e});if(!h){throw null==g||g.set({_forceMount:!1,_exporting:!1}),f.setElementsPixelRatio(u),_("EXPORT_FAILED",`Export is failed. Can not find stage for page ${o}. Looks like <Workspace /> component is not mounted, but it is required in order to process the export.`,{reason:"workspace-not-mounted",pageId:o})}h.length>1&&console.error(`Polotno error: Detected several canvas elements for page "${o}" in the document. This is not supported and will lead to incorrect export. Make sure to use unique ids for all pages and make sure you unmount <Workspace /> when it is not needed.`);const v=h[0];await f.waitLoading({_skipTimeout:a});const b=v.findOne(".page-container");if(!b){throw f.setElementsPixelRatio(u),null==g||g.set({_forceMount:!1,_exporting:!1}),_("EXPORT_FAILED","Export is failed. Canvas was unmounted.",{reason:"unmounted-during-export",pageId:o})}const y=v.position();v.position({x:0,y:0}),v.find("Transformer").forEach(e=>{e.setAttr("oldVisible",e.visible()),e.visible(!1)}),b.find(".page-background").forEach(e=>e.shadowEnabled(!1)),b.find(".page-background").forEach(e=>e.strokeEnabled(!1)),b.find(".highlighter").forEach(e=>e.visible(!1));const P=b.findOne(".page-background-group"),w=P.clip();P.clip({x:null,y:null,width:null,height:null});const x=b.findOne(".elements-container"),E=x.clip();x.clip({x:null,y:null,width:null,height:null});const T=b.find(e=>!e.visible()&&e.getAttr("editModeEnabled")&&!e.getAttr("hideInExport"));T.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.show()});const O=b.find(e=>e.getAttr("hideInExport"));O.forEach(e=>{e.setAttr("oldVisible",e.visible()),e.hide()}),t&&b.find(".page-background").forEach(e=>e.hide());const S=n?g.computedBleed:m;let j=S.left,R=S.top;!r.bleedVisible&&n||(r.bleedVisible||n?r.bleedVisible&&n?(j=0,R=0):r.bleedVisible&&!n&&(j=-g.computedBleed.left,R=-g.computedBleed.top):(j=0,R=0));const F=g.computedWidth+S.left+S.right,A=g.computedHeight+S.top+S.bottom,V=b.scale();b.scale({x:1,y:1});const C=I(b,{x:b.x()-j,y:b.y()-R,width:F,height:A,pixelRatio:p,sceneCanvas:null==l?void 0:l.sceneCanvas,bufferCanvas:null==l?void 0:l.bufferCanvas});b.scale(V);const L=C._canvas;if("image/jpeg"===i){const e=L.getContext("2d");e.save(),e.globalCompositeOperation="destination-over",e.fillStyle="white",e.fillRect(0,0,L.width,L.height),e.restore()}return t&&b.find(".page-background").forEach(e=>e.show()),O.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),T.forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".page-background").forEach(e=>e.shadowEnabled(!0)),b.find(".page-background").forEach(e=>e.strokeEnabled(!0)),v.find("Transformer").forEach(e=>{e.visible(e.getAttr("oldVisible"))}),b.find(".highlighter").forEach(e=>e.visible(!0)),P.clip(w),x.clip(E),v.position(y),null==g||g.set({_exporting:!1,_forceMount:!1}),await Promise.resolve(),f.setElementsPixelRatio(u),L},async toDataURL(t={}){var{mimeType:o,quality:i,dpi:n,dpiMetadata:a="auto"}=t,s=e(t,["mimeType","quality","dpi","dpiMetadata"]);const l=await f._toCanvas(Object.assign({mimeType:o},s)),d=o||"image/png",p=l.toDataURL(d,i);c.Util.releaseCanvas(l);const g=null!=n?n:r.dpi;return"image/png"!==d&&"image/jpeg"!==d||"never"===a||"auto"===a&&72===g?p:E(p,d,g)},async toBlob(t={}){var{mimeType:o,quality:i}=t,n=e(t,["mimeType","quality"]);const a=await f._toCanvas(Object.assign({mimeType:o},n)),s=await new Promise(e=>{a.toBlob(e,o,i)});return c.Util.releaseCanvas(a),s},async saveAsImage(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=(i.mimeType||"image/png").split("/")[1];h(await f.toDataURL(i),o||"polotno."+n)},async _toPDF(e){const t=e.dpi||r.dpi,o=e.parallel||1,i=e.unit||("px"===r.unit?"mm":r.unit),n=e.pixelRatio||1,a=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),s=r.pages.filter(e=>a.includes(e.id)),l=await v(),d=e=>O({px:e,unit:i,dpi:t}),p=e.cropMarkSize||0,c=d(p),g=s[0]||{},u=e.includeBleed&&g.computedBleed||m,h=d(g.computedWidth+u.left+u.right+2*c),b=d(g.computedHeight+u.top+u.bottom+2*c);var y=new l({unit:i,orientation:h>b?"landscape":"portrait",format:[h,b],compress:!0,putOnlyUsedFonts:!0});y.deletePage(1);const P=((e,t)=>{const o=[];for(let i=0;i<e.length;i+=t){o.push(e.slice(i,i+t))}return o})(s,o);let w=0;for(const r of P){const t=r.map(async t=>{const o=e.includeBleed?t.computedBleed:m,i=t.computedWidth+o.left+o.right+2*p,s=t.computedHeight+o.top+o.bottom+2*p,r=d(i),l=d(s);let c=0,g=n;for(;c<10;){c+=1;const d=await f.toDataURL(Object.assign(Object.assign({},e),{pageId:t.id,pixelRatio:g,dpiMetadata:"never"}));if(d.length>20){return g!==n&&console.error(`Polotno can not export PDF with current settings. Quality is automatically reduced. pixelRatio was reduced to ${parseFloat(g.toFixed(3))}.`),e.onProgress&&e.onProgress(++w/a.length*.9),{url:d,width:r,height:l,widthPx:i,heightPx:s,cb:o}}g*=.8}});(await Promise.all(t)).filter(e=>void 0!==e).forEach(({url:e,width:t,height:o,widthPx:n,heightPx:a,cb:s})=>{y.addPage([t,o],t>o?"landscape":"portrait");const r=y.getCurrentPageInfo();var l;switch(i){case"pt":l=1;break;case"mm":l=72/25.4;break;case"cm":l=72/2.54;break;case"in":l=72;break;case"px":l=.75;break;default:throw _("EXPORT_FAILED","Invalid unit: "+i,{reason:"invalid-options",option:"unit",value:i})}if(r.pageContext.cropBox={bottomLeftX:0,bottomLeftY:0,topRightX:t*l,topRightY:o*l},r.pageContext.artBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},r.pageContext.bleedBox={bottomLeftX:d(p+s.left)*l,bottomLeftY:d(p+s.bottom)*l,topRightX:d(n-p-s.right)*l,topRightY:d(a-p-s.top)*l},c){y.setLineWidth(d(1));const e=c+d(s.left),i=c+d(s.right),n=c+d(s.top),a=c+d(s.bottom);y.line(e,0,e,c),y.line(0,n,c,n),y.line(t-i,0,t-i,c),y.line(t,n,t-c,n),y.line(0,o-a,c,o-a),y.line(e,o,e,o-c),y.line(t,o-a,t-c,o-a),y.line(t-i,o,t-i,o-c)}y.addImage(e,c,c,t-2*c,o-2*c,void 0,"FAST")})}return y},toPDFDataURL:async e=>(await f._toPDF(Object.assign({mimeType:"image/jpeg"},e))).output("datauristring"),async toGIFDataURL(e={}){const t=e.pixelRatio||1,o=e.pageIds||(e.pageId?[e.pageId]:r.pages.map(e=>e.id)),i=r.pages.filter(e=>o.includes(e.id));if(!i.length){throw _("EXPORT_FAILED","No pages found for GIF export",{reason:"page-not-found",pageId:e.pageId,availablePageIds:r.pages.map(e=>e.id)})}const n=i[0],a=await b({width:n.computedWidth*t,height:n.computedHeight*t}),s=1e3/(e.fps||10);for(const l of i){const e=Math.max(1,Math.floor(l.duration/s));for(let o=0;o<e;o++){const e=l.startTime+o*s||1;f.setCurrentTime(e);for(const t of r.pages){t.set({_rendering:t.id===l.id})}const i=await f._toCanvas({pixelRatio:t,pageId:l.id,_skipTimeout:!0});a.addFrame(i.getContext("2d"),{delay:s,copy:!0})}}for(const l of r.pages){l.set({_rendering:!1})}return f.stop(),a.render(),new Promise(e=>{a.on("finished",function(t){!function(e,t){var o=new FileReader;o.onload=function(e){t(e.target.result)},o.readAsDataURL(e)}(t,e)})})},async saveAsGIF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);const n=await f.toGIFDataURL(i);h(n,o||"polotno.gif")},async toHTML({elementHook:e}={}){F("store.toHTML","store.toHTML()/saveAsHTML() are deprecated: install @polotno/html-export and call jsonToHTML(store.toJSON()) instead");const t=f.toJSON();return j(t,{elementHook:e,textOverflow:x.textOverflow,textSplitAllowed:x.textSplitAllowed})},async saveAsHTML({fileName:e,elementHook:t}={}){const o=await f.toHTML({elementHook:t}),i="data:text/html;base64,"+window.btoa(unescape(encodeURIComponent(o)));h(i,e||"polotno.html")},async toSVG({elementHook:e,pageId:t,fontEmbedding:o="inline"}={fontEmbedding:"inline"}){var i;F("store.toSVG","store.toSVG()/saveAsSVG() are deprecated: install @polotno/svg-export and call jsonToSVG(store.toJSON()) instead");const n=f.toJSON();t=t||(null===(i=n.pages[0])||void 0===i?void 0:i.id);const a=n.pages.find(e=>e.id===t);return R(Object.assign(Object.assign({},n),{pages:a?[a]:[]}),{elementHook:e,fontEmbedding:o})},async saveAsSVG({fileName:e,elementHook:t,pageId:o,fontEmbedding:i="inline"}={}){const n=await f.toSVG({elementHook:t,pageId:o,fontEmbedding:i}),a="data:text/svg;base64,"+window.btoa(unescape(encodeURIComponent(n)));h(a,e||"polotno.svg")},async saveAsPDF(t={}){var{fileName:o}=t,i=e(t,["fileName"]);(await f._toPDF(Object.assign({mimeType:"image/jpeg"},i))).save(o||"polotno.pdf")},async waitLoading({_skipTimeout:e=!1}={}){e||await new Promise(e=>setTimeout(e,50)),await T()},toJSON:()=>({width:r.width,height:r.height,fonts:a(r.fonts),pages:a(r.pages),audios:a(r.audios),unit:r.unit,dpi:r.dpi,custom:r.custom,schemaVersion:r.schemaVersion}),loadJSON(e,o=!1){var i,n;const s="boolean"==typeof o?o:null!==(i=null==o?void 0:o.keepHistory)&&void 0!==i&&i,l="boolean"==typeof o||null==o?void 0:o.modernizeTextBackground,d=u(e,{modernTextRenderer:x.htmlRenderEnabled||x.renderTagTextEnabled,modernizeTextBackground:l});delete d.schemaVersion;const p=r.activePage?r.pages.indexOf(r.activePage):0;let c=null===(n=d.pages[p]||d.pages[0])||void 0===n?void 0:n.id;d._activePageId=c,d._selectedPagesIds=[];const g=Object.assign({},a(r));Object.assign(g,d),g.history=s?a(r.history):{history:[],undoIdx:-1,targetPath:""},t(r,g)},clear({keepHistory:e=!1}={}){const t=r.pages.map(e=>e.id);f.deletePages(t),r.custom=null,e||r.history.clear()},addFont(e){f.removeFont(e.fontFamily),r.fonts.push(e)},removeFont(e){r.fonts.filter(t=>t.fontFamily===e).forEach(e=>i(e))},addAudio(e){const t=L.create(Object.assign({id:p(10)},e));r.audios.push(t)},removeAudio(e){const t=r.audios.find(t=>t.id===e);t&&r.audios.remove(t)},async loadFont(e,t,o,i){const n=r.fonts.find(t=>t.fontFamily===e)||w.globalFonts.find(t=>t.fontFamily===e);let a=[{fontStyle:"normal",fontWeight:"normal"},{fontStyle:"normal",fontWeight:"bold"}];return n?(n.styles&&(a=n.styles.map(e=>({fontStyle:e.fontStyle||"normal",fontWeight:e.fontWeight||"normal"}))),w.injectCustomFont(n)):w.injectGoogleFont(e),t&&o&&!a.some(e=>e.fontStyle===t&&e.fontWeight===o)&&a.push({fontStyle:t,fontWeight:o}),Promise.all(a.map(t=>w.loadFont(e,t.fontStyle,t.fontWeight,i)))},validate:e=>Store.validate(e,[{path:"",type:Store}]).map(e=>({path:"store"+e.context.map(e=>e.path).join("."),message:e.message}))};return f});export function createStore({key:e,showCredit:t}={key:"",showCredit:!1}){return P(e),Store.create({_forceShowCredit:t})}export default createStore;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "polotno",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.7.0",
|
|
4
4
|
"description": "Design Editor Framework",
|
|
5
5
|
"author": "Anton Lavrenov",
|
|
6
6
|
"keywords": [
|
|
@@ -95,31 +95,31 @@
|
|
|
95
95
|
"./polotno.blueprint.css": "./blueprint.polotno.css"
|
|
96
96
|
},
|
|
97
97
|
"dependencies": {
|
|
98
|
-
"@base-ui/react": "^1.
|
|
99
|
-
"@polotno/core": "0.
|
|
100
|
-
"@polotno/html-export": "0.
|
|
101
|
-
"@polotno/schema": "0.
|
|
102
|
-
"@polotno/svg-export": "0.
|
|
98
|
+
"@base-ui/react": "^1.7.0",
|
|
99
|
+
"@polotno/core": "0.5.0",
|
|
100
|
+
"@polotno/html-export": "0.3.0",
|
|
101
|
+
"@polotno/schema": "0.5.0",
|
|
102
|
+
"@polotno/svg-export": "0.3.0",
|
|
103
103
|
"class-variance-authority": "^0.7.1",
|
|
104
104
|
"clsx": "^2.1.1",
|
|
105
105
|
"gifuct-js": "^2.1.2",
|
|
106
106
|
"konva": "^10.3.0",
|
|
107
107
|
"lodash-es": "^4.18.1",
|
|
108
|
-
"lucide-react": "^1.
|
|
109
|
-
"mediabunny": "^1.
|
|
108
|
+
"lucide-react": "^1.29.0",
|
|
109
|
+
"mediabunny": "^1.52.3",
|
|
110
110
|
"mobx": "6.16.1",
|
|
111
111
|
"mobx-react-lite": "^4.1.1",
|
|
112
|
-
"mobx-state-tree": "7.3.
|
|
113
|
-
"nanoid": "^6.0.
|
|
112
|
+
"mobx-state-tree": "7.3.2",
|
|
113
|
+
"nanoid": "^6.0.1",
|
|
114
114
|
"quill": "^2.0.3",
|
|
115
115
|
"react-konva": "^19.2.5",
|
|
116
116
|
"react-konva-utils": "^2.0.0",
|
|
117
117
|
"react-sortablejs": "6.1.4",
|
|
118
|
-
"react-window": "^2.
|
|
119
|
-
"render-tag": "^0.1.
|
|
118
|
+
"react-window": "^2.3.0",
|
|
119
|
+
"render-tag": "^0.1.27",
|
|
120
120
|
"sortablejs": "^1.15.7",
|
|
121
121
|
"svg-round-corners": "^0.4.3",
|
|
122
|
-
"swr": "^2.
|
|
122
|
+
"swr": "^2.5.0",
|
|
123
123
|
"tailwind-merge": "^3.6.0",
|
|
124
124
|
"tinycolor2": "^1.6.0",
|
|
125
125
|
"use-image": "^1.1.4"
|
|
@@ -157,39 +157,39 @@
|
|
|
157
157
|
"@babel/core": "^8.0.1",
|
|
158
158
|
"@babel/parser": "^8.0.4",
|
|
159
159
|
"@babel/traverse": "^8.0.4",
|
|
160
|
-
"@blueprintjs/core": "6.
|
|
160
|
+
"@blueprintjs/core": "6.18.0",
|
|
161
161
|
"@blueprintjs/icons": "^6.13.0",
|
|
162
|
-
"@blueprintjs/select": "6.3.
|
|
162
|
+
"@blueprintjs/select": "6.3.4",
|
|
163
163
|
"@canvas/image": "^2.0.0",
|
|
164
|
-
"@tailwindcss/cli": "^4.3.
|
|
165
|
-
"@tailwindcss/vite": "^4.3.
|
|
164
|
+
"@tailwindcss/cli": "^4.3.3",
|
|
165
|
+
"@tailwindcss/vite": "^4.3.3",
|
|
166
166
|
"@testing-library/dom": "^10.4.1",
|
|
167
167
|
"@testing-library/react": "^16.3.2",
|
|
168
|
-
"@types/react": "^19.2.
|
|
169
|
-
"@vitejs/plugin-react": "^6.0.
|
|
168
|
+
"@types/react": "^19.2.18",
|
|
169
|
+
"@vitejs/plugin-react": "^6.0.5",
|
|
170
170
|
"@vitest/browser": "^4.1.10",
|
|
171
171
|
"@vitest/browser-playwright": "^4.1.10",
|
|
172
172
|
"assert": "^2.1.0",
|
|
173
|
-
"bippy": "^0.
|
|
173
|
+
"bippy": "^0.6.1",
|
|
174
174
|
"buffer": "^6.0.3",
|
|
175
175
|
"canvas": "^3.2.3",
|
|
176
176
|
"filehound": "^1.17.6",
|
|
177
177
|
"glob": "^13.0.6",
|
|
178
178
|
"jest-file-snapshot": "^0.7.0",
|
|
179
|
-
"jsdom": "^
|
|
179
|
+
"jsdom": "^30.0.1",
|
|
180
180
|
"license-checker": "^25.0.1",
|
|
181
|
-
"playwright": "^1.
|
|
182
|
-
"postcss": "^8.5.
|
|
181
|
+
"playwright": "^1.62.1",
|
|
182
|
+
"postcss": "^8.5.26",
|
|
183
183
|
"postcss-selector-parser": "^7.1.4",
|
|
184
184
|
"pptxgenjs": "^4.0.1",
|
|
185
185
|
"process": "^0.11.10",
|
|
186
|
-
"react": "^19.2.
|
|
187
|
-
"react-dom": "^19.2.
|
|
188
|
-
"tailwindcss": "^4.3.
|
|
189
|
-
"terser": "^5.
|
|
186
|
+
"react": "^19.2.8",
|
|
187
|
+
"react-dom": "^19.2.8",
|
|
188
|
+
"tailwindcss": "^4.3.3",
|
|
189
|
+
"terser": "^5.49.2",
|
|
190
190
|
"tw-animate-css": "^1.4.0",
|
|
191
191
|
"typescript": "~6.0.3",
|
|
192
|
-
"vite": "^8.1
|
|
192
|
+
"vite": "^8.2.1",
|
|
193
193
|
"vitest": "^4.1.10"
|
|
194
194
|
},
|
|
195
195
|
"homepage": "https://polotno.com/",
|
|
@@ -205,11 +205,11 @@
|
|
|
205
205
|
"check:parity": "node build/structural-parity.cjs",
|
|
206
206
|
"test:parity": "pnpm run check:parity && pnpm run check:agreement && pnpm run check:css",
|
|
207
207
|
"minify": "node minify.cjs",
|
|
208
|
-
"build": "pnpm run
|
|
208
|
+
"build": "pnpm run clean && pnpm run prefix-build && pnpm run tsc && pnpm run add_version && node rename-imports.js && pnpm run minify && pnpm run build:css && pnpm run check:css && pnpm run check:agreement && pnpm run build:bundle && node blueprint-scope.js && cp ./src/fonts.css ./lib/fonts.css && mkdir -p ./lib/themes && cp ./src/themes/blueprint.css ./lib/themes/blueprint.css && cp ./src/themes/carbon.css ./lib/themes/carbon.css && node build/copy-package-json.cjs && cp ./README.md ./lib && cp ./LICENSE.md ./lib && pnpm run remove-test-from-lib",
|
|
209
209
|
"remove-test-from-lib": "find ./lib -type d -name \"__tests__\" -exec rm -rf {} + && find ./lib \\( -name \"*.test.js\" -o -name \"*.test.d.ts\" \\) -type f -delete",
|
|
210
210
|
"add_version": "sed -i.bak 's/SDK_VERSION/'$npm_package_version'/' ./lib/utils/validate-key.js && rm -f ./lib/utils/validate-key.js.bak",
|
|
211
211
|
"build:bundle": "vite build && find ./lib -name '*.js.map' -type f -delete",
|
|
212
|
-
"test": "
|
|
212
|
+
"test": "node scripts/run-tests-parallel.mjs",
|
|
213
213
|
"test:unit": "vitest run --project unit",
|
|
214
214
|
"test:browser": "node scripts/run-browser-sharded.mjs",
|
|
215
215
|
"test:serial": "vitest run"
|