@open-press/core 1.1.4 → 1.2.1

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 (51) hide show
  1. package/engine/cli.mjs +3 -3
  2. package/engine/commands/_shared.mjs +89 -13
  3. package/engine/commands/deploy.mjs +19 -4
  4. package/engine/commands/image.mjs +9 -3
  5. package/engine/commands/pdf.mjs +4 -1
  6. package/engine/output/chrome-pdf.mjs +102 -0
  7. package/engine/output/static-server.mjs +64 -17
  8. package/engine/react/document-export.mjs +22 -0
  9. package/package.json +1 -1
  10. package/src/openpress/app/OpenPressApp.tsx +5 -1
  11. package/src/openpress/app/OpenPressRuntime.tsx +85 -6
  12. package/src/openpress/reader/PageThumbnailsPanel.tsx +28 -5
  13. package/src/openpress/reader/PublicReaderPage.tsx +163 -74
  14. package/src/openpress/reader/SlidePresentationPage.tsx +37 -15
  15. package/src/openpress/reader/SlidePublicPage.tsx +332 -0
  16. package/src/openpress/reader/index.ts +1 -0
  17. package/src/openpress/reader/pageViewportScaleModel.ts +5 -3
  18. package/src/openpress/reader/usePageViewportScale.ts +9 -5
  19. package/src/openpress/reader/usePanelState.ts +14 -5
  20. package/src/openpress/shared/index.ts +1 -0
  21. package/src/openpress/shared/staticSearch.ts +174 -0
  22. package/src/openpress/workbench/Workbench.tsx +61 -176
  23. package/src/openpress/workbench/actions/DeploymentControl.tsx +1 -1
  24. package/src/openpress/workbench/actions/ExportControl.tsx +267 -0
  25. package/src/openpress/workbench/actions/SearchControl.tsx +32 -43
  26. package/src/openpress/workbench/actions/index.ts +1 -1
  27. package/src/openpress/workbench/actions/useDeploymentWorkbench.ts +21 -5
  28. package/src/openpress/workbench/hooks/useWorkbenchNavigation.ts +42 -0
  29. package/src/openpress/workbench/inspector/useInspectorComments.ts +6 -6
  30. package/src/openpress/workbench/project/ProjectEntryPanel.tsx +2 -278
  31. package/src/openpress/workbench/shell/WorkbenchShell.tsx +44 -18
  32. package/src/openpress/workbench/shell/WorkbenchToolbarActions.tsx +206 -0
  33. package/src/styles/openpress/app-shell.css +0 -83
  34. package/src/styles/openpress/print-route.css +1 -3
  35. package/src/styles/openpress/project-preview-panel.css +5 -783
  36. package/src/styles/openpress/public-viewer.css +7 -249
  37. package/src/styles/openpress/reader-runtime.css +0 -274
  38. package/src/styles/openpress/slide-presenter.css +150 -0
  39. package/src/styles/openpress/slide-public-viewer.css +222 -0
  40. package/src/styles/openpress/workbench-dialog.css +267 -0
  41. package/src/styles/openpress/workbench-export.css +154 -0
  42. package/src/styles/openpress/workbench-inline-editor.css +128 -0
  43. package/src/styles/openpress/workbench-panels.css +0 -88
  44. package/src/styles/openpress/workbench-search.css +257 -0
  45. package/src/styles/openpress/workbench-toolbar.css +422 -0
  46. package/src/styles/openpress/workbench.css +34 -1263
  47. package/src/styles/openpress/workspace-gallery.css +0 -5
  48. package/src/styles/openpress.css +7 -1
  49. package/vite.config.ts +66 -17
  50. package/src/openpress/workbench/actions/ExportImageControl.tsx +0 -96
  51. package/src/styles/openpress/media-workspace.css +0 -230
@@ -0,0 +1,332 @@
1
+ import {
2
+ useCallback,
3
+ useEffect,
4
+ useMemo,
5
+ useRef,
6
+ useState,
7
+ type CSSProperties,
8
+ type MouseEvent as ReactMouseEvent,
9
+ } from "react";
10
+ import { ChevronLeft, ChevronRight, Download, Maximize2, Minimize2, PanelLeftClose, PanelLeftOpen } from "lucide-react";
11
+ import { createPageObjectEntityId } from "../document-model";
12
+ import type { DeploymentInfo, HtmlPageBlock, ReaderDocument } from "../document-model";
13
+ import { pageIndexFromHash, replacePageRoute } from "./readerPageRoute";
14
+ import { clampReaderPageIndex, formatReaderPageNumber, normalizeReaderPageCount } from "./readerStateModel";
15
+ import { usePageViewportScale } from "./usePageViewportScale";
16
+ import { PageThumbnails } from "./PageThumbnailsPanel";
17
+
18
+ type SlideUiMode = "chrome" | "immersive";
19
+
20
+ export function SlidePublicViewer({
21
+ document,
22
+ pages,
23
+ style,
24
+ deploymentInfo,
25
+ }: {
26
+ document: ReaderDocument;
27
+ pages: HtmlPageBlock[];
28
+ style: CSSProperties;
29
+ deploymentInfo?: DeploymentInfo;
30
+ }) {
31
+ const stageRef = useRef<HTMLElement | null>(null);
32
+ const sourceContainerRef = useRef<HTMLDivElement | null>(null);
33
+ const currentPageIndexRef = useRef(0);
34
+ const normalizedPageCount = normalizeReaderPageCount(pages.length);
35
+
36
+ const [currentPageIndex, setCurrentPageIndex] = useState(() => {
37
+ if (typeof window === "undefined") return 0;
38
+ return pageIndexFromHash(window.location.hash, normalizedPageCount) ?? 0;
39
+ });
40
+ const [uiMode, setUiMode] = useState<SlideUiMode>("chrome");
41
+ const [thumbPanelOpen, setThumbPanelOpen] = useState(true);
42
+
43
+ currentPageIndexRef.current = currentPageIndex;
44
+
45
+ const currentPage = pages[clampReaderPageIndex(currentPageIndex, normalizedPageCount)];
46
+ const currentPageLabel = formatReaderPageNumber(currentPageIndex + 1);
47
+ const totalPageLabel = formatReaderPageNumber(normalizedPageCount);
48
+ const pageHtml = useMemo(() => currentPage?.html ?? "", [currentPage?.html]);
49
+
50
+ const pageViewport = usePageViewportScale({
51
+ stageRef,
52
+ pageContainerRef: sourceContainerRef,
53
+ pageCount: pages.length,
54
+ layoutMode: "single",
55
+ initialScaleMode: "fit-width",
56
+ maxFitScale: Infinity,
57
+ });
58
+
59
+ const setPage = useCallback(
60
+ (pageIndex: number) => {
61
+ const target = clampReaderPageIndex(pageIndex, normalizedPageCount);
62
+ setCurrentPageIndex(target);
63
+ replacePageRoute(target);
64
+ },
65
+ [normalizedPageCount],
66
+ );
67
+
68
+ // Clamp on page count change
69
+ useEffect(() => {
70
+ setCurrentPageIndex((idx) => clampReaderPageIndex(idx, normalizedPageCount));
71
+ }, [normalizedPageCount]);
72
+
73
+ // Hash sync
74
+ useEffect(() => {
75
+ const sync = () => {
76
+ const fromHash = pageIndexFromHash(window.location.hash, normalizedPageCount);
77
+ if (fromHash !== null) setCurrentPageIndex(fromHash);
78
+ };
79
+ sync();
80
+ window.addEventListener("hashchange", sync);
81
+ return () => window.removeEventListener("hashchange", sync);
82
+ }, [normalizedPageCount]);
83
+
84
+ // Auto-enter immersive when ?fullscreen=1 is in the URL (e.g., launched from workbench play button)
85
+ useEffect(() => {
86
+ if (!shouldStartImmersive()) return;
87
+ setUiMode("immersive");
88
+ const root = globalThis.document.documentElement;
89
+ if (root?.requestFullscreen) {
90
+ void root.requestFullscreen().catch(() => {
91
+ // Fullscreen rejected — keep immersive CSS only.
92
+ });
93
+ }
94
+ }, []);
95
+
96
+ // Fullscreen change
97
+ useEffect(() => {
98
+ const handler = () => {
99
+ setUiMode(globalThis.document.fullscreenElement ? "immersive" : "chrome");
100
+ };
101
+ globalThis.document.addEventListener("fullscreenchange", handler);
102
+ return () => globalThis.document.removeEventListener("fullscreenchange", handler);
103
+ }, []);
104
+
105
+ // Keyboard navigation
106
+ useEffect(() => {
107
+ const handleKeyDown = (event: KeyboardEvent) => {
108
+ if (isEditableTarget(event.target)) return;
109
+
110
+ if (event.key === "Escape") {
111
+ const activeDoc = globalThis.document;
112
+ if (activeDoc.fullscreenElement && activeDoc.exitFullscreen) {
113
+ event.preventDefault();
114
+ void activeDoc.exitFullscreen();
115
+ }
116
+ return;
117
+ }
118
+
119
+ if (event.key === "f" || event.key === "F") {
120
+ event.preventDefault();
121
+ enterImmersive();
122
+ return;
123
+ }
124
+
125
+ if (event.key === " " || event.code === "Space" || event.key === "ArrowRight" || event.key === "PageDown") {
126
+ event.preventDefault();
127
+ setPage(currentPageIndexRef.current + 1);
128
+ } else if (event.key === "ArrowLeft" || event.key === "PageUp") {
129
+ event.preventDefault();
130
+ setPage(currentPageIndexRef.current - 1);
131
+ } else if (event.key === "Home") {
132
+ event.preventDefault();
133
+ setPage(0);
134
+ } else if (event.key === "End") {
135
+ event.preventDefault();
136
+ setPage(normalizedPageCount - 1);
137
+ }
138
+ };
139
+
140
+ window.addEventListener("keydown", handleKeyDown);
141
+ return () => window.removeEventListener("keydown", handleKeyDown);
142
+ }, [normalizedPageCount, setPage]); // eslint-disable-line react-hooks/exhaustive-deps
143
+
144
+ const enterImmersive = () => {
145
+ setUiMode("immersive");
146
+ const root = globalThis.document.documentElement;
147
+ if (root?.requestFullscreen) {
148
+ void root.requestFullscreen().catch(() => {
149
+ // Fullscreen rejected (e.g. gesture policy) — keep immersive CSS only.
150
+ });
151
+ }
152
+ };
153
+
154
+ const exitImmersive = () => {
155
+ const activeDoc = globalThis.document;
156
+ if (activeDoc.fullscreenElement && activeDoc.exitFullscreen) {
157
+ void activeDoc.exitFullscreen();
158
+ } else {
159
+ setUiMode("chrome");
160
+ }
161
+ };
162
+
163
+ const handleStageClick = (event: ReactMouseEvent<HTMLElement>) => {
164
+ if (uiMode !== "immersive") return;
165
+ if (event.defaultPrevented) return;
166
+ if (!(event.target instanceof Element)) return;
167
+ if (event.target.closest("a, button, input, textarea, select, [contenteditable]")) return;
168
+ setPage(currentPageIndexRef.current + 1);
169
+ };
170
+
171
+ const LeftIcon = thumbPanelOpen ? PanelLeftClose : PanelLeftOpen;
172
+ const leftLabel = thumbPanelOpen ? "收合縮圖面板" : "展開縮圖面板";
173
+ const pdfHref = deploymentInfo?.pdf;
174
+
175
+ return (
176
+ <main
177
+ className="openpress-workbench openpress-reader-app openpress-slide-public"
178
+ style={style}
179
+ data-openpress-react-runtime="true"
180
+ data-openpress-view-mode="paged"
181
+ data-openpress-press-type="slides"
182
+ data-openpress-presentation-mode={uiMode === "immersive" ? "on" : "off"}
183
+ data-openpress-present-ui={uiMode}
184
+ aria-label={`${document.meta.title} 投影片瀏覽`}
185
+ >
186
+ {/* Top toolbar — chrome mode only */}
187
+ <header
188
+ className="openpress-workbench-toolbar openpress-slide-public__toolbar"
189
+ role="toolbar"
190
+ aria-label="投影片操作"
191
+ data-openpress-slide-public-toolbar
192
+ >
193
+ <button
194
+ type="button"
195
+ className="openpress-workbench-toolbar-panel-toggle"
196
+ aria-label={leftLabel}
197
+ title={leftLabel}
198
+ onClick={() => setThumbPanelOpen((v) => !v)}
199
+ >
200
+ <LeftIcon aria-hidden="true" />
201
+ </button>
202
+
203
+ <div className="openpress-slide-public__nav" aria-label="翻頁">
204
+ <button
205
+ type="button"
206
+ className="openpress-workbench-toolbar-action openpress-slide-public__nav-btn"
207
+ onClick={() => setPage(currentPageIndex - 1)}
208
+ disabled={currentPageIndex === 0}
209
+ aria-label="上一頁"
210
+ title="上一頁"
211
+ >
212
+ <ChevronLeft aria-hidden="true" />
213
+ </button>
214
+ <span className="openpress-slide-public__counter" aria-live="polite" aria-label={`第 ${currentPageLabel} 頁,共 ${totalPageLabel} 頁`}>
215
+ {currentPageLabel} / {totalPageLabel}
216
+ </span>
217
+ <button
218
+ type="button"
219
+ className="openpress-workbench-toolbar-action openpress-slide-public__nav-btn"
220
+ onClick={() => setPage(currentPageIndex + 1)}
221
+ disabled={currentPageIndex >= normalizedPageCount - 1}
222
+ aria-label="下一頁"
223
+ title="下一頁"
224
+ >
225
+ <ChevronRight aria-hidden="true" />
226
+ </button>
227
+ </div>
228
+
229
+ <div className="openpress-workbench-toolbar__content" />
230
+
231
+ <div className="openpress-workbench-toolbar__group" aria-label="視圖">
232
+ <button
233
+ type="button"
234
+ className="openpress-workbench-toolbar-action"
235
+ onClick={enterImmersive}
236
+ aria-label="進入全螢幕放映"
237
+ title="全螢幕放映 (F)"
238
+ >
239
+ <Maximize2 aria-hidden="true" />
240
+ </button>
241
+ {pdfHref ? (
242
+ <a
243
+ href={pdfHref}
244
+ target="_blank"
245
+ rel="noopener noreferrer"
246
+ className="openpress-workbench-toolbar-action"
247
+ aria-label="下載 PDF"
248
+ title="下載 PDF"
249
+ >
250
+ <Download aria-hidden="true" />
251
+ </a>
252
+ ) : null}
253
+ </div>
254
+ </header>
255
+
256
+ {/* Body: thumb panel + stage */}
257
+ <div className="openpress-slide-public__body">
258
+ {/* Thumbnail panel */}
259
+ <aside
260
+ className={`openpress-slide-public__thumbs${thumbPanelOpen ? "" : " is-closed"}`}
261
+ aria-label="投影片縮圖"
262
+ data-openpress-slide-public-thumbs
263
+ >
264
+ <PageThumbnails
265
+ pages={pages}
266
+ currentPageIndex={currentPageIndex}
267
+ onSelectPage={setPage}
268
+ theme={document.theme}
269
+ />
270
+ </aside>
271
+
272
+ {/* Main slide stage */}
273
+ <section
274
+ className="openpress-slide-public__stage"
275
+ aria-label="投影片檢視區"
276
+ onClick={handleStageClick}
277
+ ref={stageRef}
278
+ >
279
+ <div
280
+ className="reader-pages openpress-public-page openpress-slide-public__pages"
281
+ ref={sourceContainerRef}
282
+ data-openpress-public-page="true"
283
+ data-openpress-page-layout="single"
284
+ >
285
+ {currentPage ? (
286
+ <div
287
+ key={currentPage.id}
288
+ id={`page-${String(currentPage.pageNumber).padStart(2, "0")}`}
289
+ className="openpress-html-page"
290
+ data-openpress-object-id={currentPage.frameKey ? createPageObjectEntityId(currentPage.frameKey) : undefined}
291
+ data-openpress-page-index={currentPage.pageNumber - 1}
292
+ data-openpress-active="true"
293
+ >
294
+ <div className="openpress-html-page__html" dangerouslySetInnerHTML={{ __html: pageHtml }} />
295
+ </div>
296
+ ) : null}
297
+ </div>
298
+ </section>
299
+ </div>
300
+
301
+ {/* Immersive mini HUD — fullscreen mode only */}
302
+ <div
303
+ className="openpress-slide-public__mini-hud"
304
+ aria-label="放映控制"
305
+ data-openpress-present-scale={pageViewport.scaleMode}
306
+ >
307
+ <span className="openpress-slide-public__mini-counter">
308
+ {currentPageLabel} / {totalPageLabel}
309
+ </span>
310
+ <button
311
+ type="button"
312
+ className="openpress-slide-public__mini-btn"
313
+ onClick={exitImmersive}
314
+ aria-label="離開全螢幕"
315
+ title="離開全螢幕 (Esc)"
316
+ >
317
+ <Minimize2 aria-hidden="true" />
318
+ </button>
319
+ </div>
320
+ </main>
321
+ );
322
+ }
323
+
324
+ function isEditableTarget(target: EventTarget | null) {
325
+ if (!(target instanceof HTMLElement)) return false;
326
+ return Boolean(target.closest("input, textarea, select, button, [contenteditable]"));
327
+ }
328
+
329
+ function shouldStartImmersive() {
330
+ if (typeof window === "undefined") return false;
331
+ return new URLSearchParams(window.location.search).get("fullscreen") === "1";
332
+ }
@@ -1,6 +1,7 @@
1
1
  export * from "./PageThumbnailsPanel";
2
2
  export * from "./PublicReaderPage";
3
3
  export * from "./ReaderNavigationPanel";
4
+ export * from "./SlidePublicPage";
4
5
  export * from "./SlidePresentationPage";
5
6
  export * from "./pageViewportScaleModel";
6
7
  export * from "./readerPageRegistry";
@@ -34,13 +34,15 @@ export function resolvePageViewportScale({
34
34
  mode,
35
35
  fitWidthScale,
36
36
  fitPageScale,
37
+ maxFitScale = MAX_FIT_PAGE_VIEWPORT_SCALE,
37
38
  }: {
38
39
  mode: PageViewportScaleMode;
39
40
  fitWidthScale: number;
40
41
  fitPageScale: number;
42
+ maxFitScale?: number;
41
43
  }) {
42
- if (mode === "fit-width") return clampPageViewportScale(fitWidthScale, MAX_FIT_PAGE_VIEWPORT_SCALE);
43
- if (mode === "fit-page") return clampPageViewportScale(fitPageScale, MAX_FIT_PAGE_VIEWPORT_SCALE);
44
+ if (mode === "fit-width") return clampPageViewportScale(fitWidthScale, maxFitScale);
45
+ if (mode === "fit-page") return clampPageViewportScale(fitPageScale, maxFitScale);
44
46
  return scaleModeToFixedValue(mode);
45
47
  }
46
48
 
@@ -68,6 +70,6 @@ function scaleModeToFixedValue(mode: PageViewportScaleMode) {
68
70
 
69
71
  function clampPageViewportScale(value: number, maxScale: number) {
70
72
  if (!Number.isFinite(value)) return 1;
71
- const safeMaxScale = Number.isFinite(maxScale) && maxScale > 0 ? maxScale : MAX_FIXED_PAGE_VIEWPORT_SCALE;
73
+ const safeMaxScale = maxScale > 0 ? maxScale : MAX_FIXED_PAGE_VIEWPORT_SCALE;
72
74
  return Math.min(Math.max(value, MIN_PAGE_VIEWPORT_SCALE), safeMaxScale);
73
75
  }
@@ -13,13 +13,17 @@ export function usePageViewportScale({
13
13
  pageContainerRef,
14
14
  pageCount,
15
15
  layoutMode = "single",
16
+ initialScaleMode = "fit-width",
17
+ maxFitScale = 1,
16
18
  }: {
17
19
  stageRef: RefObject<HTMLElement | null>;
18
20
  pageContainerRef: RefObject<HTMLElement | null>;
19
21
  pageCount: number;
20
22
  layoutMode?: PageLayoutMode;
23
+ initialScaleMode?: PageViewportScaleMode;
24
+ maxFitScale?: number;
21
25
  }) {
22
- const [scaleMode, setScaleMode] = useState<PageViewportScaleMode>("fit-width");
26
+ const [scaleMode, setScaleMode] = useState<PageViewportScaleMode>(initialScaleMode);
23
27
  const [scale, setScale] = useState(1);
24
28
 
25
29
  useLayoutEffect(() => {
@@ -66,7 +70,7 @@ export function usePageViewportScale({
66
70
  const fitPageScale = canonicalWidth > 0 && canonicalHeight > 0
67
71
  ? Math.min(availableWidth / canonicalWidth, availableHeight / canonicalHeight)
68
72
  : 1;
69
- const nextScale = resolvePageViewportScale({ mode: scaleMode, fitWidthScale, fitPageScale });
73
+ const nextScale = resolvePageViewportScale({ mode: scaleMode, fitWidthScale, fitPageScale, maxFitScale });
70
74
  const nextScaleValue = formatPageViewportScaleValue(nextScale);
71
75
 
72
76
  container.style.setProperty("--openpress-page-viewport-scale", nextScaleValue);
@@ -93,16 +97,16 @@ export function usePageViewportScale({
93
97
  window.removeEventListener("resize", syncScale);
94
98
  window.visualViewport?.removeEventListener("resize", syncScale);
95
99
  };
96
- }, [layoutMode, pageContainerRef, pageCount, scaleMode, stageRef]);
100
+ }, [layoutMode, maxFitScale, pageContainerRef, pageCount, scaleMode, stageRef]);
97
101
 
98
102
  const scaleLabel = useMemo(
99
103
  () => {
100
104
  const labelScale = scaleMode.startsWith("scale-")
101
- ? resolvePageViewportScale({ mode: scaleMode, fitWidthScale: scale, fitPageScale: scale })
105
+ ? resolvePageViewportScale({ mode: scaleMode, fitWidthScale: scale, fitPageScale: scale, maxFitScale })
102
106
  : scale;
103
107
  return formatPageViewportScaleLabel(scaleMode, labelScale);
104
108
  },
105
- [scale, scaleMode],
109
+ [maxFitScale, scale, scaleMode],
106
110
  );
107
111
 
108
112
  return {
@@ -1,4 +1,4 @@
1
- import { useCallback, useEffect, useState } from "react";
1
+ import { useCallback, useEffect, useRef, useState } from "react";
2
2
 
3
3
  export interface UsePanelStateOptions {
4
4
  leftPanelBreakpoint?: number;
@@ -31,26 +31,35 @@ export function usePanelState({
31
31
  const [rightPanelOpen, setRightPanelOpen] = useState(false);
32
32
  const [leftPanelOpen, setLeftPanelOpen] = useState(false);
33
33
 
34
+ // The auto-close-on-narrow rule is a *resize* response, not a state-change
35
+ // response. Keep current panel state in a ref so the resize listener can read
36
+ // it without re-subscribing every toggle — otherwise toggling a drawer open
37
+ // in a narrow viewport would re-run this effect, call handleResize
38
+ // synchronously, see "open + below breakpoint", and immediately close the
39
+ // panel the user just opened.
40
+ const panelStateRef = useRef({ leftPanelOpen, rightPanelOpen });
41
+ panelStateRef.current = { leftPanelOpen, rightPanelOpen };
42
+
34
43
  useEffect(() => {
35
44
  if (typeof window === "undefined") return undefined;
36
45
 
37
46
  const handleResize = () => {
38
- const closeLeftPanel = leftPanelOpen && !shouldOpenLeftPanel();
39
- const closeRightPanel = rightPanelOpen && !shouldOpenRightPanel();
47
+ const { leftPanelOpen: lo, rightPanelOpen: ro } = panelStateRef.current;
48
+ const closeLeftPanel = lo && !shouldOpenLeftPanel();
49
+ const closeRightPanel = ro && !shouldOpenRightPanel();
40
50
 
41
51
  if (closeLeftPanel) setLeftPanelOpen(false);
42
52
  if (closeRightPanel) setRightPanelOpen(false);
43
53
  if (closeLeftPanel || closeRightPanel) onAfterResize?.();
44
54
  };
45
55
 
46
- handleResize();
47
56
  window.addEventListener("resize", handleResize);
48
57
  window.visualViewport?.addEventListener("resize", handleResize);
49
58
  return () => {
50
59
  window.removeEventListener("resize", handleResize);
51
60
  window.visualViewport?.removeEventListener("resize", handleResize);
52
61
  };
53
- }, [leftPanelOpen, rightPanelOpen, shouldOpenLeftPanel, shouldOpenRightPanel, onAfterResize]);
62
+ }, [shouldOpenLeftPanel, shouldOpenRightPanel, onAfterResize]);
54
63
 
55
64
  const toggleLeftPanel = useCallback(() => setLeftPanelOpen((open) => !open), []);
56
65
  const toggleRightPanel = useCallback(() => setRightPanelOpen((open) => !open), []);
@@ -2,3 +2,4 @@ export * from "./frameScheduler";
2
2
  export * from "./numberUtils";
3
3
  export * from "./Panel";
4
4
  export * from "./runtimeMode";
5
+ export * from "./staticSearch";
@@ -0,0 +1,174 @@
1
+ // Browser-safe literal-substring search over the build-time search
2
+ // corpus (<outputDir>/openpress/search-corpus.json). Mirrors the
3
+ // `searchSourceText` logic in engine/runtime/source-text-tools.mjs so
4
+ // public deploys can search without the /__openpress/search dev endpoint.
5
+
6
+ export type SearchScope = "content" | "all";
7
+
8
+ export interface SearchCorpusFile {
9
+ scope: string;
10
+ file: string;
11
+ path: string;
12
+ text: string;
13
+ }
14
+
15
+ export interface SearchCorpus {
16
+ kind: "search-corpus";
17
+ version: number;
18
+ files: SearchCorpusFile[];
19
+ }
20
+
21
+ export interface SearchReportFile {
22
+ scope: string;
23
+ file: string;
24
+ path: string;
25
+ matchCount: number;
26
+ }
27
+
28
+ export interface SearchReportMatch {
29
+ id: string;
30
+ scope: string;
31
+ file: string;
32
+ path: string;
33
+ line: number;
34
+ column: number;
35
+ index: number;
36
+ text: string;
37
+ preview: string;
38
+ }
39
+
40
+ export interface SearchReport {
41
+ ok?: boolean;
42
+ kind: "search";
43
+ query: string;
44
+ scope: SearchScope;
45
+ caseSensitive: boolean;
46
+ matchCount: number;
47
+ files: SearchReportFile[];
48
+ matches: SearchReportMatch[];
49
+ message?: string;
50
+ }
51
+
52
+ export interface SearchCorpusQueryOptions {
53
+ query: string;
54
+ scope?: SearchScope;
55
+ caseSensitive?: boolean;
56
+ }
57
+
58
+ export function searchCorpus(corpus: SearchCorpus, options: SearchCorpusQueryOptions): SearchReport {
59
+ const query = options.query;
60
+ const scope: SearchScope = options.scope ?? "content";
61
+ const caseSensitive = options.caseSensitive ?? false;
62
+ const matches: SearchReportMatch[] = [];
63
+
64
+ if (!query) {
65
+ return { kind: "search", query, scope, caseSensitive, matchCount: 0, files: [], matches: [] };
66
+ }
67
+
68
+ for (const file of corpus.files) {
69
+ const rawMatches = findLiteralMatches(file.text, query, { caseSensitive });
70
+ for (const match of rawMatches) {
71
+ matches.push({
72
+ id: `match-${String(matches.length + 1).padStart(4, "0")}`,
73
+ scope: file.scope,
74
+ file: file.file,
75
+ path: file.path,
76
+ line: match.line,
77
+ column: match.column,
78
+ index: match.index,
79
+ text: match.text,
80
+ preview: match.preview,
81
+ });
82
+ }
83
+ }
84
+
85
+ return {
86
+ kind: "search",
87
+ query,
88
+ scope,
89
+ caseSensitive,
90
+ matchCount: matches.length,
91
+ files: summarizeFiles(matches),
92
+ matches,
93
+ };
94
+ }
95
+
96
+ interface RawMatch {
97
+ line: number;
98
+ column: number;
99
+ index: number;
100
+ text: string;
101
+ preview: string;
102
+ }
103
+
104
+ function findLiteralMatches(text: string, query: string, options: { caseSensitive: boolean }): RawMatch[] {
105
+ if (!query) return [];
106
+ const matches: RawMatch[] = [];
107
+ forEachLine(text, ({ line, lineNumber, lineOffset }) => {
108
+ for (const range of findLineMatches(line, query, options)) {
109
+ matches.push({
110
+ line: lineNumber,
111
+ column: range.start + 1,
112
+ index: lineOffset + range.start,
113
+ text: line.slice(range.start, range.end),
114
+ preview: previewLine(line, range.start, range.end),
115
+ });
116
+ }
117
+ });
118
+ return matches;
119
+ }
120
+
121
+ function findLineMatches(line: string, query: string, { caseSensitive }: { caseSensitive: boolean }) {
122
+ const haystack = caseSensitive ? line : line.toLowerCase();
123
+ const needle = caseSensitive ? query : query.toLowerCase();
124
+ const ranges: { start: number; end: number }[] = [];
125
+ let cursor = 0;
126
+ while (needle && cursor <= haystack.length) {
127
+ const start = haystack.indexOf(needle, cursor);
128
+ if (start < 0) break;
129
+ const end = start + needle.length;
130
+ ranges.push({ start, end });
131
+ cursor = end;
132
+ }
133
+ return ranges;
134
+ }
135
+
136
+ function previewLine(line: string, start: number, end: number) {
137
+ const previewStart = Math.max(0, start - 40);
138
+ const previewEnd = Math.min(line.length, end + 40);
139
+ const prefix = previewStart > 0 ? "..." : "";
140
+ const suffix = previewEnd < line.length ? "..." : "";
141
+ return `${prefix}${line.slice(previewStart, previewEnd)}${suffix}`;
142
+ }
143
+
144
+ function forEachLine(
145
+ text: string,
146
+ visit: (info: { line: string; ending: string; lineNumber: number; lineOffset: number }) => void,
147
+ ) {
148
+ const lineRe = /([^\r\n]*)(\r\n|\n|\r|$)/g;
149
+ let lineNumber = 1;
150
+ let offset = 0;
151
+ let match: RegExpExecArray | null;
152
+ while ((match = lineRe.exec(text))) {
153
+ const [full, line, ending] = match;
154
+ if (full === "") break;
155
+ visit({ line, ending, lineNumber, lineOffset: offset });
156
+ offset += full.length;
157
+ lineNumber += 1;
158
+ }
159
+ }
160
+
161
+ function summarizeFiles(matches: SearchReportMatch[]): SearchReportFile[] {
162
+ const grouped = new Map<string, SearchReportFile>();
163
+ for (const match of matches) {
164
+ const current = grouped.get(match.path) ?? {
165
+ scope: match.scope,
166
+ file: match.file,
167
+ path: match.path,
168
+ matchCount: 0,
169
+ };
170
+ current.matchCount += 1;
171
+ grouped.set(match.path, current);
172
+ }
173
+ return Array.from(grouped.values());
174
+ }