@hussmartinez/pdf-sdk 0.1.0 → 0.3.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 { g as createPdfJsEngine, h as createPdfProcessor, n as createPdfSession, t as pdfMessages, v as linkDestination, y as safeLinkUrl } from "./shared/en-CQX26xju.js";
3
+ import { createMessages, createShortcutRegistry, createToolRegistry, defineMessages, defineTool } 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);
@@ -41,10 +126,9 @@ function own(props) {
41
126
  }
42
127
  };
43
128
  }
44
- function PdfSessionProvider(props) {
45
- const { session: given, messages: overrides, locale = "en", children } = props;
129
+ function useProvidedSession(props) {
130
+ const given = props.session;
46
131
  const [owned] = useState(() => given ? void 0 : own(props));
47
- const session = given ?? owned.session;
48
132
  useEffect(() => {
49
133
  if (!owned) return;
50
134
  const pending = owned.pending;
@@ -53,6 +137,11 @@ function PdfSessionProvider(props) {
53
137
  owned.pending = setTimeout(() => owned.dispose(), 0);
54
138
  };
55
139
  }, [owned]);
140
+ return given ?? owned.session;
141
+ }
142
+ function PdfSessionProvider(props) {
143
+ const { messages: overrides, locale = "en", children } = props;
144
+ const session = useProvidedSession(props);
56
145
  const messages = useMemo(() => createMessages(pdfMessages, {
57
146
  locale,
58
147
  ...overrides ? { overrides } : {}
@@ -108,6 +197,13 @@ function useNear(observe, element, sized) {
108
197
  return near;
109
198
  }
110
199
  // src/react/use-page-drawing.ts
200
+ function present(buffer, target) {
201
+ target.width = buffer.width;
202
+ target.height = buffer.height;
203
+ target.style.width = buffer.style.width;
204
+ target.style.height = buffer.style.height;
205
+ target.getContext("2d")?.drawImage(buffer, 0, 0);
206
+ }
111
207
  function usePageDrawing(options) {
112
208
  const { session, pageKey, rotation, near, displayWidth, queue, onMeasured } = options;
113
209
  const canvas = useRef(null);
@@ -138,18 +234,23 @@ function usePageDrawing(options) {
138
234
  const turned = info.rotation === 90 || info.rotation === 270;
139
235
  const scale = displayWidth / (turned ? info.height : info.width);
140
236
  const render = queue.schedule(async (signal) => {
237
+ const buffer = document.createElement("canvas");
141
238
  try {
142
- await session.renderPage(pageKey, target, {
239
+ await session.renderPage(pageKey, buffer, {
143
240
  scale,
144
241
  pixelRatio: globalThis.devicePixelRatio || 1,
145
242
  signal
146
243
  });
147
244
  if (!signal.aborted) {
245
+ present(buffer, target);
148
246
  setDrawn(true);
149
247
  setFailure(void 0);
150
248
  }
151
249
  } catch (reason) {
152
250
  if (!signal.aborted) setFailure(reason);
251
+ } finally {
252
+ buffer.width = 0;
253
+ buffer.height = 0;
153
254
  }
154
255
  });
155
256
  return () => render.cancel();
@@ -416,6 +517,42 @@ function PdfThumbnails(props) {
416
517
  }, page.key))
417
518
  });
418
519
  }
520
+ // src/react/toolbar/icons.ts
521
+ var pdfIcons = {
522
+ open: OpenIcon,
523
+ undo: UndoIcon,
524
+ redo: RedoIcon,
525
+ "rotate-left": RotateLeftIcon,
526
+ "rotate-right": RotateRightIcon
527
+ };
528
+ // src/react/toolbar/PdfToolbar.tsx
529
+ function PdfToolbar(props) {
530
+ const { registry, shortcuts, context, icons, onRun, className } = props;
531
+ const messages = usePdfMessages();
532
+ const state = { snapshot: usePdfDocument() };
533
+ const t = messages.t;
534
+ const run = onRun ?? ((tool) => void tool.run(context));
535
+ if (registry.toolbar.length === 0) return null;
536
+ return /* @__PURE__ */ jsx(Toolbar, {
537
+ label: messages.t("toolbar.label"),
538
+ ...className ? { className } : {},
539
+ children: registry.toolbar.map((group) => /* @__PURE__ */ jsx(ToolbarGroup, {
540
+ label: t(`toolbar.groups.${group[0]?.group ?? "other"}`),
541
+ children: group.filter((tool) => tool.isAvailable?.(state) ?? true).map((tool) => {
542
+ const Icon = icons[tool.icon];
543
+ const keys = shortcuts?.ariaKeyShortcuts(tool.id);
544
+ return /* @__PURE__ */ jsx(IconButton, {
545
+ "data-hm-tool": tool.id,
546
+ label: t(tool.label),
547
+ icon: Icon ? /* @__PURE__ */ jsx(Icon, {}) : null,
548
+ disabled: !(tool.isEnabled?.(state) ?? true),
549
+ ...keys ? { "aria-keyshortcuts": keys } : {},
550
+ onClick: () => run(tool)
551
+ }, tool.id);
552
+ })
553
+ }, group.map((tool) => tool.id).join(" ")))
554
+ });
555
+ }
419
556
  // src/react/viewer/PdfViewerPage.tsx
420
557
  var join$2 = (...names) => names.filter(Boolean).join(" ");
421
558
  function PdfViewerPage(props) {
@@ -561,10 +698,12 @@ function PdfViewer(props) {
561
698
  const session = usePdfSession();
562
699
  const anchor = useRef(void 0);
563
700
  const own = useRef(void 0);
701
+ const anchoredAt = useRef(void 0);
564
702
  const findPage = useCallback((key) => root.current?.querySelector(`[data-hm-page-key="${CSS.escape(key)}"]`) ?? void 0, []);
565
703
  const scrollOwn = useCallback((element, top) => {
566
704
  element.scrollTop = top;
567
705
  own.current = element.scrollTop;
706
+ anchoredAt.current = element.scrollTop;
568
707
  }, []);
569
708
  useEffect(() => {
570
709
  const element = pages.current;
@@ -574,6 +713,10 @@ function PdfViewer(props) {
574
713
  const viewer = root.current;
575
714
  const held = anchor.current;
576
715
  if (!viewer || !held) return;
716
+ const at = anchoredAt.current;
717
+ const bottom = viewer.scrollHeight - viewer.clientHeight;
718
+ const clamped = at !== void 0 && at > bottom && Math.abs(viewer.scrollTop - bottom) < 1;
719
+ if (at !== void 0 && Math.abs(viewer.scrollTop - at) >= 1 && !clamped) return;
577
720
  const page = findPage(held.key);
578
721
  if (!page) {
579
722
  anchor.current = void 0;
@@ -607,6 +750,7 @@ function PdfViewer(props) {
607
750
  key: top.dataset["hmPageKey"],
608
751
  offset: top.offsetTop - scrollTop
609
752
  };
753
+ anchoredAt.current = scrollTop;
610
754
  }
611
755
  const key = current?.dataset["hmPageKey"];
612
756
  if (key) session.setCurrentPage(key);
@@ -753,6 +897,15 @@ function warningText(messages, warning) {
753
897
  return t(`warnings.${warning.limit}`, { actual: warning.actual });
754
898
  }
755
899
  var join = (...names) => names.filter(Boolean).join(" ");
900
+ function resultOf(tool, messages, before) {
901
+ switch (tool.id) {
902
+ case "pdf.undo": return messages.t("editor.undone");
903
+ case "pdf.redo": return messages.t("editor.redone");
904
+ case "pdf.rotate-left":
905
+ case "pdf.rotate-right": return messages.t("editor.rotated", { count: targetPages(before).length });
906
+ default: return;
907
+ }
908
+ }
756
909
  function changeBetween(before, after) {
757
910
  const pageCount = after.plan.pages.length;
758
911
  if (after.status === "ready" && after.sources[0]?.id !== before.sources[0]?.id) return {
@@ -768,16 +921,57 @@ function changeBetween(before, after) {
768
921
  pageCount
769
922
  };
770
923
  }
924
+ function AnnounceBridge({ target }) {
925
+ const announce = useAnnounce();
926
+ useEffect(() => {
927
+ target.current = announce;
928
+ }, [target, announce]);
929
+ return null;
930
+ }
771
931
  function PdfEditorBody(props) {
772
932
  const { file, onChange, className, classNames = {}, unstyled = false, handle } = props;
773
933
  const session = usePdfSession();
774
934
  const snapshot = usePdfDocument();
775
935
  const messages = usePdfMessages();
936
+ const announceTo = useRef(() => {});
937
+ const announce = useCallback((message, options) => announceTo.current(message, options), []);
938
+ const platform = usePlatform();
776
939
  const root = useRef(null);
777
940
  const startButton = useRef(null);
778
- const [announcement, setAnnouncement] = useState("");
941
+ const input = useRef(null);
779
942
  const latestOnChange = useRef(onChange);
780
943
  latestOnChange.current = onChange;
944
+ const registry = useMemo(() => createToolRegistry(pdfTools, {
945
+ ...props.tools ? { tools: props.tools } : {},
946
+ toolbar: props.toolbar ?? DEFAULT_TOOLBAR.map((group) => group.filter((id) => !props.tools || props.tools.includes(id))).filter((group) => group.length > 0)
947
+ }), [props.tools, props.toolbar]);
948
+ const shortcuts = useMemo(() => createShortcutRegistry({
949
+ platform,
950
+ tools: registry.tools
951
+ }), [platform, registry]);
952
+ const context = useMemo(() => ({
953
+ session,
954
+ chooseFile: () => input.current?.click()
955
+ }), [session]);
956
+ const icons = useMemo(() => ({
957
+ ...pdfIcons,
958
+ ...props.icons
959
+ }), [props.icons]);
960
+ const runTool = (tool) => {
961
+ const before = session.getSnapshot();
962
+ if (!(tool.isEnabled?.({ snapshot: before }) ?? true)) return;
963
+ Promise.resolve(tool.run(context)).then(() => {
964
+ const result = resultOf(tool, messages, before);
965
+ if (result) announce(result);
966
+ });
967
+ };
968
+ const onKeyDown = (event) => {
969
+ const id = shortcuts.match(event.nativeEvent);
970
+ const tool = id ? registry.get(id) : void 0;
971
+ if (!tool) return;
972
+ event.preventDefault();
973
+ runTool(tool);
974
+ };
781
975
  useImperativeHandle(handle, () => ({
782
976
  session,
783
977
  open: (next) => session.open(next),
@@ -803,11 +997,15 @@ function PdfEditorBody(props) {
803
997
  const change = changeBetween(before, after);
804
998
  before = after;
805
999
  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"));
1000
+ if (change.reason === "open") announce(messages.t("editor.opened", { count: change.pageCount }));
1001
+ else if (change.reason === "close") announce(messages.t("editor.closed"));
808
1002
  latestOnChange.current?.(change);
809
1003
  });
810
- }, [session, messages]);
1004
+ }, [
1005
+ session,
1006
+ messages,
1007
+ announce
1008
+ ]);
811
1009
  const { status } = snapshot;
812
1010
  const previous = useRef(status);
813
1011
  useEffect(() => {
@@ -850,12 +1048,33 @@ function PdfEditorBody(props) {
850
1048
  "aria-busy": status === "opening" || snapshot.busy,
851
1049
  className: join("hm-pdf-editor", className, classNames.root),
852
1050
  "data-hm-status": status,
1051
+ onKeyDown,
853
1052
  ...unstyled ? { "data-hm-unstyled": "" } : {},
854
1053
  children: [
1054
+ /* @__PURE__ */ jsx("input", {
1055
+ ref: input,
1056
+ type: "file",
1057
+ accept: "application/pdf,.pdf",
1058
+ tabIndex: -1,
1059
+ "aria-hidden": "true",
1060
+ hidden: true,
1061
+ onChange: (event) => {
1062
+ const [chosen] = event.target.files ?? [];
1063
+ event.target.value = "";
1064
+ if (chosen) open(chosen);
1065
+ }
1066
+ }),
855
1067
  /* @__PURE__ */ jsxs("div", {
856
1068
  className: join("hm-pdf-editor-header", classNames.header),
857
1069
  children: [
858
- /* @__PURE__ */ jsx("div", { className: join("hm-pdf-editor-toolbar", classNames.toolbar) }),
1070
+ /* @__PURE__ */ jsx(PdfToolbar, {
1071
+ registry,
1072
+ shortcuts,
1073
+ context,
1074
+ icons,
1075
+ onRun: runTool,
1076
+ className: join("hm-pdf-editor-toolbar", classNames.toolbar)
1077
+ }),
859
1078
  status === "ready" && showError ? /* @__PURE__ */ jsx("p", {
860
1079
  role: "alert",
861
1080
  className: join("hm-pdf-editor-alert", classNames.alert),
@@ -872,28 +1091,39 @@ function PdfEditorBody(props) {
872
1091
  className: join("hm-pdf-editor-body", classNames.body),
873
1092
  children: content
874
1093
  }),
875
- /* @__PURE__ */ jsx("p", {
876
- role: "status",
877
- className: "hm-pdf-editor-announcer",
878
- children: announcement
879
- })
1094
+ /* @__PURE__ */ jsx(AnnouncerProvider, { children: /* @__PURE__ */ jsx(AnnounceBridge, { target: announceTo }) })
880
1095
  ]
881
1096
  });
882
1097
  }
883
1098
  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 } : {}
1099
+ const { file, onChange, className, classNames, unstyled, tools, toolbar, icons, messages: overrides, locale = "en", ...source } = props;
1100
+ const session = useProvidedSession(source);
1101
+ const messages = useMemo(() => createMessages(pdfEditorMessages, {
1102
+ locale,
1103
+ ...overrides ? { overrides } : {}
1104
+ }), [locale, overrides]);
1105
+ const value = useMemo(() => ({
1106
+ session,
1107
+ messages
1108
+ }), [session, messages]);
1109
+ return /* @__PURE__ */ jsx(PdfContext.Provider, {
1110
+ value,
1111
+ children: /* @__PURE__ */ jsx(UiMessagesProvider, {
1112
+ messages,
1113
+ children: /* @__PURE__ */ jsx(PdfEditorBody, {
1114
+ handle,
1115
+ ...file !== void 0 ? { file } : {},
1116
+ ...onChange ? { onChange } : {},
1117
+ ...className !== void 0 ? { className } : {},
1118
+ ...classNames ? { classNames } : {},
1119
+ ...unstyled !== void 0 ? { unstyled } : {},
1120
+ ...tools ? { tools } : {},
1121
+ ...toolbar ? { toolbar } : {},
1122
+ ...icons ? { icons } : {}
1123
+ })
894
1124
  })
895
1125
  });
896
1126
  });
897
- export { PdfEditor, PdfSessionProvider, PdfThumbnails, PdfViewer, usePdfDocument, usePdfMessages, usePdfSession };
1127
+ export { PdfEditor, PdfSessionProvider, PdfThumbnails, PdfToolbar, PdfViewer, pdfEditorMessages, pdfIcons, pdfTools, usePdfDocument, usePdfMessages, usePdfSession };
898
1128
 
899
1129
  //# sourceMappingURL=react.js.map