Repository navigation
Expand file tree
/
Copy pathspreadsheet-editor.tsx
More file actions
383 lines (383 loc) · 14.7 KB
/
Copy pathspreadsheet-editor.tsx
File metadata and controls
383 lines (383 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
import { useI18n } from "@web/shared/i18n.js";
import { OfflineEditingNotice } from "@web/features/documents/offline-editing-notice.js";
import { replicaCodecs } from "@web/features/documents/replica-database.js";
import { useAI } from "@web/features/ai/ai-context.js";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { DocumentDownload, downloadResult } from "@web/features/documents/file-transfer.js";
import { spreadsheetXlsxOptions } from "@web/features/documents/spreadsheet-xlsx.js";
import { useDocumentEditorMode } from "@web/features/documents/document-mode.js";
import { useSheetZoomPreference } from "@web/features/documents/sheet-zoom-preference.js";
import { revealSheetComment } from "@web/features/documents/sheet-comment-reveal.js";
import {
SpreadsheetEditor,
type SpreadsheetEditorHandle,
type ResourceAdapter,
type SpreadsheetCellSelection,
type SpreadsheetMenuExtension,
type SpreadsheetViewPreferences,
} from "@smartdoca/sheet";
import {
restoreExlsxDocument,
createExlsxCollaborationSession,
EXLSX_SCHEMA_VERSION,
type ExlsxCollaborationSession,
} from "@smartdoca/sheet/yjs";
import * as Y from "yjs";
import {
assetUrl,
uploadFile,
roleRank,
type Detail,
type User,
} from "@web/shared/api.js";
import { realtime } from "@web/features/documents/realtime.js";
import { SheetFind } from "@web/features/search/sheet-find.js";
import { Feedback } from "@web/shared/components/feedback.js";
import { useSurfaceSync, type SurfaceFactory } from "@web/features/documents/surface-sync.js";
import { RegionComments, type RegionController } from "@web/features/comments/region-comments.js";
import { useCommentHighlight } from "@web/features/comments/use-comment-highlight.js";
import { activeCommentCandidate } from "@web/features/comments/region-comment-interaction.js";
import { renderSheetObject } from "@web/features/documents/sheet-interactions.js";
import { useAttachmentPreview } from "@web/features/documents/attachment-preview.js";
import { SheetNativeMentions, useSheetMentionKeyboard } from "@web/features/documents/sheet-native-mentions.js";
import { useSheetDocumentLinks } from "@web/features/documents/sheet-document-links.js";
import { useSheetDocumentPicker } from "@web/features/documents/sheet-document-picker.js";
import { useSheetPluginElements } from "./sheet-plugin-elements.js";
import { useSheetTouch } from "@web/features/documents/sheet-touch-pan.js";
import { useSheetKeyboardGuard } from "@web/features/documents/sheet-keyboard-guard.js";
import { useSheetQuickEdit } from "@web/features/documents/sheet-quick-edit.js";
import { useSheetClipboardWriteFallback } from "@web/features/documents/sheet-clipboard-write-fallback.js";
import "@smartdoca/sheet/style.css";
import "@web/features/documents/surface.css";
import { Sparkles, MessageSquare } from "lucide-react";
const factory: SurfaceFactory<ExlsxCollaborationSession> = async (
b,
sessionId,
) => {
const doc = await restoreExlsxDocument({
baseline: b.baseline,
update: b.update,
checkpointSeq: 0,
});
const value = await createExlsxCollaborationSession({
doc,
baseline: b.baseline,
sessionId,
readOnly: true,
});
return {
value,
vector: () => Y.encodeStateVector(doc),
checkpoint: () => Y.encodeStateAsUpdate(doc),
apply: (update) =>
value.applyUpdate({
codec: "exlsx-cell-registers",
schemaVersion: b.baseline.schemaVersion,
epochId: b.epochId,
update,
}),
local: (callback) => value.onLocalTransaction((t) => callback(t.update)),
dispose: () => {
value.dispose();
doc.destroy();
},
};
};
export default function SheetDocument({
detail,
user,
changed,
targetComment,
loadMoreComments,
}: {
detail: Detail;
user: User | null;
changed(): void;
targetComment?: string | null;
loadMoreComments?: () => Promise<void>;
}) {
const { locale, t } = useI18n();
const mentionKeyboard = useSheetMentionKeyboard();
const id = detail.resource.id,
sync = useSurfaceSync(
id,
user?.id,
replicaCodecs.spreadsheet,
factory,
changed,
EXLSX_SCHEMA_VERSION,
);
const createComment = useRef<() => void>(() => {});
const { zoomRatio, status: zoomStatus, onChange: changeZoom } = useSheetZoomPreference(user?.id, id);
const viewPreferences = useMemo<SpreadsheetViewPreferences>(() => ({ zoomRatio }), [zoomRatio]);
const changeViewPreferences = useCallback((value: SpreadsheetViewPreferences) => changeZoom(value.zoomRatio), [changeZoom]);
const zoomWarning = zoomStatus === "unsupported"
? t("editor.sheetZoomUnsupported")
: zoomStatus === "unavailable" ? t("editor.sheetZoomUnavailable") : "";
const rank = Math.min(roleRank(detail.resource.role), sync.rank);
const { readOnly: reading, showRemoteSelections, mode, setMode } = useDocumentEditorMode(
sync.binding ? rank >= 3 : undefined,
);
const editable = !reading && rank >= 3 && !!sync.binding && !sync.blocked;
const ref = useRef<SpreadsheetEditorHandle>(null),
[handle, setHandle] = useState<SpreadsheetEditorHandle | null>(null);
const [active, setActive] = useState<string | null>(null),
[candidateIds, setCandidateIds] = useState<string[]>([]),
[error, setError] = useState("");
const [showCommentMarks, setShowCommentMarks] = useState(false);
const [highlightedComment, highlightComment] = useCommentHighlight(id, detail.comments);
const attachmentPreview = useAttachmentPreview({ sheetImages: () => ref.current?.getImageGallery() ?? [] });
const surface = useRef<HTMLElement>(null);
// Reading on a touch screen: the soft keyboard stays down, a drag pans, and a reader who may edit
// double-taps one cell to edit it, after which the sheet is read again.
const mayEdit = rank >= 3 && !!sync.binding && !sync.blocked;
const quickEdit = useSheetQuickEdit(handle, mode, setMode);
useSheetKeyboardGuard(surface, reading);
useSheetClipboardWriteFallback();
useSheetTouch(surface, handle, { open: () => reading, wants: () => mayEdit, doubleTap: quickEdit });
const pasteDocumentLink = useSheetDocumentLinks(handle, editable, setError);
const documentPicker = useSheetDocumentPicker(id, editable);
const [slots, setSlots] = useState<{
live: HTMLElement | null;
download: HTMLElement | null;
}>({ live: null, download: null });
useEffect(() => {
setSlots({
live: document.getElementById("document-live-info"),
download: document.getElementById("document-export-slot"),
});
}, [id]);
const ai = useAI();
const aiRef = useRef(ai); aiRef.current = ai;
const session = sync.binding?.value;
const [, refreshSessionPermissions] = useState(0);
useLayoutEffect(() => {
if (!session) return;
session.setReadOnly(!editable);
// The package samples session.capabilities during render. Publish the
// current host permission before painting its toolbar after a mode change.
refreshSessionPermissions((revision) => revision + 1);
}, [session, editable]);
const elements = useSheetPluginElements(id, handle, editable);
const menus = useMemo<SpreadsheetMenuExtension[]>(
() => [
...elements.menus,
{ id: "doca-ai", title: t("editor.citeAi"), ariaLabel: t("editor.citeAi"), path: "ribbon.others.others", order: 998, icon: <Sparkles size={18} />, requiresEditPermission: false, enabled: context => !!context.selection && !!aiRef.current?.userId, action: () => aiRef.current?.add() },
{
id: "doca-region-comment",
title: t("editor.comment"),
ariaLabel: t("editor.commentSelection"),
path: "ribbon.others.others",
order: 999,
icon: <MessageSquare size={18} />,
tone: "amber",
requiresEditPermission: false,
enabled: (context) =>
!!context.selection && rank >= 2 && sync.connected && !sync.blocked,
action: () => createComment.current(),
},
],
[elements.menus, rank, sync.connected, sync.blocked, t],
);
const publish = useCallback(
(selection: SpreadsheetCellSelection | null) => {
if (!selection && !document.hasFocus() && editable && sync.connected)
return;
if (sync.connected)
realtime.send({
type: "cursor",
id: crypto.randomUUID(),
room: id,
epochId: session?.baseline.epochId,
selection:
editable && selection ? { ...selection, kind: "cells" } : null,
});
},
[id, session, sync.connected, editable],
);
useEffect(() => { if (!editable && session) publish(null); }, [editable, session, publish]);
const remoteSelections = useMemo(
() =>
sync.connected && editable && showRemoteSelections
? sync.presence.sessions
.filter((p) => p.selection?.kind === "cells")
.map((p) => ({
sessionId: p.connectionId,
userId: p.userId,
name: p.name,
color: p.color,
selection: { ...p.selection, type: "cells" as const },
}))
: [],
[sync.presence, sync.connected, editable, showRemoteSelections],
);
const controller = useMemo<RegionController | null>(
() =>
handle
? {
capture: () => handle.captureCommentAnchor(),
valid: (a) => handle.resolveCommentAnchorRanges(a).length > 0,
reveal: (a) => {
void revealSheetComment(handle, a).catch((error) => setError(error.message));
},
label: (a) =>
a.version === 3
? t("editor.selection.sheetRecords", { count: a.rowIds.length })
: t("editor.selection.sheetRows", { start: +a.startRowId.slice(2) + 1, end: +a.endRowId.slice(2) + 1 }),
}
: null,
[handle, t],
);
const markers = useMemo(
() =>
detail.comments
.filter((c) => c.anchor && !c.parent_id && !c.resolved && !c.deleted_at)
.flatMap((c) => {
try {
const anchor = JSON.parse(c.anchor!);
return controller?.valid(anchor)
? [
{
id: c.id,
anchor,
color: active === c.id ? "#e5a000" : "#f2c94c",
},
]
: [];
} catch {
return [];
}
}),
[detail.comments, controller, active, sync.revision],
);
const resources = useMemo<ResourceAdapter>(
() => ({
upload: async (file, resource, context) => {
const a = await uploadFile(file, "attachment", id, context.signal);
return {
id: a.id,
kind: resource.kind,
name: a.filename,
size: a.size,
mimeType: a.mime,
};
},
resolve: async (r) =>
/^[a-f0-9-]{36}$/.test(r.id) ? assetUrl(r.id) : "",
download: async (r) =>
/^[a-f0-9-]{36}$/.test(r.id) ? assetUrl(r.id) + "?download=1" : "",
}),
[id],
);
return (
<section ref={surface} className={`surface-editor sheet-document ${reading ? "is-reading" : ""}`}>
<OfflineEditingNotice editable={!!user && editable} connected={sync.connected} />
{documentPicker.picker}
{attachmentPreview.dialog}
{slots.live &&
createPortal(<span role="status">{sync.status}</span>, slots.live)}
<DocumentDownload
disabled={!handle}
onError={setError}
options={[
{
label: "Excel(.xlsx)",
run: async () => {
if (handle)
downloadResult({
...(await handle.exportXlsx(spreadsheetXlsxOptions())),
filename: `${detail.resource.title}.xlsx`,
});
},
},
]}
/>
<Feedback message={sync.error || error} tone="error" />
<Feedback message={zoomWarning} tone="warning" />
{sync.binding && (!sync.connected || sync.blocked) && (
<button
className="surface-recovery"
onClick={() =>
void sync.exportRecovery().catch((e) => setError(e.message))
}
>
{t("editor.sync.exportRecovery")}
</button>
)}
{handle && (
<SheetNativeMentions
keyboard={mentionKeyboard}
handle={handle}
enabled={editable}
onError={setError}
/>
)}
{handle && (
<SheetFind documentId={id} handle={handle} revision={sync.revision} canEdit={editable} />
)}
{session ? (
<SpreadsheetEditor
locale={locale}
toolbarLayout="two-row"
viewPreferences={viewPreferences}
onViewPreferencesChange={changeViewPreferences}
menus={menus}
cellRenderers={elements.renderers}
renderCellObject={(object) => renderSheetObject(object, attachmentPreview.previewFile)}
onAttachmentPreview={attachmentPreview.onSheetAttachmentPreview}
onImagePreview={attachmentPreview.onSheetImagePreview}
onPasteContent={pasteDocumentLink}
ref={ref}
workbookId={id}
collaboration={session}
onReady={setHandle}
readOnly={!editable}
autoSave={false}
autoFitContent={false}
showHeader={false}
showInsertToolbar={false}
showSaveState={false}
currentUserId={user?.id}
currentSessionId={sync.presence.self}
remoteSelections={remoteSelections}
onSelectionChange={publish}
resourceAdapter={resources}
inlineActions={documentPicker.actions}
commentMarkers={showCommentMarks ? markers : []}
activeCommentId={showCommentMarks ? active : null}
commentHighlightAnchor={showCommentMarks
? markers.find(marker => marker.id === highlightedComment)?.anchor ?? null
: null}
onCommentAnchorsClick={({ candidateIds: ids }) => {
setCandidateIds(ids);
setActive(current => activeCommentCandidate(current, ids));
}}
onError={(e) => setError(e.message)}
style={{ flex: 1, height: "100%", minHeight: 0 }}
/>
) : (
<p className="empty">{t("common.loading")}</p>
)}
<RegionComments
onHighlightChange={highlightComment}
onOpenChange={setShowCommentMarks}
candidateIds={candidateIds}
createAction={createComment}
detail={detail}
user={user}
rank={rank}
connected={sync.connected}
dirty={sync.dirty}
controller={controller}
changed={changed}
revision={sync.revision}
active={active}
setActive={setActive}
targetComment={targetComment}
loadMoreComments={loadMoreComments}
/>
{elements.ui}
</section>
);
}