fabricjs-document-engine 1.1.0 → 1.2.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 (70) hide show
  1. package/README.md +39 -1
  2. package/README.zh-CN.md +39 -1
  3. package/dist/assets/asset-pipeline.cjs +10 -8
  4. package/dist/assets/asset-pipeline.d.cts +1 -1
  5. package/dist/assets/asset-pipeline.d.ts +1 -1
  6. package/dist/assets/asset-pipeline.js +10 -8
  7. package/dist/assets/image-check.cjs +4 -3
  8. package/dist/assets/image-check.d.cts +1 -1
  9. package/dist/assets/image-check.d.ts +1 -1
  10. package/dist/assets/image-check.js +4 -3
  11. package/dist/commands/clipboard.cjs +5 -0
  12. package/dist/commands/clipboard.js +5 -0
  13. package/dist/document/document-format.d.cts +15 -0
  14. package/dist/document/document-format.d.ts +15 -0
  15. package/dist/document/validate-document.cjs +8 -0
  16. package/dist/document/validate-document.js +8 -0
  17. package/dist/engine/create-document-engine.cjs +115 -21
  18. package/dist/engine/create-document-engine.d.cts +24 -6
  19. package/dist/engine/create-document-engine.d.ts +24 -6
  20. package/dist/engine/create-document-engine.js +116 -22
  21. package/dist/engine/errors.d.cts +1 -1
  22. package/dist/engine/errors.d.ts +1 -1
  23. package/dist/export/export-options.cjs +3 -0
  24. package/dist/export/export-options.d.cts +6 -0
  25. package/dist/export/export-options.d.ts +6 -0
  26. package/dist/export/export-options.js +3 -0
  27. package/dist/export/preflight-export.d.cts +1 -1
  28. package/dist/export/preflight-export.d.ts +1 -1
  29. package/dist/export/render-export.cjs +42 -4
  30. package/dist/export/render-export.js +43 -5
  31. package/dist/export/svg/clip-masks.cjs +39 -0
  32. package/dist/export/svg/clip-masks.js +37 -0
  33. package/dist/export/svg/embed-assets.cjs +1 -0
  34. package/dist/export/svg/embed-assets.js +1 -0
  35. package/dist/export/svg/raster-object.cjs +82 -0
  36. package/dist/export/svg/raster-object.js +81 -0
  37. package/dist/{pdf → export/svg}/text-decorations.cjs +3 -3
  38. package/dist/{pdf → export/svg}/text-decorations.js +3 -3
  39. package/dist/export/svg/text-on-path.cjs +0 -10
  40. package/dist/export/svg/text-on-path.js +1 -10
  41. package/dist/fabric/fabric-adapter.cjs +5 -3
  42. package/dist/fabric/fabric-adapter.js +5 -3
  43. package/dist/fabric/page-state.cjs +69 -0
  44. package/dist/fabric/page-state.js +64 -0
  45. package/dist/history/apply-state.cjs +19 -2
  46. package/dist/history/apply-state.js +19 -2
  47. package/dist/history/create-history.cjs +53 -13
  48. package/dist/history/create-history.d.cts +8 -0
  49. package/dist/history/create-history.d.ts +8 -0
  50. package/dist/history/create-history.js +53 -13
  51. package/dist/history/snapshot.cjs +10 -1
  52. package/dist/history/snapshot.js +10 -2
  53. package/dist/index.d.cts +3 -3
  54. package/dist/index.d.ts +3 -3
  55. package/dist/migrations/migrate-document.cjs +2 -1
  56. package/dist/migrations/migrate-document.js +2 -1
  57. package/dist/pdf/export-pdf.cjs +8 -67
  58. package/dist/pdf/export-pdf.js +8 -67
  59. package/dist/recovery/recovery-controller.cjs +148 -29
  60. package/dist/recovery/recovery-controller.d.cts +8 -0
  61. package/dist/recovery/recovery-controller.d.ts +8 -0
  62. package/dist/recovery/recovery-controller.js +148 -29
  63. package/dist/security/content-limits.cjs +43 -3
  64. package/dist/security/content-limits.d.cts +8 -0
  65. package/dist/security/content-limits.d.ts +8 -0
  66. package/dist/security/content-limits.js +39 -4
  67. package/dist/util/concurrency.cjs +16 -3
  68. package/dist/util/concurrency.js +16 -3
  69. package/package.json +1 -1
  70. package/schema/document-v1.schema.json +5 -1
@@ -1,6 +1,6 @@
1
+ const require_snapshot = require("./snapshot.cjs");
1
2
  const require_apply_state = require("./apply-state.cjs");
2
3
  const require_history_stack = require("./history-stack.cjs");
3
- const require_snapshot = require("./snapshot.cjs");
4
4
  //#region src/history/create-history.ts
5
5
  const verbsByAction = {
6
6
  drag: "Move",
@@ -24,18 +24,23 @@ function describePendingChanges(changes) {
24
24
  return changes.length === 1 ? `${verb} ${changes[0].noun}` : `${verb} ${changes.length} objects`;
25
25
  }
26
26
  function createHistory(options) {
27
- const { canvas, serializeObjects, onChange, onContentChange } = options;
27
+ const { canvas, serializeState, onChange, onContentChange, onLiveChange } = options;
28
+ const takeSnapshot = () => {
29
+ const { objects, page } = serializeState();
30
+ return require_snapshot.createSnapshot(objects, page);
31
+ };
28
32
  const stack = require_history_stack.createHistoryStack({
29
33
  steps: Math.max(1, options.limit ?? 100),
30
34
  bytes: Math.max(0, options.maxBytes ?? 67108864)
31
35
  });
32
- let snapshot = require_snapshot.createSnapshot(serializeObjects());
36
+ let snapshot = takeSnapshot();
33
37
  let pendingChanges = [];
34
38
  let flushScheduled = false;
35
39
  let transactionDepth = 0;
36
40
  let pausedDepth = 0;
37
41
  let applying = false;
38
42
  let queue = Promise.resolve();
43
+ let epoch = 0;
39
44
  function state() {
40
45
  const undoLabels = stack.undoLabels();
41
46
  const redoLabels = stack.redoLabels();
@@ -48,7 +53,7 @@ function createHistory(options) {
48
53
  }
49
54
  function commit(label) {
50
55
  pendingChanges = [];
51
- const nextSnapshot = require_snapshot.createSnapshot(serializeObjects());
56
+ const nextSnapshot = takeSnapshot();
52
57
  const difference = require_snapshot.diffSnapshots(snapshot, nextSnapshot);
53
58
  snapshot = nextSnapshot;
54
59
  if (difference === null) return false;
@@ -86,26 +91,56 @@ function createHistory(options) {
86
91
  notice(verbsByAction[action] ?? "Transform", event.target);
87
92
  };
88
93
  const handleTextEdited = ({ target }) => notice("Edit", target);
94
+ const handleTextChanged = () => {
95
+ if (!applying && pausedDepth === 0) onLiveChange?.();
96
+ };
89
97
  const listeners = [
90
98
  ["object:added", handleAdded],
91
99
  ["object:removed", handleRemoved],
92
100
  ["object:modified", handleModified],
93
- ["text:editing:exited", handleTextEdited]
101
+ ["text:editing:exited", handleTextEdited],
102
+ ["text:changed", handleTextChanged]
94
103
  ];
95
104
  const eventTarget = canvas;
96
105
  listeners.forEach(([name, handler]) => eventTarget.on(name, handler));
97
- function transaction(label, work) {
106
+ /**
107
+ * Puts the canvas back to the last recorded snapshot. The snapshot is the
108
+ * state before the transaction, so the difference to undo is exactly what
109
+ * the transaction changed: one serialization, then only the changed
110
+ * objects are rebuilt.
111
+ */
112
+ function rollBack() {
113
+ const difference = require_snapshot.diffSnapshots(snapshot, takeSnapshot());
114
+ pendingChanges = [];
115
+ if (difference === null) return Promise.resolve();
116
+ applying = true;
117
+ return runInOrder(async () => {
118
+ try {
119
+ await require_apply_state.applyStateChange(canvas, difference.before);
120
+ } finally {
121
+ applying = false;
122
+ }
123
+ });
124
+ }
125
+ function transaction(label, work, transactionOptions = {}) {
98
126
  if (transactionDepth === 0) commitPendingChanges();
127
+ const outermost = transactionDepth === 0;
99
128
  transactionDepth += 1;
100
129
  const finish = () => {
101
130
  transactionDepth -= 1;
102
131
  if (transactionDepth === 0) commit(label);
103
132
  };
133
+ const fail = () => {
134
+ transactionDepth -= 1;
135
+ if (transactionDepth > 0) return void 0;
136
+ if (outermost && transactionOptions.rollback) return rollBack();
137
+ commit(label);
138
+ };
104
139
  let result;
105
140
  try {
106
141
  result = work();
107
142
  } catch (error) {
108
- finish();
143
+ fail()?.catch(() => void 0);
109
144
  throw error;
110
145
  }
111
146
  if (!isPromiseLike(result)) {
@@ -115,8 +150,8 @@ function createHistory(options) {
115
150
  return Promise.resolve(result).then((value) => {
116
151
  finish();
117
152
  return value;
118
- }, (error) => {
119
- finish();
153
+ }, async (error) => {
154
+ await fail();
120
155
  throw error;
121
156
  });
122
157
  }
@@ -148,16 +183,19 @@ function createHistory(options) {
148
183
  commitPendingChanges();
149
184
  const step = takeStep();
150
185
  if (step === void 0) return false;
186
+ const startedIn = epoch;
151
187
  applying = true;
188
+ let applied;
152
189
  try {
153
- await require_apply_state.applyStateChange(canvas, pickChange(step));
190
+ applied = await require_apply_state.applyStateChange(canvas, pickChange(step), () => epoch !== startedIn);
154
191
  } catch (error) {
155
- putBack(step);
192
+ if (epoch === startedIn) putBack(step);
156
193
  throw error;
157
194
  } finally {
158
195
  applying = false;
159
196
  }
160
- snapshot = require_snapshot.createSnapshot(serializeObjects());
197
+ if (!applied) return false;
198
+ snapshot = takeSnapshot();
161
199
  moveTo(step);
162
200
  onContentChange();
163
201
  onChange(state());
@@ -170,6 +208,7 @@ function createHistory(options) {
170
208
  return commit(label);
171
209
  },
172
210
  transaction,
211
+ settled: () => queue.then(() => void 0),
173
212
  undo: () => travel(() => stack.takeUndo(), (step) => step.before, (step) => stack.returnUndo(step), (step) => stack.returnRedo(step)),
174
213
  redo: () => travel(() => stack.takeRedo(), (step) => step.after, (step) => stack.returnRedo(step), (step) => stack.returnUndo(step)),
175
214
  state,
@@ -182,7 +221,8 @@ function createHistory(options) {
182
221
  reset() {
183
222
  pendingChanges = [];
184
223
  stack.clear();
185
- snapshot = require_snapshot.createSnapshot(serializeObjects());
224
+ epoch += 1;
225
+ snapshot = takeSnapshot();
186
226
  onChange(state());
187
227
  },
188
228
  destroy() {
@@ -10,4 +10,12 @@ export interface HistoryState {
10
10
  undoLabel: string | undefined;
11
11
  redoLabel: string | undefined;
12
12
  }
13
+ export interface TransactionOptions {
14
+ /**
15
+ * When `work` throws or rejects, put the canvas back as it was before the
16
+ * transaction, record no undo step and leave the document's unsaved state
17
+ * alone. Applies to the outermost transaction.
18
+ */
19
+ rollback?: boolean;
20
+ }
13
21
  //#endregion
@@ -10,4 +10,12 @@ export interface HistoryState {
10
10
  undoLabel: string | undefined;
11
11
  redoLabel: string | undefined;
12
12
  }
13
+ export interface TransactionOptions {
14
+ /**
15
+ * When `work` throws or rejects, put the canvas back as it was before the
16
+ * transaction, record no undo step and leave the document's unsaved state
17
+ * alone. Applies to the outermost transaction.
18
+ */
19
+ rollback?: boolean;
20
+ }
13
21
  //#endregion
@@ -1,6 +1,6 @@
1
+ import { createSnapshot, diffSnapshots } from "./snapshot.js";
1
2
  import { applyStateChange } from "./apply-state.js";
2
3
  import { createHistoryStack } from "./history-stack.js";
3
- import { createSnapshot, diffSnapshots } from "./snapshot.js";
4
4
  //#region src/history/create-history.ts
5
5
  const verbsByAction = {
6
6
  drag: "Move",
@@ -24,18 +24,23 @@ function describePendingChanges(changes) {
24
24
  return changes.length === 1 ? `${verb} ${changes[0].noun}` : `${verb} ${changes.length} objects`;
25
25
  }
26
26
  function createHistory(options) {
27
- const { canvas, serializeObjects, onChange, onContentChange } = options;
27
+ const { canvas, serializeState, onChange, onContentChange, onLiveChange } = options;
28
+ const takeSnapshot = () => {
29
+ const { objects, page } = serializeState();
30
+ return createSnapshot(objects, page);
31
+ };
28
32
  const stack = createHistoryStack({
29
33
  steps: Math.max(1, options.limit ?? 100),
30
34
  bytes: Math.max(0, options.maxBytes ?? 67108864)
31
35
  });
32
- let snapshot = createSnapshot(serializeObjects());
36
+ let snapshot = takeSnapshot();
33
37
  let pendingChanges = [];
34
38
  let flushScheduled = false;
35
39
  let transactionDepth = 0;
36
40
  let pausedDepth = 0;
37
41
  let applying = false;
38
42
  let queue = Promise.resolve();
43
+ let epoch = 0;
39
44
  function state() {
40
45
  const undoLabels = stack.undoLabels();
41
46
  const redoLabels = stack.redoLabels();
@@ -48,7 +53,7 @@ function createHistory(options) {
48
53
  }
49
54
  function commit(label) {
50
55
  pendingChanges = [];
51
- const nextSnapshot = createSnapshot(serializeObjects());
56
+ const nextSnapshot = takeSnapshot();
52
57
  const difference = diffSnapshots(snapshot, nextSnapshot);
53
58
  snapshot = nextSnapshot;
54
59
  if (difference === null) return false;
@@ -86,26 +91,56 @@ function createHistory(options) {
86
91
  notice(verbsByAction[action] ?? "Transform", event.target);
87
92
  };
88
93
  const handleTextEdited = ({ target }) => notice("Edit", target);
94
+ const handleTextChanged = () => {
95
+ if (!applying && pausedDepth === 0) onLiveChange?.();
96
+ };
89
97
  const listeners = [
90
98
  ["object:added", handleAdded],
91
99
  ["object:removed", handleRemoved],
92
100
  ["object:modified", handleModified],
93
- ["text:editing:exited", handleTextEdited]
101
+ ["text:editing:exited", handleTextEdited],
102
+ ["text:changed", handleTextChanged]
94
103
  ];
95
104
  const eventTarget = canvas;
96
105
  listeners.forEach(([name, handler]) => eventTarget.on(name, handler));
97
- function transaction(label, work) {
106
+ /**
107
+ * Puts the canvas back to the last recorded snapshot. The snapshot is the
108
+ * state before the transaction, so the difference to undo is exactly what
109
+ * the transaction changed: one serialization, then only the changed
110
+ * objects are rebuilt.
111
+ */
112
+ function rollBack() {
113
+ const difference = diffSnapshots(snapshot, takeSnapshot());
114
+ pendingChanges = [];
115
+ if (difference === null) return Promise.resolve();
116
+ applying = true;
117
+ return runInOrder(async () => {
118
+ try {
119
+ await applyStateChange(canvas, difference.before);
120
+ } finally {
121
+ applying = false;
122
+ }
123
+ });
124
+ }
125
+ function transaction(label, work, transactionOptions = {}) {
98
126
  if (transactionDepth === 0) commitPendingChanges();
127
+ const outermost = transactionDepth === 0;
99
128
  transactionDepth += 1;
100
129
  const finish = () => {
101
130
  transactionDepth -= 1;
102
131
  if (transactionDepth === 0) commit(label);
103
132
  };
133
+ const fail = () => {
134
+ transactionDepth -= 1;
135
+ if (transactionDepth > 0) return void 0;
136
+ if (outermost && transactionOptions.rollback) return rollBack();
137
+ commit(label);
138
+ };
104
139
  let result;
105
140
  try {
106
141
  result = work();
107
142
  } catch (error) {
108
- finish();
143
+ fail()?.catch(() => void 0);
109
144
  throw error;
110
145
  }
111
146
  if (!isPromiseLike(result)) {
@@ -115,8 +150,8 @@ function createHistory(options) {
115
150
  return Promise.resolve(result).then((value) => {
116
151
  finish();
117
152
  return value;
118
- }, (error) => {
119
- finish();
153
+ }, async (error) => {
154
+ await fail();
120
155
  throw error;
121
156
  });
122
157
  }
@@ -148,16 +183,19 @@ function createHistory(options) {
148
183
  commitPendingChanges();
149
184
  const step = takeStep();
150
185
  if (step === void 0) return false;
186
+ const startedIn = epoch;
151
187
  applying = true;
188
+ let applied;
152
189
  try {
153
- await applyStateChange(canvas, pickChange(step));
190
+ applied = await applyStateChange(canvas, pickChange(step), () => epoch !== startedIn);
154
191
  } catch (error) {
155
- putBack(step);
192
+ if (epoch === startedIn) putBack(step);
156
193
  throw error;
157
194
  } finally {
158
195
  applying = false;
159
196
  }
160
- snapshot = createSnapshot(serializeObjects());
197
+ if (!applied) return false;
198
+ snapshot = takeSnapshot();
161
199
  moveTo(step);
162
200
  onContentChange();
163
201
  onChange(state());
@@ -170,6 +208,7 @@ function createHistory(options) {
170
208
  return commit(label);
171
209
  },
172
210
  transaction,
211
+ settled: () => queue.then(() => void 0),
173
212
  undo: () => travel(() => stack.takeUndo(), (step) => step.before, (step) => stack.returnUndo(step), (step) => stack.returnRedo(step)),
174
213
  redo: () => travel(() => stack.takeRedo(), (step) => step.after, (step) => stack.returnRedo(step), (step) => stack.returnUndo(step)),
175
214
  state,
@@ -182,7 +221,8 @@ function createHistory(options) {
182
221
  reset() {
183
222
  pendingChanges = [];
184
223
  stack.clear();
185
- snapshot = createSnapshot(serializeObjects());
224
+ epoch += 1;
225
+ snapshot = takeSnapshot();
186
226
  onChange(state());
187
227
  },
188
228
  destroy() {
@@ -1,7 +1,15 @@
1
1
  //#region src/history/snapshot.ts
2
- function createSnapshot(objects) {
2
+ /**
3
+ * The page itself (size, background, overlay, mask) is one more entry in the
4
+ * same map under this reserved key. It never appears in `order`, so the
5
+ * diff stays proportional to what changed and object ordering is unaffected.
6
+ * Object ids come from `createId`, which never produces this value.
7
+ */
8
+ const PAGE_KEY = "__page__";
9
+ function createSnapshot(objects, page) {
3
10
  const objectsById = /* @__PURE__ */ new Map();
4
11
  const order = [];
12
+ if (page !== void 0) objectsById.set(PAGE_KEY, JSON.stringify(page));
5
13
  for (const object of objects) {
6
14
  const id = object.id ?? "";
7
15
  objectsById.set(id, JSON.stringify(object));
@@ -43,5 +51,6 @@ function diffSnapshots(previous, next) {
43
51
  };
44
52
  }
45
53
  //#endregion
54
+ exports.PAGE_KEY = PAGE_KEY;
46
55
  exports.createSnapshot = createSnapshot;
47
56
  exports.diffSnapshots = diffSnapshots;
@@ -1,7 +1,15 @@
1
1
  //#region src/history/snapshot.ts
2
- function createSnapshot(objects) {
2
+ /**
3
+ * The page itself (size, background, overlay, mask) is one more entry in the
4
+ * same map under this reserved key. It never appears in `order`, so the
5
+ * diff stays proportional to what changed and object ordering is unaffected.
6
+ * Object ids come from `createId`, which never produces this value.
7
+ */
8
+ const PAGE_KEY = "__page__";
9
+ function createSnapshot(objects, page) {
3
10
  const objectsById = /* @__PURE__ */ new Map();
4
11
  const order = [];
12
+ if (page !== void 0) objectsById.set(PAGE_KEY, JSON.stringify(page));
5
13
  for (const object of objects) {
6
14
  const id = object.id ?? "";
7
15
  objectsById.set(id, JSON.stringify(object));
@@ -43,4 +51,4 @@ function diffSnapshots(previous, next) {
43
51
  };
44
52
  }
45
53
  //#endregion
46
- export { createSnapshot, diffSnapshots };
54
+ export { PAGE_KEY, createSnapshot, diffSnapshots };
package/dist/index.d.cts CHANGED
@@ -9,7 +9,7 @@ import { ContentLimits, isSafeImageUrl, refuseUnsafeImageUrls, secureDocument }
9
9
  import { SvgImportOptions, SvgImportResult, SvgImportWarning, SvgImportWarningCode } from "./import/svg-import.cjs";
10
10
  import { NewDocumentOptions } from "./document/create-document.cjs";
11
11
  import { CustomObjectDefinition } from "./fabric/object-registry.cjs";
12
- import { HistoryOptions, HistoryState } from "./history/create-history.cjs";
12
+ import { HistoryOptions, HistoryState, TransactionOptions } from "./history/create-history.cjs";
13
13
  import { DocumentVersion, VersionKind, VersionOptions, VersionStorage, VersionSummary } from "./versions/document-version.cjs";
14
14
  import { RecoveryStore } from "./recovery/recovery-store.cjs";
15
15
  import { InterruptedLoad, RecoveryOptions, RecoveryRecord } from "./recovery/recovery-controller.cjs";
@@ -19,7 +19,7 @@ import { DocumentEngineError, DocumentEngineErrorDetails, DocumentErrorCode, Doc
19
19
  import { DocumentStorage, SaveContext, SaveResult } from "./storage/storage-contract.cjs";
20
20
  import { SaveOptions, SaveRetryEvent, SaveState, SaveStatus } from "./save/save-controller.cjs";
21
21
  import { Unsubscribe } from "./engine/event-emitter.cjs";
22
- import { DocumentEngine, DocumentEngineEvents, DocumentEngineOptions, ExportResult, ImportOptions, LoadOptions, LoadProgress, LoadStage, NewDocumentRequest, createDocumentEngine } from "./engine/create-document-engine.cjs";
22
+ import { DocumentEngine, DocumentEngineEvents, DocumentEngineOptions, ExportResult, ImportOptions, LoadOptions, LoadProgress, LoadStage, NewDocumentRequest, PageChanges, RestoreRecoveryOptions, createDocumentEngine } from "./engine/create-document-engine.cjs";
23
23
  import { validateDocument } from "./document/validate-document.cjs";
24
24
  import { KeyboardShortcutOptions, UndoRedoTarget, bindKeyboardShortcuts } from "./history/keyboard-shortcuts.cjs";
25
25
  import { UnsavedChangesSource, bindUnsavedChangesWarning } from "./save/unsaved-changes-warning.cjs";
@@ -29,4 +29,4 @@ import { Migration, MigrationContext, MigrationResult, detectSchemaVersion, migr
29
29
  import { DocumentState, DocumentStateStore, createDocumentStateStore } from "./state/document-state-store.cjs";
30
30
  import { CLIPBOARD_FORMAT, Clipboard, ClipboardContent, ClipboardOptions, PasteOptions, createClipboard } from "./commands/clipboard.cjs";
31
31
  import { LayerInfo, LayerOptions, LayerPin, bringForward, bringToFront, getLayers, moveToIndex, sendBackward, sendToBack } from "./commands/layers.cjs";
32
- export { type AssetManifest, type AssetOptions, type AssetReport, type AssetWarning, type AssetWarningCode, type AutosaveOptions, CLIPBOARD_FORMAT, CURRENT_SCHEMA_VERSION, type Clipboard, type ClipboardContent, type ClipboardOptions, type ContentLimits, type CustomObjectDefinition, type DocumentCanvas, type DocumentEngine, DocumentEngineError, type DocumentEngineErrorDetails, type DocumentEngineEvents, type DocumentEngineOptions, type DocumentErrorCode, type DocumentInfo, type DocumentIssue, type DocumentState, type DocumentStateStore, type DocumentStorage, type DocumentVersion, type DownloadableExport, type ExportArea, type ExportBackground, type ExportFormat, type ExportOptions, type ExportPreflight, type ExportProblem, type ExportProblemCode, type ExportRect, type ExportResult, type FabricDocument, type FontAsset, type FontLoader, type FontSource, type HistoryOptions, type HistoryState, type ImageAsset, type ImageFailureReason, type ImageLoadFailure, type ImportOptions, type InterruptedLoad, type KeyboardShortcutOptions, type LayerInfo, type LayerOptions, type LayerPin, type LoadOptions, type LoadProgress, type LoadStage, type Migration, type MigrationContext, type MigrationResult, type NewDocumentOptions, type NewDocumentRequest, type PasteOptions, type RecoveryOptions, type RecoveryRecord, type RecoveryStore, type RenderDocumentsOptions, type RenderedDocument, type RetryOptions, type SaveContext, type SaveOptions, type SaveResult, type SaveRetryEvent, type SaveState, type SaveStatus, type SerializedFabricObject, type SvgExportOptions, type SvgImportOptions, type SvgImportResult, type SvgImportWarning, type SvgImportWarningCode, type UndoRedoTarget, type UnsavedChangesSource, type Unsubscribe, type UploadRequest, type VersionKind, type VersionOptions, type VersionStorage, type VersionSummary, bindKeyboardShortcuts, bindUnsavedChangesWarning, bringForward, bringToFront, createClipboard, createConflictError, createDocumentEngine, createDocumentStateStore, detectSchemaVersion, downloadExport, getLayers, isDocumentEngineError, isSafeImageUrl, migrateDocument, moveToIndex, refuseUnsafeImageUrls, renderDocuments, secureDocument, sendBackward, sendToBack, validateDocument };
32
+ export { type AssetManifest, type AssetOptions, type AssetReport, type AssetWarning, type AssetWarningCode, type AutosaveOptions, CLIPBOARD_FORMAT, CURRENT_SCHEMA_VERSION, type Clipboard, type ClipboardContent, type ClipboardOptions, type ContentLimits, type CustomObjectDefinition, type DocumentCanvas, type DocumentEngine, DocumentEngineError, type DocumentEngineErrorDetails, type DocumentEngineEvents, type DocumentEngineOptions, type DocumentErrorCode, type DocumentInfo, type DocumentIssue, type DocumentState, type DocumentStateStore, type DocumentStorage, type DocumentVersion, type DownloadableExport, type ExportArea, type ExportBackground, type ExportFormat, type ExportOptions, type ExportPreflight, type ExportProblem, type ExportProblemCode, type ExportRect, type ExportResult, type FabricDocument, type FontAsset, type FontLoader, type FontSource, type HistoryOptions, type HistoryState, type ImageAsset, type ImageFailureReason, type ImageLoadFailure, type ImportOptions, type InterruptedLoad, type KeyboardShortcutOptions, type LayerInfo, type LayerOptions, type LayerPin, type LoadOptions, type LoadProgress, type LoadStage, type Migration, type MigrationContext, type MigrationResult, type NewDocumentOptions, type NewDocumentRequest, type PageChanges, type PasteOptions, type RecoveryOptions, type RecoveryRecord, type RecoveryStore, type RenderDocumentsOptions, type RenderedDocument, type RestoreRecoveryOptions, type RetryOptions, type SaveContext, type SaveOptions, type SaveResult, type SaveRetryEvent, type SaveState, type SaveStatus, type SerializedFabricObject, type SvgExportOptions, type SvgImportOptions, type SvgImportResult, type SvgImportWarning, type SvgImportWarningCode, type TransactionOptions, type UndoRedoTarget, type UnsavedChangesSource, type Unsubscribe, type UploadRequest, type VersionKind, type VersionOptions, type VersionStorage, type VersionSummary, bindKeyboardShortcuts, bindUnsavedChangesWarning, bringForward, bringToFront, createClipboard, createConflictError, createDocumentEngine, createDocumentStateStore, detectSchemaVersion, downloadExport, getLayers, isDocumentEngineError, isSafeImageUrl, migrateDocument, moveToIndex, refuseUnsafeImageUrls, renderDocuments, secureDocument, sendBackward, sendToBack, validateDocument };
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ import { ContentLimits, isSafeImageUrl, refuseUnsafeImageUrls, secureDocument }
9
9
  import { SvgImportOptions, SvgImportResult, SvgImportWarning, SvgImportWarningCode } from "./import/svg-import.js";
10
10
  import { NewDocumentOptions } from "./document/create-document.js";
11
11
  import { CustomObjectDefinition } from "./fabric/object-registry.js";
12
- import { HistoryOptions, HistoryState } from "./history/create-history.js";
12
+ import { HistoryOptions, HistoryState, TransactionOptions } from "./history/create-history.js";
13
13
  import { DocumentVersion, VersionKind, VersionOptions, VersionStorage, VersionSummary } from "./versions/document-version.js";
14
14
  import { RecoveryStore } from "./recovery/recovery-store.js";
15
15
  import { InterruptedLoad, RecoveryOptions, RecoveryRecord } from "./recovery/recovery-controller.js";
@@ -19,7 +19,7 @@ import { DocumentEngineError, DocumentEngineErrorDetails, DocumentErrorCode, Doc
19
19
  import { DocumentStorage, SaveContext, SaveResult } from "./storage/storage-contract.js";
20
20
  import { SaveOptions, SaveRetryEvent, SaveState, SaveStatus } from "./save/save-controller.js";
21
21
  import { Unsubscribe } from "./engine/event-emitter.js";
22
- import { DocumentEngine, DocumentEngineEvents, DocumentEngineOptions, ExportResult, ImportOptions, LoadOptions, LoadProgress, LoadStage, NewDocumentRequest, createDocumentEngine } from "./engine/create-document-engine.js";
22
+ import { DocumentEngine, DocumentEngineEvents, DocumentEngineOptions, ExportResult, ImportOptions, LoadOptions, LoadProgress, LoadStage, NewDocumentRequest, PageChanges, RestoreRecoveryOptions, createDocumentEngine } from "./engine/create-document-engine.js";
23
23
  import { validateDocument } from "./document/validate-document.js";
24
24
  import { KeyboardShortcutOptions, UndoRedoTarget, bindKeyboardShortcuts } from "./history/keyboard-shortcuts.js";
25
25
  import { UnsavedChangesSource, bindUnsavedChangesWarning } from "./save/unsaved-changes-warning.js";
@@ -29,4 +29,4 @@ import { Migration, MigrationContext, MigrationResult, detectSchemaVersion, migr
29
29
  import { DocumentState, DocumentStateStore, createDocumentStateStore } from "./state/document-state-store.js";
30
30
  import { CLIPBOARD_FORMAT, Clipboard, ClipboardContent, ClipboardOptions, PasteOptions, createClipboard } from "./commands/clipboard.js";
31
31
  import { LayerInfo, LayerOptions, LayerPin, bringForward, bringToFront, getLayers, moveToIndex, sendBackward, sendToBack } from "./commands/layers.js";
32
- export { type AssetManifest, type AssetOptions, type AssetReport, type AssetWarning, type AssetWarningCode, type AutosaveOptions, CLIPBOARD_FORMAT, CURRENT_SCHEMA_VERSION, type Clipboard, type ClipboardContent, type ClipboardOptions, type ContentLimits, type CustomObjectDefinition, type DocumentCanvas, type DocumentEngine, DocumentEngineError, type DocumentEngineErrorDetails, type DocumentEngineEvents, type DocumentEngineOptions, type DocumentErrorCode, type DocumentInfo, type DocumentIssue, type DocumentState, type DocumentStateStore, type DocumentStorage, type DocumentVersion, type DownloadableExport, type ExportArea, type ExportBackground, type ExportFormat, type ExportOptions, type ExportPreflight, type ExportProblem, type ExportProblemCode, type ExportRect, type ExportResult, type FabricDocument, type FontAsset, type FontLoader, type FontSource, type HistoryOptions, type HistoryState, type ImageAsset, type ImageFailureReason, type ImageLoadFailure, type ImportOptions, type InterruptedLoad, type KeyboardShortcutOptions, type LayerInfo, type LayerOptions, type LayerPin, type LoadOptions, type LoadProgress, type LoadStage, type Migration, type MigrationContext, type MigrationResult, type NewDocumentOptions, type NewDocumentRequest, type PasteOptions, type RecoveryOptions, type RecoveryRecord, type RecoveryStore, type RenderDocumentsOptions, type RenderedDocument, type RetryOptions, type SaveContext, type SaveOptions, type SaveResult, type SaveRetryEvent, type SaveState, type SaveStatus, type SerializedFabricObject, type SvgExportOptions, type SvgImportOptions, type SvgImportResult, type SvgImportWarning, type SvgImportWarningCode, type UndoRedoTarget, type UnsavedChangesSource, type Unsubscribe, type UploadRequest, type VersionKind, type VersionOptions, type VersionStorage, type VersionSummary, bindKeyboardShortcuts, bindUnsavedChangesWarning, bringForward, bringToFront, createClipboard, createConflictError, createDocumentEngine, createDocumentStateStore, detectSchemaVersion, downloadExport, getLayers, isDocumentEngineError, isSafeImageUrl, migrateDocument, moveToIndex, refuseUnsafeImageUrls, renderDocuments, secureDocument, sendBackward, sendToBack, validateDocument };
32
+ export { type AssetManifest, type AssetOptions, type AssetReport, type AssetWarning, type AssetWarningCode, type AutosaveOptions, CLIPBOARD_FORMAT, CURRENT_SCHEMA_VERSION, type Clipboard, type ClipboardContent, type ClipboardOptions, type ContentLimits, type CustomObjectDefinition, type DocumentCanvas, type DocumentEngine, DocumentEngineError, type DocumentEngineErrorDetails, type DocumentEngineEvents, type DocumentEngineOptions, type DocumentErrorCode, type DocumentInfo, type DocumentIssue, type DocumentState, type DocumentStateStore, type DocumentStorage, type DocumentVersion, type DownloadableExport, type ExportArea, type ExportBackground, type ExportFormat, type ExportOptions, type ExportPreflight, type ExportProblem, type ExportProblemCode, type ExportRect, type ExportResult, type FabricDocument, type FontAsset, type FontLoader, type FontSource, type HistoryOptions, type HistoryState, type ImageAsset, type ImageFailureReason, type ImageLoadFailure, type ImportOptions, type InterruptedLoad, type KeyboardShortcutOptions, type LayerInfo, type LayerOptions, type LayerPin, type LoadOptions, type LoadProgress, type LoadStage, type Migration, type MigrationContext, type MigrationResult, type NewDocumentOptions, type NewDocumentRequest, type PageChanges, type PasteOptions, type RecoveryOptions, type RecoveryRecord, type RecoveryStore, type RenderDocumentsOptions, type RenderedDocument, type RestoreRecoveryOptions, type RetryOptions, type SaveContext, type SaveOptions, type SaveResult, type SaveRetryEvent, type SaveState, type SaveStatus, type SerializedFabricObject, type SvgExportOptions, type SvgImportOptions, type SvgImportResult, type SvgImportWarning, type SvgImportWarningCode, type TransactionOptions, type UndoRedoTarget, type UnsavedChangesSource, type Unsubscribe, type UploadRequest, type VersionKind, type VersionOptions, type VersionStorage, type VersionSummary, bindKeyboardShortcuts, bindUnsavedChangesWarning, bringForward, bringToFront, createClipboard, createConflictError, createDocumentEngine, createDocumentStateStore, detectSchemaVersion, downloadExport, getLayers, isDocumentEngineError, isSafeImageUrl, migrateDocument, moveToIndex, refuseUnsafeImageUrls, renderDocuments, secureDocument, sendBackward, sendToBack, validateDocument };
@@ -1,3 +1,4 @@
1
+ const require_page_state = require("../fabric/page-state.cjs");
1
2
  const require_errors = require("../engine/errors.cjs");
2
3
  require("../document/document-format.cjs");
3
4
  const require_ids = require("../document/ids.cjs");
@@ -19,7 +20,7 @@ function fromFabricJson(json, context) {
19
20
  canvas: {
20
21
  width: positiveNumberOr(json.width, context.canvasWidth),
21
22
  height: positiveNumberOr(json.height, context.canvasHeight),
22
- ...json.background === void 0 ? {} : { background: json.background }
23
+ ...require_page_state.pickPageFields(json)
23
24
  },
24
25
  objects: json.objects,
25
26
  metadata: { ...context.metadata }
@@ -1,3 +1,4 @@
1
+ import { pickPageFields } from "../fabric/page-state.js";
1
2
  import { DocumentEngineError } from "../engine/errors.js";
2
3
  import "../document/document-format.js";
3
4
  import { createId } from "../document/ids.js";
@@ -19,7 +20,7 @@ function fromFabricJson(json, context) {
19
20
  canvas: {
20
21
  width: positiveNumberOr(json.width, context.canvasWidth),
21
22
  height: positiveNumberOr(json.height, context.canvasHeight),
22
- ...json.background === void 0 ? {} : { background: json.background }
23
+ ...pickPageFields(json)
23
24
  },
24
25
  objects: json.objects,
25
26
  metadata: { ...context.metadata }
@@ -3,12 +3,13 @@ const require_object_ids = require("../fabric/object-ids.cjs");
3
3
  const require_walk_objects = require("../fabric/walk-objects.cjs");
4
4
  const require_overrides = require("../export/svg/overrides.cjs");
5
5
  const require_text_on_path = require("../export/svg/text-on-path.cjs");
6
+ const require_raster_object = require("../export/svg/raster-object.cjs");
7
+ const require_text_decorations = require("../export/svg/text-decorations.cjs");
6
8
  const require_render_export = require("../export/render-export.cjs");
7
9
  const require_embed_assets = require("../export/svg/embed-assets.cjs");
8
10
  const require_batch_render = require("../export/batch-render.cjs");
9
11
  const require_fonts = require("./fonts.cjs");
10
12
  const require_page_layout = require("./page-layout.cjs");
11
- const require_text_decorations = require("./text-decorations.cjs");
12
13
  //#region src/pdf/export-pdf.ts
13
14
  const RASTER_REASONS = {
14
15
  shadow: "it has a shadow, which PDF vectors cannot draw",
@@ -16,7 +17,8 @@ const RASTER_REASONS = {
16
17
  gradientStroke: "its outline is a gradient or pattern",
17
18
  uniformStroke: "it keeps its outline width while scaled (strokeUniform)",
18
19
  font: "its font has no TrueType file in fonts",
19
- characters: "it uses characters the built-in PDF fonts do not have; add a TrueType font that has them"
20
+ characters: "it uses characters the built-in PDF fonts do not have; add a TrueType font that has them",
21
+ mask: "it uses an inverted or nested clip path, which PDF vectors cannot draw"
20
22
  };
21
23
  function stop(signal) {
22
24
  if (signal?.aborted) throw new require_errors.DocumentEngineError("EXPORT_ABORTED", "The PDF export was cancelled");
@@ -74,6 +76,7 @@ function rasterReason(object, registered, missingFonts) {
74
76
  require_walk_objects.walkObjects([object], (child) => {
75
77
  if (reason) return;
76
78
  if (child.shadow) reason = "shadow";
79
+ else if (child.clipPath?.inverted || child.clipPath?.clipPath) reason = "mask";
77
80
  else if (child.globalCompositeOperation && child.globalCompositeOperation !== "source-over") reason = "blend";
78
81
  else if (typeof child.stroke === "object" && child.stroke !== null && child.strokeWidth > 0) reason = "gradientStroke";
79
82
  else if (child.strokeUniform && child.stroke && child.strokeWidth > 0) {
@@ -90,69 +93,6 @@ function rasterReason(object, registered, missingFonts) {
90
93
  });
91
94
  return reason;
92
95
  }
93
- function shadowPadding(object) {
94
- let padding = 0;
95
- require_walk_objects.walkObjects([object], (child) => {
96
- const shadow = child.shadow;
97
- if (shadow) padding = Math.max(padding, shadow.blur + Math.max(Math.abs(shadow.offsetX), Math.abs(shadow.offsetY)));
98
- });
99
- return padding + 2;
100
- }
101
- function usesBlendMode(object) {
102
- let blends = false;
103
- require_walk_objects.walkObjects([object], (child) => {
104
- if (child.globalCompositeOperation && child.globalCompositeOperation !== "source-over") blends = true;
105
- });
106
- return blends;
107
- }
108
- /**
109
- * An object as a picture placed where it sits on the canvas. Usually the
110
- * object alone, so the vectors underneath show through. An object with a
111
- * blend mode mixes with what lies below it, so its picture includes
112
- * everything below it within its bounds, which covers those vectors exactly.
113
- */
114
- function rasterMarkup(canvas, object, multiplier) {
115
- object.setCoords();
116
- const bounds = object.getBoundingRect();
117
- const padding = shadowPadding(object);
118
- const left = Math.max(0, Math.floor(bounds.left - padding));
119
- const top = Math.max(0, Math.floor(bounds.top - padding));
120
- const right = Math.min(canvas.getWidth(), Math.ceil(bounds.left + bounds.width + padding));
121
- const bottom = Math.min(canvas.getHeight(), Math.ceil(bounds.top + bounds.height + padding));
122
- if (right <= left || bottom <= top) return "";
123
- const blends = usesBlendMode(object);
124
- const stack = canvas.getObjects();
125
- const position = stack.indexOf(object);
126
- const saved = {
127
- backgroundColor: canvas.backgroundColor,
128
- backgroundImage: canvas.backgroundImage,
129
- overlayColor: canvas.overlayColor,
130
- overlayImage: canvas.overlayImage
131
- };
132
- if (!blends) {
133
- canvas.backgroundColor = "";
134
- canvas.backgroundImage = void 0;
135
- }
136
- canvas.overlayColor = "";
137
- canvas.overlayImage = void 0;
138
- let element;
139
- try {
140
- const filter = (candidate) => blends ? stack.indexOf(candidate) <= position : candidate === object;
141
- element = canvas.toCanvasElement(multiplier, {
142
- left,
143
- top,
144
- width: right - left,
145
- height: bottom - top,
146
- filter
147
- });
148
- } finally {
149
- Object.assign(canvas, saved);
150
- }
151
- const url = element.toDataURL("image/png");
152
- element.width = 0;
153
- element.height = 0;
154
- return `<image x="${left}" y="${top}" width="${right - left}" height="${bottom - top}" preserveAspectRatio="none" xlink:href="${url}" />\n`;
155
- }
156
96
  function quoteFamily(name) {
157
97
  return /^[a-z-]+$/i.test(name) ? name : `"${name.replace(/"/g, "")}"`;
158
98
  }
@@ -238,7 +178,7 @@ function clipTo(context, draw) {
238
178
  }
239
179
  async function drawRasterPage(canvas, context) {
240
180
  const { layout, options } = context;
241
- const multiplier = layout.scale * (options.dpi ?? 300) / 72;
181
+ const multiplier = require_raster_object.safeMultiplier(layout.scale * (options.dpi ?? 300) / 72, canvas.getWidth(), canvas.getHeight(), options.limits);
242
182
  const element = require_render_export.withExportView(canvas, options.background ?? "keep", "png", () => canvas.toCanvasElement(multiplier));
243
183
  try {
244
184
  await clipTo(context, () => {
@@ -262,7 +202,7 @@ async function drawVectorPage(canvas, context) {
262
202
  const reason = rasterReason(object, registered, missingFonts);
263
203
  if (!reason) continue;
264
204
  if (mode === "hybrid") {
265
- rasters.set(object, rasterMarkup(canvas, object, multiplier));
205
+ rasters.set(object, require_raster_object.rasterMarkup(canvas, object, multiplier, options.limits));
266
206
  warnings.push({
267
207
  code: "PDF_RASTERIZED",
268
208
  message: `An object was drawn as a picture at ${options.dpi ?? 300} dpi because ${RASTER_REASONS[reason]}`,
@@ -295,6 +235,7 @@ async function drawVectorPage(canvas, context) {
295
235
  });
296
236
  const embedded = await require_embed_assets.embedSvgAssets(require_render_export.repairFabricSvg(svg), canvas, {
297
237
  textOnPath: "vector",
238
+ textDecorations: "shapes",
298
239
  embedImages: true,
299
240
  maxEmbeddedImageBytes: Number.MAX_SAFE_INTEGER,
300
241
  embedFonts: {}