Repository navigation
Expand file tree
/
Copy pathsheet-plugin-elements.tsx
More file actions
326 lines (325 loc) · 10.4 KB
/
Copy pathsheet-plugin-elements.tsx
File metadata and controls
326 lines (325 loc) · 10.4 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
import { bilingualLocale } from "@doca/i18n";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SPREADSHEET_MENU_PATHS } from "@smartdoca/sheet";
import type {
SpreadsheetCellRenderer,
SpreadsheetEditorHandle,
SpreadsheetCommentAnchor,
SpreadsheetCellRange,
SpreadsheetMenuExtension,
} from "@smartdoca/sheet";
import {
isPluginElementPayload,
type PluginElementPayload,
} from "@smartdoca/plugin-contracts";
import type {
PluginElementContext,
PluginElementContribution,
PluginElementState,
} from "@smartdoca/web-plugin-registry";
import { webPluginRegistry } from "@web/plugins/registry.js";
import { useI18n } from "@web/shared/i18n.js";
import { notifyFeedback } from "@web/shared/components/feedback.js";
import {
PluginElementDialog,
pluginElementState,
usePluginElements,
type ElementDialogSession,
} from "./plugin-elements.js";
import { PackagePlus } from "lucide-react";
import { createElementViewRefresh } from "./plugin-element-refresh.js";
export const SHEET_ELEMENT_PROPERTY = "docaElement";
export function useSheetPluginElements(
documentId: string,
handle: SpreadsheetEditorHandle | null,
editable: boolean,
) {
const { locale, t } = useI18n();
const providers = usePluginElements("spreadsheet");
const registryRevision = webPluginRegistry.elements.snapshot();
const [session, setSession] = useState<ElementDialogSession | null>(null);
useEffect(() => {
if (!editable) setSession(null);
}, [editable]);
const live = useRef({ handle, editable, locale, t });
live.current = { handle, editable, locale, t };
const abort = useMemo(
() => new AbortController(),
[documentId, registryRevision],
);
useEffect(() => () => abort.abort(), [abort]);
useEffect(() => {
setSession(null);
}, [documentId, handle, abort]);
const context = (): PluginElementContext => ({
documentId,
format: "spreadsheet",
locale: bilingualLocale(live.current.locale),
readOnly: !live.current.editable,
signal: abort.signal,
});
const refresh = () =>
live.current.handle
?.getRuntime()
?.univerAPI.getActiveWorkbook()
?.getActiveSheet()
.refreshCanvas();
const viewRefresh = useMemo(
() =>
createElementViewRefresh(
refresh,
() =>
!abort.signal.aborted && !document.hidden && !!live.current.handle,
),
[documentId, abort],
);
const renderers = useMemo<SpreadsheetCellRenderer[]>(() => {
let revision = -1;
let cache = new WeakMap<
object,
{
provider: PluginElementContribution | undefined;
state: PluginElementState;
}
>();
const stateOf = (
value: unknown,
provider: PluginElementContribution | undefined,
) => {
const nextRevision = webPluginRegistry.elements.snapshot();
if (revision !== nextRevision) {
revision = nextRevision;
cache = new WeakMap();
}
if (!value || typeof value !== "object") return "unsupported";
const cached = cache.get(value);
if (cached && cached.provider === provider) return cached.state;
const state = pluginElementState(value, provider, "spreadsheet");
cache.set(value, { provider, state });
return state;
};
return [
{
zIndex: 30,
drawWith(canvas, info) {
const custom = info.data?.custom;
if (!custom || !Object.hasOwn(custom, SHEET_ELEMENT_PROPERTY)) return;
const value = custom[SHEET_ELEMENT_PROPERTY];
const type = typeof value?.type === "string" ? value.type : undefined;
const provider = type
? webPluginRegistry.elements.get(type)
: undefined;
const state = stateOf(value, provider);
const cell = info.primaryWithCoord;
const rect = {
x: cell.startX,
y: cell.startY,
width: cell.endX - cell.startX,
height: cell.endY - cell.startY,
};
canvas.save();
try {
canvas.beginPath();
canvas.rect(
rect.x + 1,
rect.y + 1,
Math.max(0, rect.width - 2),
Math.max(0, rect.height - 2),
);
canvas.clip();
canvas.fillStyle = "#fff";
canvas.fillRect(
rect.x + 1,
rect.y + 1,
rect.width - 2,
rect.height - 2,
);
let reason: "unsupported" | "invalid" | "failed" =
state === "invalid" ? "invalid" : "unsupported";
if (state === "ready") {
try {
provider!.renderCell!({
...context(),
canvas,
rect,
payload: structuredClone(value) as PluginElementPayload,
});
if (provider!.refreshIntervalMs)
viewRefresh.schedule(provider!.refreshIntervalMs);
return;
} catch {
reason = "failed";
}
}
canvas.fillStyle = "#b42318";
canvas.font = "12px sans-serif";
canvas.textBaseline = "middle";
canvas.fillText(
live.current.t(`editor.element.${reason}`),
rect.x + 6,
rect.y + rect.height / 2,
Math.max(1, rect.width - 12),
);
} finally {
canvas.restore();
}
},
isHit(_position, info) {
return (
!!info.data?.custom &&
Object.hasOwn(info.data.custom, SHEET_ELEMENT_PROPERTY)
);
},
onPointerDown(info) {
const value = info.data?.custom?.[SHEET_ELEMENT_PROPERTY];
const provider = isPluginElementPayload(value)
? webPluginRegistry.elements.get(value.type)
: undefined;
if (pluginElementState(value, provider, "spreadsheet") !== "ready")
return;
try {
provider?.onCellClick?.(structuredClone(value), context());
} catch {
notifyFeedback(live.current.t("editor.element.failed"), "error");
}
},
},
];
}, [documentId, abort, viewRefresh]);
useEffect(() => {
refresh();
const visible = () => {
if (document.hidden) viewRefresh.cancel();
else refresh();
};
document.addEventListener("visibilitychange", visible);
return () => {
document.removeEventListener("visibilitychange", visible);
viewRefresh.cancel();
};
}, [handle, locale, registryRevision, abort, viewRefresh]);
const open = useCallback(() => {
if (!handle || !editable || handle.getFormatState().editing) return;
const selection = handle.getSelection();
if (
!selection ||
selection.startRow !== selection.endRow ||
selection.startColumn !== selection.endColumn
) {
notifyFeedback(t("editor.element.singleCell"), "error");
return;
}
const anchor: SpreadsheetCommentAnchor | null =
handle.captureCommentAnchor();
if (!anchor) return;
const read = (range: SpreadsheetCellRange) =>
handle
.getRuntime()
?.univerAPI.getActiveWorkbook()
?.getWorkbook?.()
?.getSheetBySheetId(range.sheetId)
?.getCell(range.startRow, range.startColumn);
const original = read(selection);
const fingerprint = (cell: ReturnType<typeof read>) =>
JSON.stringify({
v: cell?.v,
f: cell?.f,
p: cell?.p,
custom: cell?.custom,
});
const expected = fingerprint(original);
const payload = original?.custom?.[SHEET_ELEMENT_PROPERTY];
const current = isPluginElementPayload(payload) ? payload : null;
const target = () => {
if (
abort.signal.aborted ||
!live.current.editable ||
live.current.handle !== handle ||
handle.getFormatState().editing
)
throw Error("Editor unavailable");
const resolved = handle.resolveCommentAnchor(anchor);
if (!resolved || fingerprint(read(resolved)) !== expected)
throw Error("Cell changed or removed");
const sheet = handle
.getRuntime()
?.univerAPI.getActiveWorkbook()
?.getSheets()
.find((sheet) => sheet.getSheetId() === resolved.sheetId);
if (!sheet) throw Error("Worksheet removed");
return sheet.getRange(resolved.startRow, resolved.startColumn, 1, 1);
};
setSession({
type: payload
? typeof payload.type === "string"
? payload.type
: "unsupported"
: undefined,
unsupported:
payload !== undefined &&
pluginElementState(
payload,
current ? webPluginRegistry.elements.get(current.type) : undefined,
"spreadsheet",
) !== "ready",
initialData: current?.data,
commit(next) {
if (
current &&
(next.type !== current.type ||
next.dataVersion !== current.dataVersion)
)
throw Error("Unsupported element version");
const range = target();
range.setValue({
v: next.text,
f: null,
p: null,
t: 1,
// Keep the native text projection inside this canvas-backed cell.
s: { ...range.getCellStyleData(), tb: 2 },
custom: { [SHEET_ELEMENT_PROPERTY]: next },
});
},
remove:
payload !== undefined
? () => {
target().setValue({ v: null, f: null, p: null, custom: null });
}
: undefined,
});
}, [handle, editable, abort, t]);
const menus = useMemo<SpreadsheetMenuExtension[]>(
() => [
{
id: "doca-plugin-elements",
title: t("editor.element.insert"),
ariaLabel: t("editor.element.insert"),
path: SPREADSHEET_MENU_PATHS.toolbarEnd,
order: 997,
icon: <PackagePlus size={18} />,
requiresEditPermission: true,
visible: editable && providers.length > 0,
enabled: () => !!handle && !handle.getFormatState().editing,
action: open,
},
],
[editable, providers.length, handle, open, t],
);
return {
renderers,
menus,
ui: (
<>
{session && editable && (
<PluginElementDialog
documentId={documentId}
format="spreadsheet"
session={session}
close={() => setSession(null)}
/>
)}
</>
),
};
}