@lincyaw/workbench 0.2.0-rc.11 → 0.2.0-rc.110

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 (108) hide show
  1. package/package.json +5 -4
  2. package/src/AgentActivityBar.tsx +25 -0
  3. package/src/MediaClipEditor.tsx +4 -3
  4. package/src/StepProductionEditor.tsx +13 -4
  5. package/src/agent-activity-messages.ts +14 -0
  6. package/src/agent-activity.ts +38 -0
  7. package/src/approvals.tsx +6 -1
  8. package/src/audio-recording-messages.ts +5 -5
  9. package/src/audio-recording.ts +27 -5
  10. package/src/authoring-client.ts +10 -10
  11. package/src/authoring-draft-fragment.ts +3 -1
  12. package/src/authoring-window.ts +100 -0
  13. package/src/base-controls.tsx +2 -2
  14. package/src/body-draft-actions.ts +60 -0
  15. package/src/caption-timing-drafts.ts +18 -1
  16. package/src/caption-timing-messages.ts +2 -2
  17. package/src/component-property-drafts.ts +5 -5
  18. package/src/components.tsx +34 -36
  19. package/src/container-layout.ts +21 -0
  20. package/src/context.tsx +5 -3
  21. package/src/diagnostics.ts +1 -1
  22. package/src/document-draft-store.ts +45 -18
  23. package/src/document-drafts.ts +28 -19
  24. package/src/document-editing.ts +484 -0
  25. package/src/document-editor/BlockNoteSurface.tsx +39 -13
  26. package/src/document-editor/CommentComposer.tsx +24 -0
  27. package/src/document-editor/ComponentMaterials.tsx +3 -9
  28. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  29. package/src/document-editor/DocumentBlockPreview.tsx +11 -4
  30. package/src/document-editor/DocumentComments.tsx +85 -14
  31. package/src/document-editor/DocumentEditor.tsx +56 -7
  32. package/src/document-editor/DocumentStepNarration.tsx +37 -26
  33. package/src/document-editor/NarrationEditor.tsx +54 -20
  34. package/src/document-editor/NewCommentDrafts.tsx +120 -37
  35. package/src/document-editor/PlaceComment.tsx +252 -0
  36. package/src/document-editor/agent-targets.ts +34 -0
  37. package/src/document-editor/blocknote-messages.ts +2 -0
  38. package/src/document-editor/comment-draft-actions.ts +40 -20
  39. package/src/document-editor/comment-draft-inspection.ts +2 -2
  40. package/src/document-editor/comment-drafts.ts +73 -25
  41. package/src/document-editor/comments.ts +30 -10
  42. package/src/document-editor/component-label.ts +11 -0
  43. package/src/document-editor/file-input.ts +2 -2
  44. package/src/document-editor/focus.ts +0 -2
  45. package/src/document-editor/insertion-place.ts +60 -0
  46. package/src/document-editor/messages.ts +3 -3
  47. package/src/document-editor/narration-schema.tsx +12 -6
  48. package/src/document-editor/narration.ts +19 -3
  49. package/src/document-editor/page-body.ts +60 -0
  50. package/src/document-editor/popover.tsx +4 -2
  51. package/src/document-editor/projection.ts +2 -2
  52. package/src/document-editor/rich-text.ts +3 -2
  53. package/src/document-editor/selection.ts +13 -0
  54. package/src/document-editor/style.css +7 -1
  55. package/src/document-editor/table-identities.ts +2 -1
  56. package/src/document-production.ts +491 -0
  57. package/src/document-session.ts +202 -56
  58. package/src/document-timing-drafts.ts +22 -2
  59. package/src/history.ts +5 -5
  60. package/src/index.ts +11 -5
  61. package/src/jobs.ts +1 -1
  62. package/src/mcp-settings-messages.ts +39 -0
  63. package/src/media-drafts.ts +43 -1
  64. package/src/messages.ts +33 -16
  65. package/src/panels/DocumentNarrationPanel.tsx +2 -2
  66. package/src/panels/DocumentView.tsx +97 -65
  67. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  68. package/src/panels/DocumentVoiceField.tsx +1 -1
  69. package/src/panels/ExportPanel.tsx +2 -10
  70. package/src/panels/HistoryPanel.tsx +34 -7
  71. package/src/panels/HomePanel.tsx +3 -1
  72. package/src/panels/McpSettingsPanel.tsx +86 -0
  73. package/src/panels/PageDeleteDialog.tsx +4 -4
  74. package/src/panels/PageRenameDialog.tsx +1 -1
  75. package/src/panels/PreviewPanel.tsx +1 -4
  76. package/src/panels/ProductionCaptionSize.tsx +20 -0
  77. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  78. package/src/panels/ProductionMediaClips.tsx +23 -7
  79. package/src/panels/ProductionPanel.tsx +16 -13
  80. package/src/panels/ProductionRecording.tsx +86 -9
  81. package/src/panels/ProductionRecordingRange.tsx +21 -19
  82. package/src/panels/ProductionTimeline.tsx +6 -1
  83. package/src/panels/ProductionTranscription.tsx +5 -4
  84. package/src/panels/SourceDocumentPanel.tsx +18 -36
  85. package/src/panels/SpeechSettingsPanel.tsx +1 -1
  86. package/src/panels/TranscriptionAdoption.tsx +40 -34
  87. package/src/panels/VoiceCloneDialog.tsx +2 -1
  88. package/src/panels/VoiceoverDialog.tsx +1 -1
  89. package/src/places.ts +1 -36
  90. package/src/preview-playback.ts +1 -1
  91. package/src/production-draft-actions.ts +37 -0
  92. package/src/production-messages.ts +6 -0
  93. package/src/production-playback.ts +1 -1
  94. package/src/production-voice-playback.ts +3 -2
  95. package/src/sha256.ts +9 -0
  96. package/src/speech-settings-messages.ts +5 -5
  97. package/src/styles.css +43 -79
  98. package/src/transcription-drafts.ts +124 -0
  99. package/src/use-recording-adoption.ts +2 -2
  100. package/src/voice-drafts.ts +32 -8
  101. package/src/voice-messages.ts +9 -9
  102. package/src/voiceover-jobs.ts +1 -1
  103. package/src/workbench-state.ts +159 -0
  104. package/src/workbench.ts +303 -952
  105. package/src/workspace-client.ts +30 -11
  106. package/src/assistant-mascot.ts +0 -62
  107. package/src/mascot-preference.ts +0 -37
  108. package/src/panels/ChangeTrail.tsx +0 -79
@@ -1,3 +1,4 @@
1
+ import type { McpConnectionSettings, McpConnectionChange } from '@lincyaw/kernel'
1
2
  import type { ProjectOperation, ProjectPlan, ProjectPlanRequest, ProjectApply, ProjectApplied } from '@lincyaw/kernel'
2
3
  import type { PreviewEventSubscription } from '@lincyaw/kernel'
3
4
  import type { SpeechSettingsAnswer, SpeechSettingsChange } from '@lincyaw/kernel'
@@ -13,6 +14,7 @@ import type { DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, Docu
13
14
  import type { DocumentImageImport, DocumentImageImportAnswer } from '@lincyaw/kernel'
14
15
  import type { ProductionAssetAnswer, ProductionAssetQuery, ProductionMediaQuery, ProductionPlan, ProductionPlanQuery } from '@lincyaw/kernel'
15
16
  import type { DocumentTranscriptionRequest, TranscriptionCapabilities, TranscriptionTask, TranscriptionListAnswer, TranscriptionRevision, TranscriptionCancellation, TranscriptionAdoptionDraft, TranscriptionAdoptionPlan, TranscriptionAdoptionApply, TranscriptionAdoptionAnswer } from '@lincyaw/kernel'
17
+ import { randomUUID } from '@lincyaw/kernel'
16
18
 
17
19
  /** A change of the host's pending approvals that this author may answer. */
18
20
  export type ApprovalEvent =
@@ -64,12 +66,17 @@ export interface WorkspaceCapabilities {
64
66
  }
65
67
 
66
68
  export interface WorkspaceClient {
69
+ readMcpSettings?(signal?: AbortSignal): Promise<McpConnectionSettings>
70
+ changeMcpSettings?(change: McpConnectionChange, signal?: AbortSignal): Promise<McpConnectionSettings>
71
+ exportMcpSettings?(revision: string, signal?: AbortSignal): Promise<unknown>
72
+ subscribeAgentActivity?(received: (snapshot: import('@lincyaw/kernel').AgentActivitySnapshot) => void, failed: () => void): () => void
67
73
  readSpeechSettings?(signal?: AbortSignal): Promise<SpeechSettingsAnswer>
68
74
  changeSpeechSettings?(change: SpeechSettingsChange, signal?: AbortSignal): Promise<SpeechSettingsAnswer>
69
75
  openSpeechSettings?(): boolean
70
76
  capabilities?: Readonly<WorkspaceCapabilities>
71
77
  subscribePreviewEvents?: PreviewEventSubscription
72
78
  openAuthoringClient?: AuthoringClientSubscription
79
+ openAuthoringWindow?: AuthoringWindowSubscription
73
80
  subscribeRequests?(listener: (event: WorkspaceRequestEvent) => void): () => void
74
81
  readDocuments(document?: string): Promise<DocumentsAnswer>
75
82
  planProjectChange(request: ProjectPlanRequest): Promise<ProjectPlan>
@@ -80,14 +87,14 @@ export interface WorkspaceClient {
80
87
  /** Saves a small set of files in one document with one version and rollback boundary. */
81
88
  saveSourceTransaction(document: string, changes: SourceTransactionChange[], message?: string): Promise<SourceTransactionAnswer>
82
89
  readIr(document: string): Promise<IrAnswer>
83
- readDocument(document: string): Promise<DocumentAnswer>
90
+ readDocument(document: string, signal?: AbortSignal): Promise<DocumentAnswer>
84
91
  readAuthoringCapabilities(document: string, signal?: AbortSignal): Promise<AuthoringCapabilities>
85
92
  planDocumentAction(document: string, request: DocumentAuthoringActionRequest, signal?: AbortSignal): Promise<DocumentAuthoringActionPlan>
86
93
  readDocumentActionPlan(document: string, reference: DocumentAuthoringActionRead, signal?: AbortSignal): Promise<DocumentAuthoringActionInspection>
87
94
  applyDocumentAction(document: string, reference: DocumentAuthoringActionReference, signal?: AbortSignal): Promise<AppliedDocumentAuthoringAction>
88
95
  /** A same-origin display URL; the canonical asset location remains untouched. */
89
96
  documentAssetURL(document: string, assetId: string): string
90
- changeDocument(document: string, change: DocumentChange): Promise<DocumentChangeAnswer>
97
+ changeDocument(document: string, change: DocumentChange, signal?: AbortSignal): Promise<DocumentChangeAnswer>
91
98
  importDocumentImage(document: string, file: File, change: DocumentImageImport, signal?: AbortSignal): Promise<DocumentImageImportAnswer>
92
99
  readDocumentAudio(document: string, assetId: string, baseDocumentVersion: string, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer>
93
100
  importDocumentAudio(document: string, file: File, change: DocumentAudioImport, signal?: AbortSignal): Promise<DocumentAudioImportAnswer>
@@ -129,16 +136,16 @@ export interface WorkspaceClient {
129
136
  prefetchPreview(document: string, renderer: PreviewRenderer): Promise<PreviewAnswer>
130
137
  /** The MCP address and the workspace root, read once. */
131
138
  readWorkbenchInfo(): Promise<WorkbenchAnswer>
132
- readFocus(document: string): Promise<FocusAnswer>
139
+ readFocus(document: string, signal?: AbortSignal): Promise<FocusAnswer>
133
140
  writeFocus(document: string, focus: FocusReport[]): Promise<FocusAnswer>
134
141
  subscribeReview(document: string, update: (event: ReviewUpdate) => void): () => void
135
142
  acceptReview(document: string, body: { reject?: string[], message?: string }): Promise<{ ended: ReviewEnd }>
136
143
  rejectReview(document: string, paths?: string[]): Promise<ReviewUpdate>
137
144
  restoreReview(document: string, step: string): Promise<{ review: ReviewSnapshot }>
138
- readChanges(document: string): Promise<{ files: UncommittedFile[] }>
145
+ readChanges(document: string, signal?: AbortSignal): Promise<{ files: UncommittedFile[] }>
139
146
  commitChanges(document: string, message: string, paths?: string[]): Promise<unknown>
140
147
  discardChanges(document: string, paths?: string[]): Promise<unknown>
141
- readRevisions(document: string, query?: import('@lincyaw/kernel').DocumentHistoryQuery): Promise<RevisionsAnswer>
148
+ readRevisions(document: string, query?: import('@lincyaw/kernel').DocumentHistoryQuery, signal?: AbortSignal): Promise<RevisionsAnswer>
142
149
  readHistoryFile(document: string, query: import('@lincyaw/kernel').DocumentHistoryRead): Promise<import('@lincyaw/kernel').DocumentHistoryFile>
143
150
  revertRevision(document: string, request: import('@lincyaw/kernel').DocumentHistoryChange): Promise<import('@lincyaw/kernel').DocumentHistoryChanged>
144
151
  /** Takes back the document's latest change; `expect` is the `undo` of the history read, refused when it is not the latest any more. */
@@ -169,9 +176,16 @@ export interface AuthoringClientChannel {
169
176
  close(): void
170
177
  }
171
178
  export type AuthoringClientSubscription = (document: string, open: import('@lincyaw/kernel').AuthoringClientOpen, received: (event: import('@lincyaw/kernel').AuthoringClientEvent) => void, failed: () => void) => AuthoringClientChannel
179
+ export interface AuthoringWindowChannel {
180
+ publish(connectionId: string, report: import('@lincyaw/kernel').AuthoringWindowReport): Promise<void>
181
+ acknowledge(connectionId: string, report: import('@lincyaw/kernel').AuthoringWindowAcknowledgement): Promise<void>
182
+ close(): void
183
+ }
184
+ export type AuthoringWindowSubscription = (open: import('@lincyaw/kernel').AuthoringWindowOpen, received: (event: import('@lincyaw/kernel').AuthoringWindowEvent) => void, failed: () => void) => AuthoringWindowChannel
172
185
  export interface WorkspaceSubscription {
173
186
  (address: string, event: string, received: (data: string, event?: string) => void, failed?: () => void, ready?: () => void): () => void
174
187
  openAuthoringClient?: AuthoringClientSubscription
188
+ openAuthoringWindow?: AuthoringWindowSubscription
175
189
  }
176
190
 
177
191
  /** A remote host may add its CSRF header without replacing the page's global fetch. */
@@ -328,7 +342,9 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
328
342
  }
329
343
  const projectIntents = new Map<string, { id: string, plan?: ProjectPlan }>()
330
344
  return client = {
345
+ subscribeAgentActivity: (received, failed) => subscribe(url('agent-activity/events', ''), 'agent-activity', received, failed),
331
346
  ...subscription?.openAuthoringClient ? { openAuthoringClient: subscription.openAuthoringClient } : {},
347
+ ...subscription?.openAuthoringWindow ? { openAuthoringWindow: subscription.openAuthoringWindow } : {},
332
348
  ...subscription ? { subscribePreviewEvents: ((target, received) => {
333
349
  const address = new URL(base, globalThis.document.baseURI)
334
350
  for (const [key, value] of Object.entries(target)) if (key !== 'topic') address.searchParams.set(key, value)
@@ -341,7 +357,7 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
341
357
  if (operation.op === 'delete' && (!planned || JSON.stringify(planned.operation) !== JSON.stringify(operation))) throw new Error('project-deletion-plan-required')
342
358
  const key = JSON.stringify(operation)
343
359
  let intent = projectIntents.get(key)
344
- if (!intent) { intent = { id: crypto.randomUUID() }; projectIntents.set(key, intent) }
360
+ if (!intent) { intent = { id: randomUUID() }; projectIntents.set(key, intent) }
345
361
  while (projectIntents.size > 64) projectIntents.delete(projectIntents.keys().next().value!)
346
362
  try {
347
363
  intent.plan ??= planned
@@ -358,13 +374,13 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
358
374
  saveSource: (document, path, content, base, message) => post(url('source', document), { path, content, base, ...message ? { message } : {} }),
359
375
  saveSourceTransaction: (document, changes, message) => post(url('source/transaction', document), { changes, ...message ? { message } : {} }),
360
376
  readIr,
361
- readDocument: document => call(url('document', document)),
377
+ readDocument: (document, signal) => call(url('document', document), { signal }),
362
378
  readAuthoringCapabilities: (document, signal) => call(url('document/capabilities', document), { signal }),
363
379
  planDocumentAction: (document, request, signal) => post(url('document/action/plan', document), request, signal),
364
380
  readDocumentActionPlan: (document, reference, signal) => call(url('document/action/plan', document, { planId: reference.planId, digest: reference.digest }), { signal }),
365
381
  applyDocumentAction: (document, reference, signal) => post(url('document/action/apply', document), reference, signal),
366
382
  documentAssetURL: (document, asset) => url('document/asset', document, { asset }),
367
- changeDocument: (document, change) => post(url('document/change', document), change),
383
+ changeDocument: (document, change, signal) => post(url('document/change', document), change, signal),
368
384
  importDocumentImage: (document, file, change, signal) => {
369
385
  const body = new FormData()
370
386
  body.set('change', JSON.stringify(change)); body.set('file', file)
@@ -389,6 +405,9 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
389
405
  subscribeDocument: (document, changed, failed) => subscribe(url('document/events', document), 'document', changed, failed),
390
406
  readPageDeletion: (document, section) => call(url('pages/delete', document, { section })),
391
407
  deletePage: (document, request) => post(url('pages/delete', document), request),
408
+ readMcpSettings: signal => call(url('mcp-settings'), { signal }),
409
+ changeMcpSettings: (change, signal) => post(url('mcp-settings'), change, signal),
410
+ exportMcpSettings: (revision, signal) => post(url('mcp-settings'), { action: 'export', revision }, signal),
392
411
  readSpeechSettings: signal => call(url('speech-settings'), { signal }),
393
412
  changeSpeechSettings: (change, signal) => post(url('speech-settings'), change, signal),
394
413
  readVoiceCatalog: (document, engine, lang, signal) => call(url('voice-catalog', document, { ...engine ? { engine } : {}, ...lang ? { lang } : {} }), { signal }),
@@ -433,20 +452,20 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
433
452
  })
434
453
  return workbenchInfo
435
454
  },
436
- readFocus: document => call(url('focus', document)),
455
+ readFocus: (document, signal) => call(url('focus', document), { signal }),
437
456
  writeFocus: (document, focus) => post(url('focus'), { document, focus }),
438
457
  subscribeReview: (document, update) => subscribe(url('review', document), 'review', update),
439
458
  acceptReview: (document, body) => post(url('review/accept', document), body),
440
459
  rejectReview: (document, paths) => post(url('review/reject', document), paths ? { paths } : {}),
441
460
  restoreReview: (document, step) => post(url('review/restore', document), { step }),
442
- readChanges: document => call(url('changes', document)),
461
+ readChanges: (document, signal) => call(url('changes', document), { signal }),
443
462
  commitChanges: (document, message, paths) => post(url('changes/commit', document), { message, ...paths ? { paths } : {} }),
444
463
  discardChanges: (document, paths) => post(url('changes/discard', document), paths ? { paths } : {}),
445
464
  readJobs: document => call(url('jobs', document)),
446
465
  startJob: (document, target, source) => post(url('jobs', document), { target, source } satisfies StartJobRequest),
447
466
  cancelJob: (document, id) => post(url('jobs/cancel', document), { id }),
448
467
  subscribeJobs: (document, changed, failed, ready) => subscribe(url('jobs/events', document), 'job', changed, failed, ready),
449
- readRevisions: (document, query = {}) => call(url('revisions', document, { query: JSON.stringify(query) })),
468
+ readRevisions: (document, query = {}, signal) => call(url('revisions', document, { query: JSON.stringify(query) }), { signal }),
450
469
  readHistoryFile: (document, query) => call(url('history/file', document, { query: JSON.stringify(query) })),
451
470
  revertRevision: (document, request) => post(url('revisions/revert', document), request),
452
471
  undo: (document, request) => post(url('history/undo', document), request),
@@ -1,62 +0,0 @@
1
- // What the kitten beside the assistant does, from what the assistant is doing: asking the author to approve
2
- // something, reading the document it was asked about, writing into it, thinking, just finished, or idle (sitting,
3
- // then lying down, then asleep the longer nothing happens).
4
- import { useEffect, useState } from 'react'
5
- import type { MascotAction } from '@lincyaw/design/mascot'
6
- import { useWorkbench, useWorkbenchState } from './context.tsx'
7
-
8
- const DONE_MS = 2400
9
- const LOAF_MS = 90_000
10
- const SLEEP_MS = 300_000
11
-
12
- export interface AssistantActivity {
13
- /** The assistant's turn is running. */
14
- running: boolean
15
- /** It holds a review of the open document: still working in it, and how many changes it has made. */
16
- review?: { running: boolean, changes: number }
17
- /** Operations wait for the author's approval. */
18
- approvals: number
19
- /** How long ago the assistant last stopped, in milliseconds (Infinity if it has not run). */
20
- sinceStopped: number
21
- }
22
-
23
- export function assistantMascotAction(a: AssistantActivity): MascotAction {
24
- if (a.approvals > 0) return 'ask'
25
- if (a.review?.running) return a.review.changes > 0 ? 'write' : 'read'
26
- if (a.running) return 'think'
27
- if (a.review && a.review.changes > 0) return 'ask'
28
- if (a.sinceStopped < DONE_MS) return 'done'
29
- if (a.sinceStopped > SLEEP_MS) return 'sleep'
30
- if (a.sinceStopped > LOAF_MS) return 'loaf'
31
- return 'sit'
32
- }
33
-
34
- /** The kitten's action for the assistant, given whether its turn is running; follows the workbench's review and the
35
- * operations waiting for approval, and moves on by itself as time passes. */
36
- export function useAssistantMascot(running: boolean): MascotAction {
37
- const { client } = useWorkbench()
38
- // two plain values rather than one object, so the selection compares equal while nothing changes
39
- const reviewRunning = useWorkbenchState(state => state.review?.running)
40
- const changes = useWorkbenchState(state => state.review?.changes.length)
41
- const review = reviewRunning === undefined ? undefined : { running: reviewRunning, changes: changes ?? 0 }
42
- const [approvals, setApprovals] = useState<string[]>([])
43
- const [stoppedAt, setStoppedAt] = useState<number>(() => performance.now() - LOAF_MS / 2)
44
- const [, setNow] = useState(0)
45
- const busy = running || Boolean(review?.running)
46
- useEffect(() => client.subscribeApprovals(event => {
47
- if (event.type === 'reset') setApprovals([])
48
- else if (event.type === 'settled') setApprovals(list => list.filter(id => id !== event.id))
49
- else setApprovals(list => list.includes(event.id) ? list : [...list, event.id])
50
- }), [client])
51
- useEffect(() => { if (!busy) setStoppedAt(performance.now()) }, [busy])
52
- // Wake up at the next moment the idle kitten changes what it does.
53
- const since = performance.now() - stoppedAt
54
- useEffect(() => {
55
- if (busy) return
56
- const next = [DONE_MS, LOAF_MS, SLEEP_MS].find(ms => ms > since)
57
- if (next === undefined) return
58
- const timer = setTimeout(() => setNow(performance.now()), next - since + 50)
59
- return () => clearTimeout(timer)
60
- }, [busy, since])
61
- return assistantMascotAction({ running, review, approvals: approvals.length, sinceStopped: busy ? 0 : since })
62
- }
@@ -1,37 +0,0 @@
1
- // Whether the author wants the kitten: one choice for every place it shows, kept in this browser and followed by
2
- // every open tab. It is on until the author turns it off.
3
- import { useSyncExternalStore } from 'react'
4
-
5
- const KEY = 'presmium.mascot'
6
- const listeners = new Set<() => void>()
7
-
8
- function read(): boolean {
9
- try { return localStorage.getItem(KEY) !== 'off' } catch { return true }
10
- }
11
-
12
- let enabled = typeof localStorage === 'undefined' ? true : read()
13
-
14
- function subscribe(listener: () => void): () => void {
15
- listeners.add(listener)
16
- const storage = (event: StorageEvent) => {
17
- if (event.key !== KEY) return
18
- enabled = read()
19
- for (const each of listeners) each()
20
- }
21
- window.addEventListener('storage', storage)
22
- return () => { listeners.delete(listener); window.removeEventListener('storage', storage) }
23
- }
24
-
25
- export function mascotEnabled(): boolean {
26
- return enabled
27
- }
28
-
29
- export function setMascotEnabled(on: boolean): void {
30
- enabled = on
31
- try { localStorage.setItem(KEY, on ? 'on' : 'off') } catch { /* The choice holds for this page only. */ }
32
- for (const listener of listeners) listener()
33
- }
34
-
35
- export function useMascotEnabled(): boolean {
36
- return useSyncExternalStore(subscribe, mascotEnabled, () => true)
37
- }
@@ -1,79 +0,0 @@
1
- import { useEffect, useRef, useState } from 'react'
2
- import type { CSSProperties, RefObject } from 'react'
3
- import type { MascotAction } from '@lincyaw/design/mascot'
4
- import { PmMascot } from '../components.tsx'
5
- import { useMascotEnabled } from '../mascot-preference.ts'
6
- import { useWorkbenchState } from '../context.tsx'
7
- import { pageId, richNodeIds } from '../document-editor/projection.ts'
8
-
9
- /** How long the kitten walks from one changed place to the next, pats it, and stays when it is done (ms). */
10
- const WALK_MS = 700, PAT_MS = 900, DONE_MS = 2200
11
- /** At most this many changed places are visited. */
12
- const STOPS = 6
13
-
14
- type Point = { x: number, y: number }
15
- type Phase = 'walk' | 'pat' | 'done' | 'gone'
16
-
17
- /**
18
- * The kitten visiting a list of points in its host (each the lower left of a changed place): it walks to each, pats it,
19
- * hops when it is done and leaves. A new `id` starts it again from the first point; `where(i)` is asked on every
20
- * render, so the kitten follows the places as the host lays out again. Nothing shows when the kitten is turned off.
21
- */
22
- function KittenTrail({ id, count, where }: { id: number | undefined, count: number, where(index: number): Point | undefined }) {
23
- const enabled = useMascotEnabled()
24
- const [step, setStep] = useState<{ id: number, stop: number, phase: Phase }>()
25
- const facing = useRef<'left' | 'right'>('right'), last = useRef<Point>()
26
- useEffect(() => {
27
- if (id !== undefined && count > 0) setStep(current => current?.id === id ? current : { id, stop: 0, phase: 'walk' })
28
- }, [id, count])
29
- useEffect(() => {
30
- if (!step || step.phase === 'gone') return
31
- const stops = Math.min(STOPS, count)
32
- const next: typeof step = step.phase === 'walk' ? { ...step, phase: 'pat' }
33
- : step.phase === 'pat' ? (step.stop + 1 < stops ? { ...step, stop: step.stop + 1, phase: 'walk' } : { ...step, phase: 'done' })
34
- : { ...step, phase: 'gone' }
35
- const timer = setTimeout(() => setStep(next), step.phase === 'walk' ? WALK_MS : step.phase === 'pat' ? PAT_MS : DONE_MS)
36
- return () => clearTimeout(timer)
37
- }, [step, count])
38
- if (!enabled || !step || step.phase === 'gone' || step.id !== id) return null
39
- const point = where(Math.min(step.stop, count - 1))
40
- if (!point) return null
41
- if (last.current && Math.abs(point.x - last.current.x) > 2 && step.phase === 'walk') facing.current = point.x < last.current.x ? 'left' : 'right'
42
- if (step.phase === 'walk') last.current = point
43
- const action: MascotAction = step.phase === 'walk' ? 'walk' : step.phase === 'pat' ? 'write' : 'done'
44
- return (
45
- <div className="pmw-change-trail" data-phase={step.phase} style={{ '--pmw-trail-x': `${point.x}px`, '--pmw-trail-y': `${point.y}px` } as CSSProperties}>
46
- <div className="pmw-change-trail__facing" data-facing={facing.current}><PmMascot size="small" action={action} /></div>
47
- </div>
48
- )
49
- }
50
-
51
- /** In the preview: the blocks the preview reports blinking, in the active frame's viewport. */
52
- export function PreviewChangeTrail({ stage, frames }: { stage: RefObject<HTMLDivElement | null>, frames: RefObject<HTMLDivElement | null> }) {
53
- const trail = useWorkbenchState(state => state.changeTrail)
54
- return <KittenTrail id={trail?.id} count={trail?.rects.length ?? 0} where={index => {
55
- const rect = trail?.rects[index]
56
- const frame = frames.current?.querySelector<HTMLIFrameElement>('iframe[data-active="true"]:not([hidden])')
57
- const host = stage.current
58
- if (!rect || !frame || !host) return undefined
59
- const offset = frame.getBoundingClientRect(), origin = host.getBoundingClientRect()
60
- return { x: offset.left - origin.left + rect.x, y: offset.top - origin.top + rect.y + rect.height }
61
- }} />
62
- }
63
-
64
- /** In the editor: each changed block (a text block by its first paragraph), else its page's title, on the sheet. */
65
- export function EditorChangeTrail({ sheet }: { sheet: RefObject<HTMLDivElement | null> }) {
66
- const places = useWorkbenchState(state => state.changedPlaces)
67
- const content = useWorkbenchState(state => state.authoring?.content)
68
- return <KittenTrail id={places?.id} count={places?.targets.length ?? 0} where={index => {
69
- const target = places?.targets[index], host = sheet.current
70
- if (!target || !host) return undefined
71
- const block = target.block ? content?.blocks[target.block] : undefined
72
- const ids = [...target.block ? [target.block] : [], ...block?.type === 'text' ? richNodeIds(block.content) : [], pageId(target.section)]
73
- const element = ids.map(id => host.querySelector<HTMLElement>(`[data-id="${CSS.escape(id)}"]`)).find(Boolean)
74
- if (!element) return undefined
75
- const box = element.getBoundingClientRect(), origin = host.getBoundingClientRect()
76
- // the kitten stands on the place's first line, at its left edge
77
- return { x: box.left - origin.left, y: box.top - origin.top + Math.min(box.height, 28) }
78
- }} />
79
- }