@open-press/core 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/engine/commands/dev.mjs +2 -2
  2. package/engine/commands/upgrade.mjs +47 -5
  3. package/engine/output/chrome-pdf.mjs +18 -3
  4. package/engine/output/static-server.mjs +39 -0
  5. package/engine/react/comment-endpoint.mjs +13 -39
  6. package/engine/react/comment-marker.mjs +30 -6
  7. package/engine/react/document-entry.mjs +11 -0
  8. package/engine/react/document-export.mjs +45 -5
  9. package/engine/react/http-json.mjs +24 -0
  10. package/engine/react/mdx-compile.mjs +187 -3
  11. package/engine/react/measurement-css.mjs +93 -1
  12. package/engine/react/object-entities.mjs +119 -0
  13. package/engine/react/pipeline/allocate.mjs +10 -7
  14. package/engine/react/pipeline/frame-measurement.mjs +40 -9
  15. package/engine/react/project-asset-endpoint.mjs +6 -24
  16. package/engine/react/source-edit-endpoint.d.mts +10 -0
  17. package/engine/react/source-edit-endpoint.mjs +75 -0
  18. package/engine/react/sources/mdx-resolver.mjs +12 -14
  19. package/engine/react/style-discovery.mjs +1 -4
  20. package/engine/runtime/file-walk.mjs +22 -0
  21. package/engine/runtime/inspection.mjs +1 -20
  22. package/engine/runtime/path-utils.mjs +20 -0
  23. package/engine/runtime/source-text-tools.d.mts +102 -0
  24. package/engine/runtime/source-text-tools.mjs +551 -16
  25. package/engine/runtime/source-workspace.mjs +4 -31
  26. package/package.json +1 -1
  27. package/src/openpress/{App.tsx → app/OpenPressApp.tsx} +25 -12
  28. package/src/openpress/{renderer.tsx → app/OpenPressRuntime.tsx} +10 -7
  29. package/src/openpress/app/index.ts +2 -0
  30. package/src/openpress/core/Frame.tsx +9 -11
  31. package/src/openpress/core/FrameContext.tsx +8 -3
  32. package/src/openpress/core/MdxArea.tsx +11 -12
  33. package/src/openpress/core/cn.ts +4 -0
  34. package/src/openpress/core/index.tsx +2 -1
  35. package/src/openpress/core/primitives.tsx +29 -8
  36. package/src/openpress/core/types.ts +8 -0
  37. package/src/openpress/{anchorMap.ts → document-model/anchorMapModel.ts} +1 -1
  38. package/src/openpress/{indexes.ts → document-model/documentIndexes.ts} +1 -1
  39. package/src/openpress/{types.ts → document-model/documentTypes.ts} +42 -0
  40. package/src/openpress/document-model/index.ts +6 -0
  41. package/src/openpress/document-model/objectEntityModel.ts +51 -0
  42. package/src/openpress/{projectIdentity.ts → document-model/projectIdentityModel.ts} +1 -1
  43. package/src/openpress/{reactDocumentMetadata.ts → document-model/reactDocumentMetadataModel.ts} +1 -1
  44. package/src/openpress/manuscript/index.tsx +49 -7
  45. package/src/openpress/{publicPage.tsx → reader/PublicReaderPage.tsx} +31 -51
  46. package/src/openpress/{workbenchPanels.tsx → reader/ReaderNavigationPanel.tsx} +6 -5
  47. package/src/openpress/reader/index.ts +10 -0
  48. package/src/openpress/reader/pageViewportScaleModel.ts +73 -0
  49. package/src/openpress/reader/readerTypes.ts +4 -0
  50. package/src/openpress/reader/usePageViewportScale.ts +119 -0
  51. package/src/openpress/reader/usePanelState.ts +56 -0
  52. package/src/openpress/reader/useReaderHashSync.ts +61 -0
  53. package/src/openpress/reader/useReaderKeyboardNav.ts +48 -0
  54. package/src/openpress/reader/useReaderRuntime.ts +146 -0
  55. package/src/openpress/reader/useReaderScrollAnchor.ts +64 -0
  56. package/src/openpress/shared/Panel.tsx +77 -0
  57. package/src/openpress/shared/index.ts +4 -0
  58. package/src/openpress/shared/numberUtils.ts +3 -0
  59. package/src/openpress/{runtimeMode.ts → shared/runtimeMode.ts} +0 -11
  60. package/src/openpress/workbench/Workbench.tsx +407 -0
  61. package/src/openpress/workbench/actions/DeploymentControl.tsx +157 -0
  62. package/src/openpress/workbench/actions/PageZoomControl.tsx +182 -0
  63. package/src/openpress/workbench/actions/SearchControl.tsx +345 -0
  64. package/src/openpress/workbench/actions/deploymentStatusModel.ts +112 -0
  65. package/src/openpress/workbench/actions/index.ts +5 -0
  66. package/src/openpress/workbench/actions/useDeploymentWorkbench.ts +136 -0
  67. package/src/openpress/workbench/dialog/WorkbenchDialog.tsx +72 -0
  68. package/src/openpress/workbench/dialog/index.ts +1 -0
  69. package/src/openpress/workbench/document/components/DocumentPanel.tsx +127 -0
  70. package/src/openpress/workbench/document/components/InlineSourceEditorLayer.tsx +207 -0
  71. package/src/openpress/workbench/document/components/ReaderStage.tsx +9 -0
  72. package/src/openpress/workbench/document/hooks/useDocumentWorkbenchModel.ts +34 -0
  73. package/src/openpress/workbench/document/hooks/useInlineDocumentEditor.ts +525 -0
  74. package/src/openpress/workbench/document/index.ts +10 -0
  75. package/src/openpress/workbench/index.ts +2 -0
  76. package/src/openpress/workbench/inspector/InlineInspectorLayer.tsx +459 -0
  77. package/src/openpress/workbench/inspector/index.ts +5 -0
  78. package/src/openpress/workbench/inspector/inlineCommentModel.ts +125 -0
  79. package/src/openpress/workbench/inspector/inspectorGeometryModel.ts +160 -0
  80. package/src/openpress/workbench/inspector/inspectorModel.ts +408 -0
  81. package/src/openpress/workbench/inspector/useInspectorComments.ts +248 -0
  82. package/src/openpress/workbench/mentions/MentionSuggestionList.tsx +41 -0
  83. package/src/openpress/workbench/mentions/index.ts +2 -0
  84. package/src/openpress/{composerMentions.ts → workbench/mentions/useComposerMentions.ts} +1 -4
  85. package/src/openpress/workbench/panels/Panel.tsx +1 -0
  86. package/src/openpress/workbench/panels/PendingCommentsPanel.tsx +76 -0
  87. package/src/openpress/workbench/panels/WorkbenchControlPanel.tsx +29 -0
  88. package/src/openpress/workbench/panels/index.ts +3 -0
  89. package/src/openpress/workbench/project/ProjectEntryPanel.tsx +523 -0
  90. package/src/openpress/workbench/project/ProjectPreviewDialog.tsx +35 -0
  91. package/src/openpress/workbench/project/index.ts +2 -0
  92. package/src/openpress/workbench/project/projectPreviewTypes.ts +11 -0
  93. package/src/openpress/workbench/shell/WorkbenchShell.tsx +167 -0
  94. package/src/openpress/workbench/shell/index.ts +1 -0
  95. package/src/openpress/workbench/workbenchFormatters.ts +120 -0
  96. package/src/openpress/workbench/workbenchTypes.ts +35 -0
  97. package/src/styles/openpress/print-route.css +0 -2
  98. package/src/styles/openpress/{project-workspace.css → project-preview-panel.css} +13 -407
  99. package/src/styles/openpress/public-viewer.css +25 -320
  100. package/src/styles/openpress/reader-runtime.css +243 -55
  101. package/src/styles/openpress/responsive.css +145 -270
  102. package/src/styles/openpress/workbench-panels.css +214 -178
  103. package/src/styles/openpress/workbench.css +986 -451
  104. package/src/styles/openpress.css +1 -1
  105. package/vite.config.ts +50 -0
  106. package/src/openpress/inspector.ts +0 -282
  107. package/src/openpress/projectWorkspace.tsx +0 -919
  108. package/src/openpress/readerRuntime.ts +0 -230
  109. package/src/openpress/workbench.tsx +0 -1265
  110. package/src/openpress/workbenchTypes.ts +0 -4
  111. /package/src/openpress/{readerPageRegistry.ts → reader/readerPageRegistry.ts} +0 -0
  112. /package/src/openpress/{pageRoute.ts → reader/readerPageRoute.ts} +0 -0
  113. /package/src/openpress/{readerScroll.ts → reader/readerScroll.ts} +0 -0
  114. /package/src/openpress/{readerState.ts → reader/readerStateModel.ts} +0 -0
  115. /package/src/openpress/{frameScheduler.ts → shared/frameScheduler.ts} +0 -0
  116. /package/src/openpress/{projectSources.ts → workbench/project/projectSourceModel.ts} +0 -0
@@ -0,0 +1,136 @@
1
+ import { useCallback, useMemo, useState } from "react";
2
+ import { isLocalWorkspaceHost } from "../../shared";
3
+ import type { DeploymentInfo } from "../../document-model";
4
+ import type { DeployStatus, PdfActionStatus } from "../workbenchTypes";
5
+ import { parseDeployError, workbenchPdfButtonText, workbenchPdfStatusMessage } from "./deploymentStatusModel";
6
+
7
+ export interface UseDeploymentWorkbenchOptions {
8
+ deploymentInfo: DeploymentInfo;
9
+ }
10
+
11
+ export interface DeploymentWorkbench {
12
+ status: DeployStatus;
13
+ pdfActionStatus: PdfActionStatus;
14
+ currentDeploymentInfo: DeploymentInfo;
15
+ staticPdfHref: string | undefined;
16
+ localDeployEnabled: boolean;
17
+ pdfButtonText: string;
18
+ pdfButtonDisabled: boolean;
19
+ pdfStatusMessage: string | null;
20
+ pdfToolbarExpanded: boolean;
21
+ handleDeploy: () => Promise<void>;
22
+ handleOpenWorkbenchPdf: () => void;
23
+ }
24
+
25
+ export function useDeploymentWorkbench({ deploymentInfo }: UseDeploymentWorkbenchOptions): DeploymentWorkbench {
26
+ const [status, setStatus] = useState<DeployStatus>("idle");
27
+ const [pdfActionStatus, setPdfActionStatus] = useState<PdfActionStatus>("idle");
28
+ const [currentDeploymentInfo, setCurrentDeploymentInfo] = useState(deploymentInfo);
29
+ const staticPdfHref = currentDeploymentInfo.pdf;
30
+
31
+ const localDeployEnabled = useMemo(() => {
32
+ if (typeof window === "undefined") return false;
33
+ return isLocalWorkspaceHost(window.location.hostname);
34
+ }, []);
35
+
36
+ const pdfButtonText = workbenchPdfButtonText(localDeployEnabled, pdfActionStatus, staticPdfHref);
37
+ const pdfStatusMessage = workbenchPdfStatusMessage(localDeployEnabled, pdfActionStatus);
38
+ const pdfButtonDisabled = localDeployEnabled
39
+ ? pdfActionStatus === "generating" || pdfActionStatus === "opening"
40
+ : !staticPdfHref;
41
+ const pdfToolbarExpanded = pdfActionStatus !== "idle";
42
+
43
+ const handleDeploy = useCallback(async () => {
44
+ if (status === "deploying") return;
45
+ if (currentDeploymentInfo.configured === false) {
46
+ setStatus("setup");
47
+ return;
48
+ }
49
+ setStatus("deploying");
50
+ try {
51
+ const response = await fetch("/__openpress/deploy", { method: "POST" });
52
+ if (response.status === 404 || response.status === 405) {
53
+ setStatus("unavailable");
54
+ return;
55
+ }
56
+ if (!response.ok) {
57
+ const text = await response.text().catch(() => "");
58
+ const result = parseDeployError(text);
59
+ if (result?.deploy_configured === false) {
60
+ setCurrentDeploymentInfo((info) => ({
61
+ ...info,
62
+ configured: false,
63
+ adapter: result.deploy_adapter ?? info.adapter,
64
+ source: result.deploy_source ?? info.source,
65
+ projectName: result.deploy_project_name ?? info.projectName,
66
+ setupMessage: result.message ?? info.setupMessage,
67
+ }));
68
+ setStatus("setup");
69
+ return;
70
+ }
71
+ console.error("OpenPress deploy failed", text);
72
+ setStatus("failed");
73
+ return;
74
+ }
75
+ const result = (await response.json().catch(() => null)) as {
76
+ deployed_at?: string;
77
+ pdf?: string;
78
+ public_url?: string;
79
+ } | null;
80
+ setCurrentDeploymentInfo((info) => ({
81
+ online: true,
82
+ deployedAt: result?.deployed_at ?? new Date().toISOString(),
83
+ pdf: result?.pdf ?? info.pdf ?? __OPENPRESS_PDF_HREF__,
84
+ publicUrl: result?.public_url ?? info.publicUrl,
85
+ dirty: false,
86
+ }));
87
+ setStatus("deployed");
88
+ setTimeout(() => setStatus("idle"), 3200);
89
+ } catch (error) {
90
+ console.error("OpenPress deploy unavailable", error);
91
+ setStatus("unavailable");
92
+ }
93
+ }, [status, currentDeploymentInfo.configured]);
94
+
95
+ const handleOpenLatestLocalPdf = useCallback(async () => {
96
+ if (pdfActionStatus === "generating") return;
97
+ setPdfActionStatus("generating");
98
+ try {
99
+ const response = await fetch("/__openpress/local-pdf-export", { method: "POST" });
100
+ if (!response.ok) {
101
+ const text = await response.text().catch(() => "");
102
+ throw new Error(text || `Local PDF export failed with status ${response.status}`);
103
+ }
104
+ const result = (await response.json().catch(() => null)) as { pdf?: string } | null;
105
+ const pdfHref = result?.pdf ?? "/__openpress/local-pdf-file";
106
+ setPdfActionStatus("opening");
107
+ window.setTimeout(() => window.location.assign(pdfHref), 180);
108
+ } catch (error) {
109
+ console.error("OpenPress local PDF export failed", error);
110
+ setPdfActionStatus("failed");
111
+ }
112
+ }, [pdfActionStatus]);
113
+
114
+ const handleOpenWorkbenchPdf = useCallback(() => {
115
+ if (localDeployEnabled) {
116
+ void handleOpenLatestLocalPdf();
117
+ return;
118
+ }
119
+ if (!staticPdfHref) return;
120
+ window.open(staticPdfHref, "_blank", "noopener,noreferrer");
121
+ }, [handleOpenLatestLocalPdf, localDeployEnabled, staticPdfHref]);
122
+
123
+ return {
124
+ status,
125
+ pdfActionStatus,
126
+ currentDeploymentInfo,
127
+ staticPdfHref,
128
+ localDeployEnabled,
129
+ pdfButtonText,
130
+ pdfButtonDisabled,
131
+ pdfStatusMessage,
132
+ pdfToolbarExpanded,
133
+ handleDeploy,
134
+ handleOpenWorkbenchPdf,
135
+ };
136
+ }
@@ -0,0 +1,72 @@
1
+ import { type ReactNode } from "react";
2
+ import { createPortal } from "react-dom";
3
+ import { X } from "lucide-react";
4
+
5
+ export function WorkbenchDialog({
6
+ titleId,
7
+ title,
8
+ eyebrow,
9
+ titleMeta,
10
+ className,
11
+ backdropClassName,
12
+ headerClassName,
13
+ closeLabel,
14
+ onClose,
15
+ children,
16
+ footer,
17
+ }: {
18
+ titleId: string;
19
+ title: ReactNode;
20
+ eyebrow?: ReactNode;
21
+ titleMeta?: ReactNode;
22
+ className?: string;
23
+ backdropClassName?: string;
24
+ headerClassName?: string;
25
+ closeLabel: string;
26
+ onClose: () => void;
27
+ children: ReactNode;
28
+ footer?: ReactNode;
29
+ }) {
30
+ if (typeof document === "undefined") return null;
31
+
32
+ return createPortal(
33
+ <div
34
+ className={joinClassNames("openpress-workbench-dialog-backdrop", backdropClassName)}
35
+ role="presentation"
36
+ onClick={onClose}
37
+ >
38
+ <section
39
+ className={joinClassNames("openpress-workbench-dialog", className)}
40
+ role="dialog"
41
+ aria-modal="true"
42
+ aria-labelledby={titleId}
43
+ onClick={(event) => event.stopPropagation()}
44
+ >
45
+ <header className={joinClassNames("openpress-workbench-dialog__header", headerClassName)}>
46
+ <div className="openpress-workbench-dialog__heading">
47
+ {eyebrow ? <span className="openpress-workbench-dialog__eyebrow">{eyebrow}</span> : null}
48
+ <div className="openpress-workbench-dialog__title-row">
49
+ <h2 id={titleId}>{title}</h2>
50
+ {titleMeta ? <div className="openpress-workbench-dialog__title-meta">{titleMeta}</div> : null}
51
+ </div>
52
+ </div>
53
+ <button
54
+ type="button"
55
+ className="openpress-workbench-dialog__close"
56
+ aria-label={closeLabel}
57
+ onClick={onClose}
58
+ >
59
+ <X aria-hidden="true" />
60
+ </button>
61
+ </header>
62
+ {children}
63
+ {footer ? <footer className="openpress-workbench-dialog__footer">{footer}</footer> : null}
64
+ </section>
65
+ </div>,
66
+ document.body,
67
+ );
68
+ }
69
+
70
+ function joinClassNames(...classNames: Array<string | false | null | undefined>) {
71
+ return classNames.filter(Boolean).join(" ");
72
+ }
@@ -0,0 +1 @@
1
+ export { WorkbenchDialog } from "./WorkbenchDialog";
@@ -0,0 +1,127 @@
1
+ import { createContext, useContext, useId, useState, type ReactNode } from "react";
2
+ import { FolderKanban, MessageSquareText, type LucideIcon } from "lucide-react";
3
+
4
+ type DocumentPanelProps = {
5
+ children: ReactNode;
6
+ };
7
+
8
+ type DocumentPanelTabValue = "comments" | "project";
9
+
10
+ type DocumentPanelContextValue = {
11
+ activeTab: DocumentPanelTabValue;
12
+ setActiveTab: (tab: DocumentPanelTabValue) => void;
13
+ baseId: string;
14
+ };
15
+
16
+ const DocumentPanelContext = createContext<DocumentPanelContextValue | null>(null);
17
+
18
+ const PANEL_TABS: Array<{ value: DocumentPanelTabValue; label: string; icon: LucideIcon }> = [
19
+ { value: "comments", label: "註解", icon: MessageSquareText },
20
+ { value: "project", label: "Project", icon: FolderKanban },
21
+ ];
22
+
23
+ function useDocumentPanel() {
24
+ const value = useContext(DocumentPanelContext);
25
+ if (!value) throw new Error("DocumentPanel compound components must be rendered inside <DocumentPanel>.");
26
+ return value;
27
+ }
28
+
29
+ function DocumentPanelRoot({ children }: DocumentPanelProps) {
30
+ const reactId = useId();
31
+ const [activeTab, setActiveTab] = useState<DocumentPanelTabValue>("comments");
32
+ const baseId = `openpress-document-panel-${reactId.replaceAll(":", "")}`;
33
+
34
+ return (
35
+ <DocumentPanelContext.Provider value={{ activeTab, setActiveTab, baseId }}>
36
+ <section
37
+ className="openpress-document-panel"
38
+ data-openpress-document-panel
39
+ data-openpress-document-panel-tab={activeTab}
40
+ >
41
+ {children}
42
+ </section>
43
+ </DocumentPanelContext.Provider>
44
+ );
45
+ }
46
+
47
+ function DocumentPanelTabs() {
48
+ const { activeTab, setActiveTab, baseId } = useDocumentPanel();
49
+
50
+ return (
51
+ <div className="openpress-dev-control-tabs openpress-document-panel-tabs" role="tablist" aria-label="側邊面板">
52
+ {PANEL_TABS.map((item) => {
53
+ const Icon = item.icon;
54
+ const selected = activeTab === item.value;
55
+ return (
56
+ <button
57
+ type="button"
58
+ role="tab"
59
+ aria-selected={selected}
60
+ aria-controls={`${baseId}-${item.value}`}
61
+ id={`${baseId}-${item.value}-tab`}
62
+ className={selected ? "is-active" : undefined}
63
+ key={item.value}
64
+ onClick={() => setActiveTab(item.value)}
65
+ >
66
+ <Icon aria-hidden="true" />
67
+ <span>{item.label}</span>
68
+ </button>
69
+ );
70
+ })}
71
+ </div>
72
+ );
73
+ }
74
+
75
+ function DocumentPanelTabPanel({
76
+ value,
77
+ className,
78
+ children,
79
+ }: DocumentPanelProps & {
80
+ value: DocumentPanelTabValue;
81
+ className?: string;
82
+ }) {
83
+ const { activeTab, baseId } = useDocumentPanel();
84
+ const active = activeTab === value;
85
+
86
+ return (
87
+ <section
88
+ id={`${baseId}-${value}`}
89
+ className={className}
90
+ role="tabpanel"
91
+ aria-labelledby={`${baseId}-${value}-tab`}
92
+ data-openpress-document-panel-tab-panel={value}
93
+ data-active={active ? "true" : "false"}
94
+ hidden={!active}
95
+ >
96
+ {children}
97
+ </section>
98
+ );
99
+ }
100
+
101
+ function DocumentPanelProject({ children }: DocumentPanelProps) {
102
+ return (
103
+ <DocumentPanelTabPanel value="project" className="openpress-document-panel__project">
104
+ {children}
105
+ </DocumentPanelTabPanel>
106
+ );
107
+ }
108
+
109
+ function DocumentPanelPendingComments({ children }: DocumentPanelProps) {
110
+ return (
111
+ <DocumentPanelTabPanel value="comments" className="openpress-document-panel__comments">
112
+ {children}
113
+ </DocumentPanelTabPanel>
114
+ );
115
+ }
116
+
117
+ function DocumentPanelSlot({ children }: DocumentPanelProps) {
118
+ return <>{children}</>;
119
+ }
120
+
121
+ export const DocumentPanel = Object.assign(DocumentPanelRoot, {
122
+ Tabs: DocumentPanelTabs,
123
+ Project: DocumentPanelProject,
124
+ PendingComments: DocumentPanelPendingComments,
125
+ Actions: DocumentPanelSlot,
126
+ CurrentPage: DocumentPanelSlot,
127
+ });
@@ -0,0 +1,207 @@
1
+ import { useEffect, useMemo, useState } from "react";
2
+ import type {
3
+ InlineDocumentEditStatus,
4
+ InlineDocumentSourceTarget,
5
+ } from "../hooks/useInlineDocumentEditor";
6
+
7
+ export function InlineSourceEditorLayer({
8
+ target,
9
+ fetchImpl,
10
+ onClose,
11
+ onStatusChange,
12
+ geometryVersion,
13
+ }: {
14
+ target: InlineDocumentSourceTarget | null;
15
+ fetchImpl?: typeof fetch;
16
+ onClose: () => void;
17
+ onStatusChange?: (status: InlineDocumentEditStatus) => void;
18
+ geometryVersion?: unknown;
19
+ }) {
20
+ const [text, setText] = useState("");
21
+ const [status, setStatus] = useState<"idle" | "loading" | "saving" | "failed">("idle");
22
+ const [error, setError] = useState("");
23
+ const sourceRequestUrl = useMemo(() => target ? sourceReadUrl(target) : "", [target]);
24
+ const targetRect = useMemo(() => target ? resolveSourceEditorTargetRect(target) : null, [geometryVersion, target]);
25
+
26
+ useEffect(() => {
27
+ if (!target) {
28
+ setText("");
29
+ setStatus("idle");
30
+ setError("");
31
+ return undefined;
32
+ }
33
+
34
+ const request = fetchImpl ?? globalThis.fetch?.bind(globalThis);
35
+ if (!request) {
36
+ setStatus("failed");
37
+ setError("Source edit endpoint is unavailable.");
38
+ return undefined;
39
+ }
40
+
41
+ let canceled = false;
42
+ setStatus("loading");
43
+ setError("");
44
+ void request(sourceRequestUrl, { method: "GET" })
45
+ .then(async (response) => {
46
+ if (!response.ok) {
47
+ const message = await response.text().catch(() => "");
48
+ throw new Error(message || `Source read failed with status ${response.status}`);
49
+ }
50
+ return response.json() as Promise<{ source?: { text?: string } }>;
51
+ })
52
+ .then((result) => {
53
+ if (canceled) return;
54
+ setText(result.source?.text ?? "");
55
+ setStatus("idle");
56
+ onStatusChange?.({ state: "editing", blockId: target.block.id });
57
+ })
58
+ .catch((readError) => {
59
+ if (canceled) return;
60
+ const message = readError instanceof Error ? readError.message : String(readError);
61
+ setStatus("failed");
62
+ setError(message);
63
+ onStatusChange?.({ state: "failed", blockId: target.block.id, message });
64
+ });
65
+
66
+ return () => {
67
+ canceled = true;
68
+ };
69
+ }, [fetchImpl, onStatusChange, sourceRequestUrl, target]);
70
+
71
+ if (!target) return null;
72
+
73
+ const block = target.block;
74
+ const position = sourceEditorPosition(targetRect ?? target.rect);
75
+ const canSave = status !== "loading" && status !== "saving" && text.trim().length > 0;
76
+
77
+ const handleSave = async () => {
78
+ const request = fetchImpl ?? globalThis.fetch?.bind(globalThis);
79
+ if (!request) {
80
+ setStatus("failed");
81
+ setError("Source edit endpoint is unavailable.");
82
+ return;
83
+ }
84
+
85
+ setStatus("saving");
86
+ setError("");
87
+ onStatusChange?.({ state: "saving", blockId: block.id });
88
+ try {
89
+ const response = await request("/__openpress/source-edit", {
90
+ method: "POST",
91
+ headers: { "Content-Type": "application/json" },
92
+ body: JSON.stringify({
93
+ blockId: block.id,
94
+ path: block.path,
95
+ kind: block.kind,
96
+ name: block.name,
97
+ source: block.source,
98
+ sourceMode: true,
99
+ text,
100
+ }),
101
+ });
102
+ if (!response.ok) {
103
+ const message = await response.text().catch(() => "");
104
+ throw new Error(message || `Source edit failed with status ${response.status}`);
105
+ }
106
+ setStatus("idle");
107
+ onStatusChange?.({ state: "saved", blockId: block.id });
108
+ onClose();
109
+ } catch (saveError) {
110
+ const message = saveError instanceof Error ? saveError.message : String(saveError);
111
+ setStatus("failed");
112
+ setError(message);
113
+ onStatusChange?.({ state: "failed", blockId: block.id, message });
114
+ }
115
+ };
116
+
117
+ const statusText = sourceEditorStatusText(status, error);
118
+
119
+ return (
120
+ <div className="openpress-inline-source-editor-layer" onMouseDown={(event) => event.stopPropagation()}>
121
+ <section
122
+ className="openpress-inline-source-editor"
123
+ role="dialog"
124
+ aria-label="Source 編輯"
125
+ style={position}
126
+ >
127
+ <header className="openpress-inline-source-editor__header">
128
+ <div>
129
+ <span className="openpress-inline-source-editor__eyebrow">SOURCE</span>
130
+ <strong>{block.name ?? block.kind ?? "Block"}</strong>
131
+ </div>
132
+ <button type="button" onClick={onClose} aria-label="關閉 source 編輯">
133
+ ×
134
+ </button>
135
+ </header>
136
+ <textarea
137
+ aria-label="Source 內容"
138
+ value={text}
139
+ disabled={status === "loading" || status === "saving"}
140
+ spellCheck={false}
141
+ onChange={(event) => {
142
+ setText(event.target.value);
143
+ onStatusChange?.({ state: "editing", blockId: block.id });
144
+ }}
145
+ onKeyDown={(event) => {
146
+ if (event.key === "Escape") {
147
+ event.stopPropagation();
148
+ onClose();
149
+ }
150
+ }}
151
+ />
152
+ <footer className="openpress-inline-source-editor__footer">
153
+ <span data-openpress-source-editor-status={status} role="status" aria-live="polite">
154
+ {statusText}
155
+ </span>
156
+ <div>
157
+ <button type="button" onClick={onClose}>
158
+ 取消
159
+ </button>
160
+ <button type="button" onClick={handleSave} disabled={!canSave}>
161
+ 儲存 source
162
+ </button>
163
+ </div>
164
+ </footer>
165
+ </section>
166
+ </div>
167
+ );
168
+ }
169
+
170
+ function sourceReadUrl(target: InlineDocumentSourceTarget) {
171
+ const params = new URLSearchParams();
172
+ params.set("path", target.block.path);
173
+ params.set("line", String(target.block.source?.line ?? 1));
174
+ params.set("column", String(target.block.source?.column ?? 1));
175
+ params.set("endLine", String(target.block.source?.endLine ?? target.block.source?.line ?? 1));
176
+ params.set("endColumn", String(target.block.source?.endColumn ?? target.block.source?.column ?? 1));
177
+ return `/__openpress/source-edit?${params.toString()}`;
178
+ }
179
+
180
+ function resolveSourceEditorTargetRect(target: InlineDocumentSourceTarget) {
181
+ const rect = target.element.getBoundingClientRect();
182
+ if (rect.width > 0 || rect.height > 0 || rect.left !== 0 || rect.top !== 0) return rect;
183
+ return target.rect;
184
+ }
185
+
186
+ function sourceEditorPosition(rect: DOMRect) {
187
+ const width = 420;
188
+ const margin = 14;
189
+ const viewportWidth = typeof window === "undefined" ? 1280 : window.innerWidth;
190
+ const viewportHeight = typeof window === "undefined" ? 900 : window.innerHeight;
191
+ const left = Math.min(Math.max(rect.left, margin), Math.max(margin, viewportWidth - width - margin));
192
+ const top = rect.bottom + 12 + 280 < viewportHeight
193
+ ? rect.bottom + 12
194
+ : Math.max(margin, rect.top - 292);
195
+ return {
196
+ left,
197
+ top,
198
+ width,
199
+ };
200
+ }
201
+
202
+ function sourceEditorStatusText(status: "idle" | "loading" | "saving" | "failed", error: string) {
203
+ if (status === "loading") return "讀取中";
204
+ if (status === "saving") return "儲存中";
205
+ if (status === "failed") return error || "儲存失敗";
206
+ return "可編輯 source";
207
+ }
@@ -0,0 +1,9 @@
1
+ import { forwardRef, type ReactNode } from "react";
2
+
3
+ export const ReaderStage = forwardRef<HTMLElement, { children: ReactNode }>(function ReaderStage({ children }, ref) {
4
+ return (
5
+ <main className="reader-stage" tabIndex={-1} ref={ref}>
6
+ {children}
7
+ </main>
8
+ );
9
+ });
@@ -0,0 +1,34 @@
1
+ import { useMemo } from "react";
2
+ import {
3
+ collectBookmarkIndex,
4
+ collectMediaAssetIndex,
5
+ createAnchorPageMap,
6
+ getSourceBlockMap,
7
+ type ReaderDocument,
8
+ } from "../../../document-model";
9
+ import type { DisplayPage } from "../../../reader";
10
+ import { groupSourceBlocksByPath } from "../../inspector";
11
+ import { createProjectComponentUsages, createProjectMentionItems } from "../../project";
12
+
13
+ export function useDocumentWorkbenchModel(document: ReaderDocument, pages: DisplayPage[]) {
14
+ const mediaAssets = useMemo(() => collectMediaAssetIndex(pages), [pages]);
15
+ const anchorPageMap = useMemo(() => createAnchorPageMap(pages), [pages]);
16
+ const projectComponentUsages = useMemo(() => createProjectComponentUsages(pages), [pages]);
17
+ const bookmarks = useMemo(() => collectBookmarkIndex(pages), [pages]);
18
+ const sourceBlockMap = useMemo(() => getSourceBlockMap(document), [document]);
19
+ const sourceBlocksByPath = useMemo(() => groupSourceBlocksByPath(sourceBlockMap), [sourceBlockMap]);
20
+ const projectMentionItems = useMemo(
21
+ () => createProjectMentionItems(mediaAssets, projectComponentUsages, bookmarks),
22
+ [bookmarks, mediaAssets, projectComponentUsages],
23
+ );
24
+
25
+ return {
26
+ mediaAssets,
27
+ anchorPageMap,
28
+ projectComponentUsages,
29
+ bookmarks,
30
+ sourceBlockMap,
31
+ sourceBlocksByPath,
32
+ projectMentionItems,
33
+ };
34
+ }