polotno 2.40.1 → 2.40.2
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/canvas/context-menu/context-menu.js +1 -1
- package/canvas/element.js +1 -1
- package/canvas/figure-element.js +1 -1
- package/canvas/gif-element.js +1 -1
- package/canvas/hotkeys.js +1 -1
- package/canvas/html-element.js +2 -2
- package/canvas/image-element.js +1 -1
- package/canvas/line-element.js +1 -1
- package/canvas/page-controls.js +1 -1
- package/canvas/page.js +1 -1
- package/canvas/table-element.js +1 -1
- package/canvas/text-element.js +1 -1
- package/canvas/video-element.js +1 -1
- package/model/group-model.d.ts +8 -0
- package/model/store.d.ts +4 -0
- package/model/store.js +1 -1
- package/model/table-model.d.ts +15 -0
- package/model/table-model.js +1 -1
- package/package.json +2 -2
- package/pages-timeline/elements.js +1 -1
- package/polotno.bundle.js +245 -245
- package/side-panel/layers-panel.js +1 -1
- package/toolbar/table-toolbar.js +1 -1
- package/toolbar/toolbar.js +5 -5
- package/utils/l10n.d.ts +11 -6
- package/utils/l10n.js +1 -1
- package/utils/text-html.js +1 -1
- package/utils/to-html.js +1 -1
- package/utils/to-svg.js +1 -1
- package/utils/validate-key.js +1 -1
- package/utils/xml.d.ts +1 -0
- package/utils/xml.js +7 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{observer as t}from"mobx-react-lite";import{Button as l,EditableText as n,Card as i}from"@blueprintjs/core";import{
|
|
1
|
+
import e from"react";import{observer as t}from"mobx-react-lite";import{Button as l,EditableText as n,Card as i}from"@blueprintjs/core";import{ROLES as a}from"../model/store.js";import{t as r}from"../utils/l10n.js";import{isMobile as o}from"../utils/screen.js";import{ReactSortable as s}from"react-sortablejs";import{removeTags as d}from"../utils/text.js";import{DragHandleVertical as m,Trash as c,Lock as p,Unlock as u,EyeOpen as E,EyeOff as v}from"@blueprintjs/icons";const y=t(({element:t,store:o})=>{const s=o.selectedElements.indexOf(t)>=0,[y,x]=e.useState(!1),g=()=>x(!1),h=y?t.name:t.name||d(t.text)||`#${t.id}`;return e.createElement(i,{onMouseDown:e=>{const l=e.ctrlKey||e.metaKey||e.shiftKey?[...o.selectedElementsIds]:[];l.indexOf(t.id)<0&&l.push(t.id),o.selectElements(l)},className:s?"selected":"",style:{padding:"5px",margin:"0px 1px 5px 1px",backgroundColor:s?"rgb(0, 161, 255, 0.2)":"",display:t.selectable||o.role===a.ADMIN?"auto":"none"}},e.createElement("div",{style:{display:"flex",justifyContent:"space-between"}},e.createElement("div",{style:{lineHeight:"30px",display:"flex"}},e.createElement("div",{className:"drag-handle",style:{display:"flex",justifyContent:"center",alignItems:"center",cursor:"move",height:"30px"}},e.createElement(m,null)),e.createElement("div",{style:{padding:"0 7px",opacity:.5,width:"60px"}},r("sidePanel.layerTypes."+t.type)),e.createElement("div",{style:{maxWidth:"142px"}},e.createElement(n,{minWidth:130,placeholder:r("sidePanel.namePlaceholder"),value:h,maxLines:1,onEdit:()=>x(!0),onCancel:g,onConfirm:g,onChange:e=>{t.set({name:e})}}))),e.createElement("div",null,e.createElement(l,{minimal:!0,icon:(null==t?void 0:t.visible)?e.createElement(E,null):e.createElement(v,null),onClick:()=>{t.set({visible:!t.visible})}}),e.createElement(l,{minimal:!0,icon:(null==t?void 0:t.locked)?e.createElement(p,null):e.createElement(u,null),onClick:()=>{t.set({draggable:t.locked,contentEditable:t.locked,styleEditable:t.locked,resizable:t.locked,removable:t.locked})}}),e.createElement(l,{icon:e.createElement(c,null),minimal:!0,disabled:!t.removable,onClick:()=>{o.deleteElements([t.id])},style:{marginLeft:"auto"}}))))});export const LayersPanel=t(({store:t})=>{var l;const n=(null===(l=t.activePage)||void 0===l?void 0:l.children.map(e=>({id:e.id})))||[];n.reverse();const i=o();return e.createElement("div",{style:{height:"100%",overflow:"auto"}},e.createElement("div",{style:{height:"40px",paddingTop:"5px"}},r("sidePanel.layersTip")),e.createElement("div",null,0===n.length?e.createElement("div",null,r("sidePanel.noLayers")):null,e.createElement(s,{list:n,setList:e=>{const l=e.filter(e=>Boolean(null==e?void 0:e.id));l.forEach(({id:e},n)=>{var i,a;const r=l.length-n-1,o=t.getElementById(e),s=null===(i=t.activePage)||void 0===i?void 0:i.children.indexOf(o);o&&s!==r&&(null===(a=t.activePage)||void 0===a||a.setElementZIndex(o.id,r))})},direction:"horizontal",handle:i?".drag-handle":void 0},n.map(({id:l})=>{const n=t.getElementById(l);return e.createElement(y,{element:n,store:t,key:l})}))))});
|
package/toolbar/table-toolbar.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"react";import{observer as t}from"mobx-react-lite";import{Button as o,Popover as l,Position as r,Tooltip as n,Menu as i,MenuItem as a,MenuDivider as c,Slider as s}from"@blueprintjs/core";import m from"@meronex/icons/zo/ZoStrokeWidth.js";import{Disable as d}from"@blueprintjs/icons";import h from"./color-picker.js";import{NumberInput as b}from"./filters-picker.js";import{ElementContainer as E,extendToolbar as u}from"./element-container.js";import{TextFontFamily as g,TextFontSize as x,TextFill as y,TextFontVariant as p,TextSpacing as k,VERTICAL_ALIGN_OPTIONS as C,VERTICAL_ALIGN_ICONS as f}from"./text-toolbar.js";import{AnimationsPicker as w}from"./animations-picker.js";import{flags as v}from"../utils/flags.js";import{t as T}from"../utils/l10n.js";const B=()=>e.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},e.createElement("rect",{x:"1.5",y:"1.5",width:"13",height:"13",stroke:"currentColor",strokeWidth:"2",fill:"none"})),S=()=>e.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},e.createElement("rect",{x:"1.5",y:"1.5",width:"13",height:"13",stroke:"currentColor",strokeWidth:"1",strokeOpacity:"0.3",fill:"none"}),e.createElement("line",{x1:"1",y1:"1.5",x2:"15",y2:"1.5",stroke:"currentColor",strokeWidth:"2"})),O=()=>e.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},e.createElement("rect",{x:"1.5",y:"1.5",width:"13",height:"13",stroke:"currentColor",strokeWidth:"1",strokeOpacity:"0.3",fill:"none"}),e.createElement("line",{x1:"1",y1:"14.5",x2:"15",y2:"14.5",stroke:"currentColor",strokeWidth:"2"})),W=()=>e.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},e.createElement("rect",{x:"1.5",y:"1.5",width:"13",height:"13",stroke:"currentColor",strokeWidth:"1",strokeOpacity:"0.3",fill:"none"}),e.createElement("line",{x1:"1.5",y1:"1",x2:"1.5",y2:"15",stroke:"currentColor",strokeWidth:"2"})),j=()=>e.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},e.createElement("rect",{x:"1.5",y:"1.5",width:"13",height:"13",stroke:"currentColor",strokeWidth:"1",strokeOpacity:"0.3",fill:"none"}),e.createElement("line",{x1:"14.5",y1:"1",x2:"14.5",y2:"15",stroke:"currentColor",strokeWidth:"2"})),R=()=>e.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},e.createElement("rect",{x:"1.5",y:"1.5",width:"13",height:"13",stroke:"currentColor",strokeWidth:"1",strokeOpacity:"0.3",fill:"none"}),e.createElement("line",{x1:"4",y1:"4",x2:"12",y2:"12",stroke:"currentColor",strokeWidth:"1.5"}),e.createElement("line",{x1:"12",y1:"4",x2:"4",y2:"12",stroke:"currentColor",strokeWidth:"1.5"})),A=["top","right","bottom","left"];export const TableBorderSettings=t(({elements:t,store:i})=>{const a=t[0],c="tablecell"===a.type,[E,u]=e.useState(new Set(A)),g=c?i.selectedElements[0]:a,x=[...E][0]||"top";let y;y=c?a:"bottom"===x?g.getCell(g.rows-1,0):"right"===x?g.getCell(0,g.cols-1):g.getCell(0,0);const p=(null==y?void 0:y.getEffectiveBorder)?y.getEffectiveBorder(x):{color:g.borderColor,width:g.borderWidth,style:g.borderStyle},k=p.color,C=p.width,f=p.style,w=e=>{i.history.transaction(()=>{const o={};if("borderColor"in e&&(o.color=e.borderColor),"borderWidth"in e&&(o.width=e.borderWidth),"borderStyle"in e&&(o.style=e.borderStyle),c){const e=t.map(e=>e.id);g.setCellBorders(e,[...E],o)}else{for(const{cellIds:e,sides:t}of(()=>{const e=[...E];if(4===e.length){return[{cellIds:g.cells.map(e=>e.id),sides:e}]}const t=[];for(const o of e){let e;e="top"===o?g.cells.filter(e=>0===e.row):"bottom"===o?g.cells.filter(e=>e.row===g.rows-1):"left"===o?g.cells.filter(e=>0===e.col):g.cells.filter(e=>e.col===g.cols-1),t.push({cellIds:e.map(e=>e.id),sides:[o]})}return t})()){g.setCellBorders(e,t,o)}4===E.size&&t.forEach(t=>t.set(e))}})};return e.createElement(l,{position:r.BOTTOM,content:e.createElement("div",{style:{padding:"15px",width:"270px"}},e.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"15px"}},e.createElement(n,{content:T("toolbar.borderAllSides"),position:r.TOP},e.createElement(o,{small:!0,active:4===E.size,onClick:()=>u(new Set(A)),icon:e.createElement(B,null)})),e.createElement(n,{content:T("toolbar.borderTop"),position:r.TOP},e.createElement(o,{small:!0,active:E.has("top")&&1===E.size,onClick:()=>u(new Set(["top"])),icon:e.createElement(S,null)})),e.createElement(n,{content:T("toolbar.borderBottom"),position:r.TOP},e.createElement(o,{small:!0,active:E.has("bottom")&&1===E.size,onClick:()=>u(new Set(["bottom"])),icon:e.createElement(O,null)})),e.createElement(n,{content:T("toolbar.borderLeft"),position:r.TOP},e.createElement(o,{small:!0,active:E.has("left")&&1===E.size,onClick:()=>u(new Set(["left"])),icon:e.createElement(W,null)})),e.createElement(n,{content:T("toolbar.borderRight"),position:r.TOP},e.createElement(o,{small:!0,active:E.has("right")&&1===E.size,onClick:()=>u(new Set(["right"])),icon:e.createElement(j,null)})),e.createElement(n,{content:T("toolbar.borderNone"),position:r.TOP},e.createElement(o,{small:!0,onClick:()=>{w({borderStyle:"none"}),u(new Set(A))},icon:e.createElement(R,null)}))),e.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"15px"}},e.createElement(o,{onClick:()=>w({borderStyle:"none"}),active:"none"===f,style:{width:"44px",height:"34px"},icon:e.createElement(d,{size:20})}),e.createElement(o,{onClick:()=>w({borderStyle:"solid"}),active:"solid"===f},e.createElement("svg",{width:"24",height:"24",viewBox:"0 0 24 24"},e.createElement("line",{x2:"24",y1:"50%",y2:"50%",stroke:"currentColor",strokeWidth:"2"}))),e.createElement(o,{onClick:()=>w({borderStyle:"dashed"}),active:"dashed"===f},e.createElement("svg",{width:"24",height:"24",viewBox:"0 0 24 24"},e.createElement("line",{x1:"-1",x2:"25",y1:"50%",y2:"50%",stroke:"currentColor",strokeDasharray:"12 2",strokeWidth:"2"}))),e.createElement(o,{onClick:()=>w({borderStyle:"dotted"}),active:"dotted"===f},e.createElement("svg",{width:"24",height:"24",viewBox:"0 0 24 24"},e.createElement("line",{x1:"1",x2:"23",y1:"50%",y2:"50%",stroke:"currentColor",strokeDasharray:"2 2",strokeWidth:"2"})))),e.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"10px"}},e.createElement("div",{className:"bp5-control bp5-align-right"},T("toolbar.tableBorderColor")),e.createElement(h,{value:k,onChange:e=>w({borderColor:e}),store:i})),e.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:"5px"}},e.createElement("div",{className:"bp5-control bp5-align-right"},T("toolbar.tableBorderWidth")),e.createElement(b,{value:C,onValueChange:e=>w({borderWidth:e}),style:{width:"50px"},min:0,max:20,buttonPosition:"none"})),e.createElement(s,{value:C,onChange:e=>w({borderWidth:e}),min:0,max:20,labelRenderer:!1}))},e.createElement(n,{content:T("toolbar.tableBorderSettings"),position:r.BOTTOM},e.createElement(o,{minimal:!0,icon:e.createElement(m,null),"aria-label":T("toolbar.tableBorderSettings")})))});const P=()=>e.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},e.createElement("rect",{x:"1",y:"1",width:"14",height:"14",rx:"1",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),e.createElement("line",{x1:"5.5",y1:"1",x2:"5.5",y2:"15",stroke:"currentColor",strokeWidth:"1"}),e.createElement("line",{x1:"10.5",y1:"1",x2:"10.5",y2:"15",stroke:"currentColor",strokeWidth:"1"}),e.createElement("line",{x1:"1",y1:"5.5",x2:"15",y2:"5.5",stroke:"currentColor",strokeWidth:"1"}),e.createElement("line",{x1:"1",y1:"10.5",x2:"15",y2:"10.5",stroke:"currentColor",strokeWidth:"1"}));export const TableStructureMenu=t(({element:t,store:o})=>{const l=t.focusedCells[0],r=null==l?void 0:l.row,n=null==l?void 0:l.col,s=null!=l;return e.createElement(i,null,s&&e.createElement(e.Fragment,null,e.createElement(c,{title:T("toolbar.tableRows")}),e.createElement(a,{text:T("toolbar.insertRowAbove"),onClick:()=>{o.history.transaction(()=>{t.addRow(r)})}}),e.createElement(a,{text:T("toolbar.insertRowBelow"),onClick:()=>{o.history.transaction(()=>{t.addRow(r+1)})}}),e.createElement(a,{text:T("toolbar.deleteRow"),disabled:t.rows<=1,onClick:()=>{o.history.transaction(()=>{t.removeRow(r)})}}),e.createElement(c,{title:T("toolbar.tableColumns")}),e.createElement(a,{text:T("toolbar.insertColumnLeft"),onClick:()=>{o.history.transaction(()=>{t.addColumn(n)})}}),e.createElement(a,{text:T("toolbar.insertColumnRight"),onClick:()=>{o.history.transaction(()=>{t.addColumn(n+1)})}}),e.createElement(a,{text:T("toolbar.deleteColumn"),disabled:t.cols<=1,onClick:()=>{o.history.transaction(()=>{t.removeColumn(n)})}}),e.createElement(c,null)),e.createElement(a,{text:T("toolbar.distributeRowsEvenly"),onClick:()=>{o.history.transaction(()=>{t.distributeRowsEvenly()})}}),e.createElement(a,{text:T("toolbar.distributeColumnsEvenly"),onClick:()=>{o.history.transaction(()=>{t.distributeColumnsEvenly()})}}))});export const TableStructure=t(({elements:t,store:i})=>{const a=t[0];return e.createElement(l,{position:r.BOTTOM,content:e.createElement(TableStructureMenu,{element:a,store:i})},e.createElement(n,{content:T("toolbar.tableStructure"),position:r.BOTTOM},e.createElement(o,{minimal:!0,icon:e.createElement(P,null),"aria-label":T("toolbar.tableStructure")})))});export const CellPadding=t(({elements:t,store:o})=>e.createElement(n,{content:T("toolbar.cellPadding"),position:r.BOTTOM},e.createElement(b,{value:t[0].cellPadding,onValueChange:e=>o.history.transaction(()=>{t.forEach(t=>t.set({cellPadding:e}))}),style:{width:"50px"},min:0,max:50,buttonPosition:"none"})));export const CellBackground=t(({elements:t,store:o})=>e.createElement(n,{content:T("toolbar.cellBackground"),position:r.BOTTOM},e.createElement(h,{value:t[0].cellBackground,style:{marginRight:"5px"},onChange:e=>o.history.transaction(()=>{t.forEach(t=>t.set({cellBackground:e}))}),store:o})));export const CellVerticalAlign=t(({elements:t,store:l})=>{const i=t[0];return e.createElement(n,{content:T("toolbar.verticalAlign"),position:r.BOTTOM},e.createElement(o,{minimal:!0,icon:f[i.verticalAlign],onClick:()=>{const e=(C.indexOf(i.verticalAlign)+1+C.length)%C.length,o=C[e];l.history.transaction(()=>{t.forEach(e=>e.set({verticalAlign:o}))})},"aria-label":T("toolbar.verticalAlign")}))});const F={TableStructure,TableAnimations:w},z={TableBorderSettings,TextFontFamily:g,TextFontSize:x,TextFill:y,CellBackground,TextFontVariant:p,CellVerticalAlign,TextSpacing:k},M=Object.assign(Object.assign({},F),z);export const TableToolbar=t(({store:t,components:o})=>{const l=t.selectedElements[0],r=l.focusedCells,n=r.length>0,i=["TableBorderSettings","CellBackground","TableStructure",...n?["TextFontFamily","TextFontSize","TextFill","TextFontVariant","CellVerticalAlign","TextSpacing"]:[],v.animationsEnabled&&"TableAnimations"],a=u({type:"table",usedItems:i,components:o});return e.createElement(E,{items:a,itemRender:i=>{const a=o[i]||M[i],c=!!z[i];if(c&&!n&&"TableBorderSettings"!==i&&"CellBackground"!==i){return null}let s;return s=c?n?r:"TableBorderSettings"===i?t.selectedElements:l.cells.slice():t.selectedElements,e.createElement(a,{element:l,store:t,key:i,elements:s})}})});export default TableToolbar;
|
|
1
|
+
import e from"react";import{observer as t}from"mobx-react-lite";import{Button as l,Popover as n,Position as o,Tooltip as r,Menu as i,MenuItem as a,MenuDivider as c,Slider as s}from"@blueprintjs/core";import m from"@meronex/icons/zo/ZoStrokeWidth.js";import{Disable as d}from"@blueprintjs/icons";import y from"./color-picker.js";import{NumberInput as b}from"./filters-picker.js";import{ElementContainer as u,extendToolbar as x}from"./element-container.js";import{TextFontFamily as g,TextFontSize as E,TextFill as h,TextFontVariant as p,TextSpacing as C,VERTICAL_ALIGN_OPTIONS as k,VERTICAL_ALIGN_ICONS as f}from"./text-toolbar.js";import{AnimationsPicker as v}from"./animations-picker.js";import{flags as O}from"../utils/flags.js";import{t as w}from"../utils/l10n.js";const T={stroke:"currentColor",strokeWidth:1,strokeOpacity:.25},B={stroke:"currentColor",strokeWidth:2},j=()=>e.createElement(e.Fragment,null,e.createElement("rect",Object.assign({x:"2",y:"2",width:"16",height:"16",fill:"none"},T)),e.createElement("line",Object.assign({x1:"10",y1:"2",x2:"10",y2:"18"},T)),e.createElement("line",Object.assign({x1:"2",y1:"10",x2:"18",y2:"10"},T))),S=({children:t})=>e.createElement("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none"},e.createElement(j,null),t),M=[{key:"all",labelKey:"toolbar.borderModeAll",icon:()=>e.createElement("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none"},e.createElement("rect",Object.assign({x:"2",y:"2",width:"16",height:"16",fill:"none"},B)),e.createElement("line",Object.assign({x1:"10",y1:"2",x2:"10",y2:"18"},B)),e.createElement("line",Object.assign({x1:"2",y1:"10",x2:"18",y2:"10"},B)))},{key:"outer",labelKey:"toolbar.borderModeOuter",icon:()=>e.createElement(S,null,e.createElement("rect",Object.assign({x:"2",y:"2",width:"16",height:"16",fill:"none"},B)))},{key:"inner",labelKey:"toolbar.borderModeInner",icon:()=>e.createElement(S,null,e.createElement("line",Object.assign({x1:"10",y1:"2",x2:"10",y2:"18"},B)),e.createElement("line",Object.assign({x1:"2",y1:"10",x2:"18",y2:"10"},B)))},{key:"topOnly",labelKey:"toolbar.borderModeTopOnly",icon:()=>e.createElement(S,null,e.createElement("line",Object.assign({x1:"2",y1:"2",x2:"18",y2:"2"},B)))},{key:"innerHorizontal",labelKey:"toolbar.borderModeInnerHorizontal",icon:()=>e.createElement(S,null,e.createElement("line",Object.assign({x1:"2",y1:"10",x2:"18",y2:"10"},B)))},{key:"bottomOnly",labelKey:"toolbar.borderModeBottomOnly",icon:()=>e.createElement(S,null,e.createElement("line",Object.assign({x1:"2",y1:"18",x2:"18",y2:"18"},B)))},{key:"leftOnly",labelKey:"toolbar.borderModeLeftOnly",icon:()=>e.createElement(S,null,e.createElement("line",Object.assign({x1:"2",y1:"2",x2:"2",y2:"18"},B)))},{key:"innerVertical",labelKey:"toolbar.borderModeInnerVertical",icon:()=>e.createElement(S,null,e.createElement("line",Object.assign({x1:"10",y1:"2",x2:"10",y2:"18"},B)))},{key:"rightOnly",labelKey:"toolbar.borderModeRightOnly",icon:()=>e.createElement(S,null,e.createElement("line",Object.assign({x1:"18",y1:"2",x2:"18",y2:"18"},B)))}];export const TableBorderSettings=t(({elements:t,store:i})=>{const a=t[0],c="tablecell"===a.type,u=c?i.selectedElements[0]:a,[x,g]=e.useState("all");let E,h;if(c){const e=u.getFocusedCellRange();E=e?e.maxRow-e.minRow+1:1,h=e?e.maxCol-e.minCol+1:1}else{E=u.rows,h=u.cols}const p=E>1,C=h>1,k=e=>"innerHorizontal"===e?!p:("innerVertical"===e||"inner"===e&&!p)&&!C;e.useEffect(()=>{k(x)&&g("all")},[x,p,C]);const f={all:"top",outer:"top",topOnly:"top",topBottom:"top",bottomOnly:"bottom",innerHorizontal:"bottom",inner:"bottom",leftOnly:"left",rightOnly:"right",innerVertical:"right"}[x],v=c?a:"bottomOnly"===x?u.getCell(u.rows-1,0):"rightOnly"===x?u.getCell(0,u.cols-1):u.getCell(0,0),O=(null==v?void 0:v.getEffectiveBorder)?v.getEffectiveBorder(f):{color:u.borderColor,width:u.borderWidth,style:u.borderStyle},T=O.color,B=O.width,j=O.style,S=(e,l={})=>{var n,o;const r=B<=0||"none"===j,a=null!==(n=l.style)&&void 0!==n?n:r?"solid":j,s=void 0!==l.width?l.width:r?1:B,m={color:null!==(o=l.color)&&void 0!==o?o:T,width:s,style:a};i.history.transaction(()=>{u.applyBorderMode(e,m),"all"!==e||c||t.forEach(e=>e.set({borderColor:m.color,borderWidth:m.width,borderStyle:m.style}))})},R=e=>{S(x,{style:e})},A=e=>{S(x,{width:e})};return e.createElement(n,{position:o.BOTTOM,content:e.createElement("div",{style:{padding:"12px",display:"flex",gap:"12px"}},e.createElement("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, 32px)",gridAutoRows:"32px",gap:"4px"}},M.map(({key:t,labelKey:n,icon:i})=>{const a=k(t);return e.createElement(r,{key:t,content:w(n),position:o.TOP},e.createElement(l,{small:!0,disabled:a,active:!a&&x===t,onClick:()=>{g(t)},icon:e.createElement(i,null),"aria-label":w(n),style:{width:"32px",height:"32px",padding:0}}))})),e.createElement("div",{style:{width:"1px",background:"rgba(17,20,24,0.15)"}}),e.createElement("div",{style:{display:"flex",flexDirection:"column",gap:"8px",width:"170px"}},e.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},e.createElement("span",{style:{fontSize:"12px"}},w("toolbar.tableBorderColor")),e.createElement(y,{value:T,onChange:e=>{S(x,{color:e})},store:i})),e.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"}},e.createElement("span",{style:{fontSize:"12px"}},w("toolbar.tableBorderWidth")),e.createElement(b,{value:B,onValueChange:A,style:{width:"50px"},min:0,max:20,buttonPosition:"none"})),e.createElement(s,{value:B,onChange:A,min:0,max:20,labelRenderer:!1}),e.createElement("div",{style:{display:"flex",justifyContent:"space-between",gap:"4px"}},e.createElement(l,{small:!0,onClick:()=>R("none"),active:"none"===j,icon:e.createElement(d,{size:16}),style:{flex:1}}),e.createElement(l,{small:!0,onClick:()=>R("solid"),active:"solid"===j,style:{flex:1}},e.createElement("svg",{width:"20",height:"14",viewBox:"0 0 20 14"},e.createElement("line",{x2:"20",y1:"7",y2:"7",stroke:"currentColor",strokeWidth:"2"}))),e.createElement(l,{small:!0,onClick:()=>R("dashed"),active:"dashed"===j,style:{flex:1}},e.createElement("svg",{width:"20",height:"14",viewBox:"0 0 20 14"},e.createElement("line",{x2:"20",y1:"7",y2:"7",stroke:"currentColor",strokeDasharray:"4 2",strokeWidth:"2"}))),e.createElement(l,{small:!0,onClick:()=>R("dotted"),active:"dotted"===j,style:{flex:1}},e.createElement("svg",{width:"20",height:"14",viewBox:"0 0 20 14"},e.createElement("line",{x2:"20",y1:"7",y2:"7",stroke:"currentColor",strokeDasharray:"2 2",strokeWidth:"2"}))))))},e.createElement(r,{content:w("toolbar.tableBorderSettings"),position:o.BOTTOM},e.createElement(l,{minimal:!0,icon:e.createElement(m,null),"aria-label":w("toolbar.tableBorderSettings")})))});const R=()=>e.createElement("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none"},e.createElement("rect",{x:"1",y:"1",width:"14",height:"14",rx:"1",stroke:"currentColor",strokeWidth:"1.5",fill:"none"}),e.createElement("line",{x1:"5.5",y1:"1",x2:"5.5",y2:"15",stroke:"currentColor",strokeWidth:"1"}),e.createElement("line",{x1:"10.5",y1:"1",x2:"10.5",y2:"15",stroke:"currentColor",strokeWidth:"1"}),e.createElement("line",{x1:"1",y1:"5.5",x2:"15",y2:"5.5",stroke:"currentColor",strokeWidth:"1"}),e.createElement("line",{x1:"1",y1:"10.5",x2:"15",y2:"10.5",stroke:"currentColor",strokeWidth:"1"}));export const TableStructureMenu=t(({element:t,store:l})=>{const n=t.focusedCells[0],o=null==n?void 0:n.row,r=null==n?void 0:n.col,s=null!=n;return e.createElement(i,null,s&&e.createElement(e.Fragment,null,e.createElement(c,{title:w("toolbar.tableRows")}),e.createElement(a,{text:w("toolbar.insertRowAbove"),onClick:()=>{l.history.transaction(()=>{t.addRow(o)})}}),e.createElement(a,{text:w("toolbar.insertRowBelow"),onClick:()=>{l.history.transaction(()=>{t.addRow(o+1)})}}),e.createElement(a,{text:w("toolbar.deleteRow"),disabled:t.rows<=1,onClick:()=>{l.history.transaction(()=>{t.removeRow(o)})}}),e.createElement(c,{title:w("toolbar.tableColumns")}),e.createElement(a,{text:w("toolbar.insertColumnLeft"),onClick:()=>{l.history.transaction(()=>{t.addColumn(r)})}}),e.createElement(a,{text:w("toolbar.insertColumnRight"),onClick:()=>{l.history.transaction(()=>{t.addColumn(r+1)})}}),e.createElement(a,{text:w("toolbar.deleteColumn"),disabled:t.cols<=1,onClick:()=>{l.history.transaction(()=>{t.removeColumn(r)})}}),e.createElement(c,null)),e.createElement(a,{text:w("toolbar.distributeRowsEvenly"),onClick:()=>{l.history.transaction(()=>{t.distributeRowsEvenly()})}}),e.createElement(a,{text:w("toolbar.distributeColumnsEvenly"),onClick:()=>{l.history.transaction(()=>{t.distributeColumnsEvenly()})}}))});export const TableStructure=t(({elements:t,store:i})=>{const a=t[0];return e.createElement(n,{position:o.BOTTOM,content:e.createElement(TableStructureMenu,{element:a,store:i})},e.createElement(r,{content:w("toolbar.tableStructure"),position:o.BOTTOM},e.createElement(l,{minimal:!0,icon:e.createElement(R,null),"aria-label":w("toolbar.tableStructure")})))});export const CellPadding=t(({elements:t,store:l})=>e.createElement(r,{content:w("toolbar.cellPadding"),position:o.BOTTOM},e.createElement(b,{value:t[0].cellPadding,onValueChange:e=>l.history.transaction(()=>{t.forEach(t=>t.set({cellPadding:e}))}),style:{width:"50px"},min:0,max:50,buttonPosition:"none"})));export const CellBackground=t(({elements:t,store:l})=>e.createElement(r,{content:w("toolbar.cellBackground"),position:o.BOTTOM},e.createElement(y,{value:t[0].cellBackground,style:{marginRight:"5px"},onChange:e=>l.history.transaction(()=>{t.forEach(t=>t.set({cellBackground:e}))}),store:l})));export const CellVerticalAlign=t(({elements:t,store:n})=>{const i=t[0];return e.createElement(r,{content:w("toolbar.verticalAlign"),position:o.BOTTOM},e.createElement(l,{minimal:!0,icon:f[i.verticalAlign],onClick:()=>{const e=(k.indexOf(i.verticalAlign)+1+k.length)%k.length,l=k[e];n.history.transaction(()=>{t.forEach(e=>e.set({verticalAlign:l}))})},"aria-label":w("toolbar.verticalAlign")}))});const A={TableStructure,TableAnimations:v},W={TableBorderSettings,TextFontFamily:g,TextFontSize:E,TextFill:h,CellBackground,TextFontVariant:p,CellVerticalAlign,TextSpacing:C},F=Object.assign(Object.assign({},A),W);export const TableToolbar=t(({store:t,components:l})=>{const n=t.selectedElements[0],o=n.focusedCells,r=o.length>0,i=["TableBorderSettings","CellBackground","TableStructure",...r?["TextFontFamily","TextFontSize","TextFill","TextFontVariant","CellVerticalAlign","TextSpacing"]:[],O.animationsEnabled&&"TableAnimations"],a=x({type:"table",usedItems:i,components:l});return e.createElement(u,{items:a,itemRender:i=>{const a=l[i]||F[i],c=!!W[i];if(c&&!r&&"TableBorderSettings"!==i&&"CellBackground"!==i){return null}let s;return s=c?r?o:"TableBorderSettings"===i?t.selectedElements:n.cells.slice():t.selectedElements,e.createElement(a,{element:n,store:t,key:i,elements:s})}})});export default TableToolbar;
|
package/toolbar/toolbar.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import e from"react";import{observer as t}from"mobx-react-lite";import{Navbar as o,Alignment as r,Divider as n}from"@blueprintjs/core";import s from"../utils/styled.js";import{mobileStyle as
|
|
1
|
+
import e from"react";import{observer as t}from"mobx-react-lite";import{Navbar as o,Alignment as r,Divider as n}from"@blueprintjs/core";import{ROLES as s}from"../model/store.js";import l from"../utils/styled.js";import{mobileStyle as i}from"../utils/screen.js";import{HistoryButtons as m}from"./history-buttons.js";import{TextToolbar as a}from"./text-toolbar.js";import{HtmlToolbar as c}from"./html-toolbar.js";import{ImageToolbar as d}from"./image-toolbar.js";import{SvgToolbar as p}from"./svg-toolbar.js";import{LineToolbar as u}from"./line-toolbar.js";import{VideoToolbar as b}from"./video-toolbar.js";import{FigureToolbar as f}from"./figure-toolbar.js";import{GifToolbar as v}from"./gif-toolbar.js";import{ManyToolbar as j}from"./many-toolbar.js";import{TableToolbar as E}from"./table-toolbar.js";import{PageToolbar as g}from"./page-toolbar.js";import{DownloadButton as y}from"./download-button.js";import{DuplicateButton as h}from"./duplicate-button.js";import{RemoveButton as w}from"./remove-button.js";import{LockButton as x}from"./lock-button.js";import{PositionPicker as R}from"./position-picker.js";import{OpacityPicker as k}from"./opacity-picker.js";import{AdminButton as C}from"./admin-button.js";import{GroupButton as O}from"./group-button.js";import{flags as T}from"../utils/flags.js";import{CopyStyleButton as A}from"./copy-style.js";const z={text:a,image:d,svg:p,many:j,line:u,video:b,figure:f,gif:v,table:E,page:g};export function registerToolbarComponent(e,t){z[e]=t}export function useToolbarCondensed(t=480){const o=e.useRef(null),[r,n]=e.useState(!1),s=e.useCallback(()=>{const e=o.current;e&&n(e.clientWidth<t)},[t]);return e.useEffect(()=>{const e=o.current;if(!e){return}const t=new ResizeObserver(()=>s());t.observe(e);const r=new MutationObserver(()=>s());return r.observe(e,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("resize",s),requestAnimationFrame(s),()=>{t.disconnect(),r.disconnect(),window.removeEventListener("resize",s)}},[s]),{containerRef:o,condensed:r}}const L=l("div",e.forwardRef)`
|
|
2
2
|
white-space: nowrap;
|
|
3
3
|
|
|
4
4
|
/* Add special style for a button with text inside, to make sure it has good with */
|
|
@@ -16,9 +16,9 @@ import e from"react";import{observer as t}from"mobx-react-lite";import{Navbar as
|
|
|
16
16
|
display: none;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
${
|
|
20
|
-
`,
|
|
19
|
+
${i("\n max-width: 100vw;\n overflow-x: auto;\n overflow-y: hidden;\n ")}
|
|
20
|
+
`,G=l("div")`
|
|
21
21
|
width: 100%;
|
|
22
22
|
height: 100%;
|
|
23
|
-
${
|
|
24
|
-
`;export const Toolbar=t(({store:t,downloadButtonEnabled:
|
|
23
|
+
${i("\n display: flex;\n ")}
|
|
24
|
+
`;export const Toolbar=t(({store:t,downloadButtonEnabled:l,components:i={}})=>{const d=1===new Set(t.selectedElements.map(e=>e.type)).size,p=1===t.selectedElements.length,u=t.selectedElements[0],b=t.selectedElements.every(e=>e.styleEditable);let f=b&&p&&z[u.type];d?f=z[u.type]:t.selectedElements.length>1&&(f=z.many),0===t.selectedElements.length&&1===t._selectedPagesIds.length&&(f=z.page),p&&"text"===u.type&&T.htmlRenderEnabled&&z.text===a&&(f=c);const v=p&&u._cropModeEnabled,j=e.useRef(i);(Object.keys(i).some(e=>i[e]!==j.current[e])||Object.keys(j.current).some(e=>!(e in i)))&&(j.current=Object.assign({},i));const E=j.current,{containerRef:g,condensed:I}=useToolbarCondensed(480),M=(null==E?void 0:E.ActionControls)||(l?y:null),S=(null==E?void 0:E.Position)||R,D=(null==E?void 0:E.Opacity)||k,F=(null==E?void 0:E.Lock)||x,H=(null==E?void 0:E.Duplicate)||h,N=(null==E?void 0:E.Remove)||w,P=(null==E?void 0:E.Group)||O,$=(null==E?void 0:E.History)||m,_=(null==E?void 0:E.Admin)||C,q=(null==E?void 0:E.CopyStyle)||A;return e.createElement(L,{ref:g,className:"bp5-navbar polotno-toolbar"+(I?" condensed":"")},e.createElement(G,null,!v&&e.createElement($,{store:t}),f&&b&&e.createElement(f,{store:t,components:E}),!v&&e.createElement(o.Group,{align:r.RIGHT},t.role===s.ADMIN&&e.createElement(_,{store:t}),e.createElement(P,{store:t}),e.createElement(S,{store:t}),b&&e.createElement(D,{store:t}),e.createElement(F,{store:t}),e.createElement(H,{store:t}),e.createElement(N,{store:t}),e.createElement(q,{store:t}),M&&e.createElement(e.Fragment,null,e.createElement(n,{style:{height:"100%",margin:"0 15px"}}),e.createElement(M,{store:t})))))});export default Toolbar;
|
package/utils/l10n.d.ts
CHANGED
|
@@ -116,12 +116,15 @@ export declare const getTranslations: () => {
|
|
|
116
116
|
tableBorderColor: string;
|
|
117
117
|
tableBorderWidth: string;
|
|
118
118
|
tableBorderStyle: string;
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
119
|
+
borderModeAll: string;
|
|
120
|
+
borderModeOuter: string;
|
|
121
|
+
borderModeInner: string;
|
|
122
|
+
borderModeBottomOnly: string;
|
|
123
|
+
borderModeTopOnly: string;
|
|
124
|
+
borderModeLeftOnly: string;
|
|
125
|
+
borderModeRightOnly: string;
|
|
126
|
+
borderModeInnerHorizontal: string;
|
|
127
|
+
borderModeInnerVertical: string;
|
|
125
128
|
tableStructure: string;
|
|
126
129
|
tableRows: string;
|
|
127
130
|
tableColumns: string;
|
|
@@ -131,6 +134,8 @@ export declare const getTranslations: () => {
|
|
|
131
134
|
insertColumnLeft: string;
|
|
132
135
|
insertColumnRight: string;
|
|
133
136
|
deleteColumn: string;
|
|
137
|
+
deleteRows: string;
|
|
138
|
+
deleteColumns: string;
|
|
134
139
|
distributeRowsEvenly: string;
|
|
135
140
|
distributeColumnsEvenly: string;
|
|
136
141
|
cellPadding: string;
|
package/utils/l10n.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{observable as e,action as o,toJS as
|
|
1
|
+
import{observable as e,action as o,toJS as r}from"mobx";const a=e({toolbar:{duration:"Duration",opacity:"Opacity",effects:"Effects",blur:"Blur",curvedText:"Curved text",curvePower:"Power",temperature:"Temperature",saturation:"Saturation",contrast:"Contrast",shadows:"Shadows",white:"White",black:"Black",vibrance:"Vibrance",textBackground:"Background",backgroundCornerRadius:"Corner radius",backgroundOpacity:"Opacity",backgroundPadding:"Padding",brightness:"Brightness",filters:"Filters",sepia:"Sepia",grayscale:"Grayscale",cold:"Cold",natural:"Natural",warm:"Warm",textStroke:"Text Stroke",shadow:"Shadow",border:"Border",cornerRadius:"Corner Radius",copyStyle:"Copy style",uppercase:"Uppercase",position:"Position",layering:"Layering",toForward:"To Front",up:"Forward",down:"Backward",toBottom:"To back",alignLeft:"Align left",alignCenter:"Align center",alignRight:"Align right",alignTop:"Align top",alignMiddle:"Align middle",alignBottom:"Align bottom",flip:"Flip",flipHorizontally:"Flip horizontally",flipVertically:"Flip vertically",fitToBackground:"Fit to page",removeBackground:"Remove background",removeBackgroundTitle:"Remove background from image",cancelRemoveBackground:"Cancel",confirmRemoveBackground:"Confirm",crop:"Crop",cropDone:"Done",cropCancel:"Cancel",clip:"Apply mask",removeClip:"Remove mask",removeMask:"Remove mask",transparency:"Transparency",lockedDescription:"Object is locked. Unlock it to allow changes from canvas.",unlockedDescription:"Object is unlocked. Lock it to prevent changes from canvas.",removeElements:"Remove elements",duplicateElements:"Duplicate elements",download:"Download",saveAsImage:"Save as image",saveAsPDF:"Save as PDF",lineHeight:"Line height",letterSpacing:"Letter spacing",offsetX:"Offset X",offsetY:"Offset Y",color:"Color",selectable:"Selectable",draggable:"Draggable",removable:"Removable",resizable:"Resizable",contentEditable:"Can change content",styleEditable:"Can change style",alwaysOnTop:"Always on top",showInExport:"Show in export",ungroupElements:"Ungroup",groupElements:"Group",lineSize:"Line size",fade:"Fade",move:"Move",zoom:"Zoom",animate:"Animate",rotate:"Rotate",none:"None",bounce:"Bounce",blink:"Blink",strength:"Strength",spaceEvenly:"Space evenly",horizontalDistribution:"Horizontally",verticalDistribution:"Vertically",strokeWidth:"Stroke Width",strokeSettings:"Stroke settings",spacing:"Spacing",volume:"Volume",lineStyle:"Line style",lineStartHead:"Line start",lineEndHead:"Line end",textDirection:"Text direction",fontSize:"Font size",fontFamily:"Font family",textAlign:"Text align",verticalAlign:"Vertical align",bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",cellBackground:"Cell background",tableBorderSettings:"Border settings",tableBorderColor:"Border color",tableBorderWidth:"Border width",tableBorderStyle:"Border style",borderModeAll:"All borders",borderModeOuter:"Outer borders",borderModeInner:"Inner borders",borderModeBottomOnly:"Bottom only",borderModeTopOnly:"Top only",borderModeLeftOnly:"Left only",borderModeRightOnly:"Right only",borderModeInnerHorizontal:"Inner horizontal",borderModeInnerVertical:"Inner vertical",tableStructure:"Table structure",tableRows:"Rows",tableColumns:"Columns",insertRowAbove:"Insert row above",insertRowBelow:"Insert row below",deleteRow:"Delete row",insertColumnLeft:"Insert column left",insertColumnRight:"Insert column right",deleteColumn:"Delete column",deleteRows:"Delete rows",deleteColumns:"Delete columns",distributeRowsEvenly:"Distribute rows evenly",distributeColumnsEvenly:"Distribute columns evenly",cellPadding:"Cell padding",listFormat:"List",colorPicker:{solid:"Solid",linear:"Linear",angle:"Angle"},aiText:{aiWrite:"AI write",rewrite:"Rewrite",shorten:"Shorten",continue:"Continue writing",proofread:"Proofread",tones:"Tones",friendly:"Friendly",professional:"Professional",humorous:"Humorous",formal:"Formal",customPrompt:"Custom prompt",generatedResult:"Generated result",cancel:"Cancel",generate:"Generate",back:"Back",tryAgain:"Try Again",insert:"Insert",promptPlaceholder:"Describe what you want to generate"}},workspace:{noPages:"There are no pages yet...",addPage:"Add page",removePage:"Remove page",duplicatePage:"Duplicate page",moveUp:"Move up",moveDown:"Move down",moveLeft:"Move left",moveRight:"Move right"},scale:{reset:"Reset"},error:{removeBackground:"Ops! Something went wrong. Background can not be removed."},sidePanel:{templates:"Templates",searchTemplatesWithSameSize:"Show templates with the same size",searchPlaceholder:"Search...",otherFormats:"Other formats",noResults:"No results",error:"Loading is failed...",text:"Text",uploadFont:"Upload font",myFonts:"My fonts",photos:"Photos",videos:"Videos",animations:"Animations",effects:"Effects",elements:"Elements",shapes:"Shapes",tables:"Tables",lines:"Lines",draw:"Draw",upload:"Upload",uploadImage:"Add file",uploadTip:"Upload your assets",background:"Background",resize:"Resize",layers:"Layers",animate:"Animate",layerTypes:{image:"Image",text:"Text",svg:"SVG",line:"Line",figure:"Figure",group:"Group"},layersTip:"Elements on your active page:",noLayers:"No elements on the page...",namePlaceholder:"Type element name...",useMagicResize:"Use magic resize",clipImage:"Mask image",width:"Width",height:"Height",magicResizeDescription:"Magic resize will automatically resize and move all elements on the canvas",headerText:"Header",createHeader:"Create header",subHeaderText:"Sub Header",createSubHeader:"Create sub header",bodyText:"Body text",createBody:"Create body text"},pagesTimeline:{pages:"Pages",removePage:"Remove page",addPage:"Add page",duplicatePage:"Duplicate page",removeAudio:"Remove audio",duplicateAudio:"Duplicate audio",muteAudio:"Mute",unmuteAudio:"Unmute",volume:"Volume"},contextMenu:{duplicate:"Duplicate",remove:"Remove",lock:"Lock",unlock:"Unlock",copy:"Copy",paste:"Paste",copyStyle:"Copy style",moveUp:"Move up",moveDown:"Move down",moveBack:"Move back",moveForward:"Move forward"}}),n=e=>e&&"object"==typeof e;function i(e,o){Object.keys(o).forEach(r=>{const a=e[r],l=o[r];n(l)&&n(a)?i(a,l):e[r]=l})}function l(e,o,r=""){Object.keys(o).forEach(a=>{const i=o[a],s=r?`${r}.${a}`:a;n(i)?n(e[a])?l(e[a],i,s):console.warn(`Missing nested translation object at '${s}'`):void 0===e[a]&&console.warn(`Missing translation '${s}'`)})}export const setTranslations=o((e,{validate:o=!1}={})=>{o&&l(e,a),i(a,e)});export const getTranslations=()=>r(a);const s={};export const t=e=>{const o=function(e,o){var r,a=o.split("."),n=e;for(r=0;r<a.length;++r){if(null==n[a[r]]){return}n=n[a[r]]}return n}(a,e);if(void 0!==o){return o}s[e]||(s[e]=!0,console.warn(`Missing translation '${e}'`));const r=e.split("."),n=r[r.length-1]||" ";return n.charAt(0).toUpperCase()+n.slice(1)};
|
package/utils/text-html.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"konva";import*as e from"./gradient.js";import{removeTags as n,sanitizeHtml as o,parseHtmlToSegments as i}from"./text.js";import{flags as r}from"./flags.js";import{
|
|
1
|
+
import t from"konva";import*as e from"./gradient.js";import{removeTags as n,sanitizeHtml as o,parseHtmlToSegments as i}from"./text.js";import{flags as r}from"./flags.js";import{xmlEscape as l}from"./xml.js";import{applyTextDefaults as a}from"./text-types.js";function s(t){var e="֑-߿יִ-﷽ﹰ-ﻼ";return new RegExp("^[^"+e+"]*?["+e+"]").test(t)}export function getDir(t){return function(t){t=t.replace(/\s/g,"");let e=0;for(var n=0;n<t.length;n++){s(t[n])&&(e+=1)}return e>t.length/2}(t)?"rtl":"ltr"}export function getCurvePath(t,e,n,o){const i=Math.max(-.9999,Math.min(.9999,n));if(Math.abs(i)<1e-4){return`M 0 ${e/2} L ${t} ${e/2}`}const r=5*o/(2*Math.abs(i))-o,l=t/2;if(i>0){const t=2*r+o/2;return[`M ${l} ${t}`,`A ${r} ${r} 0 1 1 ${l} ${t-2*r}`,`A ${r} ${r} 0 1 1 ${l} ${t}`].join(" ")}{const t=-(2*r-Math.round(e))-o/2;return[`M ${l} ${t}`,`A ${r} ${r} 0 1 0 ${l} ${t+2*r}`,`A ${r} ${r} 0 1 0 ${l} ${t}`].join(" ")}}export function createSVGGradientDef(t,n,o,i){if(!e.isGradient(t)){return""}const{stops:r,rotation:l}=e.parseColor(t),a=l*Math.PI/180;return`<linearGradient id="${n}" x1="${100*(.5-.5*Math.sin(a))}%" y1="${100*(.5+.5*Math.cos(a))}%" x2="${100*(.5+.5*Math.sin(a))}%" y2="${100*(.5-.5*Math.cos(a))}%">${r.map(({offset:t,color:e})=>`<stop offset="${100*t}%" stop-color="${e}" />`).join("")}</linearGradient>`}export function getCurveTextHeight(e){var o,i,r,l;const s=e.a?e.a:e,f=a(e),$=null!==(o=s.fontSize)&&void 0!==o?o:f.fontSize,d=new t.TextPath({data:getCurvePath(null!==(i=s.width)&&void 0!==i?i:f.width,null!==(l=null!==(r=s.height)&&void 0!==r?r:f.height)&&void 0!==l?l:0,f.curvePower,$),align:"center",textBaseline:"middle",text:n(f.text),fontSize:$,fontFamily:f.fontFamily,fontWeight:f.fontWeight,fontStyle:f.fontStyle,letterSpacing:f.letterSpacing*$,fill:f.fill}),c=d.getSelfRect().height||$;return d.destroy(),c}export function segmentsToTspans(t,e,n){return t.map(t=>{const o=[];t.bold&&"bold"!==e.fontWeight&&o.push('font-weight="bold"'),t.italic&&"italic"!==e.fontStyle&&o.push('font-style="italic"'),t.underline&&o.push('text-decoration="underline"'),t.strike&&o.push('text-decoration="line-through"'),!(null==n?void 0:n.omitColors)&&t.color&&t.color!==e.fill&&o.push(`fill="${l(t.color)}"`);const i=l(t.text);return 0===o.length?i:`<tspan ${o.join(" ")}>${i}</tspan>`}).join("")}export function getHtml(t,{fontFamily:l="",color:s="black",forEditor:f=!1}={}){const $=a(t),d=l||$.fontFamily,c=e.isGradient($.fill),h=e.isGradient($.stroke)&&!!$.strokeWidth,p="ellipsis"===r.textOverflow&&!f&&!$.curveEnabled&&!!$.height,x=(()=>{if(!p){return[]}const t=Math.max(1,Math.round($.height)),e="number"==typeof $.lineHeight?$.lineHeight:1.2,n=Math.max(1,e*$.fontSize),o=Math.max(1,Math.floor(t/n));return[`max-height: ${t}px`,"overflow: hidden","display: -webkit-box","-webkit-box-orient: vertical",`-webkit-line-clamp: ${o}`,`line-clamp: ${o}`]})(),g=t=>`\n background-image: ${t};\n background-size: 100% 100%;\n background-repeat: repeat;\n -webkit-background-clip: text;\n -moz-background-clip: text;\n background-clip: text;\n -webkit-text-fill-color: transparent;\n color: transparent\n `.trim();let u=`color: ${s||$.fill}`,m="";h&&$.strokeWidth?(u=`color: ${s||$.fill}; ${g($.stroke)}`,m=`-webkit-text-stroke: ${$.strokeWidth}px transparent`):c&&(u=g($.fill));const k=["white-space: pre-wrap","word-break: break-word",`width: ${Math.round($.width||100)}px`,...x,u,`font-size: ${$.fontSize}px`,`font-family: '${d}'`,`text-align: ${$.align}`,`text-transform: ${$.textTransform}`,$.textDecoration?`text-decoration: ${$.textDecoration}; text-decoration-color: ${s||$.fill}; text-decoration-layer: over`:"",$.lineHeight?`line-height: ${$.lineHeight}`:"",$.letterSpacing?`letter-spacing: ${$.letterSpacing*$.fontSize}px`:"",$.fontStyle?`font-style: ${$.fontStyle}`:"",$.fontWeight?`font-weight: ${$.fontWeight}`:"",m||($.strokeWidth?`-webkit-text-stroke: ${$.strokeWidth}px ${$.stroke}`:""),$.strokeWidth&&!h?"paint-order: stroke fill":""].filter(Boolean).join("; ");if($.curveEnabled&&!f){const e=getCurveTextHeight(t),n=Math.round($.width||100),o=getCurvePath(n,e,$.curvePower,$.fontSize),r=i($.text),l={fontWeight:$.fontWeight||"normal",fontStyle:$.fontStyle||"normal",fill:s||$.fill||"black"},a=segmentsToTspans(r,l),f=segmentsToTspans(r,l,{omitColors:!0}),p=`curve-${$.id||"temp"}`,x=$.strokeWidth&&(h||c&&!h);let g=`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${e}" overflow="visible">\n <defs>\n <path id="${p}" d="${o}" fill="none" />`;if(c){const t=`curve-fill-grad-${$.id||"temp"}`;g+=createSVGGradientDef($.fill,t,n,e)}if(h&&$.strokeWidth){const t=`curve-stroke-grad-${$.id||"temp"}`;g+=createSVGGradientDef($.stroke,t,n,e)}if(g+="</defs>",x){const t=`\n font-family="'${d}'"\n font-size="${$.fontSize}"\n font-weight="${$.fontWeight}"\n font-style="${$.fontStyle}"\n text-anchor="middle"\n dominant-baseline="central"\n letter-spacing="${$.letterSpacing*$.fontSize}px"${$.textDecoration?` text-decoration="${$.textDecoration}"`:""}`,e=h?`url(#curve-stroke-grad-${$.id||"temp"})`:$.stroke;g+=`\n <text ${t} fill="${e}" stroke="${e}" stroke-width="${$.strokeWidth}">\n <textPath href="#${p}" startOffset="50%">${f}</textPath>\n </text>`,g+=`\n <text ${t} fill="${c?`url(#curve-fill-grad-${$.id||"temp"})`:s}">\n <textPath href="#${p}" startOffset="50%">${a}</textPath>\n </text>`}else{const t=c?`url(#curve-fill-grad-${$.id||"temp"})`:s,e=h?`url(#curve-stroke-grad-${$.id||"temp"})`:$.stroke;g+=`\n <text\n font-family="'${d}'"\n font-size="${$.fontSize}"\n font-weight="${$.fontWeight}"\n font-style="${$.fontStyle}"\n fill="${t}"\n text-anchor="middle"\n dominant-baseline="central"\n letter-spacing="${$.letterSpacing*$.fontSize}px"${$.textDecoration?` text-decoration="${$.textDecoration}"`:""}${$.strokeWidth?` stroke="${e}" stroke-width="${$.strokeWidth}" paint-order="stroke fill"`:""}>\n <textPath href="#${p}" startOffset="50%">${a}</textPath>\n </text>`}return g+="</svg>",g}if($.strokeWidth&&(h||c&&!h)&&!f){const t=o($.text).replace(/\n/g,"<br/>"),e=Math.round($.width||100),i=["white-space: pre-wrap","word-break: break-word",`width: ${e}px`,...x,`font-size: ${$.fontSize}px`,`font-family: '${d}'`,`text-align: ${$.align}`,`text-transform: ${$.textTransform}`,$.textDecoration?`text-decoration: ${$.textDecoration}; text-decoration-color: ${s||$.fill}; text-decoration-layer: over`:"",$.lineHeight?`line-height: ${$.lineHeight}`:"",$.letterSpacing?`letter-spacing: ${$.letterSpacing*$.fontSize}px`:"",$.fontStyle?`font-style: ${$.fontStyle}`:"",$.fontWeight?`font-weight: ${$.fontWeight}`:""].filter(Boolean).join("; ");let r;r=h?`${i}; ${g($.stroke)}; -webkit-text-stroke: ${$.strokeWidth}px transparent`:`${i}; color: transparent; -webkit-text-stroke: ${$.strokeWidth}px ${$.stroke}`;const l=`${i}; ${c?g($.fill):`color: ${s||$.fill}`}`;let a="";if(c||h){const t=[];h&&$.strokeWidth&&t.push(`.stroke-layer li, .stroke-layer li::before { ${g($.stroke)}; }`),c&&t.push(`.fill-layer li, .fill-layer li::before { ${g($.fill)}; }`),t.length&&(a=`<style>${t.join("\n")}</style>`)}return`\n <div style="position: relative; width: ${e}px;">\n <div class="stroke-layer" style="${r}; position: absolute; top: 0; left: 0; pointer-events: none;" aria-hidden="true">${t}</div>\n <div class="fill-layer" style="${l}; position: relative;" contentEditable dir="${getDir(n($.text))}">${t}</div>\n </div>\n ${a}\n `}let y="";return c&&!h&&(y=`<style>\n li, li::before {\n ${g($.fill)};\n }\n </style>`),`<div style="${k}" contentEditable dir="${getDir(n($.text))}">${o($.text).replace(/\n/g,"</br>")}</div>${y}`}export function resolveLineHeight({fontFamily:t,fontSize:e,lineHeight:n}){if("number"==typeof n){return n}const o=document.createElement("div");o.style.fontFamily=t,o.style.fontSize=e+"px",o.style.lineHeight=n,o.innerText="Test text",document.body.appendChild(o);const i=o.offsetHeight;return document.body.removeChild(o),i/e}
|
package/utils/to-html.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=this&&this.__rest||function(t,e){var o={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(o[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++){e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(o[i[n]]=t[i[n]])}}return o};import{getCrop as e,loadImage as o}from"./image.js";import*as i from"./svg.js";import{figureToSvg as n}from"./figure-to-svg.js";import{resetStyleContent as r}from"./reset-style.js";import{Effects as s,shapeFilterToCSS as a}from"./filters.js";import{getVideoSize as l}from"./video.js";import{getGoogleFontsUrl as d}from"./fonts.js";import{forEveryNode as c}from"../model/group-model.js";import{getCurvePath as g}from"../canvas/text-element.js";import{removeTags as p,parseHtmlToSegments as f}from"./text.js";import b from"konva";import*as u from"./gradient.js";import{createSVGGradientDef as m,segmentsToTspans as k,getHtml as y}from"./text-html.js";import{generateBackgroundShapeFromRects as x}from"./background-shape.js";import{detectLineRects as w,detectSize as $}from"./html2canvas.js";export const h=(t,e,...o)=>({type:t,props:e,children:o||[]});function v(t){return u.isGradient(t),t}export function fixRatio(t){var e=(new DOMParser).parseFromString(t,"image/svg+xml");return e.documentElement.setAttribute("preserveAspectRatio","none"),(new XMLSerializer).serializeToString(e)}const j=async({element:t,page:e,store:n})=>{let{src:r}=t;if("svg"===t.type){let e=await i.urlToString(r);e=fixRatio(e),r=Object.keys(t.colorsReplace).length?i.replaceColors(e,new Map(Object.entries(t.colorsReplace))):i.svgToURL(e)}let s="";t.flipX&&(s+="scaleX(-1)"),t.flipY&&(s+="scaleY(-1)"),s||(s="none");const a={};if("svg"===t.type&&t.maskSrc){const e=await i.urlToBase64(r);a["mask-image"]=`url(${e})`,a["mask-size"]="100% 100%",a["mask-position"]="0 0",a["mask-repeat"]="no-repeat",a["-webkit-mask-image"]=`url(${e})`,a["-webkit-mask-size"]="100% 100%",a["-webkit-mask-position"]="0 0",a["-webkit-mask-repeat"]="no-repeat",r=t.maskSrc}else if(t.clipSrc){const e=t.clipSrc,o=await i.urlToBase64(e);a["mask-image"]=`url(${o})`,a["mask-size"]="100% 100%",a["mask-position"]="0 0",a["mask-repeat"]="no-repeat",a["-webkit-mask-image"]=`url(${o})`,a["-webkit-mask-size"]="100% 100%",a["-webkit-mask-position"]="0 0",a["-webkit-mask-repeat"]="no-repeat"}const l=await o(r),d=l.width*t.cropWidth,c=l.height*t.cropHeight,g=t.width/t.height;let p,f;const b=d/c,m="svg"===t.type||t.stretchEnabled;m?(p=d,f=c):g>=b?(p=d,f=d/g):(p=c*g,f=c);const k=p/l.width,y=f/l.height,x=p/f>t.width/t.height?t.height/f:t.width/p,w=m?t.width/p:x,$=m?t.height/f:x,j=p*w/k,S=f*$/y;let O=t.cropX*w*l.width,z=t.cropY*$*l.height;t.flipX&&(O=(1-t.cropX-t.cropWidth)*w*l.width),t.flipY&&(z=(1-t.cropY-t.cropHeight)*$*l.height);const H=t.borderSize&&u.isGradient(t.borderColor),M=H?Math.max(0,t.cornerRadius-t.borderSize):t.cornerRadius,T=h("div",{style:Object.assign(Object.assign({},a),{width:"100%",height:"100%",borderRadius:M+"px",border:t.borderSize&&!H?`${t.borderSize}px solid ${t.borderColor}`:"none",backgroundRepeat:"no-repeat",backgroundImage:`url(${r})`,transform:s,backgroundSize:`${Math.round(j)}px ${Math.round(S)}px`,backgroundPositionX:-Math.round(O)+"px",backgroundPositionY:-Math.round(z)+"px"})});return H?h("div",{style:{width:"100%",height:"100%",borderRadius:t.cornerRadius+"px",background:v(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},T):T},S=({element:t,type:e})=>{const o={"stroke-width":t.height,stroke:t.color,"stroke-linecap":"round","stroke-linejoin":"round",opacity:t.opacity},i=Object.assign(Object.assign({},o),{fill:t.color}),n=Object.assign(Object.assign({},o),{fill:"none"});return"arrow"===e?h("polyline",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},n)):"triangle"===e?h("polygon",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},i)):"bar"===e?h("polyline",Object.assign({points:`0,${2*-t.height} 0,${2*t.height}`},n)):"circle"===e?h("circle",Object.assign({cx:2*t.height,cy:0,r:2*t.height},i)):"square"===e?h("polygon",Object.assign({points:`0,${2*-t.height} ${4*t.height},${2*-t.height} ${4*t.height},${2*t.height} 0,${2*t.height}`},i)):null},O={image:j,svg:j,text:async({element:t,page:e,store:o})=>{const i=u.isGradient(t.fill),n=u.isGradient(t.stroke);if(t.curveEnabled){const e=g(t.width,t.height,t.curvePower,t.fontSize),o=f(t.text),r={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black"},s=k(o,r);let a=`\n <svg xmlns="http://www.w3.org/2000/svg" width="${t.width}" height="${t.height}" style="display: block;">\n <defs>\n <path id="curve-${t.id}" d="${e}" fill="none" />`;if(i){const e=`curve-fill-grad-${t.id}`;a+=m(t.fill,e)}if(n&&t.strokeWidth){const e=`curve-stroke-grad-${t.id}`;a+=m(t.stroke,e)}a+=`</defs>\n <text\n font-family="'${t.fontFamily}'"\n font-size="${t.fontSize}"\n font-weight="${t.fontWeight}"\n font-style="${t.fontStyle}"\n fill="${i?`url(#curve-fill-grad-${t.id})`:t.fill}"\n text-anchor="middle"\n dominant-baseline="central"\n letter-spacing="${t.letterSpacing*t.fontSize}px"${t.textDecoration?` text-decoration="${t.textDecoration}"`:""}${t.strokeWidth?` stroke="${n?`url(#curve-stroke-grad-${t.id})`:t.stroke}" stroke-width="${t.strokeWidth}" paint-order="stroke fill"`:""}>\n <textPath href="#curve-${t.id}" startOffset="50%">${s}</textPath>\n </text>\n </svg>`;const l=t.backgroundPadding*(t.fontSize*t.lineHeight),d=t.backgroundEnabled&&h("div",{style:{position:"absolute",top:-l/2+"px",left:-l/2+"px",width:t.width+l+"px",height:t.height+l+"px",backgroundColor:t.backgroundColor,opacity:t.backgroundOpacity,borderRadius:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)+"px"}}),c=h("div",{style:{width:"100%",height:"100%",position:"absolute",top:0,left:0},innerHTML:a});return h("div",{style:{position:"relative",width:"100%",height:"100%"}},d,c)}const s=t=>({backgroundImage:t,backgroundSize:"100% 100%",backgroundRepeat:"repeat",WebkitBackgroundClip:"text",MozBackgroundClip:"text",backgroundClip:"text",WebkitTextFillColor:"transparent",MozTextFillColor:"transparent",color:"transparent"});let a={top:0,left:0};i&&(a=Object.assign(Object.assign({},a),s(t.fill)));let l=null;if(t.backgroundEnabled){if(t.legacyBackground){const e=t.backgroundPadding*(t.fontSize*t.lineHeight);l=h("div",{style:{position:"absolute",top:-e/2+"px",left:-e/2+"px",display:"block",width:t.width+e+"px",height:t.height+e+"px",backgroundColor:t.backgroundColor,opacity:t.backgroundOpacity,borderRadius:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)+"px"}})}else{const e=y(t);let o=[];try{o=w(e)}catch(O){o=[]}if(o.length){const i=t.backgroundPadding*(t.fontSize*t.lineHeight*.5),n=t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5),r=x({rects:o,padding:i,cornerRadius:n});if(r){let n=0;try{const{height:o}=$(e);"middle"===t.verticalAlign?n=(t.height-o)/2:"bottom"===t.verticalAlign&&(n=t.height-o)}catch(z){}const s=Math.min(...o.map(t=>t.top)),a=Math.max(...o.map(t=>t.bottom)),d=Math.min(...o.map(t=>t.left)),c=d-i,g=s-i,p=Math.max(...o.map(t=>t.right))-d+2*i,f=a-s+2*i;l=h("svg",{xmlns:"http://www.w3.org/2000/svg",width:p,height:f,viewBox:`${c} ${g} ${p} ${f}`,style:{position:"absolute",top:n+g+"px",left:c+"px",opacity:t.backgroundOpacity,pointerEvents:"none"},innerHTML:`<path d="${r}" fill="${t.backgroundColor}" />`})}}}}else{l=null}"middle"===t.verticalAlign?(a.top="50%",a.transform="translateY(-50%)"):"bottom"===t.verticalAlign&&(a.bottom=0);const d=/<[a-z][\s\S]*>/i.test(t.text),c=d?t.text:t.text.split("\n").join("<br />");if(t.strokeWidth&&(n||i&&!n)){const e=Object.assign({position:"absolute",width:t.width+"px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:t.fontSize+"px",textAlign:t.align,fontFamily:`'${t.fontFamily}'`,textDecoration:t.textDecoration||"none",textDecorationColor:t.textDecoration?t.fill:void 0,textTransform:t.textTransform||"none",lineHeight:t.lineHeight,letterSpacing:t.letterSpacing*t.fontSize+"px",fontStyle:t.fontStyle,fontWeight:t.fontWeight},a),o=n?Object.assign(Object.assign(Object.assign({},e),s(t.stroke)),{WebkitTextStroke:`${t.strokeWidth}px transparent`}):Object.assign(Object.assign({},e),{color:"transparent",WebkitTextStroke:`${t.strokeWidth}px ${t.stroke}`}),g=i?Object.assign(Object.assign({},e),s(t.fill)):Object.assign(Object.assign({},e),{color:t.fill}),p="el-"+t.id,f=d?`<style>#${p} {${r}}</style>`:"",b=h("div",{style:Object.assign(Object.assign({},o),{position:"absolute",top:0,left:0,pointerEvents:"none"}),"aria-hidden":"true",innerHTML:d?`${f}${c}`:c}),u=h("div",Object.assign(Object.assign({style:Object.assign(Object.assign({},g),{position:"relative"})},d?{id:p}:{}),{innerHTML:d?`${f}${c}`:c}));return h("div",{style:{position:"relative",width:"100%",height:"100%"}},l,h("div",{style:{position:"relative",width:t.width+"px"}},b,u))}const p=Object.assign(Object.assign({},a),{position:"absolute",width:t.width+"px",color:t.fill,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:t.fontSize+"px",textAlign:t.align,fontFamily:`'${t.fontFamily}'`,textDecoration:t.textDecoration||"none",textDecorationColor:t.textDecoration?t.fill:void 0,textTransform:t.textTransform||"none",lineHeight:t.lineHeight,letterSpacing:t.letterSpacing*t.fontSize+"px",fontStyle:t.fontStyle,fontWeight:t.fontWeight,WebkitTextStroke:t.strokeWidth?`${t.strokeWidth}px ${t.stroke}`:void 0,paintOrder:t.strokeWidth?"stroke fill":void 0}),b="el-"+t.id,v=d?{id:b}:{},j=`<style>#${b} {${r}}</style>`,S=h("div",Object.assign(Object.assign({style:p},v),{innerHTML:d?`${j}${c}`:c}));return h("div",{style:{position:"relative",width:"100%",height:"100%"}},l,S)},line:async({element:t,page:e,store:o})=>h("svg",{style:{width:"100%",height:"100%",contain:"layout style size",overflow:"visible"}},h("line",{x1:0,y1:t.height/2,x2:t.width,y2:t.height/2,stroke:t.color,"stroke-width":t.height,"stroke-dasharray":t.dash&&t.dash.length?t.dash.map(e=>e*t.height).join(" "):void 0}),h("g",{transform:`translate(0 ${t.height/2})`},S({element:t,type:t.startHead})),h("g",{transform:`translate(${t.width} ${t.height/2}) rotate(180)`},S({element:t,type:t.endHead}))),figure:async({element:t,page:e,store:o,elementHook:i})=>{let r=n(t);if(t.strokeWidth&&u.isGradient(t.stroke)){const e=`figure-stroke-grad-${t.id}`,o=m(t.stroke,e);r=r.replace(new RegExp(`stroke="${t.stroke.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"`,"g"),`stroke="url(#${e})"`),r=r.replace("</defs>",`${o}</defs>`)}if(u.isGradient(t.fill)){const e=`figure-fill-grad-${t.id}`,o=m(t.fill,e);r=r.replace(new RegExp(`fill="${t.fill.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"`,"g"),`fill="url(#${e})"`),r=r.replace("</defs>",`${o}</defs>`)}const s=h("div",{innerHTML:r});return i&&i({dom:s,element:t})||s},group:async({element:t,page:e,store:o,elementHook:i})=>{const n=await Promise.all(t.children.map(t=>z({element:t,page:e,store:o,elementHook:i}))),r=h("div",{style:{transformOrigin:"top left",opacity:t.opacity}},...n);return i&&i({dom:r,element:t})||r},video:async({element:t,page:e,store:o,elementHook:i})=>{const{cropX:n,cropY:r,cropWidth:s,cropHeight:a}=t,d=await l(t.src),c=d.width*s,g=d.height*a,p=t.width/t.height;let f,b;p>=c/g?(f=c,b=c/p):(f=g*p,b=g);const m=f/s,k=b/a,y=n*d.width,x=r*d.height,w=Math.max(t.width/d.width,t.height/d.height),$={position:"absolute",width:`${Math.round(m*w)}px`,height:`${Math.round(k*w)}px`,left:-Math.round(y*w)+"px",top:-Math.round(x*w)+"px",objectFit:"fill"},j=`video-${t.id}`,S=t.borderSize&&u.isGradient(t.borderColor),O=S?Math.max(0,t.cornerRadius-t.borderSize):t.cornerRadius,z=h("div",{style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",borderRadius:O+"px",border:t.borderSize&&!S?`${t.borderSize}px solid ${t.borderColor}`:"none"}},h("video",{id:j,src:t.src,style:$,controls:!0,playsInline:!0,muted:!0,volume:t.volume}));if(S){const e=h("div",{style:{width:"100%",height:"100%",borderRadius:t.cornerRadius+"px",background:v(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},z);return i&&i({dom:e,element:t})||e}return i&&i({dom:z,element:t})||z},gif:j,table:async({element:t})=>{const e=t.rows,o=t.cols,i=t.colWidths,n=t.rowHeights,r=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],s=(t.cells||[]).map(e=>{if(!e){return e}const o=Object.assign({},e);for(const i of r){void 0===o[i]&&(o[i]=t[i])}return o}),a=[];for(let d=0;d<e;d++){const e=[];for(let i=0;i<o;i++){const r=s[d*o+i];if(!r||r.mergedInto){continue}const a=r.cellPadding||4,l=r.colSpan||1,c=r.rowSpan||1,g=e=>{var o,i,n,s,a;const l=null===(o=r.borders)||void 0===o?void 0:o[e];return`${null!==(i=null==l?void 0:l.width)&&void 0!==i?i:t.borderWidth}px ${null!==(s=null!==(n=null==l?void 0:l.style)&&void 0!==n?n:t.borderStyle)&&void 0!==s?s:"solid"} ${null!==(a=null==l?void 0:l.color)&&void 0!==a?a:t.borderColor}`},f={style:{padding:a+"px",background:r.cellBackground||"transparent",fontSize:(r.fontSize||12)+"px",fontFamily:`'${r.fontFamily||"Roboto"}'`,fontWeight:r.fontWeight||"normal",fontStyle:r.fontStyle||"normal",color:r.fill||"black",textAlign:r.align||"left",verticalAlign:r.verticalAlign||"top",lineHeight:String(r.lineHeight||1.2),letterSpacing:r.letterSpacing?r.letterSpacing*(r.fontSize||12)+"px":void 0,textDecoration:r.textDecoration||"none",textTransform:r.textTransform||"none",borderTop:g("top"),borderRight:g("right"),borderBottom:g("bottom"),borderLeft:g("left"),overflow:"hidden",wordBreak:"break-word",whiteSpace:"pre-wrap",height:n[d]*t.height+"px"}};l>1&&(f.colspan=String(l)),c>1&&(f.rowspan=String(c)),e.push(h("td",f,p(r.text||"")))}a.push(h("tr",{},...e))}const l=i.map(t=>h("col",{style:{width:100*t+"%"}}));return h("table",{style:{width:"100%",height:"100%",borderCollapse:"collapse",tableLayout:"fixed"}},h("colgroup",{},...l),h("tbody",{},...a))}};async function z({element:t,page:e,store:o,elementHook:i}){var n;let r=await O[t.type];if(r||(r=()=>h("div",{}),console.error(`HTML export does not support ${t.type} type...`)),!t.visible){return null}const l=await r({element:t,page:e,store:o}),d=[],c=[];if(t.blurEnabled&&d.push(`blur(${t.blurRadius/2}px)`),t.brightnessEnabled&&d.push(`brightness(${100*t.brightness+100}%)`),t.sepiaEnabled&&d.push("sepia()"),t.grayscaleEnabled&&d.push("grayscale()"),t.filters){for(const[p,f]of Object.entries(t.filters)){const t=a(s[p],f.intensity);t&&(d.push(t.filter),t.html&&c.push(t.html))}}if(t.shadowEnabled){const e=function(t,e){if(1===e){return t}const o=b.Util.colorToRGBA(t);return o?`rgba(${o.r}, ${o.g}, ${o.b}, ${o.a*e})`:t}(t.shadowColor,null!==(n=t.shadowOpacity)&&void 0!==n?n:1);d.push(`drop-shadow(${t.shadowOffsetX}px ${t.shadowOffsetY}px ${t.shadowBlur/2}px ${e})`)}const g=h("div",{id:t.id,style:{position:"absolute",left:t.x+"px",top:t.y+"px",width:t.width+"px",height:t.height+"px",transform:`rotate(${t.rotation}deg)`,transformOrigin:"top left",opacity:t.opacity,display:t.visible&&t.showInExport?"block":"none",filter:d.join(" ")||"none"}},l,...c);return i&&i({dom:g,element:t})||g}export async function jsonToDOM({json:t,elementHook:i}){const n=await Promise.all(t.pages.map(n=>async function({page:t,store:i,elementHook:n}){const r=await Promise.all(t.children.map(e=>z({element:e,page:t,store:i,elementHook:n}))),s="auto"===t.width?i.width:t.width,a="auto"===t.height?i.height:t.height;let l={};if(t.background.indexOf("url")>=0||t.background.indexOf("http")>=0||t.background.indexOf(".jpg")>=0||t.background.indexOf(".png")>=0||t.background.indexOf(".jpeg")>=0){const{width:n,height:l}=await o(t.background),d=await j({element:Object.assign({x:0,y:0,width:s,height:a,src:t.background,cornerRadius:0},e({width:s,height:a},{width:n,height:l})),page:t,store:i});r.unshift(d)}else{l=u.isGradient(t.background)?Object.assign(Object.assign({},l),{backgroundImage:t.background}):Object.assign(Object.assign({},l),{backgroundColor:t.background})}return h("div",{className:"page",id:t.id,style:Object.assign(Object.assign({},l),{width:s+"px",height:a+"px",overflow:"hidden",position:"relative"})},...r)}({page:n,store:t,elementHook:i}))),r=[];c({children:t.pages},t=>{"text"!==t.type&&"tablecell"!==t.type&&"table"!==t.type||!t.fontFamily||-1!==r.indexOf(t.fontFamily)||r.push(t.fontFamily)});const s=r.map(e=>{const o=t.fonts.find(t=>t.fontFamily===e);if(o){const t=(o.styles||(o.url?[{src:`url("${o.url}")`}]:[])).map(t=>`\n @font-face {\n font-family: '${o.fontFamily}';\n src: ${t.src};\n font-style: ${t.fontStyle||"normal"};\n font-weight: ${t.fontWeight||"normal"};\n font-display: swap;\n }`).join("\n");return h("style",{},t)}return h("link",{href:d(e),rel:"stylesheet"})});return h("div",{className:"design"},...s,...n)}const H=({dom:e})=>{if("string"==typeof e){return e}if(!e){return""}const o=e.props,{innerHTML:i}=o,n=t(o,["innerHTML"]),r=Object.keys(n).map(t=>"style"===t&&"object"==typeof n[t]?`style="${Object.keys(n[t]).filter(e=>null!=n[t][e]).map(e=>`${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}: ${n[t][e]}`).join("; ")}"`:((t,e)=>null==e||""===e?"":"object"==typeof e?`${t}="${Object.keys(e).map(t=>`${t.replace(/-([a-z])/g,t=>t[1].toUpperCase())}:${e[t]};`).join(" ")}"`:`${t}="${e}"`)(t,n[t])).filter(t=>t&&t.trim().length>0).join(" ");return`<${e.type} ${r}>${i||e.children.map(t=>H({dom:t})).join("")}</${e.type}>`};export async function jsonToHTML({json:t,elementHook:e}){const o=await jsonToDOM({json:t,elementHook:e});return H({dom:o})}
|
|
1
|
+
var t=this&&this.__rest||function(t,e){var o={};for(var i in t){Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(o[i]=t[i])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(i=Object.getOwnPropertySymbols(t);n<i.length;n++){e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(o[i[n]]=t[i[n]])}}return o};import{getCrop as e,loadImage as o}from"./image.js";import*as i from"./svg.js";import{figureToSvg as n}from"./figure-to-svg.js";import{resetStyleContent as r}from"./reset-style.js";import{Effects as s,shapeFilterToCSS as a}from"./filters.js";import{getVideoSize as l}from"./video.js";import{getGoogleFontsUrl as d}from"./fonts.js";import{forEveryNode as c}from"../model/group-model.js";import{getCurvePath as g}from"../canvas/text-element.js";import{removeTags as p,parseHtmlToSegments as f}from"./text.js";import b from"konva";import*as u from"./gradient.js";import{createSVGGradientDef as m,segmentsToTspans as k,getHtml as y}from"./text-html.js";import{generateBackgroundShapeFromRects as x}from"./background-shape.js";import{detectLineRects as w,detectSize as $}from"./html2canvas.js";export const h=(t,e,...o)=>({type:t,props:e,children:o||[]});function v(t){return u.isGradient(t),t}export function fixRatio(t){var e=(new DOMParser).parseFromString(t,"image/svg+xml");return e.documentElement.setAttribute("preserveAspectRatio","none"),(new XMLSerializer).serializeToString(e)}const j=async({element:t,page:e,store:n})=>{let{src:r}=t;if("svg"===t.type){let e=await i.urlToString(r);e=fixRatio(e),r=Object.keys(t.colorsReplace).length?i.replaceColors(e,new Map(Object.entries(t.colorsReplace))):i.svgToURL(e)}let s="";t.flipX&&(s+="scaleX(-1)"),t.flipY&&(s+="scaleY(-1)"),s||(s="none");const a={};if("svg"===t.type&&t.maskSrc){const e=await i.urlToBase64(r);a["mask-image"]=`url(${e})`,a["mask-size"]="100% 100%",a["mask-position"]="0 0",a["mask-repeat"]="no-repeat",a["-webkit-mask-image"]=`url(${e})`,a["-webkit-mask-size"]="100% 100%",a["-webkit-mask-position"]="0 0",a["-webkit-mask-repeat"]="no-repeat",r=t.maskSrc}else if(t.clipSrc){const e=t.clipSrc,o=await i.urlToBase64(e);a["mask-image"]=`url(${o})`,a["mask-size"]="100% 100%",a["mask-position"]="0 0",a["mask-repeat"]="no-repeat",a["-webkit-mask-image"]=`url(${o})`,a["-webkit-mask-size"]="100% 100%",a["-webkit-mask-position"]="0 0",a["-webkit-mask-repeat"]="no-repeat"}const l=await o(r),d=l.width*t.cropWidth,c=l.height*t.cropHeight,g=t.width/t.height;let p,f;const b=d/c,m="svg"===t.type||t.stretchEnabled;m?(p=d,f=c):g>=b?(p=d,f=d/g):(p=c*g,f=c);const k=p/l.width,y=f/l.height,x=p/f>t.width/t.height?t.height/f:t.width/p,w=m?t.width/p:x,$=m?t.height/f:x,j=p*w/k,S=f*$/y;let O=t.cropX*w*l.width,z=t.cropY*$*l.height;t.flipX&&(O=(1-t.cropX-t.cropWidth)*w*l.width),t.flipY&&(z=(1-t.cropY-t.cropHeight)*$*l.height);const H=t.borderSize&&u.isGradient(t.borderColor),M=H?Math.max(0,t.cornerRadius-t.borderSize):t.cornerRadius,T=h("div",{style:Object.assign(Object.assign({},a),{width:"100%",height:"100%",borderRadius:M+"px",border:t.borderSize&&!H?`${t.borderSize}px solid ${t.borderColor}`:"none",backgroundRepeat:"no-repeat",backgroundImage:`url(${r})`,transform:s,backgroundSize:`${Math.round(j)}px ${Math.round(S)}px`,backgroundPositionX:-Math.round(O)+"px",backgroundPositionY:-Math.round(z)+"px"})});return H?h("div",{style:{width:"100%",height:"100%",borderRadius:t.cornerRadius+"px",background:v(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},T):T},S=({element:t,type:e})=>{const o={"stroke-width":t.height,stroke:t.color,"stroke-linecap":"round","stroke-linejoin":"round",opacity:t.opacity},i=Object.assign(Object.assign({},o),{fill:t.color}),n=Object.assign(Object.assign({},o),{fill:"none"});return"arrow"===e?h("polyline",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},n)):"triangle"===e?h("polygon",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},i)):"bar"===e?h("polyline",Object.assign({points:`0,${2*-t.height} 0,${2*t.height}`},n)):"circle"===e?h("circle",Object.assign({cx:2*t.height,cy:0,r:2*t.height},i)):"square"===e?h("polygon",Object.assign({points:`0,${2*-t.height} ${4*t.height},${2*-t.height} ${4*t.height},${2*t.height} 0,${2*t.height}`},i)):null},O={image:j,svg:j,text:async({element:t,page:e,store:o})=>{const i=u.isGradient(t.fill),n=u.isGradient(t.stroke);if(t.curveEnabled){const e=g(t.width,t.height,t.curvePower,t.fontSize),o=f(t.text),r={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black"},s=k(o,r);let a=`\n <svg xmlns="http://www.w3.org/2000/svg" width="${t.width}" height="${t.height}" style="display: block;">\n <defs>\n <path id="curve-${t.id}" d="${e}" fill="none" />`;if(i){const e=`curve-fill-grad-${t.id}`;a+=m(t.fill,e)}if(n&&t.strokeWidth){const e=`curve-stroke-grad-${t.id}`;a+=m(t.stroke,e)}a+=`</defs>\n <text\n font-family="'${t.fontFamily}'"\n font-size="${t.fontSize}"\n font-weight="${t.fontWeight}"\n font-style="${t.fontStyle}"\n fill="${i?`url(#curve-fill-grad-${t.id})`:t.fill}"\n text-anchor="middle"\n dominant-baseline="central"\n letter-spacing="${t.letterSpacing*t.fontSize}px"${t.textDecoration?` text-decoration="${t.textDecoration}"`:""}${t.strokeWidth?` stroke="${n?`url(#curve-stroke-grad-${t.id})`:t.stroke}" stroke-width="${t.strokeWidth}" paint-order="stroke fill"`:""}>\n <textPath href="#curve-${t.id}" startOffset="50%">${s}</textPath>\n </text>\n </svg>`;const l=t.backgroundPadding*(t.fontSize*t.lineHeight),d=t.backgroundEnabled&&h("div",{style:{position:"absolute",top:-l/2+"px",left:-l/2+"px",width:t.width+l+"px",height:t.height+l+"px",backgroundColor:t.backgroundColor,opacity:t.backgroundOpacity,borderRadius:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)+"px"}}),c=h("div",{style:{width:"100%",height:"100%",position:"absolute",top:0,left:0},innerHTML:a});return h("div",{style:{position:"relative",width:"100%",height:"100%"}},d,c)}const s=t=>({backgroundImage:t,backgroundSize:"100% 100%",backgroundRepeat:"repeat",WebkitBackgroundClip:"text",MozBackgroundClip:"text",backgroundClip:"text",WebkitTextFillColor:"transparent",MozTextFillColor:"transparent",color:"transparent"}),a="middle"===t.verticalAlign?{top:"50%",transform:"translateY(-50%)"}:"bottom"===t.verticalAlign?{bottom:0}:{top:0};let l=Object.assign(Object.assign({left:0},a),i?s(t.fill):{}),d=null;if(t.backgroundEnabled){if(t.legacyBackground){const e=t.backgroundPadding*(t.fontSize*t.lineHeight);d=h("div",{style:{position:"absolute",top:-e/2+"px",left:-e/2+"px",display:"block",width:t.width+e+"px",height:t.height+e+"px",backgroundColor:t.backgroundColor,opacity:t.backgroundOpacity,borderRadius:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)+"px"}})}else{const e=y(t);let o=[];try{o=w(e)}catch(z){o=[]}if(o.length){const i=t.backgroundPadding*(t.fontSize*t.lineHeight*.5),n=t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5),r=x({rects:o,padding:i,cornerRadius:n});if(r){let n=0;try{const{height:o}=$(e);"middle"===t.verticalAlign?n=(t.height-o)/2:"bottom"===t.verticalAlign&&(n=t.height-o)}catch(H){}const s=Math.min(...o.map(t=>t.top)),a=Math.max(...o.map(t=>t.bottom)),l=Math.min(...o.map(t=>t.left)),c=l-i,g=s-i,p=Math.max(...o.map(t=>t.right))-l+2*i,f=a-s+2*i;d=h("svg",{xmlns:"http://www.w3.org/2000/svg",width:p,height:f,viewBox:`${c} ${g} ${p} ${f}`,style:{position:"absolute",top:n+g+"px",left:c+"px",opacity:t.backgroundOpacity,pointerEvents:"none"},innerHTML:`<path d="${r}" fill="${t.backgroundColor}" />`})}}}}else{d=null}const c=/<[a-z][\s\S]*>/i.test(t.text),p=c?t.text:t.text.split("\n").join("<br />");if(t.strokeWidth&&(n||i&&!n)){const e={position:"absolute",width:t.width+"px",whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:t.fontSize+"px",textAlign:t.align,fontFamily:`'${t.fontFamily}'`,textDecoration:t.textDecoration||"none",textDecorationColor:t.textDecoration?t.fill:void 0,textTransform:t.textTransform||"none",lineHeight:t.lineHeight,letterSpacing:t.letterSpacing*t.fontSize+"px",fontStyle:t.fontStyle,fontWeight:t.fontWeight},o=n?Object.assign(Object.assign(Object.assign({},e),s(t.stroke)),{WebkitTextStroke:`${t.strokeWidth}px transparent`}):Object.assign(Object.assign({},e),{color:"transparent",WebkitTextStroke:`${t.strokeWidth}px ${t.stroke}`}),l=i?Object.assign(Object.assign({},e),s(t.fill)):Object.assign(Object.assign({},e),{color:t.fill}),g="el-"+t.id,f=c?`<style>#${g} {${r}}</style>`:"",b=h("div",{style:Object.assign(Object.assign({},o),{position:"absolute",top:0,left:0,pointerEvents:"none"}),"aria-hidden":"true",innerHTML:c?`${f}${p}`:p}),u=h("div",Object.assign(Object.assign({style:Object.assign(Object.assign({},l),{position:"relative"})},c?{id:g}:{}),{innerHTML:c?`${f}${p}`:p}));return h("div",{style:{position:"relative",width:"100%",height:"100%"}},d,h("div",{style:Object.assign({position:"absolute",width:t.width+"px",left:0},a)},b,u))}const b=Object.assign(Object.assign({},l),{position:"absolute",width:t.width+"px",color:t.fill,whiteSpace:"pre-wrap",wordBreak:"break-word",fontSize:t.fontSize+"px",textAlign:t.align,fontFamily:`'${t.fontFamily}'`,textDecoration:t.textDecoration||"none",textDecorationColor:t.textDecoration?t.fill:void 0,textTransform:t.textTransform||"none",lineHeight:t.lineHeight,letterSpacing:t.letterSpacing*t.fontSize+"px",fontStyle:t.fontStyle,fontWeight:t.fontWeight,WebkitTextStroke:t.strokeWidth?`${t.strokeWidth}px ${t.stroke}`:void 0,paintOrder:t.strokeWidth?"stroke fill":void 0}),v="el-"+t.id,j=c?{id:v}:{},S=`<style>#${v} {${r}}</style>`,O=h("div",Object.assign(Object.assign({style:b},j),{innerHTML:c?`${S}${p}`:p}));return h("div",{style:{position:"relative",width:"100%",height:"100%"}},d,O)},line:async({element:t,page:e,store:o})=>h("svg",{style:{width:"100%",height:"100%",contain:"layout style size",overflow:"visible"}},h("line",{x1:0,y1:t.height/2,x2:t.width,y2:t.height/2,stroke:t.color,"stroke-width":t.height,"stroke-dasharray":t.dash&&t.dash.length?t.dash.map(e=>e*t.height).join(" "):void 0}),h("g",{transform:`translate(0 ${t.height/2})`},S({element:t,type:t.startHead})),h("g",{transform:`translate(${t.width} ${t.height/2}) rotate(180)`},S({element:t,type:t.endHead}))),figure:async({element:t,page:e,store:o,elementHook:i})=>{let r=n(t);if(t.strokeWidth&&u.isGradient(t.stroke)){const e=`figure-stroke-grad-${t.id}`,o=m(t.stroke,e);r=r.replace(new RegExp(`stroke="${t.stroke.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"`,"g"),`stroke="url(#${e})"`),r=r.replace("</defs>",`${o}</defs>`)}if(u.isGradient(t.fill)){const e=`figure-fill-grad-${t.id}`,o=m(t.fill,e);r=r.replace(new RegExp(`fill="${t.fill.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}"`,"g"),`fill="url(#${e})"`),r=r.replace("</defs>",`${o}</defs>`)}const s=h("div",{innerHTML:r});return i&&i({dom:s,element:t})||s},group:async({element:t,page:e,store:o,elementHook:i})=>{const n=await Promise.all(t.children.map(t=>z({element:t,page:e,store:o,elementHook:i}))),r=h("div",{style:{transformOrigin:"top left",opacity:t.opacity}},...n);return i&&i({dom:r,element:t})||r},video:async({element:t,page:e,store:o,elementHook:i})=>{const{cropX:n,cropY:r,cropWidth:s,cropHeight:a}=t,d=await l(t.src),c=d.width*s,g=d.height*a,p=t.width/t.height;let f,b;p>=c/g?(f=c,b=c/p):(f=g*p,b=g);const m=f/s,k=b/a,y=n*d.width,x=r*d.height,w=Math.max(t.width/d.width,t.height/d.height),$={position:"absolute",width:`${Math.round(m*w)}px`,height:`${Math.round(k*w)}px`,left:-Math.round(y*w)+"px",top:-Math.round(x*w)+"px",objectFit:"fill"},j=`video-${t.id}`,S=t.borderSize&&u.isGradient(t.borderColor),O=S?Math.max(0,t.cornerRadius-t.borderSize):t.cornerRadius,z=h("div",{style:{position:"relative",width:"100%",height:"100%",overflow:"hidden",borderRadius:O+"px",border:t.borderSize&&!S?`${t.borderSize}px solid ${t.borderColor}`:"none"}},h("video",{id:j,src:t.src,style:$,controls:!0,playsInline:!0,muted:!0,volume:t.volume}));if(S){const e=h("div",{style:{width:"100%",height:"100%",borderRadius:t.cornerRadius+"px",background:v(t.borderColor),padding:t.borderSize+"px",boxSizing:"border-box"}},z);return i&&i({dom:e,element:t})||e}return i&&i({dom:z,element:t})||z},gif:j,table:async({element:t})=>{const e=t.rows,o=t.cols,i=t.colWidths,n=t.rowHeights,r=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],s=(t.cells||[]).map(e=>{if(!e){return e}const o=Object.assign({},e);for(const i of r){void 0===o[i]&&(o[i]=t[i])}return o}),a=[];for(let d=0;d<e;d++){const e=[];for(let i=0;i<o;i++){const r=s[d*o+i];if(!r||r.mergedInto){continue}const a=r.cellPadding||4,l=r.colSpan||1,c=r.rowSpan||1,g=e=>{var o,i,n,s,a;const l=null===(o=r.borders)||void 0===o?void 0:o[e];return`${null!==(i=null==l?void 0:l.width)&&void 0!==i?i:t.borderWidth}px ${null!==(s=null!==(n=null==l?void 0:l.style)&&void 0!==n?n:t.borderStyle)&&void 0!==s?s:"solid"} ${null!==(a=null==l?void 0:l.color)&&void 0!==a?a:t.borderColor}`},f={style:{padding:a+"px",background:r.cellBackground||"transparent",fontSize:(r.fontSize||12)+"px",fontFamily:`'${r.fontFamily||"Roboto"}'`,fontWeight:r.fontWeight||"normal",fontStyle:r.fontStyle||"normal",color:r.fill||"black",textAlign:r.align||"left",verticalAlign:r.verticalAlign||"top",lineHeight:String(r.lineHeight||1.2),letterSpacing:r.letterSpacing?r.letterSpacing*(r.fontSize||12)+"px":void 0,textDecoration:r.textDecoration||"none",textTransform:r.textTransform||"none",borderTop:g("top"),borderRight:g("right"),borderBottom:g("bottom"),borderLeft:g("left"),overflow:"hidden",wordBreak:"break-word",whiteSpace:"pre-wrap",height:n[d]*t.height+"px"}};l>1&&(f.colspan=String(l)),c>1&&(f.rowspan=String(c)),e.push(h("td",f,p(r.text||"")))}a.push(h("tr",{},...e))}const l=i.map(t=>h("col",{style:{width:100*t+"%"}}));return h("table",{style:{width:"100%",height:"100%",borderCollapse:"collapse",tableLayout:"fixed"}},h("colgroup",{},...l),h("tbody",{},...a))}};async function z({element:t,page:e,store:o,elementHook:i}){var n;let r=await O[t.type];if(r||(r=()=>h("div",{}),console.error(`HTML export does not support ${t.type} type...`)),!t.visible){return null}const l=await r({element:t,page:e,store:o}),d=[],c=[];if(t.blurEnabled&&d.push(`blur(${t.blurRadius/2}px)`),t.brightnessEnabled&&d.push(`brightness(${100*t.brightness+100}%)`),t.sepiaEnabled&&d.push("sepia()"),t.grayscaleEnabled&&d.push("grayscale()"),t.filters){for(const[p,f]of Object.entries(t.filters)){const t=a(s[p],f.intensity);t&&(d.push(t.filter),t.html&&c.push(t.html))}}if(t.shadowEnabled){const e=function(t,e){if(1===e){return t}const o=b.Util.colorToRGBA(t);return o?`rgba(${o.r}, ${o.g}, ${o.b}, ${o.a*e})`:t}(t.shadowColor,null!==(n=t.shadowOpacity)&&void 0!==n?n:1);d.push(`drop-shadow(${t.shadowOffsetX}px ${t.shadowOffsetY}px ${t.shadowBlur/2}px ${e})`)}const g=h("div",{id:t.id,style:{position:"absolute",left:t.x+"px",top:t.y+"px",width:t.width+"px",height:t.height+"px",transform:`rotate(${t.rotation}deg)`,transformOrigin:"top left",opacity:t.opacity,display:t.visible&&t.showInExport?"block":"none",filter:d.join(" ")||"none"}},l,...c);return i&&i({dom:g,element:t})||g}export async function jsonToDOM({json:t,elementHook:i}){const n=await Promise.all(t.pages.map(n=>async function({page:t,store:i,elementHook:n}){const r=await Promise.all(t.children.map(e=>z({element:e,page:t,store:i,elementHook:n}))),s="auto"===t.width?i.width:t.width,a="auto"===t.height?i.height:t.height;let l={};if(t.background.indexOf("url")>=0||t.background.indexOf("http")>=0||t.background.indexOf(".jpg")>=0||t.background.indexOf(".png")>=0||t.background.indexOf(".jpeg")>=0){const{width:n,height:l}=await o(t.background),d=await j({element:Object.assign({x:0,y:0,width:s,height:a,src:t.background,cornerRadius:0},e({width:s,height:a},{width:n,height:l})),page:t,store:i});r.unshift(d)}else{l=u.isGradient(t.background)?Object.assign(Object.assign({},l),{backgroundImage:t.background}):Object.assign(Object.assign({},l),{backgroundColor:t.background})}return h("div",{className:"page",id:t.id,style:Object.assign(Object.assign({},l),{width:s+"px",height:a+"px",overflow:"hidden",position:"relative"})},...r)}({page:n,store:t,elementHook:i}))),r=[];c({children:t.pages},t=>{"text"!==t.type&&"tablecell"!==t.type&&"table"!==t.type||!t.fontFamily||-1!==r.indexOf(t.fontFamily)||r.push(t.fontFamily)});const s=r.map(e=>{const o=t.fonts.find(t=>t.fontFamily===e);if(o){const t=(o.styles||(o.url?[{src:`url("${o.url}")`}]:[])).map(t=>`\n @font-face {\n font-family: '${o.fontFamily}';\n src: ${t.src};\n font-style: ${t.fontStyle||"normal"};\n font-weight: ${t.fontWeight||"normal"};\n font-display: swap;\n }`).join("\n");return h("style",{},t)}return h("link",{href:d(e),rel:"stylesheet"})});return h("div",{className:"design"},...s,...n)}const H=({dom:e})=>{if("string"==typeof e){return e}if(!e){return""}const o=e.props,{innerHTML:i}=o,n=t(o,["innerHTML"]),r=Object.keys(n).map(t=>"style"===t&&"object"==typeof n[t]?`style="${Object.keys(n[t]).filter(e=>null!=n[t][e]).map(e=>`${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}: ${n[t][e]}`).join("; ")}"`:((t,e)=>null==e||""===e?"":"object"==typeof e?`${t}="${Object.keys(e).map(t=>`${t.replace(/-([a-z])/g,t=>t[1].toUpperCase())}:${e[t]};`).join(" ")}"`:`${t}="${e}"`)(t,n[t])).filter(t=>t&&t.trim().length>0).join(" ");return`<${e.type} ${r}>${i||e.children.map(t=>H({dom:t})).join("")}</${e.type}>`};export async function jsonToHTML({json:t,elementHook:e}){const o=await jsonToDOM({json:t,elementHook:e});return H({dom:o})}
|
package/utils/to-svg.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var t=this&&this.__rest||function(t,e){var i={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(i[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(t);n<o.length;n++){e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(i[o[n]]=t[o[n]])}}return i};import{cropImage as e,getCrop as i,loadImage as o}from"./image.js";import*as n from"./svg.js";import{figureToSvg as r}from"./figure-to-svg.js";import{Effects as l,shapeFilterToCSS as s}from"./filters.js";import{removeTags as a,parseHtmlToSegments as h}from"./text.js";import{segmentsToTspans as c}from"./text-html.js";import{getCurvePath as d}from"../canvas/text-element.js";import*as g from"./gradient.js";import{generateBackgroundShapeFromRects as f,textLinesToRects as p}from"./background-shape.js";export const forEveryNode=(t,e)=>{if(t.children){for(const i of t.children){if(!0===e(i)){break}forEveryNode(i,e)}}if(t.cells){for(const i of t.cells){if(!0===e(i)){break}}}};const u=(t,e,...i)=>({type:t,props:e,children:i||[]});function m(t,e){if(!g.isGradient(t)){return null}const{stops:i,rotation:o}=g.parseColor(t),n=o*Math.PI/180,r=.5-.5*Math.sin(n),l=.5+.5*Math.cos(n),s=.5+.5*Math.sin(n),a=.5-.5*Math.cos(n),h=i.map(({offset:t,color:e})=>u("stop",{offset:100*t+"%","stop-color":e}));return u("linearGradient",{id:e,x1:100*r+"%",y1:100*l+"%",x2:100*s+"%",y2:100*a+"%"},...h)}export function fixRatio(t){var e=(new DOMParser).parseFromString(t,"image/svg+xml");return e.documentElement.setAttribute("preserveAspectRatio","none"),(new XMLSerializer).serializeToString(e)}const y=async t=>{try{const e=await fetch(t);if("undefined"!=typeof Buffer){const t=await e.arrayBuffer(),i=Buffer.from(t).toString("base64");return`data:${e.headers.get("content-type")||"image/png"};base64,${i}`}{const t=await e.blob();return new Promise((e,i)=>{const o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=i,o.readAsDataURL(t)})}}catch(e){return console.error("Error converting URL to data URL:",e),t}},w=async({element:t,page:e,store:i})=>{let{src:r}=t;if("svg"===t.type){const e=await n.urlToString(r);r=n.replaceColors(e,new Map(Object.entries(t.colorsReplace)))}else{r=await y(r)}let l,s,a,h,c="";if(t.flipX||t.flipY){const e=t.flipX?-1:1,i=t.flipY?-1:1,o=t.width/2,n=t.height/2;c=`translate(${o}, ${n}) scale(${e}, ${i}) translate(${-o}, ${-n})`}t.clipSrc&&(l=`clip-img-mask-${t.id}`,s=await y(t.clipSrc)),t.maskSrc&&(a=`mask-img-${t.id}`,h=await y(t.maskSrc));const d=await o(r),f=d.width*t.cropWidth,p=d.height*t.cropHeight,w=t.width/t.height;let x,k;const b=f/p,$="boolean"==typeof t.stretchEnabled&&t.stretchEnabled||"svg"===t.type;$?(x=f,k=p):w>=b?(x=f,k=f/w):(x=p*w,k=p);const v=x/d.width,j=k/d.height,S=x/k>t.width/t.height?t.height/k:t.width/x,O=$?t.width/x:S,H=$?t.height/k:S,W=x*O/v,M=k*H/j;let E=t.cropX*d.width*O,P=t.cropY*d.height*H;t.flipX&&(E=(1-t.cropX-t.cropWidth)*d.width*O),t.flipY&&(P=(1-t.cropY-t.cropHeight)*d.height*H);const R=`clip-${t.id}`,T=t.cornerRadius||0,z=r.replace(/&/g,"&"),C={x:-E,y:-P,width:W,height:M,preserveAspectRatio:"none","clip-path":`url(#${R})`},L=[u("clipPath",{id:R},u("rect",{x:0,y:0,width:t.width,height:t.height,rx:T||void 0,ry:T||void 0}))];l&&s&&L.push(u("mask",{id:l,maskUnits:"userSpaceOnUse","mask-type":"alpha"},u("image",{href:s.replace(/&/g,"&"),x:0,y:0,width:t.width,height:t.height,preserveAspectRatio:"none"}))),a&&L.push(u("mask",{id:a,maskUnits:"userSpaceOnUse","mask-type":"alpha"},u("image",Object.assign({href:z},C))));let F=z;const B={};a&&h&&(F=h.replace(/&/g,"&"),B.mask=`url(#${a})`);const A={};l&&(A.mask=`url(#${l})`);const U=t.borderSize||0,D=U>0&&g.isGradient(t.borderColor),G=D?`border-grad-${t.id}`:null;if(D){const e=m(t.borderColor,G);e&&L.push(e)}const N=U>0?u("rect",{x:U/2,y:U/2,width:Math.max(0,t.width-U),height:Math.max(0,t.height-U),fill:"none",stroke:D?`url(#${G})`:t.borderColor,"stroke-width":U,rx:Math.max(0,T-U)||void 0,ry:Math.max(0,T-U)||void 0}):null,X=u("g",{},u("defs",{},...L),u("image",Object.assign(Object.assign({href:F},C),B)),N);return u("g",A,c?u("g",{transform:c},X):X)},x=({element:t,type:e})=>{const i={"stroke-width":t.height,stroke:t.color,"stroke-linecap":"round","stroke-linejoin":"round"},o=Object.assign(Object.assign({},i),{fill:t.color}),n=Object.assign(Object.assign({},i),{fill:"none"});return"arrow"===e?u("polyline",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},n)):"triangle"===e?u("polygon",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},o)):"bar"===e?u("polyline",Object.assign({points:`0,${2*-t.height} 0,${2*t.height}`},n)):"circle"===e?u("circle",Object.assign({cx:2*t.height,cy:0,r:2*t.height},o)):"square"===e?u("polygon",Object.assign({points:`0,${2*-t.height} ${4*t.height},${2*-t.height} ${4*t.height},${2*t.height} 0,${2*t.height}`},o)):null},k={image:w,svg:w,text:async({element:t,page:e,store:i})=>{const o=g.isGradient(t.fill),n=g.isGradient(t.stroke);if(t.curveEnabled){const e=d(t.width,t.height,t.curvePower,t.fontSize),i=`curve-path-${t.id}`,r=(a(t.text).replace(/\n/g," "),h(t.text)),l={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black"},s=c(r,l),g=c(r,l,{omitColors:!0}),f=t.backgroundPadding*(t.fontSize*t.lineHeight*.5),p=t.backgroundEnabled?u("rect",{x:-f,y:-f,width:t.width+2*f,height:t.height+2*f,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5),ry:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)}):null,y=[u("path",{id:i,d:e,fill:"none"})],w=t.strokeWidth&&(n||o&&!n);if(o){const e=`curve-fill-grad-${t.id}`,i=m(t.fill,e);i&&y.push(i)}if(n&&t.strokeWidth){const e=`curve-stroke-grad-${t.id}`,i=m(t.stroke,e);i&&y.push(i)}if(w){const e={"font-size":t.fontSize+"px","text-anchor":"middle","dominant-baseline":"central","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration||void 0,"letter-spacing":t.letterSpacing*t.fontSize+"px"},r=n?`url(#curve-stroke-grad-${t.id})`:t.stroke,l=u("text",Object.assign(Object.assign({},e),{fill:r,"stroke-width":t.strokeWidth,stroke:r}),u("textPath",{href:`#${i}`,startOffset:"50%",innerHTML:g})),a=o?`url(#curve-fill-grad-${t.id})`:t.fill,h=u("text",Object.assign(Object.assign({},e),{fill:a}),u("textPath",{href:`#${i}`,startOffset:"50%",innerHTML:s}));return u("g",{},p,u("defs",{},...y),l,h)}return u("g",{},p,u("defs",{},...y),u("text",{fill:o?`url(#curve-fill-grad-${t.id})`:t.fill,"font-size":t.fontSize+"px","text-anchor":"middle","dominant-baseline":"central","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration||void 0,"letter-spacing":t.letterSpacing*t.fontSize+"px","stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?n?`url(#curve-stroke-grad-${t.id})`:t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0},u("textPath",{href:`#${i}`,startOffset:"50%",innerHTML:s})))}const r=(t,e,i,o,n,r=0)=>{const l=document.createElement("canvas").getContext("2d");return l.font=`${n} ${o} ${e}px ${i}`,l.measureText(t).width+Math.max(0,(t?t.length:0)-1)*r*e},l=(t,e,i,o,n,l,s=0)=>{const a=[];return t.split("\n").forEach(t=>{const h=t.split(" ");let c="";for(let d=0;d<h.length;d++){const t=c+h[d]+" ";r(t,i,o,n,l,s)>e+.5&&d>0?(a.push(c.trim()),c=h[d]+" "):c=t}a.push(c.trim())}),a};let s=a(t.text);"uppercase"==t.textTransform&&(s=s.toUpperCase());let y=t.fontSize,w=[];for(;;){w=l(s,t.width,y,t.fontFamily,t.fontWeight,t.fontStyle,t.letterSpacing);const e=Math.max(...w.map(e=>r(e,y,t.fontFamily,t.fontWeight,t.fontStyle,t.letterSpacing))),i=w.length*y*t.lineHeight;if(e<=t.width&&i<=t.height){break}if(y-=1,y<4){break}}const x=y*t.lineHeight,k=w.length*x;let b=y;"middle"===t.verticalAlign?b=(t.height-k)/2+y:"bottom"===t.verticalAlign&&(b=t.height-k+y);const $="center"===t.align?"middle":"right"===t.align?"end":"start",v=w.map((e,i)=>u("tspan",{x:"center"===t.align?t.width/2:"right"===t.align?t.width:0,dy:0===i?0:x,innerHTML:""===e?"":e})),j=t.backgroundPadding*(y*t.lineHeight*.5),S=t.backgroundCornerRadius*(y*t.lineHeight*.5);let O=null;if(t.backgroundEnabled){if(t.legacyBackground){O=u("rect",{x:-j,y:-j,width:t.width+2*j,height:t.height+2*j,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:S,ry:S})}else{const e=p({lines:w.map(e=>({width:""===e?0:r(e,y,t.fontFamily,t.fontWeight,t.fontStyle,t.letterSpacing)})),lineHeight:x,width:t.width,align:"justify"===t.align?"justify":t.align});let i=0;"middle"===t.verticalAlign?i=(t.height-w.length*x)/2:"bottom"===t.verticalAlign&&(i=t.height-w.length*x);const o=f({rects:e,padding:j,cornerRadius:S});o&&(O=u("path",{d:o,fill:t.backgroundColor,opacity:t.backgroundOpacity,transform:i?`translate(0,${i})`:void 0}))}}const H=[],W=t.strokeWidth&&(n||o&&!n);if(o){const e=`text-fill-grad-${t.id}`,i=m(t.fill,e);i&&H.push(i)}if(n&&t.strokeWidth){const e=`text-stroke-grad-${t.id}`,i=m(t.stroke,e);i&&H.push(i)}if(W){const e={y:b,"font-size":y+"px","text-anchor":$,"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"line-height":t.lineHeight,"letter-spacing":t.letterSpacing*y+"px"},i=n?`url(#text-stroke-grad-${t.id})`:t.stroke,r=u("text",Object.assign(Object.assign({},e),{fill:i,"stroke-width":t.strokeWidth,stroke:i}),...v.map(t=>u("tspan",t.props,t.props.innerHTML))),l=o?`url(#text-fill-grad-${t.id})`:t.fill,s=u("text",Object.assign(Object.assign({},e),{fill:l}),...v.map(t=>u("tspan",t.props,t.props.innerHTML)));return u("g",{},O,H.length>0?u("defs",{},...H):null,r,s)}return u("g",{},O,H.length>0?u("defs",{},...H):null,u("text",{fill:o?`url(#text-fill-grad-${t.id})`:t.fill,y:b,"font-size":y+"px","text-anchor":$,"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"line-height":t.lineHeight,"letter-spacing":t.letterSpacing*y+"px","stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0},...v))},line:async({element:t,page:e,store:i})=>u("g",{},u("line",{x1:0,y1:t.height/2,x2:t.width,y2:t.height/2,stroke:t.color,"stroke-width":t.height,"stroke-dasharray":t.dash&&t.dash.length?t.dash.map(e=>e*t.height).join(" "):void 0}),u("g",{transform:`translate(0 ${t.height/2})`},x({element:t,type:t.startHead})),u("g",{transform:`translate(${t.width} ${t.height/2}) rotate(180)`},x({element:t,type:t.endHead}))),figure:async({element:t,page:e,store:i,elementHook:o})=>{let n=function(t){let e=t.replace(/<svg[^>]*>/,"");return e=e.replace(/<\/svg>/,""),e}(r(t));const l=[];if(t.strokeWidth&&g.isGradient(t.stroke)){const e=`figure-stroke-grad-${t.id}`,i=m(t.stroke,e);if(i){l.push(i);const o=t.stroke.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`stroke="${o}"`,"g"),`stroke="url(#${e})"`)}}if(g.isGradient(t.fill)){const e=`figure-fill-grad-${t.id}`,i=m(t.fill,e);if(i){l.push(i);const o=t.fill.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`fill="${o}"`,"g"),`fill="url(#${e})"`)}}if(l.length>0){const e=u("g",{},u("defs",{},...l),u("g",{innerHTML:n}));return o&&o({dom:e,element:t})||e}const s=u("g",{innerHTML:n});return o&&o({dom:s,element:t})||s},group:async({element:t,page:e,store:i,elementHook:o})=>{const n=await Promise.all(t.children.map(t=>b({element:t,page:e,store:i,elementHook:o}))),r=u("g",{style:{"transform-origin":"top left"}},...n);return o&&o({dom:r,element:t})||r},gif:w,table:async({element:t})=>{t.rows;const e=t.cols,i=t.colWidths,o=t.rowHeights,n=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],r=(t.cells||[]).map((i,o)=>{const r=Object.assign(Object.assign({},i),{row:Math.floor(o/e),col:o%e});for(const e of n){void 0===r[e]&&(r[e]=t[e])}return r}),l=[],s=(e,n,r,l)=>{let s=0;for(let o=0;o<n;o++){s+=i[o]*t.width}let a=0;for(let i=0;i<e;i++){a+=o[i]*t.height}let h=0;for(let o=n;o<n+l;o++){h+=(i[o]||0)*t.width}let c=0;for(let i=e;i<e+r;i++){c+=(o[i]||0)*t.height}return{x:s,y:a,width:h,height:c}};for(const a of r){if(!a.mergedInto&&a.cellBackground&&"transparent"!==a.cellBackground){s(a.row,a.col,a.colSpan||1,a.colSpan||1);const{x:t,y:e,width:i,height:o}=s(a.row,a.col,a.rowSpan||1,a.colSpan||1);l.push(u("rect",{x:t,y:e,width:i,height:o,fill:a.cellBackground}))}}const h=(t,e)=>"dashed"===t?`${4*e},${2*e}`:"dotted"===t?`${e},${e}`:void 0,c=(e,i)=>{var o,n,r,l,s;const a=null===(o=e.borders)||void 0===o?void 0:o[i];return{width:null!==(n=null==a?void 0:a.width)&&void 0!==n?n:t.borderWidth,style:null!==(l=null!==(r=null==a?void 0:a.style)&&void 0!==r?r:t.borderStyle)&&void 0!==l?l:"solid",color:null!==(s=null==a?void 0:a.color)&&void 0!==s?s:t.borderColor}};for(const a of r){if(a.mergedInto){continue}const t=s(a.row,a.col,a.rowSpan||1,a.colSpan||1);if(0===a.row){const e=c(a,"top");"none"!==e.style&&e.width>0&&l.push(u("line",{x1:t.x,y1:t.y+e.width/2,x2:t.x+t.width,y2:t.y+e.width/2,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}if(0===a.col){const e=c(a,"left");"none"!==e.style&&e.width>0&&l.push(u("line",{x1:t.x+e.width/2,y1:t.y,x2:t.x+e.width/2,y2:t.y+t.height,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}{const e=c(a,"bottom");"none"!==e.style&&e.width>0&&l.push(u("line",{x1:t.x,y1:t.y+t.height-e.width/2,x2:t.x+t.width,y2:t.y+t.height-e.width/2,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}{const e=c(a,"right");"none"!==e.style&&e.width>0&&l.push(u("line",{x1:t.x+t.width-e.width/2,y1:t.y,x2:t.x+t.width-e.width/2,y2:t.y+t.height,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}}for(const d of r){if(d.mergedInto){continue}let e=a(d.text||"");if(!e){continue}"uppercase"===d.textTransform&&(e=e.toUpperCase());const n=d.cellPadding||4;let r=0;for(let o=0;o<d.col;o++){r+=i[o]*t.width}let s=0;for(let i=0;i<d.row;i++){s+=o[i]*t.height}const h=i[d.col]*t.width,c=o[d.row]*t.height,g=d.fontSize||12,f=d.align||"left";let p=r+n,m="start";"center"===f?(p=r+h/2,m="middle"):"right"===f&&(p=r+h-n,m="end");let y=s+n+g;const w=d.verticalAlign||"top";"middle"===w?y=s+c/2+g/3:"bottom"===w&&(y=s+c-n),l.push(u("text",{x:p,y,"font-size":g,"font-family":d.fontFamily||"Roboto","font-weight":d.fontWeight||"normal","font-style":d.fontStyle||"normal",fill:d.fill||"black","text-anchor":m,"text-decoration":d.textDecoration||"none","letter-spacing":d.letterSpacing?d.letterSpacing*g+"px":void 0},e))}return u("g",{},...l)}};async function b({element:t,page:e,store:i,elementHook:o}){var n;let r=await k[t.type];r||(r=()=>u("g",{}),console.error(`SVG export does not support ${t.type} type...`));const a=await r({element:t,page:e,store:i}),h=[],c=[];if(t.blurEnabled&&h.push(`blur(${t.blurRadius/2}px)`),t.brightnessEnabled&&h.push(`brightness(${100*t.brightness+100}%)`),t.sepiaEnabled&&h.push("sepia()"),t.grayscaleEnabled&&h.push("grayscale()"),t.shadowEnabled&&h.push(`drop-shadow(${t.shadowOffsetX}px ${t.shadowOffsetY}px ${t.shadowBlur}px ${t.shadowColor})`),t.filters){for(const[g,f]of Object.entries(t.filters)){const t=s(l[g],f.intensity);if(t&&(h.push(t.filter),t.html)){const e=t.html.replace(/<svg([^>]*)>/,"<g$1>").replace(/<\/svg>/,"</g>");c.push(e)}}}const d=u("g",{className:"element",id:t.id,transform:"group"!==t.type?`translate(${t.x}, ${t.y}) rotate(${t.rotation})`:void 0,display:null===(n=t.visible)||void 0===n||n?void 0:"none",opacity:t.opacity,style:{"transform-origin":"top left",filter:h.join(" ")}},a,...c);return o&&o({dom:d,element:t})||d}async function $(t){try{const e=await fetch(t),i=e.headers.get("content-type")||"font/ttf",o=await e.arrayBuffer();return`data:${i};base64,${"undefined"!=typeof Buffer?Buffer.from(o).toString("base64"):function(t){const e=new Uint8Array(t);let i="";for(let o=0;o<e.length;o+=32768){const t=e.subarray(o,o+32768);i+=String.fromCharCode(...t)}if("undefined"!=typeof btoa){return btoa(i)}if("undefined"!=typeof Buffer){return Buffer.from(e).toString("base64")}throw new Error("No base64 encoder available in this environment")}(o)}`}catch(e){return console.error("Error embedding font:",e),t}}export async function jsonToDOM({json:t,elementHook:n,fontEmbedding:r="inline"}){const l=[];forEveryNode({children:t.pages},t=>{"text"!==t.type&&"tablecell"!==t.type&&"table"!==t.type||!t.fontFamily||-1!==l.indexOf(t.fontFamily)||l.push(t.fontFamily)});const s="inline"===r?await async function(t,e){return await Promise.all(t.map(async t=>{var i,o;if("Arial"===t){return null}const n=e.find(e=>e.fontFamily===t);if(n){const e=await $(n.url);return u("style",{},`@font-face { font-family: ${t}; src: url(${e}); }`)}{const e=`https://fonts.googleapis.com/css?family=${t}:bi,normal,i,b`;try{const n=await fetch(e),r=await n.text(),l=null===(o=null===(i=r.match(/url\((.*?)\)/g))||void 0===i?void 0:i.map(t=>t.replace(/url\((.*?)\)/,"$1")))||void 0===o?void 0:o.filter(t=>t.startsWith("https"));if(!(null==l?void 0:l.length)){throw new Error("No font URLs found")}const s=await Promise.all(l.map(async e=>{const i=await $(e),o=r.match(/font-style:\s*(.*?);/),n=r.match(/font-weight:\s*(.*?);/),l=o?o[1]:"normal",s=n?n[1]:"normal";return`@font-face {\n font-family: ${t};\n font-style: ${l};\n font-weight: ${s};\n src: url(${i});\n }`}));return u("style",{},s.join("\n"))}catch(r){return console.error("Error embedding Google Font:",r),u("defs",{},u("style",{type:"text/css",innerHTML:`@import url('${e}');`.replace(/&/g,"&")}))}}}))}(l,t.fonts):[],a=await Promise.all(t.pages.map(r=>async function({page:t,store:n,elementHook:r}){const l=await Promise.all(t.children.map(e=>b({element:e,page:t,store:n,elementHook:r}))),s=t.background.indexOf("url")>=0||t.background.indexOf("http")>=0||t.background.indexOf(".jpg")>=0||t.background.indexOf(".png")>=0||t.background.indexOf(".jpeg")>=0;let a;if(s){const r=await o(t.background);a=await e(t.background,Object.assign({width:n.width,height:n.height,x:0,y:0},i({width:n.width,height:n.height},{width:r.width,height:r.height})))}return u("g",{className:"page",style:{}},s?u("image",{"xlink:href":a,x:0,y:0,width:n.width,height:n.height,preserveAspectRatio:"none"}):u("rect",{x:0,y:0,width:n.width,height:n.height,fill:s?void 0:t.background}),...l)}({page:r,store:t,elementHook:n})));return u("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",viewBox:`0 0 ${t.width} ${t.height}`,width:t.width,height:t.height},...s,...a)}const v=({dom:e,nestLevel:i=0})=>{if("string"==typeof e){return e}if(!e){return""}const o=e.props,{innerHTML:n}=o,r=t(o,["innerHTML"]),l=Object.keys(r).map(t=>((t,e)=>"object"==typeof e?`${t}="${Object.keys(e).map(t=>`${t}:${e[t]};`).join(" ")}"`:null==e||""===e?"":`${t}="${e}"`)(t,r[t])).filter(t=>t&&t.trim().length>0).join(" "),s=" ".repeat(i);return`${s}<${e.type}${l?" "+l:""}>${n||"\n"+e.children.map(t=>v({dom:t,nestLevel:i+1})).join("")}${s}</${e.type}>\n`};export async function jsonToSVG({json:t,elementHook:e,fontEmbedding:i="inline"}){const o=await jsonToDOM({json:t,elementHook:e,fontEmbedding:i});return v({dom:o})}
|
|
1
|
+
var t=this&&this.__rest||function(t,e){var i={};for(var o in t){Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(i[o]=t[o])}if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(t);n<o.length;n++){e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(t,o[n])&&(i[o[n]]=t[o[n]])}}return i};import{cropImage as e,getCrop as i,loadImage as o}from"./image.js";import*as n from"./svg.js";import{figureToSvg as r}from"./figure-to-svg.js";import{Effects as l,shapeFilterToCSS as s}from"./filters.js";import{removeTags as a,parseHtmlToSegments as h}from"./text.js";import{segmentsToTspans as c}from"./text-html.js";import{xmlEscape as d}from"./xml.js";import{getCurvePath as g}from"../canvas/text-element.js";import*as f from"./gradient.js";import{generateBackgroundShapeFromRects as p,textLinesToRects as u}from"./background-shape.js";export const forEveryNode=(t,e)=>{if(t.children){for(const i of t.children){if(!0===e(i)){break}forEveryNode(i,e)}}if(t.cells){for(const i of t.cells){if(!0===e(i)){break}}}};const m=(t,e,...i)=>({type:t,props:e,children:i||[]});function y(t,e){if(!f.isGradient(t)){return null}const{stops:i,rotation:o}=f.parseColor(t),n=o*Math.PI/180,r=.5-.5*Math.sin(n),l=.5+.5*Math.cos(n),s=.5+.5*Math.sin(n),a=.5-.5*Math.cos(n),h=i.map(({offset:t,color:e})=>m("stop",{offset:100*t+"%","stop-color":e}));return m("linearGradient",{id:e,x1:100*r+"%",y1:100*l+"%",x2:100*s+"%",y2:100*a+"%"},...h)}export function fixRatio(t){var e=(new DOMParser).parseFromString(t,"image/svg+xml");return e.documentElement.setAttribute("preserveAspectRatio","none"),(new XMLSerializer).serializeToString(e)}const w=async t=>{try{const e=await fetch(t);if("undefined"!=typeof Buffer){const t=await e.arrayBuffer(),i=Buffer.from(t).toString("base64");return`data:${e.headers.get("content-type")||"image/png"};base64,${i}`}{const t=await e.blob();return new Promise((e,i)=>{const o=new FileReader;o.onloadend=()=>e(o.result),o.onerror=i,o.readAsDataURL(t)})}}catch(e){return console.error("Error converting URL to data URL:",e),t}},x=async({element:t,page:e,store:i})=>{let{src:r}=t;if("svg"===t.type){const e=await n.urlToString(r);r=n.replaceColors(e,new Map(Object.entries(t.colorsReplace)))}else{r=await w(r)}let l,s,a,h,c="";if(t.flipX||t.flipY){const e=t.flipX?-1:1,i=t.flipY?-1:1,o=t.width/2,n=t.height/2;c=`translate(${o}, ${n}) scale(${e}, ${i}) translate(${-o}, ${-n})`}t.clipSrc&&(l=`clip-img-mask-${t.id}`,s=await w(t.clipSrc)),t.maskSrc&&(a=`mask-img-${t.id}`,h=await w(t.maskSrc));const d=await o(r),g=d.width*t.cropWidth,p=d.height*t.cropHeight,u=t.width/t.height;let x,k;const b=g/p,$="boolean"==typeof t.stretchEnabled&&t.stretchEnabled||"svg"===t.type;$?(x=g,k=p):u>=b?(x=g,k=g/u):(x=p*u,k=p);const v=x/d.width,j=k/d.height,S=x/k>t.width/t.height?t.height/k:t.width/x,O=$?t.width/x:S,H=$?t.height/k:S,W=x*O/v,M=k*H/j;let E=t.cropX*d.width*O,P=t.cropY*d.height*H;t.flipX&&(E=(1-t.cropX-t.cropWidth)*d.width*O),t.flipY&&(P=(1-t.cropY-t.cropHeight)*d.height*H);const R=`clip-${t.id}`,T=t.cornerRadius||0,z=r.replace(/&/g,"&"),C={x:-E,y:-P,width:W,height:M,preserveAspectRatio:"none","clip-path":`url(#${R})`},L=[m("clipPath",{id:R},m("rect",{x:0,y:0,width:t.width,height:t.height,rx:T||void 0,ry:T||void 0}))];l&&s&&L.push(m("mask",{id:l,maskUnits:"userSpaceOnUse","mask-type":"alpha"},m("image",{href:s.replace(/&/g,"&"),x:0,y:0,width:t.width,height:t.height,preserveAspectRatio:"none"}))),a&&L.push(m("mask",{id:a,maskUnits:"userSpaceOnUse","mask-type":"alpha"},m("image",Object.assign({href:z},C))));let F=z;const B={};a&&h&&(F=h.replace(/&/g,"&"),B.mask=`url(#${a})`);const A={};l&&(A.mask=`url(#${l})`);const U=t.borderSize||0,D=U>0&&f.isGradient(t.borderColor),G=D?`border-grad-${t.id}`:null;if(D){const e=y(t.borderColor,G);e&&L.push(e)}const N=U>0?m("rect",{x:U/2,y:U/2,width:Math.max(0,t.width-U),height:Math.max(0,t.height-U),fill:"none",stroke:D?`url(#${G})`:t.borderColor,"stroke-width":U,rx:Math.max(0,T-U)||void 0,ry:Math.max(0,T-U)||void 0}):null,X=m("g",{},m("defs",{},...L),m("image",Object.assign(Object.assign({href:F},C),B)),N);return m("g",A,c?m("g",{transform:c},X):X)},k=({element:t,type:e})=>{const i={"stroke-width":t.height,stroke:t.color,"stroke-linecap":"round","stroke-linejoin":"round"},o=Object.assign(Object.assign({},i),{fill:t.color}),n=Object.assign(Object.assign({},i),{fill:"none"});return"arrow"===e?m("polyline",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},n)):"triangle"===e?m("polygon",Object.assign({points:`${3*t.height},${2*-t.height} 0,0 ${3*t.height},${2*t.height}`},o)):"bar"===e?m("polyline",Object.assign({points:`0,${2*-t.height} 0,${2*t.height}`},n)):"circle"===e?m("circle",Object.assign({cx:2*t.height,cy:0,r:2*t.height},o)):"square"===e?m("polygon",Object.assign({points:`0,${2*-t.height} ${4*t.height},${2*-t.height} ${4*t.height},${2*t.height} 0,${2*t.height}`},o)):null},b={image:x,svg:x,text:async({element:t,page:e,store:i})=>{const o=f.isGradient(t.fill),n=f.isGradient(t.stroke);if(t.curveEnabled){const e=g(t.width,t.height,t.curvePower,t.fontSize),i=`curve-path-${t.id}`,r=(a(t.text).replace(/\n/g," "),h(t.text)),l={fontWeight:t.fontWeight||"normal",fontStyle:t.fontStyle||"normal",fill:t.fill||"black"},s=c(r,l),d=c(r,l,{omitColors:!0}),f=t.backgroundPadding*(t.fontSize*t.lineHeight*.5),p=t.backgroundEnabled?m("rect",{x:-f,y:-f,width:t.width+2*f,height:t.height+2*f,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5),ry:t.backgroundCornerRadius*(t.fontSize*t.lineHeight*.5)}):null,u=[m("path",{id:i,d:e,fill:"none"})],w=t.strokeWidth&&(n||o&&!n);if(o){const e=`curve-fill-grad-${t.id}`,i=y(t.fill,e);i&&u.push(i)}if(n&&t.strokeWidth){const e=`curve-stroke-grad-${t.id}`,i=y(t.stroke,e);i&&u.push(i)}if(w){const e={"font-size":t.fontSize+"px","text-anchor":"middle","dominant-baseline":"central","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration||void 0,"letter-spacing":t.letterSpacing*t.fontSize+"px"},r=n?`url(#curve-stroke-grad-${t.id})`:t.stroke,l=m("text",Object.assign(Object.assign({},e),{fill:r,"stroke-width":t.strokeWidth,stroke:r}),m("textPath",{href:`#${i}`,startOffset:"50%",innerHTML:d})),a=o?`url(#curve-fill-grad-${t.id})`:t.fill,h=m("text",Object.assign(Object.assign({},e),{fill:a}),m("textPath",{href:`#${i}`,startOffset:"50%",innerHTML:s}));return m("g",{},p,m("defs",{},...u),l,h)}return m("g",{},p,m("defs",{},...u),m("text",{fill:o?`url(#curve-fill-grad-${t.id})`:t.fill,"font-size":t.fontSize+"px","text-anchor":"middle","dominant-baseline":"central","font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration||void 0,"letter-spacing":t.letterSpacing*t.fontSize+"px","stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?n?`url(#curve-stroke-grad-${t.id})`:t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0},m("textPath",{href:`#${i}`,startOffset:"50%",innerHTML:s})))}const r=(t,e,i,o,n,r=0)=>{const l=document.createElement("canvas").getContext("2d");return l.font=`${n} ${o} ${e}px ${i}`,l.measureText(t).width+Math.max(0,(t?t.length:0)-1)*r*e},l=(t,e,i,o,n,l,s=0)=>{const a=[];return t.split("\n").forEach(t=>{const h=t.split(" ");let c="";for(let d=0;d<h.length;d++){const t=c+h[d]+" ";r(t,i,o,n,l,s)>e+.5&&d>0?(a.push(c.trim()),c=h[d]+" "):c=t}a.push(c.trim())}),a};let s=a(t.text);"uppercase"==t.textTransform&&(s=s.toUpperCase());let w=t.fontSize,x=[];for(;;){x=l(s,t.width,w,t.fontFamily,t.fontWeight,t.fontStyle,t.letterSpacing);const e=Math.max(...x.map(e=>r(e,w,t.fontFamily,t.fontWeight,t.fontStyle,t.letterSpacing))),i=x.length*w*t.lineHeight;if(e<=t.width&&i<=t.height){break}if(w-=1,w<4){break}}const k=w*t.lineHeight,b=x.length*k;let $=w;"middle"===t.verticalAlign?$=(t.height-b)/2+w:"bottom"===t.verticalAlign&&($=t.height-b+w);const v="center"===t.align?"middle":"right"===t.align?"end":"start",j=x.map((e,i)=>m("tspan",{x:"center"===t.align?t.width/2:"right"===t.align?t.width:0,dy:0===i?0:k,innerHTML:""===e?"":d(e)})),S=t.backgroundPadding*(w*t.lineHeight*.5),O=t.backgroundCornerRadius*(w*t.lineHeight*.5);let H=null;if(t.backgroundEnabled){if(t.legacyBackground){H=m("rect",{x:-S,y:-S,width:t.width+2*S,height:t.height+2*S,fill:t.backgroundColor,opacity:t.backgroundOpacity,rx:O,ry:O})}else{const e=u({lines:x.map(e=>({width:""===e?0:r(e,w,t.fontFamily,t.fontWeight,t.fontStyle,t.letterSpacing)})),lineHeight:k,width:t.width,align:"justify"===t.align?"justify":t.align});let i=0;"middle"===t.verticalAlign?i=(t.height-x.length*k)/2:"bottom"===t.verticalAlign&&(i=t.height-x.length*k);const o=p({rects:e,padding:S,cornerRadius:O});o&&(H=m("path",{d:o,fill:t.backgroundColor,opacity:t.backgroundOpacity,transform:i?`translate(0,${i})`:void 0}))}}const W=[],M=t.strokeWidth&&(n||o&&!n);if(o){const e=`text-fill-grad-${t.id}`,i=y(t.fill,e);i&&W.push(i)}if(n&&t.strokeWidth){const e=`text-stroke-grad-${t.id}`,i=y(t.stroke,e);i&&W.push(i)}if(M){const e={y:$,"font-size":w+"px","text-anchor":v,"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"line-height":t.lineHeight,"letter-spacing":t.letterSpacing*w+"px"},i=n?`url(#text-stroke-grad-${t.id})`:t.stroke,r=m("text",Object.assign(Object.assign({},e),{fill:i,"stroke-width":t.strokeWidth,stroke:i}),...j.map(t=>m("tspan",t.props,t.props.innerHTML))),l=o?`url(#text-fill-grad-${t.id})`:t.fill,s=m("text",Object.assign(Object.assign({},e),{fill:l}),...j.map(t=>m("tspan",t.props,t.props.innerHTML)));return m("g",{},H,W.length>0?m("defs",{},...W):null,r,s)}return m("g",{},H,W.length>0?m("defs",{},...W):null,m("text",{fill:o?`url(#text-fill-grad-${t.id})`:t.fill,y:$,"font-size":w+"px","text-anchor":v,"font-family":t.fontFamily,"font-style":t.fontStyle,"font-weight":t.fontWeight,"text-decoration":t.textDecoration,"line-height":t.lineHeight,"letter-spacing":t.letterSpacing*w+"px","stroke-width":t.strokeWidth||void 0,stroke:t.strokeWidth?t.stroke:void 0,"paint-order":t.strokeWidth?"stroke fill":void 0},...j))},line:async({element:t,page:e,store:i})=>m("g",{},m("line",{x1:0,y1:t.height/2,x2:t.width,y2:t.height/2,stroke:t.color,"stroke-width":t.height,"stroke-dasharray":t.dash&&t.dash.length?t.dash.map(e=>e*t.height).join(" "):void 0}),m("g",{transform:`translate(0 ${t.height/2})`},k({element:t,type:t.startHead})),m("g",{transform:`translate(${t.width} ${t.height/2}) rotate(180)`},k({element:t,type:t.endHead}))),figure:async({element:t,page:e,store:i,elementHook:o})=>{let n=function(t){let e=t.replace(/<svg[^>]*>/,"");return e=e.replace(/<\/svg>/,""),e}(r(t));const l=[];if(t.strokeWidth&&f.isGradient(t.stroke)){const e=`figure-stroke-grad-${t.id}`,i=y(t.stroke,e);if(i){l.push(i);const o=t.stroke.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`stroke="${o}"`,"g"),`stroke="url(#${e})"`)}}if(f.isGradient(t.fill)){const e=`figure-fill-grad-${t.id}`,i=y(t.fill,e);if(i){l.push(i);const o=t.fill.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`fill="${o}"`,"g"),`fill="url(#${e})"`)}}if(l.length>0){const e=m("g",{},m("defs",{},...l),m("g",{innerHTML:n}));return o&&o({dom:e,element:t})||e}const s=m("g",{innerHTML:n});return o&&o({dom:s,element:t})||s},group:async({element:t,page:e,store:i,elementHook:o})=>{const n=await Promise.all(t.children.map(t=>$({element:t,page:e,store:i,elementHook:o}))),r=m("g",{style:{"transform-origin":"top left"}},...n);return o&&o({dom:r,element:t})||r},gif:x,table:async({element:t})=>{t.rows;const e=t.cols,i=t.colWidths,o=t.rowHeights,n=["fontSize","fontFamily","fontWeight","fontStyle","textDecoration","textTransform","fill","align","verticalAlign","lineHeight","letterSpacing","strokeWidth","stroke","cellBackground","cellPadding"],r=(t.cells||[]).map((i,o)=>{const r=Object.assign(Object.assign({},i),{row:Math.floor(o/e),col:o%e});for(const e of n){void 0===r[e]&&(r[e]=t[e])}return r}),l=[],s=(e,n,r,l)=>{let s=0;for(let o=0;o<n;o++){s+=i[o]*t.width}let a=0;for(let i=0;i<e;i++){a+=o[i]*t.height}let h=0;for(let o=n;o<n+l;o++){h+=(i[o]||0)*t.width}let c=0;for(let i=e;i<e+r;i++){c+=(o[i]||0)*t.height}return{x:s,y:a,width:h,height:c}};for(const a of r){if(!a.mergedInto&&a.cellBackground&&"transparent"!==a.cellBackground){s(a.row,a.col,a.colSpan||1,a.colSpan||1);const{x:t,y:e,width:i,height:o}=s(a.row,a.col,a.rowSpan||1,a.colSpan||1);l.push(m("rect",{x:t,y:e,width:i,height:o,fill:a.cellBackground}))}}const h=(t,e)=>"dashed"===t?`${4*e},${2*e}`:"dotted"===t?`${e},${e}`:void 0,c=(e,i)=>{var o,n,r,l,s;const a=null===(o=e.borders)||void 0===o?void 0:o[i];return{width:null!==(n=null==a?void 0:a.width)&&void 0!==n?n:t.borderWidth,style:null!==(l=null!==(r=null==a?void 0:a.style)&&void 0!==r?r:t.borderStyle)&&void 0!==l?l:"solid",color:null!==(s=null==a?void 0:a.color)&&void 0!==s?s:t.borderColor}};for(const a of r){if(a.mergedInto){continue}const t=s(a.row,a.col,a.rowSpan||1,a.colSpan||1);if(0===a.row){const e=c(a,"top");"none"!==e.style&&e.width>0&&l.push(m("line",{x1:t.x,y1:t.y+e.width/2,x2:t.x+t.width,y2:t.y+e.width/2,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}if(0===a.col){const e=c(a,"left");"none"!==e.style&&e.width>0&&l.push(m("line",{x1:t.x+e.width/2,y1:t.y,x2:t.x+e.width/2,y2:t.y+t.height,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}{const e=c(a,"bottom");"none"!==e.style&&e.width>0&&l.push(m("line",{x1:t.x,y1:t.y+t.height-e.width/2,x2:t.x+t.width,y2:t.y+t.height-e.width/2,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}{const e=c(a,"right");"none"!==e.style&&e.width>0&&l.push(m("line",{x1:t.x+t.width-e.width/2,y1:t.y,x2:t.x+t.width-e.width/2,y2:t.y+t.height,stroke:e.color,"stroke-width":e.width,"stroke-dasharray":h(e.style,e.width)}))}}for(const g of r){if(g.mergedInto){continue}let e=a(g.text||"");if(!e){continue}"uppercase"===g.textTransform&&(e=e.toUpperCase());const n=g.cellPadding||4;let r=0;for(let o=0;o<g.col;o++){r+=i[o]*t.width}let s=0;for(let i=0;i<g.row;i++){s+=o[i]*t.height}const h=i[g.col]*t.width,c=o[g.row]*t.height,f=g.fontSize||12,p=g.align||"left";let u=r+n,y="start";"center"===p?(u=r+h/2,y="middle"):"right"===p&&(u=r+h-n,y="end");let w=s+n+f;const x=g.verticalAlign||"top";"middle"===x?w=s+c/2+f/3:"bottom"===x&&(w=s+c-n),l.push(m("text",{x:u,y:w,"font-size":f,"font-family":g.fontFamily||"Roboto","font-weight":g.fontWeight||"normal","font-style":g.fontStyle||"normal",fill:g.fill||"black","text-anchor":y,"text-decoration":g.textDecoration||"none","letter-spacing":g.letterSpacing?g.letterSpacing*f+"px":void 0},d(e)))}return m("g",{},...l)}};async function $({element:t,page:e,store:i,elementHook:o}){var n;let r=await b[t.type];r||(r=()=>m("g",{}),console.error(`SVG export does not support ${t.type} type...`));const a=await r({element:t,page:e,store:i}),h=[],c=[];if(t.blurEnabled&&h.push(`blur(${t.blurRadius/2}px)`),t.brightnessEnabled&&h.push(`brightness(${100*t.brightness+100}%)`),t.sepiaEnabled&&h.push("sepia()"),t.grayscaleEnabled&&h.push("grayscale()"),t.shadowEnabled&&h.push(`drop-shadow(${t.shadowOffsetX}px ${t.shadowOffsetY}px ${t.shadowBlur}px ${t.shadowColor})`),t.filters){for(const[g,f]of Object.entries(t.filters)){const t=s(l[g],f.intensity);if(t&&(h.push(t.filter),t.html)){const e=t.html.replace(/<svg([^>]*)>/,"<g$1>").replace(/<\/svg>/,"</g>");c.push(e)}}}const d=m("g",{className:"element",id:t.id,transform:"group"!==t.type?`translate(${t.x}, ${t.y}) rotate(${t.rotation})`:void 0,display:null===(n=t.visible)||void 0===n||n?void 0:"none",opacity:t.opacity,style:{"transform-origin":"top left",filter:h.join(" ")}},a,...c);return o&&o({dom:d,element:t})||d}async function v(t){try{const e=await fetch(t),i=e.headers.get("content-type")||"font/ttf",o=await e.arrayBuffer();return`data:${i};base64,${"undefined"!=typeof Buffer?Buffer.from(o).toString("base64"):function(t){const e=new Uint8Array(t);let i="";for(let o=0;o<e.length;o+=32768){const t=e.subarray(o,o+32768);i+=String.fromCharCode(...t)}if("undefined"!=typeof btoa){return btoa(i)}if("undefined"!=typeof Buffer){return Buffer.from(e).toString("base64")}throw new Error("No base64 encoder available in this environment")}(o)}`}catch(e){return console.error("Error embedding font:",e),t}}export async function jsonToDOM({json:t,elementHook:n,fontEmbedding:r="inline"}){const l=[];forEveryNode({children:t.pages},t=>{"text"!==t.type&&"tablecell"!==t.type&&"table"!==t.type||!t.fontFamily||-1!==l.indexOf(t.fontFamily)||l.push(t.fontFamily)});const s="inline"===r?await async function(t,e){return await Promise.all(t.map(async t=>{var i,o;if("Arial"===t){return null}const n=e.find(e=>e.fontFamily===t);if(n){const e=await v(n.url);return m("style",{},`@font-face { font-family: ${t}; src: url(${e}); }`)}{const e=`https://fonts.googleapis.com/css?family=${t}:bi,normal,i,b`;try{const n=await fetch(e),r=await n.text(),l=null===(o=null===(i=r.match(/url\((.*?)\)/g))||void 0===i?void 0:i.map(t=>t.replace(/url\((.*?)\)/,"$1")))||void 0===o?void 0:o.filter(t=>t.startsWith("https"));if(!(null==l?void 0:l.length)){throw new Error("No font URLs found")}const s=await Promise.all(l.map(async e=>{const i=await v(e),o=r.match(/font-style:\s*(.*?);/),n=r.match(/font-weight:\s*(.*?);/),l=o?o[1]:"normal",s=n?n[1]:"normal";return`@font-face {\n font-family: ${t};\n font-style: ${l};\n font-weight: ${s};\n src: url(${i});\n }`}));return m("style",{},s.join("\n"))}catch(r){return console.error("Error embedding Google Font:",r),m("defs",{},m("style",{type:"text/css",innerHTML:`@import url('${e}');`.replace(/&/g,"&")}))}}}))}(l,t.fonts):[],a=await Promise.all(t.pages.map(r=>async function({page:t,store:n,elementHook:r}){const l=await Promise.all(t.children.map(e=>$({element:e,page:t,store:n,elementHook:r}))),s=t.background.indexOf("url")>=0||t.background.indexOf("http")>=0||t.background.indexOf(".jpg")>=0||t.background.indexOf(".png")>=0||t.background.indexOf(".jpeg")>=0;let a;if(s){const r=await o(t.background);a=await e(t.background,Object.assign({width:n.width,height:n.height,x:0,y:0},i({width:n.width,height:n.height},{width:r.width,height:r.height})))}return m("g",{className:"page",style:{}},s?m("image",{"xlink:href":a,x:0,y:0,width:n.width,height:n.height,preserveAspectRatio:"none"}):m("rect",{x:0,y:0,width:n.width,height:n.height,fill:s?void 0:t.background}),...l)}({page:r,store:t,elementHook:n})));return m("svg",{xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",viewBox:`0 0 ${t.width} ${t.height}`,width:t.width,height:t.height},...s,...a)}const j=({dom:e,nestLevel:i=0})=>{if("string"==typeof e){return e}if(!e){return""}const o=e.props,{innerHTML:n}=o,r=t(o,["innerHTML"]),l=Object.keys(r).map(t=>((t,e)=>"object"==typeof e?`${t}="${Object.keys(e).map(t=>`${t}:${e[t]};`).join(" ")}"`:null==e||""===e?"":`${t}="${e}"`)(t,r[t])).filter(t=>t&&t.trim().length>0).join(" "),s=" ".repeat(i);return`${s}<${e.type}${l?" "+l:""}>${n||"\n"+e.children.map(t=>j({dom:t,nestLevel:i+1})).join("")}${s}</${e.type}>\n`};export async function jsonToSVG({json:t,elementHook:e,fontEmbedding:i="inline"}){const o=await jsonToDOM({json:t,elementHook:e,fontEmbedding:i});return j({dom:o})}
|
package/utils/validate-key.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"mobx";import{getAPI as o}from"./api.js";import{setRemoveBackgroundEnabled as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const p=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let u=fetch;export const __=e=>{u=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await u(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"2.40.
|
|
1
|
+
import*as e from"mobx";import{getAPI as o}from"./api.js";import{setRemoveBackgroundEnabled as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const p=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let u=fetch;export const __=e=>{u=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await u(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"2.40.2"})});if(e.runInAction(()=>{a.value=r.headers.get("x-api-version")||""}),!n){return console.error("Polotno API is initialized without API key. It may lead to unexpected behavior and stop working. Please create API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1}),!1}if(200!==r.status){await new Promise(e=>setTimeout(e,3e3));continue}const s=await r.json();return s.is_valid||(console.error("Polotno API key is not valid. Please get new API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1})),s.is_paid||(console.log("%cPolotno Free Version. For development usage only. https://polotno.com/","background: rgb(0, 161, 255); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{0===i.value&&(i.value=2)})),s.is_domain_valid||console.log(p,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),t(s.remove_background_enabled),s.is_paid||!1}catch(r){await new Promise(e=>setTimeout(e,3e3))}}return console.error("Can not validate Polotno API key. Please report to anton@polotno.com immediately."),!0}export async function validateKey(e,o){s=e,await isKeyPaid(e)&&!o||r()}
|
package/utils/xml.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function xmlEscape(text: string): string;
|