grist-widget-sdk 0.2.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 (70) hide show
  1. package/CHANGELOG.md +730 -0
  2. package/LICENSE +15 -0
  3. package/README.md +249 -0
  4. package/dist/advanced.cjs +2749 -0
  5. package/dist/advanced.cjs.map +1 -0
  6. package/dist/advanced.d.cts +790 -0
  7. package/dist/advanced.d.ts +790 -0
  8. package/dist/advanced.js +825 -0
  9. package/dist/advanced.js.map +1 -0
  10. package/dist/chunk-64SVRWW7.js +758 -0
  11. package/dist/chunk-64SVRWW7.js.map +1 -0
  12. package/dist/chunk-BNBV24WM.js +479 -0
  13. package/dist/chunk-BNBV24WM.js.map +1 -0
  14. package/dist/chunk-ELGVOHFD.js +32 -0
  15. package/dist/chunk-ELGVOHFD.js.map +1 -0
  16. package/dist/chunk-GTTD5HPO.js +36 -0
  17. package/dist/chunk-GTTD5HPO.js.map +1 -0
  18. package/dist/chunk-JASMM2YC.js +243 -0
  19. package/dist/chunk-JASMM2YC.js.map +1 -0
  20. package/dist/chunk-PM3B4WYV.js +12 -0
  21. package/dist/chunk-PM3B4WYV.js.map +1 -0
  22. package/dist/chunk-QKXKZ27D.js +1189 -0
  23. package/dist/chunk-QKXKZ27D.js.map +1 -0
  24. package/dist/chunk-QZG7SNUG.js +463 -0
  25. package/dist/chunk-QZG7SNUG.js.map +1 -0
  26. package/dist/chunk-REV5AUXD.js +25 -0
  27. package/dist/chunk-REV5AUXD.js.map +1 -0
  28. package/dist/chunk-XE2SKNLH.js +1641 -0
  29. package/dist/chunk-XE2SKNLH.js.map +1 -0
  30. package/dist/create-grist-emulator-C_0I4wax.d.ts +80 -0
  31. package/dist/create-grist-emulator-DBS6gmiI.d.cts +80 -0
  32. package/dist/emulator/devtools.cjs +1367 -0
  33. package/dist/emulator/devtools.cjs.map +1 -0
  34. package/dist/emulator/devtools.d.cts +46 -0
  35. package/dist/emulator/devtools.d.ts +46 -0
  36. package/dist/emulator/devtools.js +480 -0
  37. package/dist/emulator/devtools.js.map +1 -0
  38. package/dist/emulator/testing.cjs +2061 -0
  39. package/dist/emulator/testing.cjs.map +1 -0
  40. package/dist/emulator/testing.d.cts +50 -0
  41. package/dist/emulator/testing.d.ts +50 -0
  42. package/dist/emulator/testing.js +124 -0
  43. package/dist/emulator/testing.js.map +1 -0
  44. package/dist/emulator/transports.cjs +1132 -0
  45. package/dist/emulator/transports.cjs.map +1 -0
  46. package/dist/emulator/transports.d.cts +37 -0
  47. package/dist/emulator/transports.d.ts +37 -0
  48. package/dist/emulator/transports.js +12 -0
  49. package/dist/emulator/transports.js.map +1 -0
  50. package/dist/emulator.cjs +1796 -0
  51. package/dist/emulator.cjs.map +1 -0
  52. package/dist/emulator.d.cts +107 -0
  53. package/dist/emulator.d.ts +107 -0
  54. package/dist/emulator.js +26 -0
  55. package/dist/emulator.js.map +1 -0
  56. package/dist/index.cjs +5511 -0
  57. package/dist/index.cjs.map +1 -0
  58. package/dist/index.d.cts +825 -0
  59. package/dist/index.d.ts +825 -0
  60. package/dist/index.js +2447 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/inline-CRwQQ-GW.d.cts +311 -0
  63. package/dist/inline-QitZwXKP.d.ts +311 -0
  64. package/dist/templates-BC7FoSdW.d.ts +24 -0
  65. package/dist/templates-DBq719O_.d.cts +24 -0
  66. package/dist/types-Fb2wplkv.d.cts +228 -0
  67. package/dist/types-Fb2wplkv.d.ts +228 -0
  68. package/dist/use-grist-widget-options-from-context-BFhQBGRY.d.ts +522 -0
  69. package/dist/use-grist-widget-options-from-context-qpFMdoBJ.d.cts +522 -0
  70. package/package.json +131 -0
@@ -0,0 +1,825 @@
1
+ import {
2
+ GristReadsContext,
3
+ fetchWithGristAuth,
4
+ getGristAccessToken,
5
+ useGristCore,
6
+ useGristReady,
7
+ useGristWidgetOptionsFromContext,
8
+ useRpcHeartbeatCoalesce
9
+ } from "./chunk-BNBV24WM.js";
10
+ import {
11
+ createGristHandshakeManager,
12
+ deriveCapabilities,
13
+ deriveErrorMessage,
14
+ deriveStatus,
15
+ initialGristSnapshot,
16
+ newRecordEvent,
17
+ optionsEvent,
18
+ recordEvent,
19
+ recordsEvent
20
+ } from "./chunk-XE2SKNLH.js";
21
+ import {
22
+ tableDataToRows
23
+ } from "./chunk-JASMM2YC.js";
24
+ import {
25
+ gristAddRecordAction,
26
+ gristBulkAddRecordAction,
27
+ gristBulkRemoveRecordAction,
28
+ gristBulkUpdateRecordAction,
29
+ gristRemoveRecordAction,
30
+ gristUpdateRecordAction
31
+ } from "./chunk-64SVRWW7.js";
32
+
33
+ // src/sdk/low-level-hooks/use-grist-availability.ts
34
+ function useGristAvailability(options) {
35
+ const { isAvailable } = useGristCore(options);
36
+ return isAvailable;
37
+ }
38
+
39
+ // src/sdk/low-level-hooks/use-grist-handshake.ts
40
+ import { useEffect, useMemo, useRef, useSyncExternalStore } from "react";
41
+ function useGristHandshake(options = {}) {
42
+ const optionsRef = useRef(options);
43
+ optionsRef.current = options;
44
+ const managerRef = useRef(null);
45
+ if (managerRef.current === null) {
46
+ managerRef.current = createGristHandshakeManager(options);
47
+ }
48
+ const manager = managerRef.current;
49
+ useEffect(() => {
50
+ manager.start();
51
+ return () => {
52
+ manager.stop();
53
+ };
54
+ }, [manager]);
55
+ const snapshot = useSyncExternalStore(
56
+ manager.subscribe,
57
+ manager.getSnapshot,
58
+ initialGristSnapshot
59
+ );
60
+ const projected = useMemo(
61
+ () => ({
62
+ status: deriveStatus(snapshot),
63
+ error: deriveErrorMessage(snapshot),
64
+ capabilities: deriveCapabilities(snapshot)
65
+ }),
66
+ [snapshot]
67
+ );
68
+ return useMemo(
69
+ () => ({
70
+ snapshot,
71
+ status: projected.status,
72
+ error: projected.error,
73
+ capabilities: projected.capabilities,
74
+ reload: manager.reload,
75
+ restart: manager.restart
76
+ }),
77
+ [snapshot, projected, manager]
78
+ );
79
+ }
80
+ function useGristCapabilities(options = {}) {
81
+ return useGristHandshake(options).capabilities;
82
+ }
83
+
84
+ // src/sdk/components/grist-handshake-provider.tsx
85
+ import {
86
+ createContext,
87
+ useContext,
88
+ useEffect as useEffect2,
89
+ useMemo as useMemo2,
90
+ useRef as useRef2,
91
+ useSyncExternalStore as useSyncExternalStore2
92
+ } from "react";
93
+ import { jsx } from "react/jsx-runtime";
94
+ var GristHandshakeReactContext = createContext(null);
95
+ function GristHandshakeProvider({ options, children }) {
96
+ const managerRef = useRef2(null);
97
+ if (managerRef.current === null) {
98
+ managerRef.current = createGristHandshakeManager(options ?? {});
99
+ }
100
+ const manager = managerRef.current;
101
+ useEffect2(() => {
102
+ manager.start();
103
+ return () => {
104
+ manager.stop();
105
+ };
106
+ }, [manager]);
107
+ const snapshot = useSyncExternalStore2(
108
+ manager.subscribe,
109
+ manager.getSnapshot,
110
+ initialGristSnapshot
111
+ );
112
+ const value = useMemo2(
113
+ () => ({
114
+ snapshot,
115
+ status: deriveStatus(snapshot),
116
+ error: deriveErrorMessage(snapshot),
117
+ capabilities: deriveCapabilities(snapshot),
118
+ reload: manager.reload,
119
+ restart: manager.restart,
120
+ recordRpcSuccess: manager.recordRpcSuccess,
121
+ recordRpcFailure: manager.recordRpcFailure
122
+ }),
123
+ [snapshot, manager]
124
+ );
125
+ return /* @__PURE__ */ jsx(GristHandshakeReactContext.Provider, { value, children });
126
+ }
127
+ function useGristHandshakeContext() {
128
+ const ctx = useContext(GristHandshakeReactContext);
129
+ if (!ctx) {
130
+ throw new Error(
131
+ "useGristHandshakeContext() must be used inside <GristHandshakeProvider>"
132
+ );
133
+ }
134
+ return ctx;
135
+ }
136
+ function useGristHandshakeContextOptional() {
137
+ return useContext(GristHandshakeReactContext);
138
+ }
139
+
140
+ // src/sdk/low-level-hooks/use-grist-record.ts
141
+ import { useEffect as useEffect3, useRef as useRef3, useState } from "react";
142
+ function useGristRecord(cb, options) {
143
+ const cbRef = useRef3(cb);
144
+ useEffect3(() => {
145
+ cbRef.current = cb;
146
+ }, [cb]);
147
+ const [mappings, setMappings] = useState(null);
148
+ const { docApi, error: readyError } = useGristReady({
149
+ requiredAccess: options?.requiredAccess ?? "read table",
150
+ columns: options?.columns,
151
+ allowSelectBy: options?.allowSelectBy,
152
+ hasCustomOptions: options?.hasCustomOptions,
153
+ onEditOptions: options?.onEditOptions
154
+ });
155
+ useEffect3(() => {
156
+ if (!docApi) return;
157
+ return recordEvent.subscribe(({ record, mappings: nextMappings }) => {
158
+ setMappings(nextMappings);
159
+ cbRef.current(record, nextMappings);
160
+ });
161
+ }, [docApi]);
162
+ return {
163
+ loading: docApi === null && !readyError,
164
+ error: readyError,
165
+ mappings
166
+ };
167
+ }
168
+
169
+ // src/sdk/low-level-hooks/use-grist-records.ts
170
+ import { useEffect as useEffect4, useRef as useRef4, useState as useState2 } from "react";
171
+ function useGristRecords(cb, options) {
172
+ const cbRef = useRef4(cb);
173
+ useEffect4(() => {
174
+ cbRef.current = cb;
175
+ }, [cb]);
176
+ const [mappings, setMappings] = useState2(null);
177
+ const { docApi, error: readyError } = useGristReady({
178
+ requiredAccess: options?.requiredAccess ?? "read table",
179
+ columns: options?.columns,
180
+ allowSelectBy: options?.allowSelectBy,
181
+ hasCustomOptions: options?.hasCustomOptions,
182
+ onEditOptions: options?.onEditOptions
183
+ });
184
+ useEffect4(() => {
185
+ if (!docApi) return;
186
+ return recordsEvent.subscribe(({ records, mappings: nextMappings }) => {
187
+ setMappings(nextMappings);
188
+ cbRef.current(records, nextMappings);
189
+ });
190
+ }, [docApi]);
191
+ return {
192
+ loading: docApi === null && !readyError,
193
+ error: readyError,
194
+ mappings
195
+ };
196
+ }
197
+
198
+ // src/sdk/low-level-hooks/use-grist-new-record.ts
199
+ import { useEffect as useEffect5, useRef as useRef5, useState as useState3 } from "react";
200
+ function useGristNewRecord(options) {
201
+ const { docApi, error: readyError } = useGristReady({
202
+ requiredAccess: options?.requiredAccess ?? "read table",
203
+ columns: options?.columns,
204
+ allowSelectBy: options?.allowSelectBy,
205
+ hasCustomOptions: options?.hasCustomOptions,
206
+ onEditOptions: options?.onEditOptions
207
+ });
208
+ const [isNewRecord, setIsNewRecord] = useState3(false);
209
+ const [mappings, setMappings] = useState3(null);
210
+ const subscribedRef = useRef5(false);
211
+ useEffect5(() => {
212
+ if (!docApi || subscribedRef.current) return;
213
+ if (typeof grist.onNewRecord !== "function") return;
214
+ subscribedRef.current = true;
215
+ return newRecordEvent.subscribe(({ mappings: nextMappings }) => {
216
+ setIsNewRecord(true);
217
+ setMappings(nextMappings);
218
+ });
219
+ }, [docApi]);
220
+ return {
221
+ isNewRecord,
222
+ mappings,
223
+ loading: docApi === null && !readyError,
224
+ error: readyError
225
+ };
226
+ }
227
+
228
+ // src/sdk/mid-level-hooks/use-grist-actions.ts
229
+ import { useCallback, useState as useState4 } from "react";
230
+ function useGristActions(options) {
231
+ const requiredAccess = options?.requiredAccess ?? "full";
232
+ const { docApi, error: readyError } = useGristReady({
233
+ requiredAccess,
234
+ columns: options?.columns,
235
+ allowSelectBy: options?.allowSelectBy,
236
+ hasCustomOptions: options?.hasCustomOptions,
237
+ onEditOptions: options?.onEditOptions
238
+ });
239
+ const [status, setStatus] = useState4("idle");
240
+ const [actionError, setActionError] = useState4(null);
241
+ const coalesceRpc = useRpcHeartbeatCoalesce();
242
+ const apply = useCallback(
243
+ async (actions, applyOptions) => {
244
+ if (!docApi) throw new Error("Grist docApi is not ready");
245
+ setStatus("running");
246
+ setActionError(null);
247
+ try {
248
+ const out = await coalesceRpc(() => docApi.applyUserActions(actions, applyOptions));
249
+ setStatus("idle");
250
+ return out;
251
+ } catch (err) {
252
+ const message = err instanceof Error ? err.message : String(err);
253
+ setActionError(message);
254
+ setStatus("error");
255
+ throw err;
256
+ }
257
+ },
258
+ [docApi, coalesceRpc]
259
+ );
260
+ const updateRecord = useCallback(
261
+ (tableId, recordId, patch, applyOptions) => apply([gristUpdateRecordAction(tableId, recordId, patch)], applyOptions),
262
+ [apply]
263
+ );
264
+ const addRecord = useCallback(
265
+ (tableId, values, applyOptions) => apply([gristAddRecordAction(tableId, values)], applyOptions),
266
+ [apply]
267
+ );
268
+ const removeRecord = useCallback(
269
+ (tableId, recordId, applyOptions) => apply([gristRemoveRecordAction(tableId, recordId)], applyOptions),
270
+ [apply]
271
+ );
272
+ const bulkAddRecord = useCallback(
273
+ (tableId, values, applyOptions) => apply([gristBulkAddRecordAction(tableId, values)], applyOptions),
274
+ [apply]
275
+ );
276
+ const bulkUpdateRecord = useCallback(
277
+ (tableId, rowIds, columnarPatch, applyOptions) => apply([gristBulkUpdateRecordAction(tableId, rowIds, columnarPatch)], applyOptions),
278
+ [apply]
279
+ );
280
+ const bulkRemoveRecord = useCallback(
281
+ (tableId, rowIds, applyOptions) => apply([gristBulkRemoveRecordAction(tableId, rowIds)], applyOptions),
282
+ [apply]
283
+ );
284
+ return {
285
+ status: readyError ? "error" : status,
286
+ error: readyError ?? actionError,
287
+ apply,
288
+ updateRecord,
289
+ addRecord,
290
+ removeRecord,
291
+ bulkAddRecord,
292
+ bulkUpdateRecord,
293
+ bulkRemoveRecord
294
+ };
295
+ }
296
+
297
+ // src/sdk/mid-level-hooks/use-grist-mapped-record.ts
298
+ import { useCallback as useCallback2, useEffect as useEffect6, useState as useState5 } from "react";
299
+ function manualMapBack(patch, mappings) {
300
+ if (!mappings) return { ...patch };
301
+ const out = {};
302
+ for (const [name, value] of Object.entries(patch)) {
303
+ const target = mappings[name];
304
+ if (Array.isArray(target)) {
305
+ if (typeof console !== "undefined") {
306
+ console.warn(`[lib/grist] mapBack: cannot reverse-map allowMultiple field "${name}" without grist.mapColumnNamesBack`);
307
+ }
308
+ continue;
309
+ }
310
+ out[target ?? name] = value;
311
+ }
312
+ return out;
313
+ }
314
+ function useGristMappedRecord(options) {
315
+ const requiredAccess = options?.requiredAccess ?? "read table";
316
+ const { docApi, error: readyError } = useGristReady({
317
+ requiredAccess,
318
+ columns: options?.columns,
319
+ allowSelectBy: options?.allowSelectBy,
320
+ hasCustomOptions: options?.hasCustomOptions,
321
+ onEditOptions: options?.onEditOptions
322
+ });
323
+ const [rawRecord, setRawRecord] = useState5(null);
324
+ const [mappedRecord, setMappedRecord] = useState5(null);
325
+ const [mappings, setMappings] = useState5(null);
326
+ useEffect6(() => {
327
+ if (!docApi) return;
328
+ return recordEvent.subscribe(({ record, mappings: nextMappings }) => {
329
+ setRawRecord(record);
330
+ setMappings(nextMappings);
331
+ if (!record) {
332
+ setMappedRecord(null);
333
+ return;
334
+ }
335
+ if (typeof grist.mapColumnNames === "function") {
336
+ const mapped = grist.mapColumnNames(record);
337
+ setMappedRecord(
338
+ mapped !== null && mapped !== void 0 ? mapped : null
339
+ );
340
+ return;
341
+ }
342
+ setMappedRecord(record);
343
+ });
344
+ }, [docApi]);
345
+ const mapBack = useCallback2(
346
+ (patch) => {
347
+ if (typeof grist.mapColumnNamesBack === "function") {
348
+ return grist.mapColumnNamesBack(patch);
349
+ }
350
+ return manualMapBack(patch, mappings);
351
+ },
352
+ [mappings]
353
+ );
354
+ const resolveColumnId = useCallback2(
355
+ (logicalName) => {
356
+ const value = mappings?.[logicalName];
357
+ if (Array.isArray(value)) return void 0;
358
+ return value ?? void 0;
359
+ },
360
+ [mappings]
361
+ );
362
+ return {
363
+ rawRecord,
364
+ mappedRecord,
365
+ mappings,
366
+ loading: docApi === null && !readyError,
367
+ error: readyError,
368
+ mapBack,
369
+ resolveColumnId
370
+ };
371
+ }
372
+
373
+ // src/sdk/mid-level-hooks/use-grist-table-ops.ts
374
+ import { useCallback as useCallback3, useState as useState6 } from "react";
375
+ function resolveOps(tableId) {
376
+ if (tableId === "selected") {
377
+ if (!grist.selectedTable) throw new Error("grist.selectedTable is not available");
378
+ return grist.selectedTable;
379
+ }
380
+ if (typeof grist.getTable !== "function") {
381
+ throw new Error("grist.getTable is not available in this Grist version");
382
+ }
383
+ return grist.getTable(tableId);
384
+ }
385
+ function useGristTableOps(options) {
386
+ const requiredAccess = options?.requiredAccess ?? "full";
387
+ const tableIdOption = options?.tableId ?? "selected";
388
+ const { docApi, error: readyError } = useGristReady({
389
+ requiredAccess,
390
+ columns: options?.columns,
391
+ allowSelectBy: options?.allowSelectBy,
392
+ hasCustomOptions: options?.hasCustomOptions,
393
+ onEditOptions: options?.onEditOptions
394
+ });
395
+ const [status, setStatus] = useState6("idle");
396
+ const [actionError, setActionError] = useState6(null);
397
+ const coalesceRpc = useRpcHeartbeatCoalesce();
398
+ let ops = null;
399
+ let resolveError = null;
400
+ if (docApi) {
401
+ try {
402
+ ops = resolveOps(tableIdOption);
403
+ } catch (err) {
404
+ resolveError = err instanceof Error ? err.message : String(err);
405
+ }
406
+ }
407
+ const wrap = useCallback3(
408
+ async (run) => {
409
+ if (!ops) throw new Error("Grist table operations are not ready");
410
+ setStatus("running");
411
+ setActionError(null);
412
+ try {
413
+ const out = await coalesceRpc(() => run(ops));
414
+ setStatus("idle");
415
+ return out;
416
+ } catch (err) {
417
+ const message = err instanceof Error ? err.message : String(err);
418
+ setActionError(message);
419
+ setStatus("error");
420
+ throw err;
421
+ }
422
+ },
423
+ [ops, coalesceRpc]
424
+ );
425
+ const getTableId = useCallback3(async () => {
426
+ if (!ops) throw new Error("Grist table operations are not ready");
427
+ return ops.getTableId();
428
+ }, [ops]);
429
+ const create = useCallback3(
430
+ (records, opOptions) => wrap((o) => o.create(records, opOptions)),
431
+ [wrap]
432
+ );
433
+ const update = useCallback3(
434
+ (records, opOptions) => wrap((o) => o.update(records, opOptions)),
435
+ [wrap]
436
+ );
437
+ const upsert = useCallback3(
438
+ (records, opOptions) => wrap((o) => o.upsert(records, opOptions)),
439
+ [wrap]
440
+ );
441
+ const destroy = useCallback3(
442
+ (recordIds) => wrap((o) => o.destroy(recordIds)),
443
+ [wrap]
444
+ );
445
+ return {
446
+ status: readyError || resolveError ? "error" : status,
447
+ error: readyError ?? resolveError ?? actionError,
448
+ getTableId,
449
+ create,
450
+ update,
451
+ upsert,
452
+ destroy
453
+ };
454
+ }
455
+
456
+ // src/sdk/mid-level-hooks/use-grist-rows-from-table.ts
457
+ import { useCallback as useCallback4, useContext as useContext2, useEffect as useEffect7, useRef as useRef6, useState as useState7 } from "react";
458
+ function useGristRowsFromTable(options) {
459
+ const requiredAccess = options.requiredAccess ?? "read table";
460
+ const { docApi, error: readyError } = useGristReady({
461
+ requiredAccess,
462
+ columns: options.columns,
463
+ allowSelectBy: options.allowSelectBy,
464
+ hasCustomOptions: options.hasCustomOptions,
465
+ onEditOptions: options.onEditOptions
466
+ });
467
+ const providerFetchTable = useContext2(GristReadsContext)?.fetchTable;
468
+ const [rows, setRows] = useState7(null);
469
+ const [loading, setLoading] = useState7(false);
470
+ const [fetchError, setFetchError] = useState7(null);
471
+ const transformRef = useRef6(options.transform);
472
+ transformRef.current = options.transform;
473
+ const coalesceRpc = useRpcHeartbeatCoalesce();
474
+ const refresh = useCallback4(async () => {
475
+ if (!docApi) return;
476
+ setLoading(true);
477
+ setFetchError(null);
478
+ try {
479
+ const data = providerFetchTable ? await providerFetchTable(options.tableId) : await coalesceRpc(
480
+ () => docApi.fetchTable(options.tableId)
481
+ );
482
+ const raw = tableDataToRows(data);
483
+ const t = transformRef.current;
484
+ setRows(t ? raw.map((r) => t(r)) : raw);
485
+ } catch (err) {
486
+ setFetchError(err instanceof Error ? err.message : String(err));
487
+ setRows(null);
488
+ } finally {
489
+ setLoading(false);
490
+ }
491
+ }, [docApi, providerFetchTable, options.tableId, coalesceRpc]);
492
+ useEffect7(() => {
493
+ if (docApi) void refresh();
494
+ }, [docApi, refresh]);
495
+ useEffect7(() => {
496
+ if (!docApi || !options.pollIntervalMs || options.pollIntervalMs <= 0) return;
497
+ const id = window.setInterval(() => void refresh(), options.pollIntervalMs);
498
+ return () => window.clearInterval(id);
499
+ }, [docApi, options.pollIntervalMs, refresh]);
500
+ return {
501
+ rows,
502
+ loading,
503
+ error: readyError ?? fetchError,
504
+ refresh
505
+ };
506
+ }
507
+
508
+ // src/sdk/mid-level-hooks/use-grist-access-token.ts
509
+ import { useCallback as useCallback5, useEffect as useEffect8, useState as useState8 } from "react";
510
+ function useGristAccessToken(options) {
511
+ const requiredAccess = options?.requiredAccess ?? "full";
512
+ const readOnlyDefault = options?.readOnly ?? false;
513
+ const prefetch = options?.prefetch ?? false;
514
+ const { docApi, error: readyError } = useGristReady({
515
+ requiredAccess,
516
+ columns: options?.columns,
517
+ allowSelectBy: options?.allowSelectBy,
518
+ hasCustomOptions: options?.hasCustomOptions,
519
+ onEditOptions: options?.onEditOptions
520
+ });
521
+ const [token, setToken] = useState8(null);
522
+ const [loading, setLoading] = useState8(false);
523
+ const [error, setError] = useState8(null);
524
+ const refresh = useCallback5(
525
+ async (overrides) => {
526
+ if (!docApi) throw new Error("Grist is not ready");
527
+ setLoading(true);
528
+ setError(null);
529
+ try {
530
+ const next = await getGristAccessToken(docApi, { readOnly: overrides?.readOnly ?? readOnlyDefault });
531
+ setToken(next);
532
+ return next;
533
+ } catch (err) {
534
+ const message = err instanceof Error ? err.message : String(err);
535
+ setError(message);
536
+ throw err;
537
+ } finally {
538
+ setLoading(false);
539
+ }
540
+ },
541
+ [docApi, readOnlyDefault]
542
+ );
543
+ const fetchFn = useCallback5(
544
+ (path, init) => {
545
+ if (!docApi) throw new Error("Grist is not ready");
546
+ return fetchWithGristAuth(docApi, path, { readOnly: readOnlyDefault, ...init });
547
+ },
548
+ [docApi, readOnlyDefault]
549
+ );
550
+ useEffect8(() => {
551
+ if (docApi && prefetch) void refresh();
552
+ }, [docApi, prefetch, refresh]);
553
+ return {
554
+ token,
555
+ loading,
556
+ error: readyError ?? error,
557
+ refresh,
558
+ fetch: fetchFn
559
+ };
560
+ }
561
+
562
+ // src/sdk/mid-level-hooks/use-grist-section.ts
563
+ import { useCallback as useCallback6, useEffect as useEffect9, useState as useState9 } from "react";
564
+ function useGristSection(options) {
565
+ const { docApi, error: readyError } = useGristReady({
566
+ requiredAccess: options?.requiredAccess ?? "read table",
567
+ columns: options?.columns,
568
+ allowSelectBy: options?.allowSelectBy,
569
+ hasCustomOptions: options?.hasCustomOptions,
570
+ onEditOptions: options?.onEditOptions
571
+ });
572
+ const [mappings, setMappings] = useState9(null);
573
+ const [loading, setLoading] = useState9(false);
574
+ const [error, setError] = useState9(null);
575
+ const refresh = useCallback6(async () => {
576
+ if (!docApi) return;
577
+ if (!grist.sectionApi?.mappings) {
578
+ setError("grist.sectionApi.mappings is not available in this Grist version");
579
+ return;
580
+ }
581
+ setLoading(true);
582
+ setError(null);
583
+ try {
584
+ const next = await grist.sectionApi.mappings();
585
+ setMappings(next);
586
+ } catch (err) {
587
+ setError(err instanceof Error ? err.message : String(err));
588
+ } finally {
589
+ setLoading(false);
590
+ }
591
+ }, [docApi]);
592
+ const configure = useCallback6(async (next) => {
593
+ if (!grist.sectionApi?.configure) {
594
+ throw new Error("grist.sectionApi.configure is not available in this Grist version");
595
+ }
596
+ await grist.sectionApi.configure(next);
597
+ }, []);
598
+ useEffect9(() => {
599
+ if (docApi) void refresh();
600
+ }, [docApi, refresh]);
601
+ return {
602
+ mappings,
603
+ loading,
604
+ error: readyError ?? error,
605
+ refresh,
606
+ configure
607
+ };
608
+ }
609
+
610
+ // src/sdk/mid-level-hooks/use-grist-widget-options.ts
611
+ import { useCallback as useCallback7, useEffect as useEffect10, useMemo as useMemo3, useRef as useRef7, useState as useState10 } from "react";
612
+ function mergeWithDefaults(defaults, stored, namespace) {
613
+ if (stored === null || stored === void 0) return { ...defaults };
614
+ const source = namespace ? stored[namespace] : stored;
615
+ if (!source || typeof source !== "object") return { ...defaults };
616
+ return { ...defaults, ...source };
617
+ }
618
+ function useGristWidgetOptions(config) {
619
+ const requiredAccess = config.requiredAccess ?? "read table";
620
+ const debounceMs = config.debounceMs ?? 250;
621
+ const hasCustomOptions = config.hasCustomOptions ?? true;
622
+ const { docApi, error: readyError } = useGristReady({
623
+ requiredAccess,
624
+ columns: config.columns,
625
+ allowSelectBy: config.allowSelectBy,
626
+ hasCustomOptions,
627
+ onEditOptions: config.onEditOptions
628
+ });
629
+ const defaultsRef = useRef7(config.defaults);
630
+ useEffect10(() => {
631
+ defaultsRef.current = config.defaults;
632
+ }, [config.defaults]);
633
+ const [options, setOptionsState] = useState10(() => ({ ...config.defaults }));
634
+ const [loading, setLoading] = useState10(true);
635
+ const [error, setError] = useState10(null);
636
+ const lastWrittenRef = useRef7(null);
637
+ const debounceRef = useRef7(null);
638
+ useEffect10(() => {
639
+ if (!docApi) return;
640
+ return optionsEvent.subscribe(({ options: stored }) => {
641
+ const merged = mergeWithDefaults(defaultsRef.current, stored, config.namespace);
642
+ lastWrittenRef.current = merged;
643
+ setOptionsState(merged);
644
+ setLoading(false);
645
+ });
646
+ }, [docApi, config.namespace]);
647
+ const flushWrite = useCallback7(
648
+ async (value) => {
649
+ try {
650
+ if (config.namespace) {
651
+ await grist.setOption(config.namespace, value);
652
+ } else {
653
+ await grist.setOptions({ ...value });
654
+ }
655
+ lastWrittenRef.current = value;
656
+ } catch (err) {
657
+ setError(err instanceof Error ? err.message : String(err));
658
+ }
659
+ },
660
+ [config.namespace]
661
+ );
662
+ const scheduleWrite = useCallback7(
663
+ (value) => {
664
+ if (debounceRef.current) window.clearTimeout(debounceRef.current);
665
+ debounceRef.current = window.setTimeout(() => {
666
+ debounceRef.current = null;
667
+ void flushWrite(value);
668
+ }, debounceMs);
669
+ },
670
+ [debounceMs, flushWrite]
671
+ );
672
+ useEffect10(() => {
673
+ return () => {
674
+ if (debounceRef.current) window.clearTimeout(debounceRef.current);
675
+ };
676
+ }, []);
677
+ const setOptionsApi = useCallback7(
678
+ (next) => {
679
+ setOptionsState(next);
680
+ scheduleWrite(next);
681
+ },
682
+ [scheduleWrite]
683
+ );
684
+ const patchOptionsApi = useCallback7(
685
+ (patch) => {
686
+ setOptionsState((prev) => {
687
+ const next = { ...prev, ...patch };
688
+ scheduleWrite(next);
689
+ return next;
690
+ });
691
+ },
692
+ [scheduleWrite]
693
+ );
694
+ const reset = useCallback7(async () => {
695
+ if (debounceRef.current) {
696
+ window.clearTimeout(debounceRef.current);
697
+ debounceRef.current = null;
698
+ }
699
+ const next = { ...defaultsRef.current };
700
+ setOptionsState(next);
701
+ await flushWrite(next);
702
+ }, [flushWrite]);
703
+ return useMemo3(
704
+ () => ({
705
+ options,
706
+ loading,
707
+ error: readyError ?? error,
708
+ setOptions: setOptionsApi,
709
+ patchOptions: patchOptionsApi,
710
+ reset
711
+ }),
712
+ [options, loading, readyError, error, setOptionsApi, patchOptionsApi, reset]
713
+ );
714
+ }
715
+
716
+ // src/sdk/use-grist-table.ts
717
+ import { useCallback as useCallback8, useEffect as useEffect11, useState as useState11 } from "react";
718
+ function isCurrentMode(option) {
719
+ return option === void 0 || option === "current";
720
+ }
721
+ function useGristTable(options) {
722
+ const requiredAccess = options?.requiredAccess ?? "read table";
723
+ const tableIdOption = options?.tableId ?? "current";
724
+ const { docApi, error: readyError } = useGristReady({
725
+ requiredAccess,
726
+ columns: options?.columns,
727
+ allowSelectBy: options?.allowSelectBy,
728
+ hasCustomOptions: options?.hasCustomOptions,
729
+ onEditOptions: options?.onEditOptions
730
+ });
731
+ const [tableId, setTableId] = useState11(null);
732
+ const [loading, setLoading] = useState11(false);
733
+ const [error, setError] = useState11(null);
734
+ const fetchTable = useCallback8(
735
+ async (targetTableId) => {
736
+ if (!docApi) throw new Error("Grist is not ready");
737
+ return docApi.fetchTable(targetTableId);
738
+ },
739
+ [docApi]
740
+ );
741
+ const listTables = useCallback8(async () => {
742
+ if (!docApi) throw new Error("Grist is not ready");
743
+ const out = await Promise.resolve(docApi.listTables());
744
+ return [...out];
745
+ }, [docApi]);
746
+ const getDocName = useCallback8(async () => {
747
+ if (!docApi) throw new Error("Grist is not ready");
748
+ return String(await Promise.resolve(docApi.getDocName()));
749
+ }, [docApi]);
750
+ const fetchSelectedTable = useCallback8(
751
+ async (fetchOptions) => {
752
+ if (!docApi) throw new Error("Grist is not ready");
753
+ const impl = docApi.fetchSelectedTable ?? grist.fetchSelectedTable;
754
+ if (!impl) throw new Error("fetchSelectedTable is not available in this Grist version");
755
+ const merged = { keepEncoded: false, format: "rows", ...fetchOptions };
756
+ return await impl(merged);
757
+ },
758
+ [docApi]
759
+ );
760
+ const fetchSelectedRecord = useCallback8(
761
+ async (rowId, fetchOptions) => {
762
+ if (!docApi) throw new Error("Grist is not ready");
763
+ const impl = docApi.fetchSelectedRecord ?? grist.fetchSelectedRecord;
764
+ if (!impl) throw new Error("fetchSelectedRecord is not available in this Grist version");
765
+ const merged = { keepEncoded: false, format: "rows", ...fetchOptions };
766
+ return await impl(rowId, merged);
767
+ },
768
+ [docApi]
769
+ );
770
+ const refresh = useCallback8(async () => {
771
+ if (!docApi) return;
772
+ if (!isCurrentMode(tableIdOption)) {
773
+ setTableId(tableIdOption);
774
+ setError(null);
775
+ return;
776
+ }
777
+ setLoading(true);
778
+ setError(null);
779
+ try {
780
+ const next = await grist.selectedTable?.getTableId();
781
+ setTableId(next ?? null);
782
+ } catch (err) {
783
+ setTableId(null);
784
+ setError(err instanceof Error ? err.message : String(err));
785
+ } finally {
786
+ setLoading(false);
787
+ }
788
+ }, [docApi, tableIdOption]);
789
+ useEffect11(() => {
790
+ if (docApi) void refresh();
791
+ }, [docApi, refresh]);
792
+ return {
793
+ tableId,
794
+ loading,
795
+ error: readyError ?? error,
796
+ refresh,
797
+ fetchTable,
798
+ listTables,
799
+ getDocName,
800
+ fetchSelectedTable,
801
+ fetchSelectedRecord
802
+ };
803
+ }
804
+ export {
805
+ GristHandshakeProvider,
806
+ useGristAccessToken,
807
+ useGristActions,
808
+ useGristAvailability,
809
+ useGristCapabilities,
810
+ useGristHandshake,
811
+ useGristHandshakeContext,
812
+ useGristHandshakeContextOptional,
813
+ useGristMappedRecord,
814
+ useGristNewRecord,
815
+ useGristReady,
816
+ useGristRecord,
817
+ useGristRecords,
818
+ useGristRowsFromTable,
819
+ useGristSection,
820
+ useGristTable,
821
+ useGristTableOps,
822
+ useGristWidgetOptions,
823
+ useGristWidgetOptionsFromContext
824
+ };
825
+ //# sourceMappingURL=advanced.js.map