@hussmartinez/pdf-sdk 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use client";
2
- import { i as createPdfJsEngine, n as createPdfSession, o as linkDestination, r as createPdfProcessor, s as safeLinkUrl, t as pdfMessages } from "./shared/en-BYB_GHqG.js";
3
- import { createMessages, createShortcutRegistry, createToolRegistry, defineMessages, defineTool, resolveAssetsBase } from "@hussmartinez/sdk-core";
4
- import { AnnouncerProvider, IconButton, OpenIcon, RedoIcon, RotateLeftIcon, RotateRightIcon, Toolbar, ToolbarGroup, UiMessagesProvider, UndoIcon, useAnnounce, usePlatform } from "@hussmartinez/ui/react";
5
- import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
+ import { T as isPdfError, _ as createPdfJsEngine, b as safeLinkUrl, g as createPdfProcessor, n as createPdfSession, r as cleanFileName, t as pdfMessages, y as linkDestination } from "./shared/en-DKR-ngAZ.js";
3
+ import { createMessages, createShortcutRegistry, createToolRegistry, defineMessages, defineTool, plural } from "@hussmartinez/sdk-core";
4
+ import { AnnouncerProvider, Button, DeleteIcon, DownloadIcon, IconButton, MoveDownIcon, MoveUpIcon, OpenIcon, PageAddIcon, RedoIcon, RotateLeftIcon, RotateRightIcon, Toolbar, ToolbarGroup, UiMessagesProvider, UndoIcon, useAnnounce, usePlatform } from "@hussmartinez/ui/react";
5
+ import { Component, createContext, forwardRef, useCallback, useContext, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
6
6
  import { uiMessages } from "@hussmartinez/ui";
7
7
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
8
  // src/features/history/history-tools.ts
@@ -54,41 +54,217 @@ function rotate({ session }, angle) {
54
54
  });
55
55
  }
56
56
  var hasTargets = ({ snapshot }) => hasDocument({ snapshot }) && targetPages(snapshot).length > 0;
57
+ var rotateLeftTool = /* @__PURE__ */ defineTool({
58
+ id: "pdf.rotate-left",
59
+ label: "tools.rotate-left",
60
+ icon: "rotate-left",
61
+ group: "pages",
62
+ isEnabled: hasTargets,
63
+ run: (context) => rotate(context, -90),
64
+ shortcuts: ["["]
65
+ });
66
+ var rotateRightTool = /* @__PURE__ */ defineTool({
67
+ id: "pdf.rotate-right",
68
+ label: "tools.rotate-right",
69
+ icon: "rotate-right",
70
+ group: "pages",
71
+ isEnabled: hasTargets,
72
+ run: (context) => rotate(context, 90),
73
+ shortcuts: ["]"]
74
+ });
75
+ // src/features/pages/delete-tool.ts
76
+ var canDelete = ({ snapshot }) => {
77
+ const targets = targetPages(snapshot).length;
78
+ return hasDocument({ snapshot }) && targets > 0 && targets < snapshot.plan.pages.length;
79
+ };
80
+ function deletePages({ session }) {
81
+ const before = session.getSnapshot();
82
+ if (!canDelete({ snapshot: before })) return;
83
+ const pages = targetPages(before);
84
+ const removed = new Set(pages);
85
+ const first = before.plan.pages.findIndex((page) => removed.has(page.key));
86
+ session.execute({
87
+ type: "pdf.deletePages",
88
+ pages
89
+ });
90
+ const remaining = session.getSnapshot().plan.pages;
91
+ const next = remaining[Math.min(first, remaining.length - 1)];
92
+ if (!next) return;
93
+ session.select([next.key]);
94
+ session.goToPage(next.key);
95
+ }
96
+ var deletePagesTool = /* @__PURE__ */ defineTool({
97
+ id: "pdf.delete-pages",
98
+ label: "tools.delete-pages",
99
+ icon: "delete",
100
+ group: "pages",
101
+ isEnabled: canDelete,
102
+ run: deletePages
103
+ });
104
+ // src/features/pages/insert-tool.ts
105
+ var insertPagesTool = /* @__PURE__ */ defineTool({
106
+ id: "pdf.insert-pages",
107
+ label: "tools.insert-pages",
108
+ icon: "page-add",
109
+ group: "file",
110
+ isEnabled: (state) => hasDocument(state) && !state.inserting,
111
+ run: ({ chooseInsertFile }) => chooseInsertFile?.()
112
+ });
113
+ // src/features/pages/move-tools.ts
114
+ function moveOf(snapshot, direction) {
115
+ if (snapshot.status !== "ready") return void 0;
116
+ const chosen = new Set(targetPages(snapshot));
117
+ const order = snapshot.plan.pages.map((page) => page.key);
118
+ const indexes = order.flatMap((key, index) => chosen.has(key) ? [index] : []);
119
+ const first = indexes[0];
120
+ const last = indexes.at(-1);
121
+ if (first === void 0 || last === void 0) return void 0;
122
+ const pages = indexes.map((index) => order[index]);
123
+ const block = last - first + 1 === pages.length;
124
+ const others = order.length - pages.length;
125
+ if (direction === "earlier") {
126
+ if (block && first === 0) return void 0;
127
+ return {
128
+ pages,
129
+ to: Math.max(0, first - 1)
130
+ };
131
+ }
132
+ if (block && last === order.length - 1) return void 0;
133
+ return {
134
+ pages,
135
+ to: Math.min(others, last + 2 - pages.length)
136
+ };
137
+ }
138
+ function move({ session }, direction) {
139
+ const before = session.getSnapshot();
140
+ const found = moveOf(before, direction);
141
+ if (!found) return;
142
+ session.execute({
143
+ type: "pdf.movePages",
144
+ pages: found.pages,
145
+ to: found.to
146
+ });
147
+ session.select(found.pages);
148
+ const current = before.currentPage;
149
+ session.goToPage(current !== void 0 && found.pages.includes(current) ? current : found.pages[0]);
150
+ }
151
+ var canMove = (direction) => ({ snapshot }) => hasDocument({ snapshot }) && moveOf(snapshot, direction) !== void 0;
57
152
  // src/features/tools.ts
58
153
  var pdfTools = [
59
154
  openTool,
155
+ insertPagesTool,
60
156
  undoTool,
61
157
  redoTool,
158
+ rotateLeftTool,
159
+ rotateRightTool,
62
160
  /* @__PURE__ */ defineTool({
63
- id: "pdf.rotate-left",
64
- label: "tools.rotate-left",
65
- icon: "rotate-left",
161
+ id: "pdf.move-earlier",
162
+ label: "tools.move-earlier",
163
+ icon: "move-up",
66
164
  group: "pages",
67
- isEnabled: hasTargets,
68
- run: (context) => rotate(context, -90),
69
- shortcuts: ["["]
165
+ isEnabled: canMove("earlier"),
166
+ run: (context) => move(context, "earlier")
70
167
  }),
71
168
  /* @__PURE__ */ defineTool({
72
- id: "pdf.rotate-right",
73
- label: "tools.rotate-right",
74
- icon: "rotate-right",
169
+ id: "pdf.move-later",
170
+ label: "tools.move-later",
171
+ icon: "move-down",
75
172
  group: "pages",
76
- isEnabled: hasTargets,
77
- run: (context) => rotate(context, 90),
78
- shortcuts: ["]"]
173
+ isEnabled: canMove("later"),
174
+ run: (context) => move(context, "later")
175
+ }),
176
+ deletePagesTool,
177
+ /* @__PURE__ */ defineTool({
178
+ id: "pdf.download",
179
+ label: "tools.download",
180
+ icon: "download",
181
+ group: "save",
182
+ isEnabled: (state) => hasDocument(state) && !state.saving,
183
+ run: ({ save }) => save?.()
79
184
  })
80
185
  ];
81
186
  var DEFAULT_TOOLBAR = [
82
- ["pdf.open"],
187
+ ["pdf.open", "pdf.insert-pages"],
83
188
  ["pdf.undo", "pdf.redo"],
84
- ["pdf.rotate-left", "pdf.rotate-right"]
189
+ [
190
+ "pdf.rotate-left",
191
+ "pdf.rotate-right",
192
+ "pdf.move-earlier",
193
+ "pdf.move-later",
194
+ "pdf.delete-pages"
195
+ ],
196
+ ["pdf.download"]
85
197
  ];
86
198
  // src/react/context.ts
87
199
  var PdfContext = /* @__PURE__ */ createContext(void 0);
200
+ // src/messages/editor-en.ts
201
+ var pdfEditorText = /* @__PURE__ */ defineMessages({
202
+ "viewer.label": "Document",
203
+ "viewer.empty": "No document is open.",
204
+ "viewer.page": "Page {page} of {count}",
205
+ "viewer.webLink": "Link to {destination}, opens in a new tab",
206
+ "viewer.emailLink": "Email {destination}",
207
+ "thumbnails.label": "Pages",
208
+ "thumbnails.page": "Page {page} of {count}",
209
+ "thumbnails.number": "{page}",
210
+ "editor.label": "PDF editor",
211
+ "editor.start.title": "Open a PDF to get started",
212
+ "editor.start.retryTitle": "Try another PDF",
213
+ "editor.start.choose": "Choose a PDF",
214
+ "editor.start.retry": "Choose another PDF",
215
+ "editor.start.hint": "Or drop one here. Your file stays on this device and is never uploaded.",
216
+ "editor.opening": "Opening the PDF…",
217
+ "editor.opened": /* @__PURE__ */ plural("count", {
218
+ one: "Opened a PDF with {count} page.",
219
+ other: "Opened a PDF with {count} pages."
220
+ }),
221
+ "editor.closed": "The PDF was closed.",
222
+ "editor.undone": "Undone.",
223
+ "editor.redone": "Redone.",
224
+ "editor.rotated": /* @__PURE__ */ plural("count", {
225
+ one: "Rotated {count} page.",
226
+ other: "Rotated {count} pages."
227
+ }),
228
+ "editor.deleted": /* @__PURE__ */ plural("count", {
229
+ one: "Deleted {count} page.",
230
+ other: "Deleted {count} pages."
231
+ }),
232
+ "editor.moved": /* @__PURE__ */ plural("count", {
233
+ one: "Moved {count} page to position {position}.",
234
+ other: "Moved {count} pages to position {position}."
235
+ }),
236
+ "editor.inserted": /* @__PURE__ */ plural("count", {
237
+ one: "Inserted {count} page after page {page}.",
238
+ other: "Inserted {count} pages after page {page}."
239
+ }),
240
+ "editor.historyTrimmed": "To make room for the inserted document, your earliest edits can no longer be undone.",
241
+ "editor.saving": "Preparing the PDF…",
242
+ "editor.cancelSave": "Cancel",
243
+ "editor.saved": "Saved {name}.",
244
+ "editor.ready": "The PDF is ready.",
245
+ "editor.saveFailed": "The PDF couldn't be saved. Please try again.",
246
+ "toolbar.label": "PDF tools",
247
+ "toolbar.groups.file": "File",
248
+ "toolbar.groups.history": "History",
249
+ "toolbar.groups.pages": "Pages",
250
+ "toolbar.groups.save": "Save",
251
+ "toolbar.groups.other": "More tools",
252
+ "tools.open": "Open a PDF",
253
+ "tools.undo": "Undo",
254
+ "tools.redo": "Redo",
255
+ "tools.rotate-left": "Rotate left",
256
+ "tools.rotate-right": "Rotate right",
257
+ "tools.delete-pages": "Delete pages",
258
+ "tools.download": "Download",
259
+ "tools.insert-pages": "Insert pages",
260
+ "tools.move-earlier": "Move earlier",
261
+ "tools.move-later": "Move later"
262
+ });
88
263
  // src/react/editor-messages.ts
89
264
  var pdfEditorMessages = /* @__PURE__ */ defineMessages({
90
265
  ...pdfMessages,
91
- ...uiMessages
266
+ ...uiMessages,
267
+ ...pdfEditorText
92
268
  });
93
269
  // src/react/hooks.ts
94
270
  function usePdfContext(hook) {
@@ -106,46 +282,11 @@ function usePdfDocument() {
106
282
  function usePdfMessages() {
107
283
  return usePdfContext("usePdfMessages").messages;
108
284
  }
109
- // src/react/lazy-ports.ts
110
- function checkAssetsUrl(assetsUrl) {
111
- if (assetsUrl === void 0) return;
112
- if (globalThis.location !== void 0) {
113
- resolveAssetsBase(assetsUrl);
114
- return;
115
- }
116
- const parsed = new URL(String(assetsUrl), "https://server.invalid/");
117
- if (parsed.search || parsed.hash) throw new TypeError("assetsUrl can't have a query or a fragment.");
118
- }
119
- function lazyEngine(create) {
120
- let engine;
121
- return {
122
- open: (source, options) => {
123
- engine ??= create();
124
- return engine.open(source, options);
125
- },
126
- destroy: async () => {
127
- await engine?.destroy();
128
- }
129
- };
130
- }
131
- function lazyProcessor(create) {
132
- let processor;
133
- return {
134
- build: (job, options) => {
135
- processor ??= create();
136
- return processor.build(job, options);
137
- },
138
- destroy: async () => {
139
- await processor?.destroy();
140
- }
141
- };
142
- }
143
285
  // src/react/PdfSessionProvider.tsx
144
286
  function own(props) {
145
287
  const assets = props.assetsUrl === void 0 ? {} : { assetsUrl: props.assetsUrl };
146
- checkAssetsUrl(props.assetsUrl);
147
- const engine = props.engine ?? lazyEngine(() => createPdfJsEngine(assets));
148
- const processor = props.processor ?? lazyProcessor(() => createPdfProcessor(assets));
288
+ const engine = props.engine ?? createPdfJsEngine(assets);
289
+ const processor = props.processor ?? createPdfProcessor(assets);
149
290
  const session = createPdfSession({
150
291
  engine,
151
292
  processor,
@@ -177,7 +318,7 @@ function useProvidedSession(props) {
177
318
  function PdfSessionProvider(props) {
178
319
  const { messages: overrides, locale = "en", children } = props;
179
320
  const session = useProvidedSession(props);
180
- const messages = useMemo(() => createMessages(pdfMessages, {
321
+ const messages = useMemo(() => createMessages(pdfEditorMessages, {
181
322
  locale,
182
323
  ...overrides ? { overrides } : {}
183
324
  }), [locale, overrides]);
@@ -371,6 +512,29 @@ var LETTER$1 = {
371
512
  width: 612,
372
513
  height: 792
373
514
  };
515
+ function focusedThumbnail(root) {
516
+ if (!root) return void 0;
517
+ const active = document.activeElement;
518
+ if (!(active instanceof HTMLElement) || !root.contains(active)) return void 0;
519
+ return active.dataset["hmPageKey"];
520
+ }
521
+ var FocusKeeper = class extends Component {
522
+ getSnapshotBeforeUpdate() {
523
+ return focusedThumbnail(this.props.root.current) ?? null;
524
+ }
525
+ componentDidUpdate(_props, _state, focused) {
526
+ const element = this.props.root.current;
527
+ if (!focused || !element) return;
528
+ const now = document.activeElement;
529
+ if (now !== null && now !== document.body) return;
530
+ const target = this.props.keys.includes(focused) ? focused : this.props.fallback;
531
+ if (!target) return;
532
+ element.querySelector(`[data-hm-page-key="${CSS.escape(target)}"]`)?.focus();
533
+ }
534
+ render() {
535
+ return null;
536
+ }
537
+ };
374
538
  var join$3 = (...names) => names.filter(Boolean).join(" ");
375
539
  function Thumbnail(props) {
376
540
  const { page, index, count, id, selected, current, active, displayWidth, classNames } = props;
@@ -421,7 +585,7 @@ function Thumbnail(props) {
421
585
  });
422
586
  }
423
587
  function PdfThumbnails(props) {
424
- const { className, classNames = {}, unstyled = false, concurrency = 2 } = props;
588
+ const { className, classNames = {}, unstyled = false, concurrency = 2, onDelete, onMove } = props;
425
589
  const session = usePdfSession();
426
590
  const snapshot = usePdfDocument();
427
591
  const messages = usePdfMessages();
@@ -486,6 +650,13 @@ function PdfThumbnails(props) {
486
650
  const onKeyDown = (event) => {
487
651
  if (keys.length === 0) return;
488
652
  const modifier = event.ctrlKey || event.metaKey;
653
+ if (event.altKey && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
654
+ if (onMove && !modifier && !event.shiftKey) {
655
+ event.preventDefault();
656
+ onMove(event.key === "ArrowUp" ? "earlier" : "later");
657
+ }
658
+ return;
659
+ }
489
660
  const move = (index) => {
490
661
  event.preventDefault();
491
662
  const target = Math.max(0, Math.min(keys.length - 1, index));
@@ -513,6 +684,13 @@ function PdfThumbnails(props) {
513
684
  case "Escape":
514
685
  if (active) session.select([active]);
515
686
  break;
687
+ case "Delete":
688
+ case "Backspace":
689
+ if (onDelete && !event.altKey && !modifier && !event.shiftKey) {
690
+ event.preventDefault();
691
+ onDelete();
692
+ }
693
+ break;
516
694
  case "a":
517
695
  case "A": if (modifier) {
518
696
  event.preventDefault();
@@ -523,7 +701,7 @@ function PdfThumbnails(props) {
523
701
  const onPointer = (index, event) => {
524
702
  choose(index, event.shiftKey ? "range" : event.ctrlKey || event.metaKey ? "toggle" : "only");
525
703
  };
526
- return /* @__PURE__ */ jsx("div", {
704
+ return /* @__PURE__ */ jsxs("div", {
527
705
  ref: root,
528
706
  role: "listbox",
529
707
  "aria-label": messages.t("thumbnails.label"),
@@ -533,7 +711,7 @@ function PdfThumbnails(props) {
533
711
  onKeyDown,
534
712
  className: join$3("hm-pdf-thumbnails", className, classNames.root),
535
713
  ...unstyled ? { "data-hm-unstyled": "" } : {},
536
- children: plan.pages.map((page, index) => /* @__PURE__ */ jsx(Thumbnail, {
714
+ children: [plan.pages.map((page, index) => /* @__PURE__ */ jsx(Thumbnail, {
537
715
  page,
538
716
  index,
539
717
  count: keys.length,
@@ -549,7 +727,11 @@ function PdfThumbnails(props) {
549
727
  onMeasured,
550
728
  onPointer,
551
729
  classNames
552
- }, page.key))
730
+ }, page.key)), /* @__PURE__ */ jsx(FocusKeeper, {
731
+ root,
732
+ keys,
733
+ fallback: active
734
+ })]
553
735
  });
554
736
  }
555
737
  // src/react/toolbar/icons.ts
@@ -558,13 +740,28 @@ var pdfIcons = {
558
740
  undo: UndoIcon,
559
741
  redo: RedoIcon,
560
742
  "rotate-left": RotateLeftIcon,
561
- "rotate-right": RotateRightIcon
743
+ "rotate-right": RotateRightIcon,
744
+ delete: DeleteIcon,
745
+ download: DownloadIcon,
746
+ "page-add": PageAddIcon,
747
+ "move-up": MoveUpIcon,
748
+ "move-down": MoveDownIcon
749
+ };
750
+ // src/features/pages/thumbnail-keys.ts
751
+ var THUMBNAIL_KEYS = {
752
+ "pdf.delete-pages": "Delete Backspace",
753
+ "pdf.move-earlier": "Alt+ArrowUp",
754
+ "pdf.move-later": "Alt+ArrowDown"
562
755
  };
563
756
  // src/react/toolbar/PdfToolbar.tsx
564
757
  function PdfToolbar(props) {
565
- const { registry, shortcuts, context, icons, onRun, className } = props;
758
+ const { registry, shortcuts, context, icons, onRun, className, saving = false, inserting = false } = props;
566
759
  const messages = usePdfMessages();
567
- const state = { snapshot: usePdfDocument() };
760
+ const state = {
761
+ snapshot: usePdfDocument(),
762
+ saving,
763
+ inserting
764
+ };
568
765
  const t = messages.t;
569
766
  const run = onRun ?? ((tool) => void tool.run(context));
570
767
  if (registry.toolbar.length === 0) return null;
@@ -575,12 +772,13 @@ function PdfToolbar(props) {
575
772
  label: t(`toolbar.groups.${group[0]?.group ?? "other"}`),
576
773
  children: group.filter((tool) => tool.isAvailable?.(state) ?? true).map((tool) => {
577
774
  const Icon = icons[tool.icon];
578
- const keys = shortcuts?.ariaKeyShortcuts(tool.id);
775
+ const keys = shortcuts?.ariaKeyShortcuts(tool.id) ?? THUMBNAIL_KEYS[tool.id];
579
776
  return /* @__PURE__ */ jsx(IconButton, {
580
777
  "data-hm-tool": tool.id,
581
778
  label: t(tool.label),
582
779
  icon: Icon ? /* @__PURE__ */ jsx(Icon, {}) : null,
583
780
  disabled: !(tool.isEnabled?.(state) ?? true),
781
+ focusableWhenDisabled: true,
584
782
  ...keys ? { "aria-keyshortcuts": keys } : {},
585
783
  onClick: () => run(tool)
586
784
  }, tool.id);
@@ -733,10 +931,12 @@ function PdfViewer(props) {
733
931
  const session = usePdfSession();
734
932
  const anchor = useRef(void 0);
735
933
  const own = useRef(void 0);
934
+ const anchoredAt = useRef(void 0);
736
935
  const findPage = useCallback((key) => root.current?.querySelector(`[data-hm-page-key="${CSS.escape(key)}"]`) ?? void 0, []);
737
936
  const scrollOwn = useCallback((element, top) => {
738
937
  element.scrollTop = top;
739
938
  own.current = element.scrollTop;
939
+ anchoredAt.current = element.scrollTop;
740
940
  }, []);
741
941
  useEffect(() => {
742
942
  const element = pages.current;
@@ -746,6 +946,10 @@ function PdfViewer(props) {
746
946
  const viewer = root.current;
747
947
  const held = anchor.current;
748
948
  if (!viewer || !held) return;
949
+ const at = anchoredAt.current;
950
+ const bottom = viewer.scrollHeight - viewer.clientHeight;
951
+ const clamped = at !== void 0 && at > bottom && Math.abs(viewer.scrollTop - bottom) < 1;
952
+ if (at !== void 0 && Math.abs(viewer.scrollTop - at) >= 1 && !clamped) return;
749
953
  const page = findPage(held.key);
750
954
  if (!page) {
751
955
  anchor.current = void 0;
@@ -779,6 +983,7 @@ function PdfViewer(props) {
779
983
  key: top.dataset["hmPageKey"],
780
984
  offset: top.offsetTop - scrollTop
781
985
  };
986
+ anchoredAt.current = scrollTop;
782
987
  }
783
988
  const key = current?.dataset["hmPageKey"];
784
989
  if (key) session.setCurrentPage(key);
@@ -919,26 +1124,146 @@ function PdfEditorStart(props) {
919
1124
  ]
920
1125
  });
921
1126
  }
1127
+ // src/features/save/download-name.ts
1128
+ var DEFAULT_DOWNLOAD_NAME = "document.pdf";
1129
+ var EXTENSION = ".pdf";
1130
+ function downloadFileName(name) {
1131
+ const clean = cleanFileName(name);
1132
+ if (clean === void 0) return DEFAULT_DOWNLOAD_NAME;
1133
+ if (clean.toLowerCase().endsWith(EXTENSION)) return clean;
1134
+ const base = Array.from(clean).slice(0, 124).join("").trimEnd();
1135
+ return base === "" ? DEFAULT_DOWNLOAD_NAME : `${base}${EXTENSION}`;
1136
+ }
1137
+ function saveFile(bytes, name) {
1138
+ const url = URL.createObjectURL(new Blob([bytes], { type: "application/pdf" }));
1139
+ const link = document.createElement("a");
1140
+ link.href = url;
1141
+ link.download = name;
1142
+ link.rel = "noopener";
1143
+ link.click();
1144
+ setTimeout(() => URL.revokeObjectURL(url), REVOKE_AFTER);
1145
+ }
1146
+ var REVOKE_AFTER = 4e4;
1147
+ // src/react/editor/use-save.ts
1148
+ var CANCEL_AFTER = 1e3;
1149
+ var IDLE = {
1150
+ saving: false,
1151
+ cancellable: false,
1152
+ failure: void 0
1153
+ };
1154
+ function useSave(options) {
1155
+ const { session, messages, announce, props } = options;
1156
+ const [state, setState] = useState(IDLE);
1157
+ const running = useRef(void 0);
1158
+ const cancel = useCallback(() => running.current?.abort(), []);
1159
+ const save = useCallback(() => {
1160
+ if (running.current) return;
1161
+ const controller = new AbortController();
1162
+ running.current = controller;
1163
+ setState({
1164
+ saving: true,
1165
+ cancellable: false,
1166
+ failure: void 0
1167
+ });
1168
+ const timer = setTimeout(() => setState((current) => current.saving ? {
1169
+ ...current,
1170
+ cancellable: true
1171
+ } : current), CANCEL_AFTER);
1172
+ let failure;
1173
+ const finish = () => {
1174
+ clearTimeout(timer);
1175
+ if (running.current === controller) running.current = void 0;
1176
+ setState({
1177
+ saving: false,
1178
+ cancellable: false,
1179
+ failure
1180
+ });
1181
+ };
1182
+ (async () => {
1183
+ const snapshot = session.getSnapshot();
1184
+ const info = {
1185
+ pageCount: snapshot.plan.pages.length,
1186
+ ...snapshot.sources[0]?.name ? { sourceName: snapshot.sources[0].name } : {}
1187
+ };
1188
+ let bytes;
1189
+ try {
1190
+ bytes = await session.export({ signal: controller.signal });
1191
+ } catch (error) {
1192
+ if (!controller.signal.aborted && !isPdfError(error, "ABORTED")) failure = messages.error(error);
1193
+ return;
1194
+ }
1195
+ if (controller.signal.aborted) return;
1196
+ const { onExport, downloadName } = props.current;
1197
+ try {
1198
+ const name = downloadFileName(downloadName ? downloadName(info) : info.sourceName);
1199
+ if (onExport) {
1200
+ await onExport(bytes, {
1201
+ fileName: name,
1202
+ pageCount: info.pageCount
1203
+ });
1204
+ announce(messages.t("editor.ready"));
1205
+ } else {
1206
+ saveFile(bytes, name);
1207
+ announce(messages.t("editor.saved", { name }));
1208
+ }
1209
+ } catch {
1210
+ failure = messages.t("editor.saveFailed");
1211
+ }
1212
+ })().finally(finish);
1213
+ }, [
1214
+ session,
1215
+ messages,
1216
+ announce,
1217
+ props
1218
+ ]);
1219
+ const opened = session.getSnapshot().sources[0]?.id;
1220
+ useEffect(() => {
1221
+ running.current?.abort();
1222
+ setState((current) => current.failure ? {
1223
+ ...current,
1224
+ failure: void 0
1225
+ } : current);
1226
+ }, [opened]);
1227
+ useEffect(() => () => running.current?.abort(), []);
1228
+ return {
1229
+ ...state,
1230
+ save,
1231
+ cancel
1232
+ };
1233
+ }
922
1234
  // src/react/editor/PdfEditor.tsx
923
1235
  function warningText(messages, warning) {
924
1236
  const t = messages.t;
925
1237
  return t(`warnings.${warning.limit}`, { actual: warning.actual });
926
1238
  }
927
1239
  var join = (...names) => names.filter(Boolean).join(" ");
928
- function resultOf(tool, messages, before) {
1240
+ function resultOf(tool, messages, before, after) {
929
1241
  switch (tool.id) {
930
1242
  case "pdf.undo": return messages.t("editor.undone");
931
1243
  case "pdf.redo": return messages.t("editor.redone");
932
1244
  case "pdf.rotate-left":
933
1245
  case "pdf.rotate-right": return messages.t("editor.rotated", { count: targetPages(before).length });
1246
+ case "pdf.delete-pages": return messages.t("editor.deleted", { count: targetPages(before).length });
1247
+ case "pdf.move-earlier":
1248
+ case "pdf.move-later": {
1249
+ if (after.plan === before.plan) return void 0;
1250
+ const [first] = after.selection;
1251
+ const position = after.plan.pages.findIndex((page) => page.key === first) + 1;
1252
+ return messages.t("editor.moved", {
1253
+ count: after.selection.length,
1254
+ position
1255
+ });
1256
+ }
934
1257
  default: return;
935
1258
  }
936
1259
  }
937
1260
  function changeBetween(before, after) {
938
1261
  const pageCount = after.plan.pages.length;
939
- if (after.status === "ready" && after.sources[0]?.id !== before.sources[0]?.id) return {
1262
+ const opened = after.sources[0];
1263
+ if (after.status === "ready" && opened?.id !== before.sources[0]?.id) return {
940
1264
  reason: "open",
941
- pageCount
1265
+ pageCount,
1266
+ ...opened?.name ? { fileName: opened.name } : {}
942
1267
  };
943
1268
  if (before.sources.length > 0 && after.sources.length === 0) return {
944
1269
  reason: "close",
@@ -967,8 +1292,18 @@ function PdfEditorBody(props) {
967
1292
  const root = useRef(null);
968
1293
  const startButton = useRef(null);
969
1294
  const input = useRef(null);
1295
+ const insertInput = useRef(null);
1296
+ const [inserting, setInserting] = useState(false);
970
1297
  const latestOnChange = useRef(onChange);
971
1298
  latestOnChange.current = onChange;
1299
+ const saveProps = useRef(props);
1300
+ saveProps.current = props;
1301
+ const saving = useSave({
1302
+ session,
1303
+ messages,
1304
+ announce,
1305
+ props: saveProps
1306
+ });
972
1307
  const registry = useMemo(() => createToolRegistry(pdfTools, {
973
1308
  ...props.tools ? { tools: props.tools } : {},
974
1309
  toolbar: props.toolbar ?? DEFAULT_TOOLBAR.map((group) => group.filter((id) => !props.tools || props.tools.includes(id))).filter((group) => group.length > 0)
@@ -979,17 +1314,29 @@ function PdfEditorBody(props) {
979
1314
  }), [platform, registry]);
980
1315
  const context = useMemo(() => ({
981
1316
  session,
982
- chooseFile: () => input.current?.click()
983
- }), [session]);
1317
+ chooseFile: () => input.current?.click(),
1318
+ chooseInsertFile: () => insertInput.current?.click(),
1319
+ save: saving.save
1320
+ }), [session, saving.save]);
984
1321
  const icons = useMemo(() => ({
985
1322
  ...pdfIcons,
986
1323
  ...props.icons
987
1324
  }), [props.icons]);
1325
+ const deleteTool = registry.get("pdf.delete-pages");
1326
+ const moveTools = {
1327
+ earlier: registry.get("pdf.move-earlier"),
1328
+ later: registry.get("pdf.move-later")
1329
+ };
988
1330
  const runTool = (tool) => {
989
1331
  const before = session.getSnapshot();
990
- if (!(tool.isEnabled?.({ snapshot: before }) ?? true)) return;
1332
+ const state = {
1333
+ snapshot: before,
1334
+ saving: saving.saving,
1335
+ inserting
1336
+ };
1337
+ if (!(tool.isEnabled?.(state) ?? true)) return;
991
1338
  Promise.resolve(tool.run(context)).then(() => {
992
- const result = resultOf(tool, messages, before);
1339
+ const result = resultOf(tool, messages, before, session.getSnapshot());
993
1340
  if (result) announce(result);
994
1341
  });
995
1342
  };
@@ -1002,7 +1349,7 @@ function PdfEditorBody(props) {
1002
1349
  };
1003
1350
  useImperativeHandle(handle, () => ({
1004
1351
  session,
1005
- open: (next) => session.open(next),
1352
+ open: (next, options) => session.open(next, options),
1006
1353
  export: (options) => session.export(options),
1007
1354
  undo: () => session.undo(),
1008
1355
  redo: () => session.redo(),
@@ -1047,12 +1394,40 @@ function PdfEditorBody(props) {
1047
1394
  const open = (chosen) => {
1048
1395
  session.open(chosen).catch(() => {});
1049
1396
  };
1397
+ const insert = async (chosen) => {
1398
+ const before = session.getSnapshot();
1399
+ const current = before.plan.pages.findIndex((page) => page.key === before.currentPage);
1400
+ const at = current >= 0 ? current + 1 : before.plan.pages.length;
1401
+ setInserting(true);
1402
+ try {
1403
+ await session.insert(chosen, { at });
1404
+ } catch {
1405
+ return;
1406
+ } finally {
1407
+ setInserting(false);
1408
+ }
1409
+ const had = new Set(before.plan.pages.map((page) => page.key));
1410
+ const added = session.getSnapshot().plan.pages.filter((page) => !had.has(page.key)).map((page) => page.key);
1411
+ const [first] = added;
1412
+ if (!first) return;
1413
+ session.select(added);
1414
+ session.goToPage(first);
1415
+ announce(messages.t("editor.inserted", {
1416
+ count: added.length,
1417
+ page: at
1418
+ }));
1419
+ };
1050
1420
  const { error, warnings } = snapshot;
1051
1421
  const showError = error !== void 0 && error.code !== "ABORTED";
1052
1422
  let content;
1053
1423
  if (status === "ready") content = /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(PdfThumbnails, {
1054
1424
  className: join("hm-pdf-editor-sidebar", classNames.sidebar),
1055
- unstyled
1425
+ unstyled,
1426
+ ...deleteTool ? { onDelete: () => runTool(deleteTool) } : {},
1427
+ ...moveTools.earlier || moveTools.later ? { onMove: (direction) => {
1428
+ const tool = moveTools[direction];
1429
+ if (tool) runTool(tool);
1430
+ } } : {}
1056
1431
  }), /* @__PURE__ */ jsx(PdfViewer, { unstyled })] });
1057
1432
  else if (status === "opening") content = /* @__PURE__ */ jsxs("div", {
1058
1433
  role: "status",
@@ -1073,7 +1448,7 @@ function PdfEditorBody(props) {
1073
1448
  ref: root,
1074
1449
  role: "group",
1075
1450
  "aria-label": messages.t("editor.label"),
1076
- "aria-busy": status === "opening" || snapshot.busy,
1451
+ "aria-busy": status === "opening" || snapshot.busy || saving.saving,
1077
1452
  className: join("hm-pdf-editor", className, classNames.root),
1078
1453
  "data-hm-status": status,
1079
1454
  onKeyDown,
@@ -1092,6 +1467,20 @@ function PdfEditorBody(props) {
1092
1467
  if (chosen) open(chosen);
1093
1468
  }
1094
1469
  }),
1470
+ /* @__PURE__ */ jsx("input", {
1471
+ ref: insertInput,
1472
+ type: "file",
1473
+ accept: "application/pdf,.pdf",
1474
+ tabIndex: -1,
1475
+ "aria-hidden": "true",
1476
+ hidden: true,
1477
+ "data-hm-insert": "",
1478
+ onChange: (event) => {
1479
+ const [chosen] = event.target.files ?? [];
1480
+ event.target.value = "";
1481
+ if (chosen) insert(chosen);
1482
+ }
1483
+ }),
1095
1484
  /* @__PURE__ */ jsxs("div", {
1096
1485
  className: join("hm-pdf-editor-header", classNames.header),
1097
1486
  children: [
@@ -1101,17 +1490,35 @@ function PdfEditorBody(props) {
1101
1490
  context,
1102
1491
  icons,
1103
1492
  onRun: runTool,
1493
+ saving: saving.saving,
1494
+ inserting,
1104
1495
  className: join("hm-pdf-editor-toolbar", classNames.toolbar)
1105
1496
  }),
1497
+ saving.saving ? /* @__PURE__ */ jsxs("div", {
1498
+ className: join("hm-pdf-editor-saving", classNames.status),
1499
+ children: [/* @__PURE__ */ jsx("p", {
1500
+ role: "status",
1501
+ children: messages.t("editor.saving")
1502
+ }), saving.cancellable ? /* @__PURE__ */ jsx(Button, {
1503
+ size: "small",
1504
+ onClick: saving.cancel,
1505
+ children: messages.t("editor.cancelSave")
1506
+ }) : null]
1507
+ }) : null,
1508
+ saving.failure ? /* @__PURE__ */ jsx("p", {
1509
+ role: "alert",
1510
+ className: join("hm-pdf-editor-alert", classNames.alert),
1511
+ children: saving.failure
1512
+ }) : null,
1106
1513
  status === "ready" && showError ? /* @__PURE__ */ jsx("p", {
1107
1514
  role: "alert",
1108
1515
  className: join("hm-pdf-editor-alert", classNames.alert),
1109
1516
  children: messages.error(error)
1110
1517
  }) : null,
1111
- status === "ready" && warnings.length > 0 ? /* @__PURE__ */ jsx("div", {
1518
+ status === "ready" && (warnings.length > 0 || snapshot.historyTrimmed) ? /* @__PURE__ */ jsx("div", {
1112
1519
  role: "status",
1113
1520
  className: join("hm-pdf-editor-warnings", classNames.status),
1114
- children: /* @__PURE__ */ jsx("ul", { children: warnings.map((warning) => /* @__PURE__ */ jsx("li", { children: warningText(messages, warning) }, warning.limit)) })
1521
+ children: /* @__PURE__ */ jsxs("ul", { children: [warnings.map((warning) => /* @__PURE__ */ jsx("li", { children: warningText(messages, warning) }, warning.limit)), snapshot.historyTrimmed ? /* @__PURE__ */ jsx("li", { children: messages.t("editor.historyTrimmed") }) : null] })
1115
1522
  }) : null
1116
1523
  ]
1117
1524
  }),
@@ -1124,7 +1531,7 @@ function PdfEditorBody(props) {
1124
1531
  });
1125
1532
  }
1126
1533
  var PdfEditor = /* @__PURE__ */ forwardRef(function PdfEditor(props, handle) {
1127
- const { file, onChange, className, classNames, unstyled, tools, toolbar, icons, messages: overrides, locale = "en", ...source } = props;
1534
+ const { file, onChange, onExport, downloadName, className, classNames, unstyled, tools, toolbar, icons, messages: overrides, locale = "en", ...source } = props;
1128
1535
  const session = useProvidedSession(source);
1129
1536
  const messages = useMemo(() => createMessages(pdfEditorMessages, {
1130
1537
  locale,
@@ -1142,6 +1549,8 @@ var PdfEditor = /* @__PURE__ */ forwardRef(function PdfEditor(props, handle) {
1142
1549
  handle,
1143
1550
  ...file !== void 0 ? { file } : {},
1144
1551
  ...onChange ? { onChange } : {},
1552
+ ...onExport ? { onExport } : {},
1553
+ ...downloadName ? { downloadName } : {},
1145
1554
  ...className !== void 0 ? { className } : {},
1146
1555
  ...classNames ? { classNames } : {},
1147
1556
  ...unstyled !== void 0 ? { unstyled } : {},