@stonecrop/stonecrop 0.31.0 → 0.32.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 (121) hide show
  1. package/dist/stonecrop.js +3548 -2740
  2. package/dist/stonecrop.js.map +1 -1
  3. package/dist/tsdoc-metadata.json +1 -1
  4. package/package.json +33 -27
  5. package/dist/src/client-action.d.ts +0 -31
  6. package/dist/src/client-action.d.ts.map +0 -1
  7. package/dist/src/client-action.js +0 -169
  8. package/dist/src/client-handler.d.ts +0 -43
  9. package/dist/src/client-handler.d.ts.map +0 -1
  10. package/dist/src/client-handler.js +0 -42
  11. package/dist/src/composables/lazy-link.d.ts +0 -25
  12. package/dist/src/composables/lazy-link.d.ts.map +0 -1
  13. package/dist/src/composables/lazy-link.js +0 -124
  14. package/dist/src/composables/operation-log.d.ts +0 -136
  15. package/dist/src/composables/operation-log.d.ts.map +0 -1
  16. package/dist/src/composables/operation-log.js +0 -224
  17. package/dist/src/composables/stonecrop.d.ts +0 -37
  18. package/dist/src/composables/stonecrop.d.ts.map +0 -1
  19. package/dist/src/composables/stonecrop.js +0 -433
  20. package/dist/src/doctype.d.ts +0 -243
  21. package/dist/src/doctype.d.ts.map +0 -1
  22. package/dist/src/doctype.js +0 -325
  23. package/dist/src/draft.d.ts +0 -35
  24. package/dist/src/draft.d.ts.map +0 -1
  25. package/dist/src/draft.js +0 -36
  26. package/dist/src/exceptions.d.ts +0 -14
  27. package/dist/src/exceptions.d.ts.map +0 -1
  28. package/dist/src/exceptions.js +0 -16
  29. package/dist/src/field-triggers.d.ts +0 -184
  30. package/dist/src/field-triggers.d.ts.map +0 -1
  31. package/dist/src/field-triggers.js +0 -577
  32. package/dist/src/index.d.ts +0 -25
  33. package/dist/src/index.d.ts.map +0 -1
  34. package/dist/src/index.js +0 -39
  35. package/dist/src/plugins/index.d.ts +0 -35
  36. package/dist/src/plugins/index.d.ts.map +0 -1
  37. package/dist/src/plugins/index.js +0 -98
  38. package/dist/src/registry.d.ts +0 -161
  39. package/dist/src/registry.d.ts.map +0 -1
  40. package/dist/src/registry.js +0 -384
  41. package/dist/src/schema-validator.d.ts +0 -78
  42. package/dist/src/schema-validator.d.ts.map +0 -1
  43. package/dist/src/schema-validator.js +0 -398
  44. package/dist/src/stonecrop.d.ts +0 -539
  45. package/dist/src/stonecrop.d.ts.map +0 -1
  46. package/dist/src/stonecrop.js +0 -610
  47. package/dist/src/stores/hst.d.ts +0 -92
  48. package/dist/src/stores/hst.d.ts.map +0 -1
  49. package/dist/src/stores/hst.js +0 -487
  50. package/dist/src/stores/index.d.ts +0 -9
  51. package/dist/src/stores/index.d.ts.map +0 -1
  52. package/dist/src/stores/index.js +0 -13
  53. package/dist/src/stores/operation-log.d.ts +0 -262
  54. package/dist/src/stores/operation-log.d.ts.map +0 -1
  55. package/dist/src/stores/operation-log.js +0 -571
  56. package/dist/src/stores/validation.d.ts +0 -83
  57. package/dist/src/stores/validation.d.ts.map +0 -1
  58. package/dist/src/stores/validation.js +0 -104
  59. package/dist/src/types/client-action.d.ts +0 -121
  60. package/dist/src/types/client-action.d.ts.map +0 -1
  61. package/dist/src/types/client-action.js +0 -0
  62. package/dist/src/types/composable.d.ts +0 -268
  63. package/dist/src/types/composable.d.ts.map +0 -1
  64. package/dist/src/types/composable.js +0 -0
  65. package/dist/src/types/doctype.d.ts +0 -34
  66. package/dist/src/types/doctype.d.ts.map +0 -1
  67. package/dist/src/types/doctype.js +0 -0
  68. package/dist/src/types/field-triggers.d.ts +0 -186
  69. package/dist/src/types/field-triggers.d.ts.map +0 -1
  70. package/dist/src/types/field-triggers.js +0 -4
  71. package/dist/src/types/hst.d.ts +0 -70
  72. package/dist/src/types/hst.d.ts.map +0 -1
  73. package/dist/src/types/hst.js +0 -0
  74. package/dist/src/types/index.d.ts +0 -11
  75. package/dist/src/types/index.d.ts.map +0 -1
  76. package/dist/src/types/index.js +0 -11
  77. package/dist/src/types/operation-log.d.ts +0 -163
  78. package/dist/src/types/operation-log.d.ts.map +0 -1
  79. package/dist/src/types/operation-log.js +0 -0
  80. package/dist/src/types/plugin.d.ts +0 -37
  81. package/dist/src/types/plugin.d.ts.map +0 -1
  82. package/dist/src/types/plugin.js +0 -0
  83. package/dist/src/types/registry.d.ts +0 -11
  84. package/dist/src/types/registry.d.ts.map +0 -1
  85. package/dist/src/types/registry.js +0 -0
  86. package/dist/src/types/schema-validator.d.ts +0 -66
  87. package/dist/src/types/schema-validator.d.ts.map +0 -1
  88. package/dist/src/types/schema-validator.js +0 -13
  89. package/dist/src/types/stonecrop.d.ts +0 -32
  90. package/dist/src/types/stonecrop.d.ts.map +0 -1
  91. package/dist/src/types/stonecrop.js +0 -0
  92. package/dist/stonecrop.tsbuildinfo +0 -1
  93. package/src/client-action.ts +0 -207
  94. package/src/client-handler.ts +0 -55
  95. package/src/composables/lazy-link.ts +0 -145
  96. package/src/composables/operation-log.ts +0 -257
  97. package/src/composables/stonecrop.ts +0 -556
  98. package/src/doctype.ts +0 -360
  99. package/src/draft.ts +0 -38
  100. package/src/exceptions.ts +0 -16
  101. package/src/field-triggers.ts +0 -686
  102. package/src/index.ts +0 -81
  103. package/src/plugins/index.ts +0 -113
  104. package/src/registry.ts +0 -433
  105. package/src/schema-validator.ts +0 -476
  106. package/src/stonecrop.ts +0 -721
  107. package/src/stores/hst.ts +0 -626
  108. package/src/stores/index.ts +0 -21
  109. package/src/stores/operation-log.ts +0 -675
  110. package/src/stores/validation.ts +0 -138
  111. package/src/types/client-action.ts +0 -121
  112. package/src/types/composable.ts +0 -288
  113. package/src/types/doctype.ts +0 -35
  114. package/src/types/field-triggers.ts +0 -201
  115. package/src/types/hst.ts +0 -77
  116. package/src/types/index.ts +0 -11
  117. package/src/types/operation-log.ts +0 -202
  118. package/src/types/plugin.ts +0 -38
  119. package/src/types/registry.ts +0 -10
  120. package/src/types/schema-validator.ts +0 -69
  121. package/src/types/stonecrop.ts +0 -33
@@ -1,675 +0,0 @@
1
- import { defineStore } from 'pinia'
2
- import { ref, computed, watch } from 'vue'
3
- import { useLocalStorage } from '@vueuse/core'
4
-
5
- import type { HSTNode } from './hst'
6
- import type {
7
- CrossTabMessage,
8
- HSTOperation,
9
- HSTOperationInput,
10
- OperationLogConfig,
11
- OperationLogSnapshot,
12
- OperationSource,
13
- UndoRedoState,
14
- } from '../types/operation-log'
15
-
16
- /**
17
- * Generate a UUID using crypto API or fallback
18
- */
19
- function generateId(): string {
20
- if (typeof crypto !== 'undefined' && crypto.randomUUID) {
21
- return crypto.randomUUID()
22
- }
23
- // Fallback for environments without crypto.randomUUID
24
- return `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`
25
- }
26
-
27
- /**
28
- * Serialize a message for BroadcastChannel
29
- * Converts Date objects to ISO strings for structured clone compatibility
30
- */
31
- type SerializedOperation = Omit<HSTOperation, 'timestamp'> & { timestamp: string }
32
- type SerializedCrossTabMessage = Omit<CrossTabMessage, 'timestamp' | 'operation' | 'operations'> & {
33
- timestamp: string
34
- operation?: SerializedOperation
35
- operations?: SerializedOperation[]
36
- }
37
-
38
- function serializeForBroadcast(message: CrossTabMessage): SerializedCrossTabMessage {
39
- const serialized: SerializedCrossTabMessage = {
40
- type: message.type,
41
- clientId: message.clientId,
42
- timestamp: message.timestamp.toISOString(),
43
- }
44
-
45
- if (message.operation) {
46
- serialized.operation = {
47
- ...message.operation,
48
- timestamp: message.operation.timestamp.toISOString(),
49
- }
50
- }
51
-
52
- if (message.operations) {
53
- serialized.operations = message.operations.map(op => ({
54
- ...op,
55
- timestamp: op.timestamp.toISOString(),
56
- }))
57
- }
58
-
59
- return serialized
60
- }
61
-
62
- /**
63
- * Deserialize a message from BroadcastChannel
64
- * Converts ISO strings back to Date objects
65
- */
66
- function deserializeFromBroadcast(serialized: SerializedCrossTabMessage): CrossTabMessage {
67
- const message: CrossTabMessage = {
68
- type: serialized.type,
69
- clientId: serialized.clientId,
70
- timestamp: new Date(serialized.timestamp),
71
- }
72
-
73
- if (serialized.operation) {
74
- message.operation = {
75
- ...serialized.operation,
76
- timestamp: new Date(serialized.operation.timestamp),
77
- }
78
- }
79
-
80
- if (serialized.operations) {
81
- message.operations = serialized.operations.map(op => ({
82
- ...op,
83
- timestamp: new Date(op.timestamp),
84
- }))
85
- }
86
-
87
- return message
88
- }
89
-
90
- /**
91
- * Revert an operation (apply beforeValue)
92
- */
93
- function revertOperation(operation: HSTOperation, store: HSTNode) {
94
- if ((operation.type === 'set' || operation.type === 'delete') && store && typeof store.set === 'function') {
95
- store.set(operation.path, operation.beforeValue, 'undo')
96
- }
97
- }
98
-
99
- /**
100
- * Apply an operation (apply afterValue)
101
- */
102
- function applyOperation(operation: HSTOperation, store: HSTNode) {
103
- if ((operation.type === 'set' || operation.type === 'delete') && store && typeof store.set === 'function') {
104
- store.set(operation.path, operation.afterValue, 'redo')
105
- }
106
- }
107
-
108
- /**
109
- * Global HST Operation Log Store
110
- * Tracks all mutations with full metadata for undo/redo, sync, and audit
111
- *
112
- * @public
113
- */
114
- export const useOperationLogStore = defineStore('hst-operation-log', () => {
115
- // Configuration
116
- const config = ref<OperationLogConfig>({
117
- maxOperations: 100,
118
- enableCrossTabSync: true,
119
- enablePersistence: false,
120
- persistenceKeyPrefix: 'stonecrop-ops',
121
- })
122
-
123
- // State
124
- const operations = ref<HSTOperation[]>([])
125
- const currentIndex = ref(-1) // Points to the last applied operation
126
- const clientId = ref(generateId())
127
- const batchMode = ref(false)
128
- const batchStack = ref<{ id: string; operations: HSTOperation[] }[]>([])
129
-
130
- // Computed
131
- const canUndo = computed(() => {
132
- // Can undo if there are operations and we're not at the beginning
133
- if (currentIndex.value < 0) return false
134
-
135
- // Check if the operation at currentIndex is reversible
136
- const operation = operations.value[currentIndex.value]
137
- return operation?.reversible ?? false
138
- })
139
-
140
- const canRedo = computed(() => {
141
- // Can redo if there are operations ahead of current index
142
- return currentIndex.value < operations.value.length - 1
143
- })
144
-
145
- const undoCount = computed(() => {
146
- let count = 0
147
- for (let i = currentIndex.value; i >= 0; i--) {
148
- if (operations.value[i]?.reversible) count++
149
- else break
150
- }
151
- return count
152
- })
153
-
154
- const redoCount = computed(() => {
155
- return operations.value.length - 1 - currentIndex.value
156
- })
157
-
158
- const undoRedoState = computed((): UndoRedoState => ({
159
- canUndo: canUndo.value,
160
- canRedo: canRedo.value,
161
- undoCount: undoCount.value,
162
- redoCount: redoCount.value,
163
- currentIndex: currentIndex.value,
164
- }))
165
-
166
- // Core Methods
167
-
168
- /**
169
- * Configure the operation log
170
- */
171
- function configure(options: Partial<OperationLogConfig>) {
172
- config.value = { ...config.value, ...options }
173
-
174
- // Set up persistence if enabled
175
- if (config.value.enablePersistence) {
176
- loadFromPersistence()
177
- setupPersistenceWatcher()
178
- }
179
-
180
- // Set up cross-tab sync if enabled
181
- if (config.value.enableCrossTabSync) {
182
- setupCrossTabSync()
183
- }
184
- }
185
-
186
- /**
187
- * Add an operation to the log
188
- */
189
- function addOperation(operation: HSTOperationInput, source: OperationSource = 'user') {
190
- const fullOperation: HSTOperation = {
191
- ...operation,
192
- id: generateId(),
193
- timestamp: new Date(),
194
- source: source,
195
- userId: config.value.userId,
196
- }
197
-
198
- // Apply filter if configured
199
- if (config.value.operationFilter && !config.value.operationFilter(fullOperation)) {
200
- return fullOperation.id
201
- }
202
-
203
- // If in batch mode, collect operations in current batch
204
- if (batchMode.value && batchStack.value.length > 0) {
205
- batchStack.value[batchStack.value.length - 1].operations.push(fullOperation)
206
- return fullOperation.id
207
- }
208
-
209
- // Remove any operations after current index (they become invalid after new operation)
210
- if (currentIndex.value < operations.value.length - 1) {
211
- operations.value = operations.value.slice(0, currentIndex.value + 1)
212
- }
213
-
214
- // Add new operation
215
- operations.value.push(fullOperation)
216
- currentIndex.value++
217
-
218
- // Enforce max operations limit
219
- if (config.value.maxOperations && operations.value.length > config.value.maxOperations) {
220
- const overflow = operations.value.length - config.value.maxOperations
221
- operations.value = operations.value.slice(overflow)
222
- currentIndex.value -= overflow
223
- }
224
-
225
- // Broadcast to other tabs
226
- if (config.value.enableCrossTabSync) {
227
- broadcastOperation(fullOperation)
228
- }
229
-
230
- return fullOperation.id
231
- }
232
-
233
- /**
234
- * Start batch mode - collect multiple operations
235
- */
236
- function startBatch() {
237
- batchMode.value = true
238
- batchStack.value.push({
239
- id: generateId(),
240
- operations: [],
241
- })
242
- }
243
-
244
- /**
245
- * Commit batch - create a single batch operation
246
- */
247
- function commitBatch(description?: string): string | null {
248
- if (!batchMode.value || batchStack.value.length === 0) {
249
- return null
250
- }
251
-
252
- const currentBatchData = batchStack.value.pop()!
253
- const batchOperations = currentBatchData.operations
254
-
255
- if (batchOperations.length === 0) {
256
- // Empty batch - just pop and continue if there are outer batches
257
- if (batchStack.value.length === 0) {
258
- batchMode.value = false
259
- }
260
- return null
261
- }
262
-
263
- const batchId = currentBatchData.id
264
- const allReversible = batchOperations.every(op => op.reversible)
265
-
266
- // Create ancestor batch operation
267
- const batchOperation: HSTOperation = {
268
- id: batchId,
269
- type: 'batch',
270
- path: '', // Batch doesn't have a single path
271
- fieldname: '',
272
- beforeValue: null,
273
- afterValue: null,
274
- doctype: batchOperations[0]?.doctype || '',
275
- timestamp: new Date(),
276
- source: 'user',
277
- reversible: allReversible,
278
- irreversibleReason: allReversible ? undefined : 'Contains irreversible operations',
279
- descendantOperationIds: batchOperations.map(op => op.id),
280
- metadata: { description },
281
- }
282
-
283
- // Add ancestor operation ID to all descendants
284
- batchOperations.forEach(op => {
285
- op.ancestorOperationId = batchId
286
- })
287
-
288
- // If we're inside a ancestor batch, add this batch as a descendant of the ancestor
289
- if (batchStack.value.length > 0) {
290
- // Nested batch - add the batch operation to the ancestor batch
291
- batchStack.value[batchStack.value.length - 1].operations.push(batchOperation)
292
- } else {
293
- // Top-level batch - add to the operations log
294
- operations.value.push(...batchOperations, batchOperation)
295
- currentIndex.value = operations.value.length - 1
296
- }
297
-
298
- // Broadcast batch
299
- if (config.value.enableCrossTabSync) {
300
- broadcastBatch(batchOperations, batchOperation)
301
- }
302
-
303
- // If no more batches on stack, exit batch mode
304
- if (batchStack.value.length === 0) {
305
- batchMode.value = false
306
- }
307
-
308
- return batchId
309
- }
310
-
311
- /**
312
- * Cancel batch mode without committing
313
- */
314
- function cancelBatch() {
315
- batchStack.value = []
316
- batchMode.value = false
317
- }
318
-
319
- /**
320
- * Undo the last operation
321
- */
322
- function undo(store: HSTNode): boolean {
323
- if (!canUndo.value) return false
324
-
325
- const operation = operations.value[currentIndex.value]
326
-
327
- if (!operation.reversible) {
328
- // Warn about irreversible operation
329
- if (typeof console !== 'undefined' && operation.irreversibleReason) {
330
- console.warn('Cannot undo irreversible operation:', operation.irreversibleReason)
331
- }
332
- return false
333
- }
334
-
335
- try {
336
- // Handle batch operations
337
- if (operation.type === 'batch' && operation.descendantOperationIds) {
338
- // Undo all descendant operations in reverse order
339
- for (let i = operation.descendantOperationIds.length - 1; i >= 0; i--) {
340
- const descendantId = operation.descendantOperationIds[i]
341
- const descendantOp = operations.value.find(op => op.id === descendantId)
342
- if (descendantOp) {
343
- revertOperation(descendantOp, store)
344
- }
345
- }
346
- } else {
347
- // Undo single operation
348
- revertOperation(operation, store)
349
- }
350
-
351
- currentIndex.value--
352
-
353
- // Broadcast undo to other tabs
354
- if (config.value.enableCrossTabSync) {
355
- broadcastUndo(operation)
356
- }
357
-
358
- return true
359
- } catch (error) {
360
- // Log error in development
361
- if (typeof console !== 'undefined') {
362
- console.error('Undo failed:', error)
363
- }
364
- return false
365
- }
366
- }
367
-
368
- /**
369
- * Redo the next operation
370
- */
371
- function redo(store: HSTNode): boolean {
372
- if (!canRedo.value) return false
373
-
374
- const operation = operations.value[currentIndex.value + 1]
375
-
376
- try {
377
- // Handle batch operations
378
- if (operation.type === 'batch' && operation.descendantOperationIds) {
379
- // Redo all descendant operations in order
380
- for (const descendantId of operation.descendantOperationIds) {
381
- const descendantOp = operations.value.find(op => op.id === descendantId)
382
- if (descendantOp) {
383
- applyOperation(descendantOp, store)
384
- }
385
- }
386
- } else {
387
- // Redo single operation
388
- applyOperation(operation, store)
389
- }
390
-
391
- currentIndex.value++
392
-
393
- // Broadcast redo to other tabs
394
- if (config.value.enableCrossTabSync) {
395
- broadcastRedo(operation)
396
- }
397
-
398
- return true
399
- } catch (error) {
400
- // Log error in development
401
- if (typeof console !== 'undefined') {
402
- console.error('Redo failed:', error)
403
- }
404
- return false
405
- }
406
- }
407
-
408
- /**
409
- * Get operation log snapshot for debugging
410
- */
411
- function getSnapshot(): OperationLogSnapshot {
412
- const reversibleOps = operations.value.filter(op => op.reversible).length
413
- const timestamps = operations.value.map(op => op.timestamp)
414
-
415
- return {
416
- operations: [...operations.value],
417
- currentIndex: currentIndex.value,
418
- totalOperations: operations.value.length,
419
- reversibleOperations: reversibleOps,
420
- irreversibleOperations: operations.value.length - reversibleOps,
421
- oldestOperation: timestamps.length > 0 ? new Date(Math.min(...timestamps.map(t => t.getTime()))) : undefined,
422
- newestOperation: timestamps.length > 0 ? new Date(Math.max(...timestamps.map(t => t.getTime()))) : undefined,
423
- }
424
- }
425
-
426
- /**
427
- * Clear all operations
428
- */
429
- function clear() {
430
- operations.value = []
431
- currentIndex.value = -1
432
- }
433
-
434
- /**
435
- * Get operations for a specific doctype and recordId
436
- */
437
- function getOperationsFor(doctype: string, recordId?: string): HSTOperation[] {
438
- return operations.value.filter(op => op.doctype === doctype && (recordId === undefined || op.recordId === recordId))
439
- }
440
-
441
- /**
442
- * Mark an operation as irreversible
443
- * @param operationId - The ID of the operation to mark
444
- * @param reason - The reason why the operation is irreversible
445
- */
446
- function markIrreversible(operationId: string, reason: string) {
447
- const operation = operations.value.find(op => op.id === operationId)
448
- if (operation) {
449
- operation.reversible = false
450
- operation.irreversibleReason = reason
451
- }
452
- }
453
-
454
- /**
455
- * Log an action execution (stateless actions like print, email, etc.)
456
- * These operations are tracked but typically not reversible
457
- * @param doctype - The doctype the action was executed on
458
- * @param actionName - The name of the action that was executed
459
- * @param recordIds - Optional array of record IDs the action was executed on
460
- * @param result - The result of the action execution
461
- * @param error - Optional error message if action failed
462
- * @returns The operation ID
463
- */
464
- function logAction(
465
- doctype: string,
466
- actionName: string,
467
- recordIds?: string[],
468
- result: 'success' | 'failure' | 'pending' = 'success',
469
- error?: string
470
- ): string {
471
- const operation: HSTOperationInput = {
472
- type: 'action',
473
- path: recordIds && recordIds.length > 0 ? `${doctype}.${recordIds[0]}` : doctype,
474
- fieldname: '',
475
- beforeValue: null,
476
- afterValue: null,
477
- doctype,
478
- recordId: recordIds && recordIds.length > 0 ? recordIds[0] : undefined,
479
- reversible: false, // Actions are typically not reversible
480
- actionName,
481
- actionRecordIds: recordIds,
482
- actionResult: result,
483
- actionError: error,
484
- }
485
-
486
- return addOperation(operation)
487
- }
488
-
489
- // Cross-tab synchronization
490
- let broadcastChannel: BroadcastChannel | null = null
491
-
492
- function setupCrossTabSync() {
493
- if (typeof window === 'undefined' || !window.BroadcastChannel) return
494
-
495
- broadcastChannel = new BroadcastChannel('stonecrop-operation-log')
496
-
497
- broadcastChannel.addEventListener('message', (event: MessageEvent) => {
498
- const rawMessage = event.data
499
-
500
- if (!rawMessage || typeof rawMessage !== 'object') return
501
-
502
- const message = deserializeFromBroadcast(rawMessage)
503
-
504
- // Ignore messages from this tab
505
- if (message.clientId === clientId.value) return
506
-
507
- if (message.type === 'operation' && message.operation) {
508
- // Add operation from another tab
509
- operations.value.push({ ...message.operation, source: 'sync' })
510
- currentIndex.value = operations.value.length - 1
511
- } else if (message.type === 'operation' && message.operations) {
512
- // Add batch operations from another tab
513
- operations.value.push(
514
- ...message.operations.map((op): HSTOperation => Object.assign({}, op, { source: 'sync' as const }))
515
- )
516
- currentIndex.value = operations.value.length - 1
517
- }
518
- })
519
- }
520
-
521
- function broadcastOperation(operation: HSTOperation) {
522
- if (!broadcastChannel) return
523
-
524
- const message: CrossTabMessage = {
525
- type: 'operation',
526
- operation,
527
- clientId: clientId.value,
528
- timestamp: new Date(),
529
- }
530
- // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage
531
- broadcastChannel.postMessage(serializeForBroadcast(message))
532
- }
533
-
534
- function broadcastBatch(descendantOps: HSTOperation[], batchOp: HSTOperation) {
535
- if (!broadcastChannel) return
536
-
537
- const message: CrossTabMessage = {
538
- type: 'operation',
539
- operations: [...descendantOps, batchOp],
540
- clientId: clientId.value,
541
- timestamp: new Date(),
542
- }
543
- // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage
544
- broadcastChannel.postMessage(serializeForBroadcast(message))
545
- }
546
-
547
- function broadcastUndo(operation: HSTOperation) {
548
- if (!broadcastChannel) return
549
-
550
- const message: CrossTabMessage = {
551
- type: 'undo',
552
- operation,
553
- clientId: clientId.value,
554
- timestamp: new Date(),
555
- }
556
- // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage
557
- broadcastChannel.postMessage(serializeForBroadcast(message))
558
- }
559
-
560
- function broadcastRedo(operation: HSTOperation) {
561
- if (!broadcastChannel) return
562
-
563
- const message: CrossTabMessage = {
564
- type: 'redo',
565
- operation,
566
- clientId: clientId.value,
567
- timestamp: new Date(),
568
- }
569
- // oxlint-disable-next-line unicorn/require-post-message-target-origin -- BroadcastChannel.postMessage does not accept targetOrigin; rule only applies to window.postMessage
570
- broadcastChannel.postMessage(serializeForBroadcast(message))
571
- }
572
-
573
- // Persistence using VueUse
574
- type PersistedData = {
575
- operations: Array<Omit<HSTOperation, 'timestamp'> & { timestamp: string }>
576
- currentIndex: number
577
- }
578
-
579
- const persistedData = useLocalStorage<PersistedData | null>('stonecrop-operations', null, {
580
- serializer: {
581
- read: (v: string) => {
582
- try {
583
- const data = JSON.parse(v)
584
- return data
585
- } catch {
586
- return null
587
- }
588
- },
589
- write: (v: PersistedData | null) => {
590
- if (!v) return ''
591
- return JSON.stringify(v)
592
- },
593
- },
594
- })
595
-
596
- function loadFromPersistence() {
597
- if (typeof window === 'undefined') return
598
-
599
- try {
600
- const data = persistedData.value
601
- if (data && Array.isArray(data.operations)) {
602
- operations.value = data.operations.map(op => ({
603
- ...op,
604
- timestamp: new Date(op.timestamp),
605
- }))
606
- currentIndex.value = data.currentIndex ?? -1
607
- }
608
- } catch (error) {
609
- // Log error in development
610
- if (typeof console !== 'undefined') {
611
- console.error('Failed to load operations from persistence:', error)
612
- }
613
- }
614
- }
615
-
616
- function saveToPersistence() {
617
- if (typeof window === 'undefined') return
618
-
619
- try {
620
- persistedData.value = {
621
- operations: operations.value.map(op => ({
622
- ...op,
623
- timestamp: op.timestamp.toISOString(),
624
- })),
625
- currentIndex: currentIndex.value,
626
- }
627
- } catch (error) {
628
- // Log error in development
629
- if (typeof console !== 'undefined') {
630
- console.error('Failed to save operations to persistence:', error)
631
- }
632
- }
633
- }
634
-
635
- function setupPersistenceWatcher() {
636
- watch(
637
- [operations, currentIndex],
638
- () => {
639
- if (config.value.enablePersistence) {
640
- saveToPersistence()
641
- }
642
- },
643
- { deep: true }
644
- )
645
- }
646
-
647
- return {
648
- // State
649
- operations,
650
- currentIndex,
651
- config,
652
- clientId,
653
- undoRedoState,
654
-
655
- // Computed
656
- canUndo,
657
- canRedo,
658
- undoCount,
659
- redoCount,
660
-
661
- // Methods
662
- configure,
663
- addOperation,
664
- startBatch,
665
- commitBatch,
666
- cancelBatch,
667
- undo,
668
- redo,
669
- clear,
670
- getOperationsFor,
671
- getSnapshot,
672
- markIrreversible,
673
- logAction,
674
- }
675
- })