@lincyaw/workbench 0.2.0-rc.10 → 0.2.0-rc.100

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 (100) 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.ts +27 -5
  9. package/src/authoring-client.ts +10 -10
  10. package/src/authoring-draft-fragment.ts +3 -1
  11. package/src/authoring-window.ts +100 -0
  12. package/src/body-draft-actions.ts +60 -0
  13. package/src/caption-timing-drafts.ts +18 -1
  14. package/src/component-property-drafts.ts +5 -5
  15. package/src/components.tsx +34 -36
  16. package/src/container-layout.ts +21 -0
  17. package/src/context.tsx +5 -3
  18. package/src/diagnostics.ts +1 -1
  19. package/src/document-draft-store.ts +45 -18
  20. package/src/document-drafts.ts +28 -19
  21. package/src/document-editing.ts +484 -0
  22. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  23. package/src/document-editor/CommentComposer.tsx +24 -0
  24. package/src/document-editor/ComponentMaterials.tsx +3 -9
  25. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  26. package/src/document-editor/DocumentBlockPreview.tsx +11 -4
  27. package/src/document-editor/DocumentComments.tsx +85 -14
  28. package/src/document-editor/DocumentEditor.tsx +56 -7
  29. package/src/document-editor/DocumentStepNarration.tsx +37 -26
  30. package/src/document-editor/NarrationEditor.tsx +54 -20
  31. package/src/document-editor/NewCommentDrafts.tsx +120 -37
  32. package/src/document-editor/PlaceComment.tsx +252 -0
  33. package/src/document-editor/agent-targets.ts +34 -0
  34. package/src/document-editor/blocknote-messages.ts +2 -0
  35. package/src/document-editor/comment-draft-actions.ts +40 -20
  36. package/src/document-editor/comment-draft-inspection.ts +2 -2
  37. package/src/document-editor/comment-drafts.ts +73 -25
  38. package/src/document-editor/comments.ts +30 -10
  39. package/src/document-editor/component-label.ts +11 -0
  40. package/src/document-editor/file-input.ts +2 -2
  41. package/src/document-editor/focus.ts +0 -2
  42. package/src/document-editor/insertion-place.ts +60 -0
  43. package/src/document-editor/messages.ts +3 -3
  44. package/src/document-editor/narration-schema.tsx +12 -6
  45. package/src/document-editor/narration.ts +19 -3
  46. package/src/document-editor/page-body.ts +60 -0
  47. package/src/document-editor/popover.tsx +4 -2
  48. package/src/document-editor/projection.ts +2 -2
  49. package/src/document-editor/rich-text.ts +3 -2
  50. package/src/document-editor/selection.ts +13 -0
  51. package/src/document-editor/style.css +7 -1
  52. package/src/document-editor/table-identities.ts +2 -1
  53. package/src/document-production.ts +491 -0
  54. package/src/document-session.ts +202 -56
  55. package/src/document-timing-drafts.ts +22 -2
  56. package/src/history.ts +5 -5
  57. package/src/index.ts +8 -5
  58. package/src/jobs.ts +1 -1
  59. package/src/media-drafts.ts +43 -1
  60. package/src/messages.ts +31 -14
  61. package/src/panels/DocumentNarrationPanel.tsx +2 -2
  62. package/src/panels/DocumentView.tsx +93 -61
  63. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  64. package/src/panels/DocumentVoiceField.tsx +1 -1
  65. package/src/panels/ExportPanel.tsx +2 -10
  66. package/src/panels/HistoryPanel.tsx +34 -7
  67. package/src/panels/HomePanel.tsx +3 -1
  68. package/src/panels/PageDeleteDialog.tsx +4 -4
  69. package/src/panels/PageRenameDialog.tsx +1 -1
  70. package/src/panels/PreviewPanel.tsx +1 -4
  71. package/src/panels/ProductionCaptionSize.tsx +20 -0
  72. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  73. package/src/panels/ProductionMediaClips.tsx +23 -7
  74. package/src/panels/ProductionPanel.tsx +16 -13
  75. package/src/panels/ProductionRecording.tsx +86 -9
  76. package/src/panels/ProductionRecordingRange.tsx +21 -19
  77. package/src/panels/ProductionTimeline.tsx +6 -1
  78. package/src/panels/ProductionTranscription.tsx +5 -4
  79. package/src/panels/SourceDocumentPanel.tsx +18 -36
  80. package/src/panels/TranscriptionAdoption.tsx +40 -34
  81. package/src/panels/VoiceCloneDialog.tsx +2 -1
  82. package/src/panels/VoiceoverDialog.tsx +1 -1
  83. package/src/places.ts +1 -36
  84. package/src/preview-playback.ts +1 -1
  85. package/src/production-draft-actions.ts +37 -0
  86. package/src/production-messages.ts +6 -0
  87. package/src/production-playback.ts +1 -1
  88. package/src/production-voice-playback.ts +3 -2
  89. package/src/sha256.ts +9 -0
  90. package/src/styles.css +43 -79
  91. package/src/transcription-drafts.ts +124 -0
  92. package/src/use-recording-adoption.ts +2 -2
  93. package/src/voice-drafts.ts +32 -8
  94. package/src/voiceover-jobs.ts +1 -1
  95. package/src/workbench-state.ts +159 -0
  96. package/src/workbench.ts +294 -951
  97. package/src/workspace-client.ts +23 -11
  98. package/src/assistant-mascot.ts +0 -62
  99. package/src/mascot-preference.ts +0 -37
  100. package/src/panels/ChangeTrail.tsx +0 -79
@@ -13,6 +13,7 @@ import type { DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, Docu
13
13
  import type { DocumentImageImport, DocumentImageImportAnswer } from '@lincyaw/kernel'
14
14
  import type { ProductionAssetAnswer, ProductionAssetQuery, ProductionMediaQuery, ProductionPlan, ProductionPlanQuery } from '@lincyaw/kernel'
15
15
  import type { DocumentTranscriptionRequest, TranscriptionCapabilities, TranscriptionTask, TranscriptionListAnswer, TranscriptionRevision, TranscriptionCancellation, TranscriptionAdoptionDraft, TranscriptionAdoptionPlan, TranscriptionAdoptionApply, TranscriptionAdoptionAnswer } from '@lincyaw/kernel'
16
+ import { randomUUID } from '@lincyaw/kernel'
16
17
 
17
18
  /** A change of the host's pending approvals that this author may answer. */
18
19
  export type ApprovalEvent =
@@ -64,12 +65,14 @@ export interface WorkspaceCapabilities {
64
65
  }
65
66
 
66
67
  export interface WorkspaceClient {
68
+ subscribeAgentActivity?(received: (snapshot: import('@lincyaw/kernel').AgentActivitySnapshot) => void, failed: () => void): () => void
67
69
  readSpeechSettings?(signal?: AbortSignal): Promise<SpeechSettingsAnswer>
68
70
  changeSpeechSettings?(change: SpeechSettingsChange, signal?: AbortSignal): Promise<SpeechSettingsAnswer>
69
71
  openSpeechSettings?(): boolean
70
72
  capabilities?: Readonly<WorkspaceCapabilities>
71
73
  subscribePreviewEvents?: PreviewEventSubscription
72
74
  openAuthoringClient?: AuthoringClientSubscription
75
+ openAuthoringWindow?: AuthoringWindowSubscription
73
76
  subscribeRequests?(listener: (event: WorkspaceRequestEvent) => void): () => void
74
77
  readDocuments(document?: string): Promise<DocumentsAnswer>
75
78
  planProjectChange(request: ProjectPlanRequest): Promise<ProjectPlan>
@@ -80,14 +83,14 @@ export interface WorkspaceClient {
80
83
  /** Saves a small set of files in one document with one version and rollback boundary. */
81
84
  saveSourceTransaction(document: string, changes: SourceTransactionChange[], message?: string): Promise<SourceTransactionAnswer>
82
85
  readIr(document: string): Promise<IrAnswer>
83
- readDocument(document: string): Promise<DocumentAnswer>
86
+ readDocument(document: string, signal?: AbortSignal): Promise<DocumentAnswer>
84
87
  readAuthoringCapabilities(document: string, signal?: AbortSignal): Promise<AuthoringCapabilities>
85
88
  planDocumentAction(document: string, request: DocumentAuthoringActionRequest, signal?: AbortSignal): Promise<DocumentAuthoringActionPlan>
86
89
  readDocumentActionPlan(document: string, reference: DocumentAuthoringActionRead, signal?: AbortSignal): Promise<DocumentAuthoringActionInspection>
87
90
  applyDocumentAction(document: string, reference: DocumentAuthoringActionReference, signal?: AbortSignal): Promise<AppliedDocumentAuthoringAction>
88
91
  /** A same-origin display URL; the canonical asset location remains untouched. */
89
92
  documentAssetURL(document: string, assetId: string): string
90
- changeDocument(document: string, change: DocumentChange): Promise<DocumentChangeAnswer>
93
+ changeDocument(document: string, change: DocumentChange, signal?: AbortSignal): Promise<DocumentChangeAnswer>
91
94
  importDocumentImage(document: string, file: File, change: DocumentImageImport, signal?: AbortSignal): Promise<DocumentImageImportAnswer>
92
95
  readDocumentAudio(document: string, assetId: string, baseDocumentVersion: string, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer>
93
96
  importDocumentAudio(document: string, file: File, change: DocumentAudioImport, signal?: AbortSignal): Promise<DocumentAudioImportAnswer>
@@ -129,16 +132,16 @@ export interface WorkspaceClient {
129
132
  prefetchPreview(document: string, renderer: PreviewRenderer): Promise<PreviewAnswer>
130
133
  /** The MCP address and the workspace root, read once. */
131
134
  readWorkbenchInfo(): Promise<WorkbenchAnswer>
132
- readFocus(document: string): Promise<FocusAnswer>
135
+ readFocus(document: string, signal?: AbortSignal): Promise<FocusAnswer>
133
136
  writeFocus(document: string, focus: FocusReport[]): Promise<FocusAnswer>
134
137
  subscribeReview(document: string, update: (event: ReviewUpdate) => void): () => void
135
138
  acceptReview(document: string, body: { reject?: string[], message?: string }): Promise<{ ended: ReviewEnd }>
136
139
  rejectReview(document: string, paths?: string[]): Promise<ReviewUpdate>
137
140
  restoreReview(document: string, step: string): Promise<{ review: ReviewSnapshot }>
138
- readChanges(document: string): Promise<{ files: UncommittedFile[] }>
141
+ readChanges(document: string, signal?: AbortSignal): Promise<{ files: UncommittedFile[] }>
139
142
  commitChanges(document: string, message: string, paths?: string[]): Promise<unknown>
140
143
  discardChanges(document: string, paths?: string[]): Promise<unknown>
141
- readRevisions(document: string, query?: import('@lincyaw/kernel').DocumentHistoryQuery): Promise<RevisionsAnswer>
144
+ readRevisions(document: string, query?: import('@lincyaw/kernel').DocumentHistoryQuery, signal?: AbortSignal): Promise<RevisionsAnswer>
142
145
  readHistoryFile(document: string, query: import('@lincyaw/kernel').DocumentHistoryRead): Promise<import('@lincyaw/kernel').DocumentHistoryFile>
143
146
  revertRevision(document: string, request: import('@lincyaw/kernel').DocumentHistoryChange): Promise<import('@lincyaw/kernel').DocumentHistoryChanged>
144
147
  /** 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 +172,16 @@ export interface AuthoringClientChannel {
169
172
  close(): void
170
173
  }
171
174
  export type AuthoringClientSubscription = (document: string, open: import('@lincyaw/kernel').AuthoringClientOpen, received: (event: import('@lincyaw/kernel').AuthoringClientEvent) => void, failed: () => void) => AuthoringClientChannel
175
+ export interface AuthoringWindowChannel {
176
+ publish(connectionId: string, report: import('@lincyaw/kernel').AuthoringWindowReport): Promise<void>
177
+ acknowledge(connectionId: string, report: import('@lincyaw/kernel').AuthoringWindowAcknowledgement): Promise<void>
178
+ close(): void
179
+ }
180
+ export type AuthoringWindowSubscription = (open: import('@lincyaw/kernel').AuthoringWindowOpen, received: (event: import('@lincyaw/kernel').AuthoringWindowEvent) => void, failed: () => void) => AuthoringWindowChannel
172
181
  export interface WorkspaceSubscription {
173
182
  (address: string, event: string, received: (data: string, event?: string) => void, failed?: () => void, ready?: () => void): () => void
174
183
  openAuthoringClient?: AuthoringClientSubscription
184
+ openAuthoringWindow?: AuthoringWindowSubscription
175
185
  }
176
186
 
177
187
  /** A remote host may add its CSRF header without replacing the page's global fetch. */
@@ -328,7 +338,9 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
328
338
  }
329
339
  const projectIntents = new Map<string, { id: string, plan?: ProjectPlan }>()
330
340
  return client = {
341
+ subscribeAgentActivity: (received, failed) => subscribe(url('agent-activity/events', ''), 'agent-activity', received, failed),
331
342
  ...subscription?.openAuthoringClient ? { openAuthoringClient: subscription.openAuthoringClient } : {},
343
+ ...subscription?.openAuthoringWindow ? { openAuthoringWindow: subscription.openAuthoringWindow } : {},
332
344
  ...subscription ? { subscribePreviewEvents: ((target, received) => {
333
345
  const address = new URL(base, globalThis.document.baseURI)
334
346
  for (const [key, value] of Object.entries(target)) if (key !== 'topic') address.searchParams.set(key, value)
@@ -341,7 +353,7 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
341
353
  if (operation.op === 'delete' && (!planned || JSON.stringify(planned.operation) !== JSON.stringify(operation))) throw new Error('project-deletion-plan-required')
342
354
  const key = JSON.stringify(operation)
343
355
  let intent = projectIntents.get(key)
344
- if (!intent) { intent = { id: crypto.randomUUID() }; projectIntents.set(key, intent) }
356
+ if (!intent) { intent = { id: randomUUID() }; projectIntents.set(key, intent) }
345
357
  while (projectIntents.size > 64) projectIntents.delete(projectIntents.keys().next().value!)
346
358
  try {
347
359
  intent.plan ??= planned
@@ -358,13 +370,13 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
358
370
  saveSource: (document, path, content, base, message) => post(url('source', document), { path, content, base, ...message ? { message } : {} }),
359
371
  saveSourceTransaction: (document, changes, message) => post(url('source/transaction', document), { changes, ...message ? { message } : {} }),
360
372
  readIr,
361
- readDocument: document => call(url('document', document)),
373
+ readDocument: (document, signal) => call(url('document', document), { signal }),
362
374
  readAuthoringCapabilities: (document, signal) => call(url('document/capabilities', document), { signal }),
363
375
  planDocumentAction: (document, request, signal) => post(url('document/action/plan', document), request, signal),
364
376
  readDocumentActionPlan: (document, reference, signal) => call(url('document/action/plan', document, { planId: reference.planId, digest: reference.digest }), { signal }),
365
377
  applyDocumentAction: (document, reference, signal) => post(url('document/action/apply', document), reference, signal),
366
378
  documentAssetURL: (document, asset) => url('document/asset', document, { asset }),
367
- changeDocument: (document, change) => post(url('document/change', document), change),
379
+ changeDocument: (document, change, signal) => post(url('document/change', document), change, signal),
368
380
  importDocumentImage: (document, file, change, signal) => {
369
381
  const body = new FormData()
370
382
  body.set('change', JSON.stringify(change)); body.set('file', file)
@@ -433,20 +445,20 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
433
445
  })
434
446
  return workbenchInfo
435
447
  },
436
- readFocus: document => call(url('focus', document)),
448
+ readFocus: (document, signal) => call(url('focus', document), { signal }),
437
449
  writeFocus: (document, focus) => post(url('focus'), { document, focus }),
438
450
  subscribeReview: (document, update) => subscribe(url('review', document), 'review', update),
439
451
  acceptReview: (document, body) => post(url('review/accept', document), body),
440
452
  rejectReview: (document, paths) => post(url('review/reject', document), paths ? { paths } : {}),
441
453
  restoreReview: (document, step) => post(url('review/restore', document), { step }),
442
- readChanges: document => call(url('changes', document)),
454
+ readChanges: (document, signal) => call(url('changes', document), { signal }),
443
455
  commitChanges: (document, message, paths) => post(url('changes/commit', document), { message, ...paths ? { paths } : {} }),
444
456
  discardChanges: (document, paths) => post(url('changes/discard', document), paths ? { paths } : {}),
445
457
  readJobs: document => call(url('jobs', document)),
446
458
  startJob: (document, target, source) => post(url('jobs', document), { target, source } satisfies StartJobRequest),
447
459
  cancelJob: (document, id) => post(url('jobs/cancel', document), { id }),
448
460
  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) })),
461
+ readRevisions: (document, query = {}, signal) => call(url('revisions', document, { query: JSON.stringify(query) }), { signal }),
450
462
  readHistoryFile: (document, query) => call(url('history/file', document, { query: JSON.stringify(query) })),
451
463
  revertRevision: (document, request) => post(url('revisions/revert', document), request),
452
464
  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
- }