polotno 4.13.0 → 4.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/blueprint/side-panel/select-video.d.ts +105 -36
  2. package/canvas/apply-filters.js +1 -1
  3. package/canvas/downscale.d.ts +4 -0
  4. package/canvas/downscale.js +1 -1
  5. package/canvas/element.d.ts +1 -1
  6. package/canvas/element.js +1 -1
  7. package/canvas/figure-element.js +1 -1
  8. package/canvas/gif-element.js +1 -1
  9. package/canvas/html-element.js +1 -1
  10. package/canvas/image-element.js +1 -1
  11. package/canvas/line-element.js +1 -1
  12. package/canvas/page.js +1 -1
  13. package/canvas/paint-opacity.d.ts +12 -0
  14. package/canvas/paint-opacity.js +1 -0
  15. package/canvas/render-tag-element.js +1 -1
  16. package/canvas/rich-editor.js +11 -3
  17. package/canvas/table-element.js +1 -1
  18. package/canvas/text-element/font-specs-loader.js +1 -1
  19. package/canvas/text-element.js +1 -1
  20. package/canvas/use-filtered-source.js +1 -1
  21. package/canvas/video-element.js +1 -1
  22. package/canvas/workspace-canvas.js +1 -1
  23. package/model/audio-model.d.ts +54 -2
  24. package/model/figure-model.d.ts +65 -24
  25. package/model/gif-model.d.ts +65 -24
  26. package/model/group-model.d.ts +497 -182
  27. package/model/group-model.js +1 -1
  28. package/model/history.js +1 -1
  29. package/model/image-model.d.ts +65 -24
  30. package/model/line-model.d.ts +65 -24
  31. package/model/node-model.d.ts +65 -24
  32. package/model/node-model.js +1 -1
  33. package/model/page-model.d.ts +4369 -445
  34. package/model/page-model.js +1 -1
  35. package/model/shape-model.d.ts +65 -24
  36. package/model/store.d.ts +480 -18060
  37. package/model/store.js +1 -1
  38. package/model/svg-model.d.ts +64 -24
  39. package/model/table-model.d.ts +40 -12
  40. package/model/table-model.js +1 -1
  41. package/model/text-model.d.ts +64 -24
  42. package/model/text-model.js +1 -1
  43. package/model/video-model.d.ts +65 -24
  44. package/package.json +8 -8
  45. package/polotno.bundle.js +167 -156
  46. package/primitives/panel-header.js +1 -1
  47. package/primitives/panel-scroll-area.d.ts +4 -0
  48. package/primitives/panel-scroll-area.js +1 -0
  49. package/primitives/select.js +1 -1
  50. package/side-panel/animations-panel.js +1 -1
  51. package/side-panel/draw-panel.js +1 -1
  52. package/side-panel/effects-panel.js +1 -1
  53. package/side-panel/elements-panel.js +1 -1
  54. package/side-panel/image-clip-panel.js +1 -1
  55. package/side-panel/layers-panel.js +1 -1
  56. package/side-panel/select-video.d.ts +105 -36
  57. package/side-panel/side-panel.js +1 -1
  58. package/side-panel/size-panel.js +1 -1
  59. package/side-panel/text-panel.js +1 -1
  60. package/toolbar/color-picker.js +1 -1
  61. package/toolbar/html-toolbar.js +3 -3
  62. package/toolbar/opacity-picker.js +1 -1
  63. package/toolbar/text-toolbar.js +1 -1
  64. package/ui.css +1 -1
  65. package/utils/canvas.d.ts +0 -3
  66. package/utils/canvas.js +1 -1
  67. package/utils/clipboard.d.ts +104 -36
  68. package/utils/fonts.js +1 -1
  69. package/utils/from-svg.js +1 -1
  70. package/utils/l10n.d.ts +21 -0
  71. package/utils/l10n.js +1 -1
  72. package/utils/pointer-drag.js +1 -1
  73. package/utils/text-format-state.d.ts +3 -0
  74. package/utils/text-format-state.js +1 -1
  75. package/utils/validate-key.js +1 -1
@@ -11,6 +11,7 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
11
11
  type: import("mobx-state-tree").IType<string | undefined, string, string>;
12
12
  name: import("mobx-state-tree").IType<string | undefined, string, string>;
13
13
  opacity: import("mobx-state-tree").IType<number | undefined, number, number>;
14
+ blendMode: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<"normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light">, [undefined]>;
14
15
  custom: import("mobx-state-tree").IType<any, any, any>;
15
16
  visible: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
16
17
  selectable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
@@ -92,6 +93,7 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
92
93
  type: import("mobx-state-tree").IType<string | undefined, string, string>;
93
94
  name: import("mobx-state-tree").IType<string | undefined, string, string>;
94
95
  opacity: import("mobx-state-tree").IType<number | undefined, number, number>;
96
+ blendMode: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<"normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light">, [undefined]>;
95
97
  custom: import("mobx-state-tree").IType<any, any, any>;
96
98
  visible: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
97
99
  selectable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
@@ -103,6 +105,7 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
103
105
  type: import("mobx-state-tree").IType<string | undefined, string, string>;
104
106
  name: import("mobx-state-tree").IType<string | undefined, string, string>;
105
107
  opacity: import("mobx-state-tree").IType<number | undefined, number, number>;
108
+ blendMode: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<"normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light">, [undefined]>;
106
109
  custom: import("mobx-state-tree").IType<any, any, any>;
107
110
  visible: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
108
111
  selectable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
@@ -114,24 +117,37 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
114
117
  type: string | undefined;
115
118
  name: string | undefined;
116
119
  opacity: number | undefined;
120
+ blendMode: "normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light" | undefined;
117
121
  custom: any;
118
122
  visible: boolean | undefined;
119
123
  selectable: boolean | undefined;
120
124
  removable: boolean | undefined;
121
125
  alwaysOnTop: boolean | undefined;
122
126
  showInExport: boolean | undefined;
123
- }>, import("mobx-state-tree").ModelSnapshotType<{
124
- id: import("mobx-state-tree").ISimpleType<string>;
125
- type: import("mobx-state-tree").IType<string | undefined, string, string>;
126
- name: import("mobx-state-tree").IType<string | undefined, string, string>;
127
- opacity: import("mobx-state-tree").IType<number | undefined, number, number>;
128
- custom: import("mobx-state-tree").IType<any, any, any>;
129
- visible: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
130
- selectable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
131
- removable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
132
- alwaysOnTop: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
133
- showInExport: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
134
- }>>>;
127
+ }>, {
128
+ id: string;
129
+ type: string;
130
+ name: string;
131
+ opacity: number;
132
+ custom: any;
133
+ visible: boolean;
134
+ selectable: boolean;
135
+ removable: boolean;
136
+ alwaysOnTop: boolean;
137
+ showInExport: boolean;
138
+ } | {
139
+ blendMode: "normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light";
140
+ id: string;
141
+ type: string;
142
+ name: string;
143
+ opacity: number;
144
+ custom: any;
145
+ visible: boolean;
146
+ selectable: boolean;
147
+ removable: boolean;
148
+ alwaysOnTop: boolean;
149
+ showInExport: boolean;
150
+ }>>;
135
151
  readonly parent: any;
136
152
  readonly zIndex: any;
137
153
  } & {
@@ -146,6 +162,18 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
146
162
  removable: boolean;
147
163
  alwaysOnTop: boolean;
148
164
  showInExport: boolean;
165
+ } | {
166
+ blendMode: "normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light";
167
+ id: string;
168
+ type: string;
169
+ name: string;
170
+ opacity: number;
171
+ custom: any;
172
+ visible: boolean;
173
+ selectable: boolean;
174
+ removable: boolean;
175
+ alwaysOnTop: boolean;
176
+ showInExport: boolean;
149
177
  };
150
178
  } & {
151
179
  clone(attrs?: any, { skipSelect }?: {
@@ -181,6 +209,7 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
181
209
  type: import("mobx-state-tree").IType<string | undefined, string, string>;
182
210
  name: import("mobx-state-tree").IType<string | undefined, string, string>;
183
211
  opacity: import("mobx-state-tree").IType<number | undefined, number, number>;
212
+ blendMode: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<"normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light">, [undefined]>;
184
213
  custom: import("mobx-state-tree").IType<any, any, any>;
185
214
  visible: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
186
215
  selectable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
@@ -262,6 +291,7 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
262
291
  type: import("mobx-state-tree").IType<string | undefined, string, string>;
263
292
  name: import("mobx-state-tree").IType<string | undefined, string, string>;
264
293
  opacity: import("mobx-state-tree").IType<number | undefined, number, number>;
294
+ blendMode: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<"normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light">, [undefined]>;
265
295
  custom: import("mobx-state-tree").IType<any, any, any>;
266
296
  visible: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
267
297
  selectable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
@@ -273,6 +303,7 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
273
303
  type: import("mobx-state-tree").IType<string | undefined, string, string>;
274
304
  name: import("mobx-state-tree").IType<string | undefined, string, string>;
275
305
  opacity: import("mobx-state-tree").IType<number | undefined, number, number>;
306
+ blendMode: import("mobx-state-tree").IOptionalIType<import("mobx-state-tree").ISimpleType<"normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light">, [undefined]>;
276
307
  custom: import("mobx-state-tree").IType<any, any, any>;
277
308
  visible: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
278
309
  selectable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
@@ -284,24 +315,37 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
284
315
  type: string | undefined;
285
316
  name: string | undefined;
286
317
  opacity: number | undefined;
318
+ blendMode: "normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light" | undefined;
287
319
  custom: any;
288
320
  visible: boolean | undefined;
289
321
  selectable: boolean | undefined;
290
322
  removable: boolean | undefined;
291
323
  alwaysOnTop: boolean | undefined;
292
324
  showInExport: boolean | undefined;
293
- }>, import("mobx-state-tree").ModelSnapshotType<{
294
- id: import("mobx-state-tree").ISimpleType<string>;
295
- type: import("mobx-state-tree").IType<string | undefined, string, string>;
296
- name: import("mobx-state-tree").IType<string | undefined, string, string>;
297
- opacity: import("mobx-state-tree").IType<number | undefined, number, number>;
298
- custom: import("mobx-state-tree").IType<any, any, any>;
299
- visible: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
300
- selectable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
301
- removable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
302
- alwaysOnTop: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
303
- showInExport: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
304
- }>>>;
325
+ }>, {
326
+ id: string;
327
+ type: string;
328
+ name: string;
329
+ opacity: number;
330
+ custom: any;
331
+ visible: boolean;
332
+ selectable: boolean;
333
+ removable: boolean;
334
+ alwaysOnTop: boolean;
335
+ showInExport: boolean;
336
+ } | {
337
+ blendMode: "normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light";
338
+ id: string;
339
+ type: string;
340
+ name: string;
341
+ opacity: number;
342
+ custom: any;
343
+ visible: boolean;
344
+ selectable: boolean;
345
+ removable: boolean;
346
+ alwaysOnTop: boolean;
347
+ showInExport: boolean;
348
+ }>>;
305
349
  readonly parent: any;
306
350
  readonly zIndex: any;
307
351
  } & {
@@ -316,6 +360,18 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
316
360
  removable: boolean;
317
361
  alwaysOnTop: boolean;
318
362
  showInExport: boolean;
363
+ } | {
364
+ blendMode: "normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light";
365
+ id: string;
366
+ type: string;
367
+ name: string;
368
+ opacity: number;
369
+ custom: any;
370
+ visible: boolean;
371
+ selectable: boolean;
372
+ removable: boolean;
373
+ alwaysOnTop: boolean;
374
+ showInExport: boolean;
319
375
  };
320
376
  } & {
321
377
  clone(attrs?: any, { skipSelect }?: {
@@ -346,18 +402,30 @@ export declare const insertTextElement: (store: StoreType, text: string, extra?:
346
402
  set(attrs: any): void;
347
403
  toggleEditMode(editing?: boolean): void;
348
404
  beforeDestroy(): void;
349
- }, any, import("mobx-state-tree").ModelSnapshotType<{
350
- id: import("mobx-state-tree").ISimpleType<string>;
351
- type: import("mobx-state-tree").IType<string | undefined, string, string>;
352
- name: import("mobx-state-tree").IType<string | undefined, string, string>;
353
- opacity: import("mobx-state-tree").IType<number | undefined, number, number>;
354
- custom: import("mobx-state-tree").IType<any, any, any>;
355
- visible: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
356
- selectable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
357
- removable: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
358
- alwaysOnTop: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
359
- showInExport: import("mobx-state-tree").IType<boolean | undefined, boolean, boolean>;
360
- }>>> & {
405
+ }, any, {
406
+ id: string;
407
+ type: string;
408
+ name: string;
409
+ opacity: number;
410
+ custom: any;
411
+ visible: boolean;
412
+ selectable: boolean;
413
+ removable: boolean;
414
+ alwaysOnTop: boolean;
415
+ showInExport: boolean;
416
+ } | {
417
+ blendMode: "normal" | "color" | "color-burn" | "color-dodge" | "darken" | "difference" | "exclusion" | "hard-light" | "hue" | "lighten" | "luminosity" | "multiply" | "overlay" | "saturation" | "screen" | "soft-light";
418
+ id: string;
419
+ type: string;
420
+ name: string;
421
+ opacity: number;
422
+ custom: any;
423
+ visible: boolean;
424
+ selectable: boolean;
425
+ removable: boolean;
426
+ alwaysOnTop: boolean;
427
+ showInExport: boolean;
428
+ }>> & {
361
429
  type: "text";
362
430
  }) | undefined;
363
431
  export declare const pasteFromEvent: (store: StoreType, e: ClipboardEvent, opts?: {
package/utils/fonts.js CHANGED
@@ -1 +1 @@
1
- import*as t from"mobx";import{triggerLoadError as o,getFontLoadTimeout as e}from"./loader.js";import{polotnoError as n}from"@polotno/core/errors";import{removeTags as r}from"@polotno/core/text";import{DEFAULT_RETRIES as s,retryDelayMs as i}from"@polotno/core/retry";import{getGoogleFontsUrl as a,getGoogleFontsVariants as c}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as l,googleFontVariantUrl as u,cssFontFamily as f}from"@polotno/core/fonts";export{setGoogleFontsVariants,getGoogleFontsVariants,getGoogleFontsUrl}from"@polotno/core/google-fonts-url";const d=["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"];let m=t.observable([...d]),p=t.observable({value:!1});export function isGoogleFontChanged(){return p.value}export function setGoogleFonts(t){if("default"===t){return m.replace([...d]),void(p.value=!1)}p.value=!0,m.splice(0,m.length),m.push(...t)}export function getFontsList(){return m}export const globalFonts=t.observable([]);export function addGlobalFont(t){globalFonts.push(t)}export function removeGlobalFont(t){const o=globalFonts.findIndex(o=>o.fontFamily===t);-1!==o&&globalFonts.splice(o,1)}export function replaceGlobalFonts(t){globalFonts.replace(t)}const g="BESbswy 0123456789 Il1Ww",x=["sans-serif","serif","monospace"];function h(t){const o=function(t=""){const o=r(t).replace(/\s+/g," ").trim();return o?Array.from(o).slice(0,10).join(""):""}(t);return o?`${g} ${o}`:g}export function _getFontProbeTextForTesting(t){return h(t)}let F;function y(t){return{width:t.width,actualBoundingBoxLeft:t.actualBoundingBoxLeft||0,actualBoundingBoxRight:t.actualBoundingBoxRight||0,actualBoundingBoxAscent:t.actualBoundingBoxAscent||0,actualBoundingBoxDescent:t.actualBoundingBoxDescent||0}}function $(t="sans-serif",o="normal",e="normal",n=g){F||(F=document.createElement("canvas"));const r=F.getContext("2d");return r.font=`${o} ${e} 40px ${t}`,y(r.measureText(n))}function B(t,o,e,n,r){return x.some(s=>{const i=function(t,o="sans-serif",e="normal",n="normal",r=g){F||(F=document.createElement("canvas"));const s=F.getContext("2d");return s.font=`${e} ${n} 40px ${f(t)}, ${o}`,y(s.measureText(r))}(t,s,o,e,n);return function(t,o,e=.01){return Math.abs(t.width-o.width)>e||Math.abs(t.actualBoundingBoxLeft-o.actualBoundingBoxLeft)>e||Math.abs(t.actualBoundingBoxRight-o.actualBoundingBoxRight)>e||Math.abs(t.actualBoundingBoxAscent-o.actualBoundingBoxAscent)>e||Math.abs(t.actualBoundingBoxDescent-o.actualBoundingBoxDescent)>e}(i,r[s])})}export function measureFontDom(t,o="sans-serif",e="normal",n="normal",r=g){if("undefined"==typeof document||!document.body){return 0}const s=document.createElement("span");s.textContent=r,s.style.cssText=`\n position:absolute;\n visibility:hidden;\n white-space:nowrap;\n top:-9999px;\n left:-9999px;\n font:${e} ${n} 90px ${f(t)}, ${o};\n `,document.body.appendChild(s);const i=s.getBoundingClientRect().width;return s.remove(),i}const b={Arial:!0};export const isFontLoaded=(t,o,e)=>o&&e?!!b[`${t}_${o}_${e}`]:Object.keys(b).some(o=>o.startsWith(t+"_"))||!!b[t];export function _setFontLoadedForTesting(t,o){o?b[t]=!0:delete b[t]}export async function loadFont(t,r,s,a){var c;const l=`${t}_${r}_${s}`;if(b[l]){return}injectGoogleFontVariant(t,r,s);const u=!!(null===(c=document.fonts)||void 0===c?void 0:c.load),d=h(a),m={"sans-serif":$("sans-serif",r,s,d),serif:$("serif",r,s,d),monospace:$("monospace",r,s,d)};if(u){try{if(await document.fonts.load(`${r} ${s} 16px ${f(t)}`,d),B(t,r,s,d,m)){return void G(l,t)}}catch(g){}}const p=e()/60;for(let e=0;e<p;e++){if("missing"===v[t]){if(E(t)){const e=`Font "${t}" not found: not registered and no matching Google Font.`;console.error(e),o(n("FONT_FAILED",e,{family:t,reason:"not-found"}))}return}if(t in w&&!w[t]&&"errored"===v[t]&&injectGoogleFont(t),u){try{await document.fonts.load(`${r} ${s} 16px ${f(t)}`,d)}catch(x){}}if(B(t,r,s,d,m)){return void G(l,t)}if(A[t]&&S(t)){const r=L(t);if("wait"===r){await new Promise(t=>setTimeout(t,60));continue}if("spent"!==r){M(t);const o=i(r);await new Promise(t=>setTimeout(t,o)),e+=Math.ceil(o/60);continue}if(E(t)){const e=`Failed to load font "${t}": its font file could not be fetched.`;console.error(e),o(n("FONT_FAILED",e,{family:t,reason:"fetch-failed"}))}return}await new Promise(t=>setTimeout(t,60))}console.warn(`Timeout for loading font "${t}". Looks like polotno can't load it. Is it a correct font family?`),o(n("FONT_FAILED",`Timeout for loading font "${t}"`,{family:t,reason:"timeout"}))}const w={},v={},T=new Set;function E(t){return!T.has(t)&&(T.add(t),setTimeout(()=>T.delete(t),e()),!0)}function G(t,o){b[t]=!0,delete v[o],delete C[o]}const C={};function L(t){const o=C[t],n=!o||Date.now()-o.at>e()?0:o.spent;return n>=s-1?"spent":o&&n>0&&Date.now()-o.at<i(n)?"wait":(C[t]={spent:n+1,at:Date.now()},n+1)}const R={};export function injectGoogleFontVariant(t,o,e){const n=parseInt(e,10);if(!Number.isFinite(n)){return}if(function(t){const o=new Set;for(const e of c().split(",")){const n=e.trim().match(/^(\d+)(italic|i)?$/);n&&!!n[2]===t&&o.add(parseInt(n[1],10))}return o}("italic"===o).has(n)){return}if(!(t in w)){return}const r="italic"===o,s=`${t}|${r?1:0}|${n}`;if(R[s]){return}R[s]=!0;const i=document.createElement("link");i.type="text/css",i.href=u(t,r,n),i.rel="stylesheet",i.onerror=()=>{i.remove()},document.getElementsByTagName("head")[0].appendChild(i)}export function injectGoogleFont(t){if(w[t]){return}const o=a(t),e=document.createElement("link");e.type="text/css",e.href=o,e.rel="stylesheet",e.onerror=()=>{e.remove(),w[t]=!1,"errored"===v[t]?function(t){v[t]="probing",fetch(a(t),{mode:"no-cors"}).then(()=>{v[t]="missing"}).catch(()=>{delete v[t]})}(t):v[t]||(v[t]="errored")},document.getElementsByTagName("head")[0].appendChild(e),w[t]=!0}const A={};let D;function _(){return D||(D=document.getElementById("polotno-font-style"),D||(D=document.createElement("style"),D.id="polotno-font-style",document.head.appendChild(D)),D)}function j(t){const o=t.fontFamily,e=l(t),n=_().sheet;return e.map(t=>{const e=n.insertRule(`\n @font-face{\n font-family:${f(o)};\n src:${t.src};\n font-style:${t.fontStyle};\n font-weight:${t.fontWeight};\n font-display:swap; /* optional but recommended */\n }`,n.cssRules.length);return n.cssRules[e]})}export function injectCustomFont(t){const o=t.fontFamily;if(!t.url&&!t.styles){return}const e=JSON.stringify(l(t)),n=A[o];if(n){if(n.src===e){return}I(n.rules),k(o)}delete v[o],A[o]={font:t,src:e,rules:j(t)}}function I(t){const o=_().sheet;for(const e of t){const t=Array.prototype.indexOf.call(o.cssRules,e);t>=0&&o.deleteRule(t)}}export function removeCustomFont(t){const o=A[t];o&&(I(o.rules),delete A[t],k(t))}function k(t){delete C[t];for(const o of Object.keys(b)){(o===t||o.startsWith(t+"_"))&&delete b[o]}}function M(t){const o=A[t];o&&(I(o.rules),o.rules=j(o.font))}const O=t=>t.trim().replace(/^["']|["']$/g,"").toLowerCase();function S(t){const o=document.fonts;if(!o||"function"!=typeof o.forEach){return!1}const e=O(t);let n=!1;return o.forEach(t=>{"error"===t.status&&O(t.family)===e&&(n=!0)}),n}
1
+ import*as t from"mobx";import{triggerLoadError as o,getFontLoadTimeout as n}from"./loader.js";import{polotnoError as e}from"@polotno/core/errors";import{removeTags as r}from"@polotno/core/text";import{DEFAULT_RETRIES as s,retryDelayMs as i}from"@polotno/core/retry";import{getGoogleFontsUrl as a,getGoogleFontsVariants as c}from"@polotno/core/google-fonts-url";import{resolveFontFaceStyles as l,googleFontVariantUrl as u,cssFontFamily as f}from"@polotno/core/fonts";export{setGoogleFontsVariants,getGoogleFontsVariants,getGoogleFontsUrl}from"@polotno/core/google-fonts-url";const d=["Roboto","Amatic SC","Press Start 2P","Marck Script","Rubik Mono One"];let m=t.observable([...d]),p=t.observable({value:!1});export function isGoogleFontChanged(){return p.value}export function setGoogleFonts(t){if("default"===t){return m.replace([...d]),void(p.value=!1)}p.value=!0,m.splice(0,m.length),m.push(...t)}export function getFontsList(){return m}export const globalFonts=t.observable([]);export function addGlobalFont(t){globalFonts.push(t)}export function removeGlobalFont(t){const o=globalFonts.findIndex(o=>o.fontFamily===t);-1!==o&&globalFonts.splice(o,1)}export function replaceGlobalFonts(t){globalFonts.replace(t)}const g="BESbswy 0123456789 Il1Ww",x=["sans-serif","serif","monospace"];function h(t){const o=function(t=""){const o=r(t).replace(/\s+/g," ").trim();return o?Array.from(o).slice(0,10).join(""):""}(t);return o?`${g} ${o}`:g}export function _getFontProbeTextForTesting(t){return h(t)}let F;function $(t){return{width:t.width,actualBoundingBoxLeft:t.actualBoundingBoxLeft||0,actualBoundingBoxRight:t.actualBoundingBoxRight||0,actualBoundingBoxAscent:t.actualBoundingBoxAscent||0,actualBoundingBoxDescent:t.actualBoundingBoxDescent||0}}function y(t="sans-serif",o="normal",n="normal",e=g){F||(F=document.createElement("canvas"));const r=F.getContext("2d");return r.font=`${o} ${n} 40px ${t}`,$(r.measureText(e))}function B(t,o,n,e,r){return x.some(s=>{const i=function(t,o="sans-serif",n="normal",e="normal",r=g){F||(F=document.createElement("canvas"));const s=F.getContext("2d");return s.font=`${n} ${e} 40px ${f(t)}, ${o}`,$(s.measureText(r))}(t,s,o,n,e);return function(t,o,n=.01){return Math.abs(t.width-o.width)>n||Math.abs(t.actualBoundingBoxLeft-o.actualBoundingBoxLeft)>n||Math.abs(t.actualBoundingBoxRight-o.actualBoundingBoxRight)>n||Math.abs(t.actualBoundingBoxAscent-o.actualBoundingBoxAscent)>n||Math.abs(t.actualBoundingBoxDescent-o.actualBoundingBoxDescent)>n}(i,r[s])})}export function measureFontDom(t,o="sans-serif",n="normal",e="normal",r=g){if("undefined"==typeof document||!document.body){return 0}const s=document.createElement("span");s.textContent=r,s.style.cssText=`\n position:absolute;\n visibility:hidden;\n white-space:nowrap;\n top:-9999px;\n left:-9999px;\n font:${n} ${e} 90px ${f(t)}, ${o};\n `,document.body.appendChild(s);const i=s.getBoundingClientRect().width;return s.remove(),i}const b={Arial:!0};export const isFontLoaded=(t,o,n)=>o&&n?!!b[`${t}_${o}_${n}`]:Object.keys(b).some(o=>o.startsWith(t+"_"))||!!b[t];export function _setFontLoadedForTesting(t,o){o?b[t]=!0:delete b[t]}export async function loadFont(t,r,s,a){var c;const l=`${t}_${r}_${s}`;if(injectGoogleFontVariant(t,r,s),b[l]&&!A(t,r,s)){return}const u=!!(null===(c=document.fonts)||void 0===c?void 0:c.load),d=h(a),m={"sans-serif":y("sans-serif",r,s,d),serif:y("serif",r,s,d),monospace:y("monospace",r,s,d)};if(u){try{if(await document.fonts.load(`${r} ${s} 16px ${f(t)}`,d),B(t,r,s,d,m)&&!A(t,r,s)){return void G(l,t)}}catch(g){}}const p=n()/60;for(let n=0;n<p;n++){if(u){try{await document.fonts.load(`${r} ${s} 16px ${f(t)}`,d)}catch(x){}}if(B(t,r,s,d,m)&&!A(t,r,s)){return void G(l,t)}if("missing"===v[t]){if(E(t)){const n=`Font "${t}" not found: not registered and no matching Google Font.`;console.error(n),o(e("FONT_FAILED",n,{family:t,reason:"not-found"}))}return}if(t in w&&!w[t]&&"errored"===v[t]&&injectGoogleFont(t),D[t]&&N(t)){const r=L(t);if("wait"===r){await new Promise(t=>setTimeout(t,60));continue}if("spent"!==r){O(t);const o=i(r);await new Promise(t=>setTimeout(t,o)),n+=Math.ceil(o/60);continue}if(E(t)){const n=`Failed to load font "${t}": its font file could not be fetched.`;console.error(n),o(e("FONT_FAILED",n,{family:t,reason:"fetch-failed"}))}return}await new Promise(t=>setTimeout(t,60))}console.warn(`Timeout for loading font "${t}". Looks like polotno can't load it. Is it a correct font family?`),o(e("FONT_FAILED",`Timeout for loading font "${t}"`,{family:t,reason:"timeout"}))}const w={},v={},T=new Set;function E(t){return!T.has(t)&&(T.add(t),setTimeout(()=>T.delete(t),n()),!0)}function G(t,o){b[t]=!0,delete v[o],delete C[o]}const C={};function L(t){const o=C[t],e=!o||Date.now()-o.at>n()?0:o.spent;return e>=s-1?"spent":o&&e>0&&Date.now()-o.at<i(e)?"wait":(C[t]={spent:e+1,at:Date.now()},e+1)}const R={};function A(t,o,n){return"loading"===w[t]||"loading"===R[`${t}|${"italic"===o?1:0}|${parseInt(n,10)}`]}export function injectGoogleFontVariant(t,o,n){const e=parseInt(n,10);if(!Number.isFinite(e)){return}if(function(t){const o=new Set;for(const n of c().split(",")){const e=n.trim().match(/^(\d+)(italic|i)?$/);e&&!!e[2]===t&&o.add(parseInt(e[1],10))}return o}("italic"===o).has(e)){return}if(!(t in w)){return}const r="italic"===o,s=`${t}|${r?1:0}|${e}`;if(R[s]){return}R[s]="loading";const i=document.createElement("link");i.type="text/css",i.href=u(t,r,e),i.rel="stylesheet",i.onload=()=>{R[s]=!0},i.onerror=()=>{R[s]=!0,i.remove()},document.getElementsByTagName("head")[0].appendChild(i)}export function injectGoogleFont(t){if(w[t]){return}const o=a(t),n=document.createElement("link");n.type="text/css",n.href=o,n.rel="stylesheet",n.onload=()=>{w[t]=!0},n.onerror=()=>{n.remove(),w[t]=!1,"errored"===v[t]?function(t){v[t]="probing",fetch(a(t),{mode:"no-cors"}).then(()=>{v[t]="missing"}).catch(()=>{delete v[t]})}(t):v[t]||(v[t]="errored")},document.getElementsByTagName("head")[0].appendChild(n),w[t]="loading"}const D={};let _;function I(){return _||(_=document.getElementById("polotno-font-style"),_||(_=document.createElement("style"),_.id="polotno-font-style",document.head.appendChild(_)),_)}function j(t){const o=t.fontFamily,n=l(t),e=I().sheet;return n.map(t=>{const n=e.insertRule(`\n @font-face{\n font-family:${f(o)};\n src:${t.src};\n font-style:${t.fontStyle};\n font-weight:${t.fontWeight};\n font-display:swap; /* optional but recommended */\n }`,e.cssRules.length);return e.cssRules[n]})}export function injectCustomFont(t){const o=t.fontFamily;if(!t.url&&!t.styles){return}const n=JSON.stringify(l(t)),e=D[o];if(e){if(e.src===n){return}k(e.rules),M(o)}delete v[o],D[o]={font:t,src:n,rules:j(t)}}function k(t){const o=I().sheet;for(const n of t){const t=Array.prototype.indexOf.call(o.cssRules,n);t>=0&&o.deleteRule(t)}}export function removeCustomFont(t){const o=D[t];o&&(k(o.rules),delete D[t],M(t))}function M(t){delete C[t];for(const o of Object.keys(b)){(o===t||o.startsWith(t+"_"))&&delete b[o]}}function O(t){const o=D[t];o&&(k(o.rules),o.rules=j(o.font))}const S=t=>t.trim().replace(/^["']|["']$/g,"").toLowerCase();function N(t){const o=document.fonts;if(!o||"function"!=typeof o.forEach){return!1}const n=S(t);let e=!1;return o.forEach(t=>{"error"===t.status&&S(t.family)===n&&(e=!0)}),e}
package/utils/from-svg.js CHANGED
@@ -1 +1 @@
1
- import t from"konva";import{getImageSize as e,getCrop as r}from"@polotno/core/image";let n=0;const o=()=>(n+=1,n.toString());function i(t){const e=t.getAttribute("viewBox"),[r,n,o,i]=(null==e?void 0:e.split(" "))||[];return(!t.getAttribute("width")||t.getAttribute("width").indexOf("%")>=0)&&t.setAttribute("width",o+"px"),(!t.getAttribute("height")||t.getAttribute("height").indexOf("%")>=0)&&t.setAttribute("height",i+"px"),{width:parseFloat(t.getAttribute("width")||o),height:parseFloat(t.getAttribute("height")||i)}}function a(e){const r=function(e){var r,n,o;const i=(null===(o=null===(n=null===(r=e.transform)||void 0===r?void 0:r.baseVal)||void 0===n?void 0:n.consolidate())||void 0===o?void 0:o.matrix)||new DOMMatrix;return new t.Transform([i.a,i.b,i.c,i.d,i.e,i.f])}(e);return e.parentNode&&"svg"!==e.parentNode.nodeName?a(e.parentNode).multiply(r):r}function s(t){return a(t).decompose()}function l(t){const{x:e,y:r}=t.getBoundingClientRect();if("svg"===t.nodeName){return{x:e,y:r}}const n=l(t.parentNode);return{x:e+n.x,y:r+n.y}}function g(t){return t.getElementsByTagName("text").length>0}function u(t){const e=Array.from(t.getElementsByTagName("rect")).find(t=>{const e=t.getAttribute("fill");return e&&e.indexOf("url")>=0});return t.getElementsByTagName("image").length>0||e}export function svgToURL(t){return"data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(t)))}function h(t="url(#pattern)"){return t.replace(/url\(([^)]+)\)/,"$1").replace(/'/g,"")}function c(t){if(!t){return"Roboto"}if(t.includes("OpenSans")){return"Open Sans"}if(t.includes("Montserrat")){return"Montserrat"}const e=t.split(",").map(t=>t.trim());return e[1]||e[0]}function d(t){return t.parentNode&&"svg"===t.parentNode.nodeName?t.parentNode:t.parentElement?d(t.parentElement):null}async function f(t){if("defs"===t.nodeName){return[]}const n=t.getAttribute("id")||o();if("text"===t.nodeName){let e=Array.from(t.children).map(t=>t.textContent);0===e.length&&(e=[t.textContent]);const r=e.join("\n"),o=parseFloat(t.getAttribute("font-size")||t.style.fontSize||"20"),{x:i,y:a,rotation:l}=s(t),g=t.getAttribute("text-anchor")||"start";let u="left";return"middle"===g?u="center":"end"===g&&(u="right"),[{type:"text",text:r,id:n,x:i+t.getBBox().x,y:a+t.getBBox().y,fontSize:o,rotation:l,lineHeight:t.getBBox().height/e.length/o,width:t.getBBox().width,height:t.getBBox().height,fontFamily:c(t.getAttribute("font-family")||void 0),fontWeight:t.getAttribute("font-weight")||"normal",fontStyle:t.getAttribute("font-style")||"normal",align:u,fill:t.getAttribute("fill")||t.style.fill||"black"}]}if("image"===t.nodeName){const{x:o,y:i,rotation:a,scaleX:l,scaleY:g}=s(t),u=t.getBBox().width*l,h=t.getBBox().height*g,c=t.getAttribute("xlink:href")||"",d=await e(c),f=r({width:u,height:h},d);return[Object.assign({type:"image",id:n,x:o+t.getBBox().x,y:i+t.getBBox().y,width:u,height:h,src:c,rotation:a},f)]}if("rect"===t.nodeName){const{x:o,y:i,rotation:a}=s(t),l=parseFloat(t.getAttribute("width")||"0"),g=parseFloat(t.getAttribute("height")||"0"),u=t.getAttribute("fill")||"",c=u.indexOf("url")>=0,d=c?h(u):null,f=d?document.querySelector(d):null;if(c){const s=null==f?void 0:f.querySelector("use"),u=null==s?void 0:s.getAttribute("xlink:href"),h=u&&document.querySelector(u),c=h&&h.getAttribute("xlink:href");if(c){const s=await e(c),u=r({width:l,height:g},s);return[Object.assign({type:"image",id:n,x:o+t.getBBox().x,y:i+t.getBBox().y,width:l,height:g,src:c,rotation:a},u)]}}t.setAttribute("transform","");const m=t.getBBox();t.setAttribute("x","0"),t.setAttribute("y","0");const x=`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${l}" height="${g}" viewBox="0 0 ${l} ${g}">${(null==f?void 0:f.outerHTML)||""}${t.outerHTML}</svg>`;return[{type:"svg",id:n,keepRatio:!1,x:o+m.x,y:i+m.y,width:l,height:g,src:svgToURL(x)}]}if("path"===t.nodeName||"polygon"===t.nodeName||"circle"===t.nodeName){const{x:e,y:r,rotation:o,scaleX:i,scaleY:a}=s(t),l=t.getBBox(),{width:g,height:u}=l;t.setAttribute("transform","");const c=t.getAttribute("fill")||"",d=c.indexOf("url")>=0?h(c):null,f=d?document.querySelector(d):null;let m=f?[f]:[];if(f&&f.getAttribute("xlink:href")){m=[f];const t=document.querySelector(f.getAttribute("xlink:href"));t&&m.push(t)}const x=`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${g}" height="${u}" viewBox="0 0 ${g} ${u}"><defs>${m.map(t=>t.outerHTML).join("")}</defs><g transform="translate(${-l.x} ${-l.y})">${t.outerHTML}</g></svg>`;return[{type:"svg",id:n,keepRatio:!1,x:e+l.x*i,y:r+l.y*a,width:g*i,height:u*a,rotation:o,src:svgToURL(x)}]}if((t=>"g"===t.nodeName&&t.getBBox().width<450&&t.getBBox().height<450)(t)&&!g(t)&&!u(t)){const{x:e,y:r}=t.getBBox(),{width:o,height:a}=(l(t),t.getBBox()),s=Array.from(t.querySelectorAll("*"));let g=e,u=r;s.forEach(t=>{if("g"===t.nodeName){return}const e=t.getBBox();g=Math.min(g,e.x),u=Math.min(u,e.y)});const h=t.getBoundingClientRect(),c=d(t),f=null==c?void 0:c.getBoundingClientRect(),m=t.getAttribute("transform");t.setAttribute("transform","");const x=`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${a}" viewBox="0 0 ${o} ${a}"><g transform="translate(${-e} ${-r})">${t.outerHTML}</g></svg>`;t.setAttribute("transform",m||"");const p=i(d(t));return[{type:"svg",id:n,keepRatio:!1,x:(h.x-f.x)/f.width*p.width,y:(h.y-f.y)/f.height*p.height,width:o,height:a,name:t.getAttribute("id")||"",src:svgToURL(x)}]}if(!g(t)&&!u(t)){const e=[];for(const r of Array.from(t.children)){e.push(...await f(r))}return e}const a=[];for(const e of Array.from(t.children)){a.push(...await f(e))}return a}function m(t){t.querySelectorAll("script, foreignObject").forEach(t=>t.remove()),t.querySelectorAll("*").forEach(t=>{for(const e of Array.from(t.attributes)){e.name.startsWith("on")&&t.removeAttribute(e.name),"href"!==e.name&&"xlink:href"!==e.name||!e.value.trim().toLowerCase().startsWith("javascript:")||t.removeAttribute(e.name)}})}export async function svgToJson(t){const e=document.createElement("div");document.body.appendChild(e),e.innerHTML=function(t){const e=(new DOMParser).parseFromString(t,"image/svg+xml");if(e.querySelector("parsererror")){const e=(new DOMParser).parseFromString(t,"text/html").querySelector("svg");return e?(m(e),e.outerHTML):t}return m(e.documentElement),e.documentElement.outerHTML}(t);const r=e.querySelector("svg"),{width:n,height:a}=i(r),s=[];for(const o of Array.from(r.children)){s.push(...await f(o))}return e.parentElement.removeChild(e),{width:n,height:a,pages:[{id:o(),children:s}]}}
1
+ import t from"konva";import{getImageSize as e,getCrop as r}from"@polotno/core/image";import{resolveSvgSize as n}from"@polotno/core/svg";let o=0;const i=()=>(o+=1,o.toString());function a(t){const{width:e,height:r}=n({documentElement:t});return t.setAttribute("width",`${e}px`),t.setAttribute("height",`${r}px`),{width:e,height:r}}function s(e){const r=function(e){var r,n,o;const i=(null===(o=null===(n=null===(r=e.transform)||void 0===r?void 0:r.baseVal)||void 0===n?void 0:n.consolidate())||void 0===o?void 0:o.matrix)||new DOMMatrix;return new t.Transform([i.a,i.b,i.c,i.d,i.e,i.f])}(e);return e.parentNode&&"svg"!==e.parentNode.nodeName?s(e.parentNode).multiply(r):r}function l(t){return s(t).decompose()}function g(t){const{x:e,y:r}=t.getBoundingClientRect();if("svg"===t.nodeName){return{x:e,y:r}}const n=g(t.parentNode);return{x:e+n.x,y:r+n.y}}function u(t){return t.getElementsByTagName("text").length>0}function c(t){const e=Array.from(t.getElementsByTagName("rect")).find(t=>{const e=t.getAttribute("fill");return e&&e.indexOf("url")>=0});return t.getElementsByTagName("image").length>0||e}export function svgToURL(t){return"data:image/svg+xml;base64,"+window.btoa(unescape(encodeURIComponent(t)))}function h(t="url(#pattern)"){return t.replace(/url\(([^)]+)\)/,"$1").replace(/'/g,"")}function d(t){if(!t){return"Roboto"}if(t.includes("OpenSans")){return"Open Sans"}if(t.includes("Montserrat")){return"Montserrat"}const e=t.split(",").map(t=>t.trim());return e[1]||e[0]}function m(t){return t.parentNode&&"svg"===t.parentNode.nodeName?t.parentNode:t.parentElement?m(t.parentElement):null}async function f(t){if("defs"===t.nodeName){return[]}const n=t.getAttribute("id")||i();if("text"===t.nodeName){let e=Array.from(t.children).map(t=>t.textContent);0===e.length&&(e=[t.textContent]);const r=e.join("\n"),o=parseFloat(t.getAttribute("font-size")||t.style.fontSize||"20"),{x:i,y:a,rotation:s}=l(t),g=t.getAttribute("text-anchor")||"start";let u="left";return"middle"===g?u="center":"end"===g&&(u="right"),[{type:"text",text:r,id:n,x:i+t.getBBox().x,y:a+t.getBBox().y,fontSize:o,rotation:s,lineHeight:t.getBBox().height/e.length/o,width:t.getBBox().width,height:t.getBBox().height,fontFamily:d(t.getAttribute("font-family")||void 0),fontWeight:t.getAttribute("font-weight")||"normal",fontStyle:t.getAttribute("font-style")||"normal",align:u,fill:t.getAttribute("fill")||t.style.fill||"black"}]}if("image"===t.nodeName){const{x:o,y:i,rotation:a,scaleX:s,scaleY:g}=l(t),u=t.getBBox().width*s,c=t.getBBox().height*g,h=t.getAttribute("xlink:href")||"",d=await e(h),m=r({width:u,height:c},d);return[Object.assign({type:"image",id:n,x:o+t.getBBox().x,y:i+t.getBBox().y,width:u,height:c,src:h,rotation:a},m)]}if("rect"===t.nodeName){const{x:o,y:i,rotation:a}=l(t),s=parseFloat(t.getAttribute("width")||"0"),g=parseFloat(t.getAttribute("height")||"0"),u=t.getAttribute("fill")||"",c=u.indexOf("url")>=0,d=c?h(u):null,m=d?document.querySelector(d):null;if(c){const l=null==m?void 0:m.querySelector("use"),u=null==l?void 0:l.getAttribute("xlink:href"),c=u&&document.querySelector(u),h=c&&c.getAttribute("xlink:href");if(h){const l=await e(h),u=r({width:s,height:g},l);return[Object.assign({type:"image",id:n,x:o+t.getBBox().x,y:i+t.getBBox().y,width:s,height:g,src:h,rotation:a},u)]}}t.setAttribute("transform","");const f=t.getBBox();t.setAttribute("x","0"),t.setAttribute("y","0");const x=`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${s}" height="${g}" viewBox="0 0 ${s} ${g}">${(null==m?void 0:m.outerHTML)||""}${t.outerHTML}</svg>`;return[{type:"svg",id:n,keepRatio:!1,x:o+f.x,y:i+f.y,width:s,height:g,src:svgToURL(x)}]}if("path"===t.nodeName||"polygon"===t.nodeName||"circle"===t.nodeName){const{x:e,y:r,rotation:o,scaleX:i,scaleY:a}=l(t),s=t.getBBox(),{width:g,height:u}=s;t.setAttribute("transform","");const c=t.getAttribute("fill")||"",d=c.indexOf("url")>=0?h(c):null,m=d?document.querySelector(d):null;let f=m?[m]:[];if(m&&m.getAttribute("xlink:href")){f=[m];const t=document.querySelector(m.getAttribute("xlink:href"));t&&f.push(t)}const x=`<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${g}" height="${u}" viewBox="0 0 ${g} ${u}"><defs>${f.map(t=>t.outerHTML).join("")}</defs><g transform="translate(${-s.x} ${-s.y})">${t.outerHTML}</g></svg>`;return[{type:"svg",id:n,keepRatio:!1,x:e+s.x*i,y:r+s.y*a,width:g*i,height:u*a,rotation:o,src:svgToURL(x)}]}if((t=>"g"===t.nodeName&&t.getBBox().width<450&&t.getBBox().height<450)(t)&&!u(t)&&!c(t)){const{x:e,y:r}=t.getBBox(),{width:o,height:i}=(g(t),t.getBBox()),s=Array.from(t.querySelectorAll("*"));let l=e,u=r;s.forEach(t=>{if("g"===t.nodeName){return}const e=t.getBBox();l=Math.min(l,e.x),u=Math.min(u,e.y)});const c=t.getBoundingClientRect(),h=m(t),d=null==h?void 0:h.getBoundingClientRect(),f=t.getAttribute("transform");t.setAttribute("transform","");const x=`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${i}" viewBox="0 0 ${o} ${i}"><g transform="translate(${-e} ${-r})">${t.outerHTML}</g></svg>`;t.setAttribute("transform",f||"");const p=a(h);return[{type:"svg",id:n,keepRatio:!1,x:(c.x-d.x)/d.width*p.width,y:(c.y-d.y)/d.height*p.height,width:o,height:i,name:t.getAttribute("id")||"",src:svgToURL(x)}]}if(!u(t)&&!c(t)){const e=[];for(const r of Array.from(t.children)){e.push(...await f(r))}return e}const o=[];for(const e of Array.from(t.children)){o.push(...await f(e))}return o}function x(t){t.querySelectorAll("script, foreignObject").forEach(t=>t.remove()),t.querySelectorAll("*").forEach(t=>{for(const e of Array.from(t.attributes)){e.name.startsWith("on")&&t.removeAttribute(e.name),"href"!==e.name&&"xlink:href"!==e.name||!e.value.trim().toLowerCase().startsWith("javascript:")||t.removeAttribute(e.name)}})}export async function svgToJson(t){const e=document.createElement("div");document.body.appendChild(e),e.innerHTML=function(t){const e=(new DOMParser).parseFromString(t,"image/svg+xml");if(e.querySelector("parsererror")){const e=(new DOMParser).parseFromString(t,"text/html").querySelector("svg");return e?(x(e),e.outerHTML):t}return x(e.documentElement),e.documentElement.outerHTML}(t);const r=e.querySelector("svg"),{width:n,height:o}=a(r),s=[];for(const i of Array.from(r.children)){s.push(...await f(i))}return e.parentElement.removeChild(e),{width:n,height:o,pages:[{id:i(),children:s}]}}
package/utils/l10n.d.ts CHANGED
@@ -28,6 +28,26 @@ export declare const getTranslations: () => {
28
28
  natural: string;
29
29
  warm: string;
30
30
  textStroke: string;
31
+ blendMode: string;
32
+ blend: {
33
+ 'pass-through': string;
34
+ normal: string;
35
+ multiply: string;
36
+ screen: string;
37
+ overlay: string;
38
+ darken: string;
39
+ lighten: string;
40
+ 'color-dodge': string;
41
+ 'color-burn': string;
42
+ 'hard-light': string;
43
+ 'soft-light': string;
44
+ difference: string;
45
+ exclusion: string;
46
+ hue: string;
47
+ saturation: string;
48
+ color: string;
49
+ luminosity: string;
50
+ };
31
51
  strokeLineJoin: string;
32
52
  joinRound: string;
33
53
  joinMiter: string;
@@ -213,6 +233,7 @@ export declare const getTranslations: () => {
213
233
  removeBackground: string;
214
234
  };
215
235
  sidePanel: {
236
+ close: string;
216
237
  templates: string;
217
238
  searchTemplatesWithSameSize: string;
218
239
  searchPlaceholder: string;
package/utils/l10n.js CHANGED
@@ -1 +1 @@
1
- import{observable as e,action as o,toJS as a}from"mobx";const r=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",strokeLineJoin:"Corners",joinRound:"Round",joinMiter:"Miter",joinBevel:"Bevel",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",speed:"Speed",seconds:"sec",lineStyle:"Line style",lineStartHead:"Line start",lineEndHead:"Line end",textDirection:"Text direction",fontSize:"Font size",fontFamily:"Font family",fontFamilyMixed:"Mixed",fontsInSelection:"Fonts in selection",textAlign:"Text align",verticalAlign:"Vertical align",bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",cellBackground:"Cell background",tableBorderSettings:"Border settings",tableBorderColor:"Border color",tableBorderWidth:"Border width",tableBorderStyle:"Border style",borderModeAll:"All borders",borderModeOuter:"Outer borders",borderModeInner:"Inner borders",borderModeBottomOnly:"Bottom only",borderModeTopOnly:"Top only",borderModeLeftOnly:"Left only",borderModeRightOnly:"Right only",borderModeInnerHorizontal:"Inner horizontal",borderModeInnerVertical:"Inner vertical",tableStructure:"Table structure",tableRows:"Rows",tableColumns:"Columns",insertRowAbove:"Insert row above",insertRowBelow:"Insert row below",deleteRow:"Delete row",insertColumnLeft:"Insert column left",insertColumnRight:"Insert column right",deleteColumn:"Delete column",deleteRows:"Delete rows",deleteColumns:"Delete columns",distributeRowsEvenly:"Distribute rows evenly",distributeColumnsEvenly:"Distribute columns evenly",cellPadding:"Cell padding",listFormat:"List",colorPicker:{solid:"Solid",linear:"Linear",angle:"Angle",colors:"Colors",resetColors:"Reset",recolorAll:"Recolor all"},clipFade:{title:"Fade",preparing:"Preparing mask…",shape:"Shape",linear:"Linear",radial:"Radial",stopOpacity:"Stop opacity",stops:"Fade stops",stop:"Stop",start:"Fade start",end:"Fade end",center:"Fade center",radius:"Fade radius",reverse:"Reverse",removeStop:"Remove stop",addStop:"Add stop",reset:"Reset",hint:"Drag the handles on the image to position the fade."},aiText:{aiWrite:"AI write",rewrite:"Rewrite",shorten:"Shorten",continue:"Continue writing",proofread:"Proofread",tones:"Tones",friendly:"Friendly",professional:"Professional",humorous:"Humorous",formal:"Formal",customPrompt:"Custom prompt",generatedResult:"Generated result",cancel:"Cancel",generate:"Generate",back:"Back",tryAgain:"Try Again",insert:"Insert",promptPlaceholder:"Describe what you want to generate"}},workspace:{noPages:"There are no pages yet...",addPage:"Add page",removePage:"Remove page",duplicatePage:"Duplicate page",moveUp:"Move up",moveDown:"Move down",moveLeft:"Move left",moveRight:"Move right"},scale:{reset:"Reset"},error:{removeBackground:"Ops! Something went wrong. Background can not be removed."},sidePanel:{templates:"Templates",searchTemplatesWithSameSize:"Show templates with the same size",searchPlaceholder:"Search...",otherFormats:"Other formats",noResults:"No results",error:"Loading is failed...",text:"Text",uploadFont:"Upload font",myFonts:"My fonts",photos:"Photos",videos:"Videos",animations:"Animations",effects:"Effects",elements:"Elements",shapes:"Shapes",tables:"Tables",lines:"Lines",draw:"Draw",drawTool:"Tool",drawSelection:"Selection",drawBrush:"Brush",drawHighlighter:"Highlighter",upload:"Upload",uploadImage:"Add file",uploadTip:"Upload your assets",uploadUnsupported:"Skipped some files. You can add images, video and audio.",uploadFailed:"Upload failed. Please try again.",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",advanced:"Advanced",bleed:"Bleed",showBleed:"Show bleed",clipImage:"Mask image",width:"Width",height:"Height",units:"Units",magicResizeDescription:"Magic resize will automatically resize and move all elements on the canvas",headerText:"Header",createHeader:"Create header",subHeaderText:"Sub Header",createSubHeader:"Create sub header",bodyText:"Body text",createBody:"Create body text"},pagesTimeline:{pages:"Pages",removePage:"Remove page",addPage:"Add page",duplicatePage:"Duplicate page",removeAudio:"Remove audio",duplicateAudio:"Duplicate audio",renameAudio:"Rename audio",muteAudio:"Mute",unmuteAudio:"Unmute",volume:"Volume",speed:"Speed",rewind:"Rewind to start",editAsVideo:"Edit as video",editAsVideoHint:"On: preview the frame at the playhead — timed elements hide outside their range. Off: show all elements while editing."},contextMenu:{duplicate:"Duplicate",split:"Split at playhead",rename:"Rename",remove:"Remove",lock:"Lock",unlock:"Unlock",copy:"Copy",paste:"Paste",copyStyle:"Copy style",moveUp:"Move up",moveDown:"Move down",moveBack:"Move back",moveForward:"Move forward"}}),n=e=>e&&"object"==typeof e;function i(e,o){Object.keys(o).forEach(a=>{const r=e[a],l=o[a];n(l)&&n(r)?i(r,l):e[a]=l})}function l(e,o,a=""){Object.keys(o).forEach(r=>{const i=o[r],s=a?`${a}.${r}`:r;n(i)?n(e[r])?l(e[r],i,s):console.warn(`Missing nested translation object at '${s}'`):void 0===e[r]&&console.warn(`Missing translation '${s}'`)})}export const setTranslations=o((e,{validate:o=!1}={})=>{o&&l(e,r),i(r,e)});export const getTranslations=()=>a(r);const s={};export const t=e=>{const o=function(e,o){var a,r=o.split("."),n=e;for(a=0;a<r.length;++a){if(null==n[r[a]]){return}n=n[r[a]]}return n}(r,e);if(void 0!==o){return o}s[e]||(s[e]=!0,console.warn(`Missing translation '${e}'`));const a=e.split("."),n=a[a.length-1]||" ";return n.charAt(0).toUpperCase()+n.slice(1)};
1
+ import{observable as e,action as o,toJS as 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",blendMode:"Blending",blend:{"pass-through":"Pass Through",normal:"Normal",multiply:"Multiply",screen:"Screen",overlay:"Overlay",darken:"Darken",lighten:"Lighten","color-dodge":"Color Dodge","color-burn":"Color Burn","hard-light":"Hard Light","soft-light":"Soft Light",difference:"Difference",exclusion:"Exclusion",hue:"Hue",saturation:"Saturation",color:"Color",luminosity:"Luminosity"},strokeLineJoin:"Corners",joinRound:"Round",joinMiter:"Miter",joinBevel:"Bevel",shadow:"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",speed:"Speed",seconds:"sec",lineStyle:"Line style",lineStartHead:"Line start",lineEndHead:"Line end",textDirection:"Text direction",fontSize:"Font size",fontFamily:"Font family",fontFamilyMixed:"Mixed",fontsInSelection:"Fonts in selection",textAlign:"Text align",verticalAlign:"Vertical align",bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",cellBackground:"Cell background",tableBorderSettings:"Border settings",tableBorderColor:"Border color",tableBorderWidth:"Border width",tableBorderStyle:"Border style",borderModeAll:"All borders",borderModeOuter:"Outer borders",borderModeInner:"Inner borders",borderModeBottomOnly:"Bottom only",borderModeTopOnly:"Top only",borderModeLeftOnly:"Left only",borderModeRightOnly:"Right only",borderModeInnerHorizontal:"Inner horizontal",borderModeInnerVertical:"Inner vertical",tableStructure:"Table structure",tableRows:"Rows",tableColumns:"Columns",insertRowAbove:"Insert row above",insertRowBelow:"Insert row below",deleteRow:"Delete row",insertColumnLeft:"Insert column left",insertColumnRight:"Insert column right",deleteColumn:"Delete column",deleteRows:"Delete rows",deleteColumns:"Delete columns",distributeRowsEvenly:"Distribute rows evenly",distributeColumnsEvenly:"Distribute columns evenly",cellPadding:"Cell padding",listFormat:"List",colorPicker:{solid:"Solid",linear:"Linear",angle:"Angle",colors:"Colors",resetColors:"Reset",recolorAll:"Recolor all"},clipFade:{title:"Fade",preparing:"Preparing mask…",shape:"Shape",linear:"Linear",radial:"Radial",stopOpacity:"Stop opacity",stops:"Fade stops",stop:"Stop",start:"Fade start",end:"Fade end",center:"Fade center",radius:"Fade radius",reverse:"Reverse",removeStop:"Remove stop",addStop:"Add stop",reset:"Reset",hint:"Drag the handles on the image to position the fade."},aiText:{aiWrite:"AI write",rewrite:"Rewrite",shorten:"Shorten",continue:"Continue writing",proofread:"Proofread",tones:"Tones",friendly:"Friendly",professional:"Professional",humorous:"Humorous",formal:"Formal",customPrompt:"Custom prompt",generatedResult:"Generated result",cancel:"Cancel",generate:"Generate",back:"Back",tryAgain:"Try Again",insert:"Insert",promptPlaceholder:"Describe what you want to generate"}},workspace:{noPages:"There are no pages yet...",addPage:"Add page",removePage:"Remove page",duplicatePage:"Duplicate page",moveUp:"Move up",moveDown:"Move down",moveLeft:"Move left",moveRight:"Move right"},scale:{reset:"Reset"},error:{removeBackground:"Ops! Something went wrong. Background can not be removed."},sidePanel:{close:"Close",templates:"Templates",searchTemplatesWithSameSize:"Show templates with the same size",searchPlaceholder:"Search...",otherFormats:"Other formats",noResults:"No results",error:"Loading is failed...",text:"Text",uploadFont:"Upload font",myFonts:"My fonts",photos:"Photos",videos:"Videos",animations:"Animations",effects:"Effects",elements:"Elements",shapes:"Shapes",tables:"Tables",lines:"Lines",draw:"Draw",drawTool:"Tool",drawSelection:"Selection",drawBrush:"Brush",drawHighlighter:"Highlighter",upload:"Upload",uploadImage:"Add file",uploadTip:"Upload your assets",uploadUnsupported:"Skipped some files. You can add images, video and audio.",uploadFailed:"Upload failed. Please try again.",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",advanced:"Advanced",bleed:"Bleed",showBleed:"Show bleed",clipImage:"Mask image",width:"Width",height:"Height",units:"Units",magicResizeDescription:"Magic resize will automatically resize and move all elements on the canvas",headerText:"Header",createHeader:"Create header",subHeaderText:"Sub Header",createSubHeader:"Create sub header",bodyText:"Body text",createBody:"Create body text"},pagesTimeline:{pages:"Pages",removePage:"Remove page",addPage:"Add page",duplicatePage:"Duplicate page",removeAudio:"Remove audio",duplicateAudio:"Duplicate audio",renameAudio:"Rename audio",muteAudio:"Mute",unmuteAudio:"Unmute",volume:"Volume",speed:"Speed",rewind:"Rewind to start",editAsVideo:"Edit as video",editAsVideoHint:"On: preview the frame at the playhead — timed elements hide outside their range. Off: show all elements while editing."},contextMenu:{duplicate:"Duplicate",split:"Split at playhead",rename:"Rename",remove:"Remove",lock:"Lock",unlock:"Unlock",copy:"Copy",paste:"Paste",copyStyle:"Copy style",moveUp:"Move up",moveDown:"Move down",moveBack:"Move back",moveForward:"Move forward"}}),n=e=>e&&"object"==typeof e;function i(e,o){Object.keys(o).forEach(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)};
@@ -1 +1 @@
1
- import e from"react";import{isAlive as t}from"mobx-state-tree";export const DRAG_SLOP_PX=4;export const isPrimaryDrag=e=>0===e.button&&e.isPrimary;export const startPointerDrag=(e,{slopX:n=0,onMove:r,onEnd:o,node:i})=>{e.preventDefault();const{pointerId:a}=e,c=e.clientX;let l=0===n,s=!1;const d=()=>{window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",u)},p=e=>{if(e.pointerId===a){if(!i||t(i)){if(!l){if(Math.abs(e.clientX-c)<n){return}l=!0}s=!0,r(e)}else{d()}}},u=e=>{e.pointerId===a&&(d(),null==o||o({moved:s,cancelled:"pointercancel"===e.type}))};return window.addEventListener("pointermove",p),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",u),d};export const usePointerDrag=()=>{const t=e.useRef(null);return e.useEffect(()=>()=>{var e;return null===(e=t.current)||void 0===e?void 0:e.call(t)},[]),e.useCallback((e,n)=>{var r;null===(r=t.current)||void 0===r||r.call(t),t.current=startPointerDrag(e,n)},[])};
1
+ import e from"react";import{isAlive as t}from"mobx-state-tree";export const DRAG_SLOP_PX=4;export const isPrimaryDrag=e=>0===e.button&&e.isPrimary;export const startPointerDrag=(e,{slopX:n=0,onMove:r,onEnd:o,node:i})=>{e.preventDefault();const{pointerId:a}=e,c=e.clientX;let l=0===n,s=!1;const d=()=>{window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",u)},p=e=>{if(e.pointerId===a){if(!i||t(i)){if(!l){if(Math.abs(e.clientX-c)<n){return}l=!0}s=!0,r(e)}else{d()}}},u=e=>{e.pointerId===a&&(d(),i&&!t(i)||null==o||o({moved:s,cancelled:"pointercancel"===e.type}))};return window.addEventListener("pointermove",p),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",u),d};export const usePointerDrag=()=>{const t=e.useRef(null);return e.useEffect(()=>()=>{var e;return null===(e=t.current)||void 0===e?void 0:e.call(t)},[]),e.useCallback((e,n)=>{var r;null===(r=t.current)||void 0===r||r.call(t),t.current=startPointerDrag(e,n)},[])};
@@ -1,3 +1,5 @@
1
+ import type Quill from 'quill';
2
+ import type { Range } from 'quill';
1
3
  import { TextFormat, TextFormatAttrs, ApplyTextFormatOptions } from './text-format.js';
2
4
  type QuillFormat = Record<string, any>;
3
5
  type QuillMixed = Record<string, boolean>;
@@ -39,6 +41,7 @@ export type TextFormatState = {
39
41
  applyTextFormat: (attrs: TextFormatAttrs, opts?: ApplyTextFormatOptions) => void;
40
42
  enabled: boolean;
41
43
  };
44
+ export declare function restoreEditorSelection(quill: Quill, range: Range): void;
42
45
  export declare function resolveSelectionScope(quill: any, fallbackSelection: {
43
46
  index: number;
44
47
  length: number;
@@ -1 +1 @@
1
- import*as t from"react";import*as e from"mobx";import{parseFontSizeToPx as o,toNumericWeight as n}from"@polotno/core/rich-text-html";import{isGradient as i}from"@polotno/core/gradient";import{getTextFormat as r,applyTextFormat as l,FORMAT_KEYS as c,DECORATION_TOKENS as a,decorationTokensOf as s,decorationTokensToString as f,decorationToQuillKey as u}from"./text-format.js";const d=e.observable({active:null},{},{deep:!1});export function getActiveTextEditor(){return d.active}export function setActiveTextEditor(t){e.runInAction(()=>{d.active=Object.assign(Object.assign({},t),{currentFormat:{},mixedFormats:{},lastSelection:null})})}export function updateActiveTextFormat(t,o,n){e.runInAction(()=>{d.active&&(d.active=Object.assign(Object.assign({},d.active),{currentFormat:t,mixedFormats:o,lastSelection:n||d.active.lastSelection}))})}export function clearActiveTextEditor(t){e.runInAction(()=>{var e;t&&(null===(e=d.active)||void 0===e?void 0:e.instance)!==t||(d.active=null)})}const m={fontSize:["size"],fontFamily:["font"],fill:["color","gradient"],fontWeight:["font-weight"],fontStyle:["italic"],textDecoration:["underline","strike"]};export const ALL_QUILL_MIXED_KEYS=Array.from(new Set(c.flatMap(t=>m[t])));function p(t,e,i){var r,l;switch(t){case"fontSize":return null!==(r=o(e.size,i.fontSize))&&void 0!==r?r:i.fontSize;case"fontFamily":return e.font?String(e.font):i.fontFamily;case"fill":return e.gradient||(null!==(l=e.color)&&void 0!==l?l:i.fill);case"fontWeight":return null!=e["font-weight"]?n(e["font-weight"]):n(i.fontWeight);case"fontStyle":return e.italic?"italic":i.fontStyle;case"textDecoration":return f(s(i.textDecoration))}}function x(t,e,o){const n=s(o.textDecoration),i=(o,i)=>n.has(o)?"on":e[i]?"mixed":t[i]?"on":"off",r=function(t,e){const o=t=>"on"===t?[!0]:"off"===t?[!1]:[!0,!1],n=[];for(const i of o(t)){for(const t of o(e)){const e=new Set;i&&e.add("underline"),t&&e.add("line-through"),n.push(f(e))}}return n}(i("underline","underline"),i("line-through","strike"));return{value:1===r.length?r[0]:void 0,mixed:r.length>1,values:r}}export function quillToTextFormat(t,e,o){const n={};for(const i of c){if("textDecoration"!==i){if(m[i].some(t=>!0===e[t])){n[i]={value:void 0,mixed:!0,values:[]}}else{const e=p(i,t,o);n[i]={value:e,mixed:!1,values:[e]}}}else{n.textDecoration=x(t,e,o)}}return n}export function attrsToQuillOps(t,e){var o;const r=[];if(void 0!==t.fontFamily&&r.push(["font",t.fontFamily]),void 0!==t.fontSize&&r.push(["size",`${t.fontSize}px`]),void 0!==t.fill&&(i(String(t.fill))?r.push(["color",!1],["gradient",t.fill]):r.push(["gradient",!1],["color",t.fill])),void 0!==t.fontWeight&&r.push(["font-weight",String(n(t.fontWeight))]),void 0!==t.fontStyle&&r.push(["italic","italic"===t.fontStyle]),void 0!==t.textDecoration){const n=null!==(o=null==e?void 0:e.decorationTokens)&&void 0!==o?o:a,i=s(t.textDecoration);for(const t of a){n.includes(t)&&r.push([u(t),i.has(t)])}}return r}function v(t){return((null==t?void 0:t.selectedElements)||[]).filter(t=>"text"===t.type)}function g(t){const e=getActiveTextEditor();return e&&e.instance&&e.store===t?e:null}export function resolveSelectionScope(t,e){const o=t.getSelection()||e||{index:0,length:0},n="function"==typeof t.getLength?t.getLength():0,i=n<=1;return o.length<=0?{scope:"collapsed",sel:o,isEmpty:i}:{scope:o.length>=n-1?"full":"partial",sel:o,isEmpty:i}}export function applyToLiveEditor(t,e,o,n){const i=attrsToQuillOps(e,n);if(!i.length){return}const{scope:r,sel:l}=resolveSelectionScope(t,null!=o?o:null);for(const[c,a]of i){"collapsed"===r?t.format(c,a,"user"):t.formatText(l.index,l.length,c,a,"user")}"collapsed"===r&&updateActiveTextFormat(t.getFormat(l.index,0),{},l)}function h(t,e){const o="function"==typeof t.getLength?t.getLength():0;t.formatText(0,o,e,!0,"api")}export function getTextFormatState(t){const e=g(t),o=v(t),n=!!e||o.length>0;var i;return{format:e?quillToTextFormat(e.currentFormat||{},e.mixedFormats||{},{fontSize:(i=e.element).fontSize,fontFamily:i.fontFamily,fill:i.fill,fontWeight:i.fontWeight,fontStyle:i.fontStyle,textDecoration:i.textDecoration}):r(o),enabled:n,applyTextFormat:(e,o)=>function(t,e,o){const n=g(t);if(!n){return void l(v(t),e,o)}const{scope:i,sel:r,isEmpty:c}=resolveSelectionScope(n.instance,n.lastSelection);"full"===i||"collapsed"===i&&!c?l([n.element],e,o):function(t,e,o,n){var i,r;const l=t.instance,c=t.element;let d=!1;if(n.length>0){if(void 0!==e.fontStyle&&"italic"!==e.fontStyle&&"italic"===c.fontStyle&&(h(l,"italic"),c.set({fontStyle:"normal"}),d=!0),void 0!==e.textDecoration){const t=null!==(i=null==o?void 0:o.decorationTokens)&&void 0!==i?i:a,n=s(e.textDecoration),r=s(c.textDecoration),m=t.filter(t=>!n.has(t)&&r.has(t));for(const e of m){h(l,u(e)),r.delete(e)}m.length&&(c.set({textDecoration:f(r)}),d=!0)}d&&"function"==typeof(null===(r=l.history)||void 0===r?void 0:r.clear)&&l.history.clear()}applyToLiveEditor(l,e,n,o)}(n,e,o,r)}(t,e,o)}}export function observeTextFormatState(t,o){return e.reaction(()=>getTextFormatState(t),t=>o(t),{fireImmediately:!0})}export function useTextFormat(e){const[o,n]=t.useState(()=>getTextFormatState(e));return t.useEffect(()=>observeTextFormatState(e,n),[e]),o}
1
+ import*as t from"react";import*as e from"mobx";import{parseFontSizeToPx as o,toNumericWeight as n}from"@polotno/core/rich-text-html";import{isGradient as i}from"@polotno/core/gradient";import{getTextFormat as r,applyTextFormat as l,FORMAT_KEYS as c,DECORATION_TOKENS as a,decorationTokensOf as s,decorationTokensToString as f,decorationToQuillKey as u}from"./text-format.js";const d=e.observable({active:null},{},{deep:!1});export function getActiveTextEditor(){return d.active}export function setActiveTextEditor(t){e.runInAction(()=>{d.active=Object.assign(Object.assign({},t),{currentFormat:{},mixedFormats:{},lastSelection:null})})}export function updateActiveTextFormat(t,o,n){e.runInAction(()=>{d.active&&(d.active=Object.assign(Object.assign({},d.active),{currentFormat:t,mixedFormats:o,lastSelection:n||d.active.lastSelection}))})}export function clearActiveTextEditor(t){e.runInAction(()=>{var e;t&&(null===(e=d.active)||void 0===e?void 0:e.instance)!==t||(d.active=null)})}const p={fontSize:["size"],fontFamily:["font"],fill:["color","gradient"],fontWeight:["font-weight"],fontStyle:["italic"],textDecoration:["underline","strike"]};export const ALL_QUILL_MIXED_KEYS=Array.from(new Set(c.flatMap(t=>p[t])));function m(t,e,i){var r,l;switch(t){case"fontSize":return null!==(r=o(e.size,i.fontSize))&&void 0!==r?r:i.fontSize;case"fontFamily":return e.font?String(e.font):i.fontFamily;case"fill":return e.gradient||(null!==(l=e.color)&&void 0!==l?l:i.fill);case"fontWeight":return null!=e["font-weight"]?n(e["font-weight"]):n(i.fontWeight);case"fontStyle":return e.italic?"italic":i.fontStyle;case"textDecoration":return f(s(i.textDecoration))}}function x(t,e,o){const n=s(o.textDecoration),i=(o,i)=>n.has(o)?"on":e[i]?"mixed":t[i]?"on":"off",r=function(t,e){const o=t=>"on"===t?[!0]:"off"===t?[!1]:[!0,!1],n=[];for(const i of o(t)){for(const t of o(e)){const e=new Set;i&&e.add("underline"),t&&e.add("line-through"),n.push(f(e))}}return n}(i("underline","underline"),i("line-through","strike"));return{value:1===r.length?r[0]:void 0,mixed:r.length>1,values:r}}export function quillToTextFormat(t,e,o){const n={};for(const i of c){if("textDecoration"!==i){if(p[i].some(t=>!0===e[t])){n[i]={value:void 0,mixed:!0,values:[]}}else{const e=m(i,t,o);n[i]={value:e,mixed:!1,values:[e]}}}else{n.textDecoration=x(t,e,o)}}return n}export function attrsToQuillOps(t,e){var o;const r=[];if(void 0!==t.fontFamily&&r.push(["font",t.fontFamily]),void 0!==t.fontSize&&r.push(["size",`${t.fontSize}px`]),void 0!==t.fill&&(i(String(t.fill))?r.push(["color",!1],["gradient",t.fill]):r.push(["gradient",!1],["color",t.fill])),void 0!==t.fontWeight&&r.push(["font-weight",String(n(t.fontWeight))]),void 0!==t.fontStyle&&r.push(["italic","italic"===t.fontStyle]),void 0!==t.textDecoration){const n=null!==(o=null==e?void 0:e.decorationTokens)&&void 0!==o?o:a,i=s(t.textDecoration);for(const t of a){n.includes(t)&&r.push([u(t),i.has(t)])}}return r}function v(t){return((null==t?void 0:t.selectedElements)||[]).filter(t=>"text"===t.type)}function g(t){const e=getActiveTextEditor();return e&&e.instance&&e.store===t?e:null}export function restoreEditorSelection(t,e){t.composition.isComposing||(t.update(),t.setSelection(e))}export function resolveSelectionScope(t,e){const o=t.getSelection()||e||{index:0,length:0},n="function"==typeof t.getLength?t.getLength():0,i=n<=1;return o.length<=0?{scope:"collapsed",sel:o,isEmpty:i}:{scope:o.length>=n-1?"full":"partial",sel:o,isEmpty:i}}export function applyToLiveEditor(t,e,o,n){const i=attrsToQuillOps(e,n);if(!i.length){return}const{scope:r,sel:l}=resolveSelectionScope(t,null!=o?o:null);for(const[c,a]of i){"collapsed"===r?t.format(c,a,"user"):t.formatText(l.index,l.length,c,a,"user")}"collapsed"===r&&updateActiveTextFormat(t.getFormat(l.index,0),{},l)}function h(t,e){const o="function"==typeof t.getLength?t.getLength():0;t.formatText(0,o,e,!0,"api")}export function getTextFormatState(t){const e=g(t),o=v(t),n=!!e||o.length>0;var i;return{format:e?quillToTextFormat(e.currentFormat||{},e.mixedFormats||{},{fontSize:(i=e.element).fontSize,fontFamily:i.fontFamily,fill:i.fill,fontWeight:i.fontWeight,fontStyle:i.fontStyle,textDecoration:i.textDecoration}):r(o),enabled:n,applyTextFormat:(e,o)=>function(t,e,o){const n=g(t);if(!n){return void l(v(t),e,o)}const{scope:i,sel:r,isEmpty:c}=resolveSelectionScope(n.instance,n.lastSelection);"full"===i||"collapsed"===i&&!c?l([n.element],e,o):function(t,e,o,n){var i,r;const l=t.instance,c=t.element;let d=!1;if(n.length>0){if(void 0!==e.fontStyle&&"italic"!==e.fontStyle&&"italic"===c.fontStyle&&(h(l,"italic"),c.set({fontStyle:"normal"}),d=!0),void 0!==e.textDecoration){const t=null!==(i=null==o?void 0:o.decorationTokens)&&void 0!==i?i:a,n=s(e.textDecoration),r=s(c.textDecoration),p=t.filter(t=>!n.has(t)&&r.has(t));for(const e of p){h(l,u(e)),r.delete(e)}p.length&&(c.set({textDecoration:f(r)}),d=!0)}d&&"function"==typeof(null===(r=l.history)||void 0===r?void 0:r.clear)&&l.history.clear()}applyToLiveEditor(l,e,n,o)}(n,e,o,r)}(t,e,o)}}export function observeTextFormatState(t,o){return e.reaction(()=>getTextFormatState(t),t=>o(t),{fireImmediately:!0})}export function useTextFormat(e){const[o,n]=t.useState(()=>getTextFormatState(e));return t.useEffect(()=>observeTextFormatState(e,n),[e]),o}
@@ -1 +1 @@
1
- import*as e from"mobx";import{getAPI as o}from"./api.js";import{setRemoveBackgroundEnabled as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";export const setKey=e=>{s=e||""};let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const p=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let u=fetch;export const __=e=>{u=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await u(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"4.13.0"})});if(e.runInAction(()=>{a.value=r.headers.get("x-api-version")||""}),!n){return console.error("Polotno API is initialized without API key. It may lead to unexpected behavior and stop working. Please create API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1}),!1}if(200!==r.status){await new Promise(e=>setTimeout(e,3e3));continue}const s=await r.json();return s.is_valid||(console.error("Polotno API key is not valid. Please get new API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1})),s.is_paid||(console.log("%cPolotno Free Version. For development usage only. https://polotno.com/","background: rgb(0, 161, 255); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{0===i.value&&(i.value=2)})),s.is_domain_valid||console.log(p,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),t(s.remove_background_enabled),s.is_paid||!1}catch(r){await new Promise(e=>setTimeout(e,3e3))}}return console.error("Can not validate Polotno API key. Please report to anton@polotno.com immediately."),!0}export async function validateKey(e){await isKeyPaid(s)&&!e||r()}
1
+ import*as e from"mobx";import{getAPI as o}from"./api.js";import{setRemoveBackgroundEnabled as t}from"./flags.js";const n=e.observable({value:!1}),a=e.observable({value:"v1"});export const ___=()=>a.value;const i=e.observable({value:0});export const ____=()=>i.value;export const isCreditVisible=()=>n.value;const r=e.action(()=>{n.value=!0});let s="";export const getKey=()=>s||"";export const setKey=e=>{s=e||""};let l="undefined"!=typeof window?window.location.origin:"";const c="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Headless")>-1,d="undefined"!=typeof navigator&&navigator.userAgent.indexOf("Electron")>-1;"file://"===l&&c&&(l="headless"),"file://"===l&&d&&(l="electron");const p=`%cPolotno error! Current domain is not allowed. It may lead to unexpected behavior and stop working. Please add "${l}" here: https://polotno.com/cabinet`;let u=fetch;export const __=e=>{u=e};export async function isKeyPaid(n){for(let s=0;s<5;s++){try{const r=await u(o()+"/validate-key",{method:"POST",body:JSON.stringify({key:n,site:location.host,skdVersion:"4.14.0"})});if(e.runInAction(()=>{a.value=r.headers.get("x-api-version")||""}),!n){return console.error("Polotno API is initialized without API key. It may lead to unexpected behavior and stop working. Please create API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1}),!1}if(200!==r.status){await new Promise(e=>setTimeout(e,3e3));continue}const s=await r.json();return s.is_valid||(console.error("Polotno API key is not valid. Please get new API key here: https://polotno.com/cabinet"),e.runInAction(()=>{i.value=1})),s.is_paid||(console.log("%cPolotno Free Version. For development usage only. https://polotno.com/","background: rgb(0, 161, 255); color: white; padding: 5px; margin: 5px;"),e.runInAction(()=>{0===i.value&&(i.value=2)})),s.is_domain_valid||console.log(p,"background: rgba(247, 101, 68, 1); color: white; padding: 5px; margin: 5px;"),t(s.remove_background_enabled),s.is_paid||!1}catch(r){await new Promise(e=>setTimeout(e,3e3))}}return console.error("Can not validate Polotno API key. Please report to anton@polotno.com immediately."),!0}export async function validateKey(e){await isKeyPaid(s)&&!e||r()}