@hussmartinez/pdf-sdk 0.1.0 → 0.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.
package/dist/react.js CHANGED
@@ -1,10 +1,95 @@
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-B0u26URn.js";
3
- import { createMessages } from "@hussmartinez/sdk-core";
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";
4
5
  import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
6
+ import { uiMessages } from "@hussmartinez/ui";
5
7
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
+ // src/features/history/history-tools.ts
9
+ var undoTool = /* @__PURE__ */ defineTool({
10
+ id: "pdf.undo",
11
+ label: "tools.undo",
12
+ icon: "undo",
13
+ group: "history",
14
+ isEnabled: ({ snapshot }) => snapshot.canUndo,
15
+ run: ({ session }) => {
16
+ session.undo();
17
+ },
18
+ shortcuts: "undo"
19
+ });
20
+ var redoTool = /* @__PURE__ */ defineTool({
21
+ id: "pdf.redo",
22
+ label: "tools.redo",
23
+ icon: "redo",
24
+ group: "history",
25
+ isEnabled: ({ snapshot }) => snapshot.canRedo,
26
+ run: ({ session }) => {
27
+ session.redo();
28
+ },
29
+ shortcuts: "redo"
30
+ });
31
+ // src/features/open/open-tool.ts
32
+ var openTool = /* @__PURE__ */ defineTool({
33
+ id: "pdf.open",
34
+ label: "tools.open",
35
+ icon: "open",
36
+ group: "file",
37
+ run: ({ chooseFile }) => chooseFile()
38
+ });
39
+ // src/features/tool-types.ts
40
+ var hasDocument = ({ snapshot }) => snapshot.status === "ready";
41
+ // src/features/pages/rotate-tools.ts
42
+ function targetPages(snapshot) {
43
+ if (snapshot.status !== "ready") return [];
44
+ if (snapshot.selection.length > 0) return snapshot.selection;
45
+ return snapshot.currentPage === void 0 ? [] : [snapshot.currentPage];
46
+ }
47
+ function rotate({ session }, angle) {
48
+ const pages = targetPages(session.getSnapshot());
49
+ if (pages.length === 0) return;
50
+ session.execute({
51
+ type: "pdf.rotatePages",
52
+ pages,
53
+ angle
54
+ });
55
+ }
56
+ var hasTargets = ({ snapshot }) => hasDocument({ snapshot }) && targetPages(snapshot).length > 0;
57
+ // src/features/tools.ts
58
+ var pdfTools = [
59
+ openTool,
60
+ undoTool,
61
+ redoTool,
62
+ /* @__PURE__ */ defineTool({
63
+ id: "pdf.rotate-left",
64
+ label: "tools.rotate-left",
65
+ icon: "rotate-left",
66
+ group: "pages",
67
+ isEnabled: hasTargets,
68
+ run: (context) => rotate(context, -90),
69
+ shortcuts: ["["]
70
+ }),
71
+ /* @__PURE__ */ defineTool({
72
+ id: "pdf.rotate-right",
73
+ label: "tools.rotate-right",
74
+ icon: "rotate-right",
75
+ group: "pages",
76
+ isEnabled: hasTargets,
77
+ run: (context) => rotate(context, 90),
78
+ shortcuts: ["]"]
79
+ })
80
+ ];
81
+ var DEFAULT_TOOLBAR = [
82
+ ["pdf.open"],
83
+ ["pdf.undo", "pdf.redo"],
84
+ ["pdf.rotate-left", "pdf.rotate-right"]
85
+ ];
6
86
  // src/react/context.ts
7
87
  var PdfContext = /* @__PURE__ */ createContext(void 0);
88
+ // src/react/editor-messages.ts
89
+ var pdfEditorMessages = /* @__PURE__ */ defineMessages({
90
+ ...pdfMessages,
91
+ ...uiMessages
92
+ });
8
93
  // src/react/hooks.ts
9
94
  function usePdfContext(hook) {
10
95
  const value = useContext(PdfContext);
@@ -21,11 +106,46 @@ function usePdfDocument() {
21
106
  function usePdfMessages() {
22
107
  return usePdfContext("usePdfMessages").messages;
23
108
  }
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
+ }
24
143
  // src/react/PdfSessionProvider.tsx
25
144
  function own(props) {
26
145
  const assets = props.assetsUrl === void 0 ? {} : { assetsUrl: props.assetsUrl };
27
- const engine = props.engine ?? createPdfJsEngine(assets);
28
- const processor = props.processor ?? createPdfProcessor(assets);
146
+ checkAssetsUrl(props.assetsUrl);
147
+ const engine = props.engine ?? lazyEngine(() => createPdfJsEngine(assets));
148
+ const processor = props.processor ?? lazyProcessor(() => createPdfProcessor(assets));
29
149
  const session = createPdfSession({
30
150
  engine,
31
151
  processor,
@@ -41,10 +161,9 @@ function own(props) {
41
161
  }
42
162
  };
43
163
  }
44
- function PdfSessionProvider(props) {
45
- const { session: given, messages: overrides, locale = "en", children } = props;
164
+ function useProvidedSession(props) {
165
+ const given = props.session;
46
166
  const [owned] = useState(() => given ? void 0 : own(props));
47
- const session = given ?? owned.session;
48
167
  useEffect(() => {
49
168
  if (!owned) return;
50
169
  const pending = owned.pending;
@@ -53,6 +172,11 @@ function PdfSessionProvider(props) {
53
172
  owned.pending = setTimeout(() => owned.dispose(), 0);
54
173
  };
55
174
  }, [owned]);
175
+ return given ?? owned.session;
176
+ }
177
+ function PdfSessionProvider(props) {
178
+ const { messages: overrides, locale = "en", children } = props;
179
+ const session = useProvidedSession(props);
56
180
  const messages = useMemo(() => createMessages(pdfMessages, {
57
181
  locale,
58
182
  ...overrides ? { overrides } : {}
@@ -108,6 +232,13 @@ function useNear(observe, element, sized) {
108
232
  return near;
109
233
  }
110
234
  // src/react/use-page-drawing.ts
235
+ function present(buffer, target) {
236
+ target.width = buffer.width;
237
+ target.height = buffer.height;
238
+ target.style.width = buffer.style.width;
239
+ target.style.height = buffer.style.height;
240
+ target.getContext("2d")?.drawImage(buffer, 0, 0);
241
+ }
111
242
  function usePageDrawing(options) {
112
243
  const { session, pageKey, rotation, near, displayWidth, queue, onMeasured } = options;
113
244
  const canvas = useRef(null);
@@ -138,18 +269,23 @@ function usePageDrawing(options) {
138
269
  const turned = info.rotation === 90 || info.rotation === 270;
139
270
  const scale = displayWidth / (turned ? info.height : info.width);
140
271
  const render = queue.schedule(async (signal) => {
272
+ const buffer = document.createElement("canvas");
141
273
  try {
142
- await session.renderPage(pageKey, target, {
274
+ await session.renderPage(pageKey, buffer, {
143
275
  scale,
144
276
  pixelRatio: globalThis.devicePixelRatio || 1,
145
277
  signal
146
278
  });
147
279
  if (!signal.aborted) {
280
+ present(buffer, target);
148
281
  setDrawn(true);
149
282
  setFailure(void 0);
150
283
  }
151
284
  } catch (reason) {
152
285
  if (!signal.aborted) setFailure(reason);
286
+ } finally {
287
+ buffer.width = 0;
288
+ buffer.height = 0;
153
289
  }
154
290
  });
155
291
  return () => render.cancel();
@@ -416,6 +552,42 @@ function PdfThumbnails(props) {
416
552
  }, page.key))
417
553
  });
418
554
  }
555
+ // src/react/toolbar/icons.ts
556
+ var pdfIcons = {
557
+ open: OpenIcon,
558
+ undo: UndoIcon,
559
+ redo: RedoIcon,
560
+ "rotate-left": RotateLeftIcon,
561
+ "rotate-right": RotateRightIcon
562
+ };
563
+ // src/react/toolbar/PdfToolbar.tsx
564
+ function PdfToolbar(props) {
565
+ const { registry, shortcuts, context, icons, onRun, className } = props;
566
+ const messages = usePdfMessages();
567
+ const state = { snapshot: usePdfDocument() };
568
+ const t = messages.t;
569
+ const run = onRun ?? ((tool) => void tool.run(context));
570
+ if (registry.toolbar.length === 0) return null;
571
+ return /* @__PURE__ */ jsx(Toolbar, {
572
+ label: messages.t("toolbar.label"),
573
+ ...className ? { className } : {},
574
+ children: registry.toolbar.map((group) => /* @__PURE__ */ jsx(ToolbarGroup, {
575
+ label: t(`toolbar.groups.${group[0]?.group ?? "other"}`),
576
+ children: group.filter((tool) => tool.isAvailable?.(state) ?? true).map((tool) => {
577
+ const Icon = icons[tool.icon];
578
+ const keys = shortcuts?.ariaKeyShortcuts(tool.id);
579
+ return /* @__PURE__ */ jsx(IconButton, {
580
+ "data-hm-tool": tool.id,
581
+ label: t(tool.label),
582
+ icon: Icon ? /* @__PURE__ */ jsx(Icon, {}) : null,
583
+ disabled: !(tool.isEnabled?.(state) ?? true),
584
+ ...keys ? { "aria-keyshortcuts": keys } : {},
585
+ onClick: () => run(tool)
586
+ }, tool.id);
587
+ })
588
+ }, group.map((tool) => tool.id).join(" ")))
589
+ });
590
+ }
419
591
  // src/react/viewer/PdfViewerPage.tsx
420
592
  var join$2 = (...names) => names.filter(Boolean).join(" ");
421
593
  function PdfViewerPage(props) {
@@ -753,6 +925,15 @@ function warningText(messages, warning) {
753
925
  return t(`warnings.${warning.limit}`, { actual: warning.actual });
754
926
  }
755
927
  var join = (...names) => names.filter(Boolean).join(" ");
928
+ function resultOf(tool, messages, before) {
929
+ switch (tool.id) {
930
+ case "pdf.undo": return messages.t("editor.undone");
931
+ case "pdf.redo": return messages.t("editor.redone");
932
+ case "pdf.rotate-left":
933
+ case "pdf.rotate-right": return messages.t("editor.rotated", { count: targetPages(before).length });
934
+ default: return;
935
+ }
936
+ }
756
937
  function changeBetween(before, after) {
757
938
  const pageCount = after.plan.pages.length;
758
939
  if (after.status === "ready" && after.sources[0]?.id !== before.sources[0]?.id) return {
@@ -768,16 +949,57 @@ function changeBetween(before, after) {
768
949
  pageCount
769
950
  };
770
951
  }
952
+ function AnnounceBridge({ target }) {
953
+ const announce = useAnnounce();
954
+ useEffect(() => {
955
+ target.current = announce;
956
+ }, [target, announce]);
957
+ return null;
958
+ }
771
959
  function PdfEditorBody(props) {
772
960
  const { file, onChange, className, classNames = {}, unstyled = false, handle } = props;
773
961
  const session = usePdfSession();
774
962
  const snapshot = usePdfDocument();
775
963
  const messages = usePdfMessages();
964
+ const announceTo = useRef(() => {});
965
+ const announce = useCallback((message, options) => announceTo.current(message, options), []);
966
+ const platform = usePlatform();
776
967
  const root = useRef(null);
777
968
  const startButton = useRef(null);
778
- const [announcement, setAnnouncement] = useState("");
969
+ const input = useRef(null);
779
970
  const latestOnChange = useRef(onChange);
780
971
  latestOnChange.current = onChange;
972
+ const registry = useMemo(() => createToolRegistry(pdfTools, {
973
+ ...props.tools ? { tools: props.tools } : {},
974
+ toolbar: props.toolbar ?? DEFAULT_TOOLBAR.map((group) => group.filter((id) => !props.tools || props.tools.includes(id))).filter((group) => group.length > 0)
975
+ }), [props.tools, props.toolbar]);
976
+ const shortcuts = useMemo(() => createShortcutRegistry({
977
+ platform,
978
+ tools: registry.tools
979
+ }), [platform, registry]);
980
+ const context = useMemo(() => ({
981
+ session,
982
+ chooseFile: () => input.current?.click()
983
+ }), [session]);
984
+ const icons = useMemo(() => ({
985
+ ...pdfIcons,
986
+ ...props.icons
987
+ }), [props.icons]);
988
+ const runTool = (tool) => {
989
+ const before = session.getSnapshot();
990
+ if (!(tool.isEnabled?.({ snapshot: before }) ?? true)) return;
991
+ Promise.resolve(tool.run(context)).then(() => {
992
+ const result = resultOf(tool, messages, before);
993
+ if (result) announce(result);
994
+ });
995
+ };
996
+ const onKeyDown = (event) => {
997
+ const id = shortcuts.match(event.nativeEvent);
998
+ const tool = id ? registry.get(id) : void 0;
999
+ if (!tool) return;
1000
+ event.preventDefault();
1001
+ runTool(tool);
1002
+ };
781
1003
  useImperativeHandle(handle, () => ({
782
1004
  session,
783
1005
  open: (next) => session.open(next),
@@ -803,11 +1025,15 @@ function PdfEditorBody(props) {
803
1025
  const change = changeBetween(before, after);
804
1026
  before = after;
805
1027
  if (!change) return;
806
- if (change.reason === "open") setAnnouncement(messages.t("editor.opened", { count: change.pageCount }));
807
- else if (change.reason === "close") setAnnouncement(messages.t("editor.closed"));
1028
+ if (change.reason === "open") announce(messages.t("editor.opened", { count: change.pageCount }));
1029
+ else if (change.reason === "close") announce(messages.t("editor.closed"));
808
1030
  latestOnChange.current?.(change);
809
1031
  });
810
- }, [session, messages]);
1032
+ }, [
1033
+ session,
1034
+ messages,
1035
+ announce
1036
+ ]);
811
1037
  const { status } = snapshot;
812
1038
  const previous = useRef(status);
813
1039
  useEffect(() => {
@@ -850,12 +1076,33 @@ function PdfEditorBody(props) {
850
1076
  "aria-busy": status === "opening" || snapshot.busy,
851
1077
  className: join("hm-pdf-editor", className, classNames.root),
852
1078
  "data-hm-status": status,
1079
+ onKeyDown,
853
1080
  ...unstyled ? { "data-hm-unstyled": "" } : {},
854
1081
  children: [
1082
+ /* @__PURE__ */ jsx("input", {
1083
+ ref: input,
1084
+ type: "file",
1085
+ accept: "application/pdf,.pdf",
1086
+ tabIndex: -1,
1087
+ "aria-hidden": "true",
1088
+ hidden: true,
1089
+ onChange: (event) => {
1090
+ const [chosen] = event.target.files ?? [];
1091
+ event.target.value = "";
1092
+ if (chosen) open(chosen);
1093
+ }
1094
+ }),
855
1095
  /* @__PURE__ */ jsxs("div", {
856
1096
  className: join("hm-pdf-editor-header", classNames.header),
857
1097
  children: [
858
- /* @__PURE__ */ jsx("div", { className: join("hm-pdf-editor-toolbar", classNames.toolbar) }),
1098
+ /* @__PURE__ */ jsx(PdfToolbar, {
1099
+ registry,
1100
+ shortcuts,
1101
+ context,
1102
+ icons,
1103
+ onRun: runTool,
1104
+ className: join("hm-pdf-editor-toolbar", classNames.toolbar)
1105
+ }),
859
1106
  status === "ready" && showError ? /* @__PURE__ */ jsx("p", {
860
1107
  role: "alert",
861
1108
  className: join("hm-pdf-editor-alert", classNames.alert),
@@ -872,28 +1119,39 @@ function PdfEditorBody(props) {
872
1119
  className: join("hm-pdf-editor-body", classNames.body),
873
1120
  children: content
874
1121
  }),
875
- /* @__PURE__ */ jsx("p", {
876
- role: "status",
877
- className: "hm-pdf-editor-announcer",
878
- children: announcement
879
- })
1122
+ /* @__PURE__ */ jsx(AnnouncerProvider, { children: /* @__PURE__ */ jsx(AnnounceBridge, { target: announceTo }) })
880
1123
  ]
881
1124
  });
882
1125
  }
883
1126
  var PdfEditor = /* @__PURE__ */ forwardRef(function PdfEditor(props, handle) {
884
- const { file, onChange, className, classNames, unstyled, ...provider } = props;
885
- return /* @__PURE__ */ jsx(PdfSessionProvider, {
886
- ...provider,
887
- children: /* @__PURE__ */ jsx(PdfEditorBody, {
888
- handle,
889
- ...file !== void 0 ? { file } : {},
890
- ...onChange ? { onChange } : {},
891
- ...className !== void 0 ? { className } : {},
892
- ...classNames ? { classNames } : {},
893
- ...unstyled !== void 0 ? { unstyled } : {}
1127
+ const { file, onChange, className, classNames, unstyled, tools, toolbar, icons, messages: overrides, locale = "en", ...source } = props;
1128
+ const session = useProvidedSession(source);
1129
+ const messages = useMemo(() => createMessages(pdfEditorMessages, {
1130
+ locale,
1131
+ ...overrides ? { overrides } : {}
1132
+ }), [locale, overrides]);
1133
+ const value = useMemo(() => ({
1134
+ session,
1135
+ messages
1136
+ }), [session, messages]);
1137
+ return /* @__PURE__ */ jsx(PdfContext.Provider, {
1138
+ value,
1139
+ children: /* @__PURE__ */ jsx(UiMessagesProvider, {
1140
+ messages,
1141
+ children: /* @__PURE__ */ jsx(PdfEditorBody, {
1142
+ handle,
1143
+ ...file !== void 0 ? { file } : {},
1144
+ ...onChange ? { onChange } : {},
1145
+ ...className !== void 0 ? { className } : {},
1146
+ ...classNames ? { classNames } : {},
1147
+ ...unstyled !== void 0 ? { unstyled } : {},
1148
+ ...tools ? { tools } : {},
1149
+ ...toolbar ? { toolbar } : {},
1150
+ ...icons ? { icons } : {}
1151
+ })
894
1152
  })
895
1153
  });
896
1154
  });
897
- export { PdfEditor, PdfSessionProvider, PdfThumbnails, PdfViewer, usePdfDocument, usePdfMessages, usePdfSession };
1155
+ export { PdfEditor, PdfSessionProvider, PdfThumbnails, PdfToolbar, PdfViewer, pdfEditorMessages, pdfIcons, pdfTools, usePdfDocument, usePdfMessages, usePdfSession };
898
1156
 
899
1157
  //# sourceMappingURL=react.js.map