@lincyaw/workbench 0.2.0-rc.12 → 0.2.0-rc.121

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 (124) hide show
  1. package/README.md +1 -1
  2. package/package.json +5 -4
  3. package/src/AgentActivityBar.tsx +25 -0
  4. package/src/MediaClipEditor.tsx +7 -6
  5. package/src/StepProductionEditor.tsx +16 -7
  6. package/src/agent-activity-messages.ts +14 -0
  7. package/src/agent-activity.ts +38 -0
  8. package/src/approvals.tsx +6 -1
  9. package/src/audio-recording-messages.ts +5 -5
  10. package/src/audio-recording.ts +27 -5
  11. package/src/authoring-client.ts +10 -10
  12. package/src/authoring-draft-fragment.ts +3 -1
  13. package/src/authoring-window.ts +100 -0
  14. package/src/base-controls.tsx +28 -7
  15. package/src/body-draft-actions.ts +60 -0
  16. package/src/caption-timing-drafts.ts +20 -3
  17. package/src/caption-timing-messages.ts +2 -2
  18. package/src/caption-timing.ts +2 -2
  19. package/src/component-draft-actions.ts +1 -1
  20. package/src/component-properties.ts +3 -3
  21. package/src/component-property-drafts.ts +6 -6
  22. package/src/components.tsx +43 -38
  23. package/src/container-layout.ts +21 -0
  24. package/src/context.tsx +5 -3
  25. package/src/diagnostics.ts +1 -1
  26. package/src/document-draft-store.ts +45 -18
  27. package/src/document-drafts.ts +30 -21
  28. package/src/document-editing.ts +485 -0
  29. package/src/document-editor/BlockNoteSurface.tsx +40 -14
  30. package/src/document-editor/CommentComposer.tsx +24 -0
  31. package/src/document-editor/ComponentMaterials.tsx +4 -10
  32. package/src/document-editor/ComponentPropertiesDialog.tsx +12 -12
  33. package/src/document-editor/DocumentBlockFallback.tsx +4 -3
  34. package/src/document-editor/DocumentBlockPreview.tsx +11 -4
  35. package/src/document-editor/DocumentComments.tsx +87 -17
  36. package/src/document-editor/DocumentEditor.tsx +66 -14
  37. package/src/document-editor/DocumentStepNarration.tsx +39 -27
  38. package/src/document-editor/NarrationEditor.tsx +55 -21
  39. package/src/document-editor/NewCommentDrafts.tsx +120 -37
  40. package/src/document-editor/PlaceComment.tsx +252 -0
  41. package/src/document-editor/agent-targets.ts +34 -0
  42. package/src/document-editor/blocknote-messages.ts +2 -0
  43. package/src/document-editor/comment-draft-actions.ts +40 -20
  44. package/src/document-editor/comment-draft-inspection.ts +2 -2
  45. package/src/document-editor/comment-drafts.ts +75 -27
  46. package/src/document-editor/comments.ts +34 -14
  47. package/src/document-editor/component-label.ts +11 -0
  48. package/src/document-editor/file-input.ts +2 -2
  49. package/src/document-editor/focus.ts +0 -2
  50. package/src/document-editor/inline.ts +1 -0
  51. package/src/document-editor/insertion-place.ts +60 -0
  52. package/src/document-editor/messages.ts +3 -3
  53. package/src/document-editor/narration-schema.tsx +12 -6
  54. package/src/document-editor/narration.ts +19 -3
  55. package/src/document-editor/page-body.ts +60 -0
  56. package/src/document-editor/popover.tsx +4 -2
  57. package/src/document-editor/projection.ts +21 -19
  58. package/src/document-editor/rich-text.ts +3 -2
  59. package/src/document-editor/selection.ts +13 -0
  60. package/src/document-editor/style.css +8 -3
  61. package/src/document-editor/table-identities.ts +2 -1
  62. package/src/document-preview.ts +3 -2
  63. package/src/document-production.ts +492 -0
  64. package/src/document-return-point.ts +2 -2
  65. package/src/document-session.ts +216 -67
  66. package/src/document-timing-drafts.ts +26 -6
  67. package/src/effective-settings.ts +12 -0
  68. package/src/history.ts +5 -5
  69. package/src/import-messages.ts +40 -0
  70. package/src/index.ts +11 -5
  71. package/src/jobs.ts +1 -1
  72. package/src/mcp-settings-messages.ts +39 -0
  73. package/src/media-drafts.ts +43 -1
  74. package/src/messages.ts +39 -18
  75. package/src/outline.ts +5 -5
  76. package/src/panels/DocumentImportDialog.tsx +59 -0
  77. package/src/panels/DocumentNarrationPanel.tsx +2 -2
  78. package/src/panels/DocumentView.tsx +106 -77
  79. package/src/panels/DocumentVoiceDialog.tsx +29 -12
  80. package/src/panels/DocumentVoiceField.tsx +3 -2
  81. package/src/panels/ExportPanel.tsx +2 -10
  82. package/src/panels/HistoryPanel.tsx +36 -10
  83. package/src/panels/HomePanel.tsx +12 -1
  84. package/src/panels/McpSettingsPanel.tsx +86 -0
  85. package/src/panels/PageDeleteDialog.tsx +4 -4
  86. package/src/panels/PageRenameDialog.tsx +1 -1
  87. package/src/panels/PreviewPanel.tsx +4 -7
  88. package/src/panels/ProductionCaptionSize.tsx +20 -0
  89. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  90. package/src/panels/ProductionMediaClips.tsx +25 -9
  91. package/src/panels/ProductionPanel.tsx +21 -17
  92. package/src/panels/ProductionRecording.tsx +86 -9
  93. package/src/panels/ProductionRecordingRange.tsx +26 -23
  94. package/src/panels/ProductionTimeline.tsx +6 -1
  95. package/src/panels/ProductionTranscription.tsx +8 -6
  96. package/src/panels/SourceDocumentPanel.tsx +24 -40
  97. package/src/panels/SpeechSettingsPanel.tsx +2 -2
  98. package/src/panels/TranscriptionAdoption.tsx +42 -36
  99. package/src/panels/VoiceCloneDialog.tsx +2 -1
  100. package/src/panels/VoicePreviewDialog.tsx +1 -1
  101. package/src/panels/VoiceScopeField.tsx +2 -2
  102. package/src/panels/VoiceoverDialog.tsx +11 -10
  103. package/src/places.ts +1 -36
  104. package/src/preview-playback.ts +1 -1
  105. package/src/production-draft-actions.ts +37 -0
  106. package/src/production-messages.ts +6 -0
  107. package/src/production-playback.ts +1 -1
  108. package/src/production-voice-playback.ts +3 -2
  109. package/src/recording-adoption.ts +4 -4
  110. package/src/sha256.ts +9 -0
  111. package/src/speech-settings-messages.ts +6 -6
  112. package/src/step-production.ts +4 -4
  113. package/src/styles.css +43 -92
  114. package/src/transcription-drafts.ts +124 -0
  115. package/src/use-recording-adoption.ts +5 -4
  116. package/src/voice-drafts.ts +32 -8
  117. package/src/voice-messages.ts +9 -9
  118. package/src/voiceover-jobs.ts +1 -1
  119. package/src/workbench-state.ts +159 -0
  120. package/src/workbench.ts +323 -956
  121. package/src/workspace-client.ts +41 -12
  122. package/src/assistant-mascot.ts +0 -62
  123. package/src/mascot-preference.ts +0 -37
  124. 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,14 +66,22 @@ 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>
82
+ importDocuments?(files: readonly File[], signal?: AbortSignal): Promise<import('@lincyaw/kernel').DocumentImportAnswer>
83
+ /** Converts the workspace's documents to the current format, one revision per document. */
84
+ migrateWorkspace?(): Promise<import('@lincyaw/kernel').WorkspaceMigrationAnswer>
75
85
  planProjectChange(request: ProjectPlanRequest): Promise<ProjectPlan>
76
86
  operateDocument(operation: ProjectOperation, planned?: ProjectPlan): Promise<OperationAnswer>
77
87
  readSource(document: string, path: string): Promise<SourceAnswer>
@@ -80,14 +90,14 @@ export interface WorkspaceClient {
80
90
  /** Saves a small set of files in one document with one version and rollback boundary. */
81
91
  saveSourceTransaction(document: string, changes: SourceTransactionChange[], message?: string): Promise<SourceTransactionAnswer>
82
92
  readIr(document: string): Promise<IrAnswer>
83
- readDocument(document: string): Promise<DocumentAnswer>
93
+ readDocument(document: string, signal?: AbortSignal): Promise<DocumentAnswer>
84
94
  readAuthoringCapabilities(document: string, signal?: AbortSignal): Promise<AuthoringCapabilities>
85
95
  planDocumentAction(document: string, request: DocumentAuthoringActionRequest, signal?: AbortSignal): Promise<DocumentAuthoringActionPlan>
86
96
  readDocumentActionPlan(document: string, reference: DocumentAuthoringActionRead, signal?: AbortSignal): Promise<DocumentAuthoringActionInspection>
87
97
  applyDocumentAction(document: string, reference: DocumentAuthoringActionReference, signal?: AbortSignal): Promise<AppliedDocumentAuthoringAction>
88
98
  /** A same-origin display URL; the canonical asset location remains untouched. */
89
99
  documentAssetURL(document: string, assetId: string): string
90
- changeDocument(document: string, change: DocumentChange): Promise<DocumentChangeAnswer>
100
+ changeDocument(document: string, change: DocumentChange, signal?: AbortSignal): Promise<DocumentChangeAnswer>
91
101
  importDocumentImage(document: string, file: File, change: DocumentImageImport, signal?: AbortSignal): Promise<DocumentImageImportAnswer>
92
102
  readDocumentAudio(document: string, assetId: string, baseDocumentVersion: string, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer>
93
103
  importDocumentAudio(document: string, file: File, change: DocumentAudioImport, signal?: AbortSignal): Promise<DocumentAudioImportAnswer>
@@ -129,16 +139,16 @@ export interface WorkspaceClient {
129
139
  prefetchPreview(document: string, renderer: PreviewRenderer): Promise<PreviewAnswer>
130
140
  /** The MCP address and the workspace root, read once. */
131
141
  readWorkbenchInfo(): Promise<WorkbenchAnswer>
132
- readFocus(document: string): Promise<FocusAnswer>
142
+ readFocus(document: string, signal?: AbortSignal): Promise<FocusAnswer>
133
143
  writeFocus(document: string, focus: FocusReport[]): Promise<FocusAnswer>
134
144
  subscribeReview(document: string, update: (event: ReviewUpdate) => void): () => void
135
145
  acceptReview(document: string, body: { reject?: string[], message?: string }): Promise<{ ended: ReviewEnd }>
136
146
  rejectReview(document: string, paths?: string[]): Promise<ReviewUpdate>
137
147
  restoreReview(document: string, step: string): Promise<{ review: ReviewSnapshot }>
138
- readChanges(document: string): Promise<{ files: UncommittedFile[] }>
148
+ readChanges(document: string, signal?: AbortSignal): Promise<{ files: UncommittedFile[] }>
139
149
  commitChanges(document: string, message: string, paths?: string[]): Promise<unknown>
140
150
  discardChanges(document: string, paths?: string[]): Promise<unknown>
141
- readRevisions(document: string, query?: import('@lincyaw/kernel').DocumentHistoryQuery): Promise<RevisionsAnswer>
151
+ readRevisions(document: string, query?: import('@lincyaw/kernel').DocumentHistoryQuery, signal?: AbortSignal): Promise<RevisionsAnswer>
142
152
  readHistoryFile(document: string, query: import('@lincyaw/kernel').DocumentHistoryRead): Promise<import('@lincyaw/kernel').DocumentHistoryFile>
143
153
  revertRevision(document: string, request: import('@lincyaw/kernel').DocumentHistoryChange): Promise<import('@lincyaw/kernel').DocumentHistoryChanged>
144
154
  /** 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 +179,16 @@ export interface AuthoringClientChannel {
169
179
  close(): void
170
180
  }
171
181
  export type AuthoringClientSubscription = (document: string, open: import('@lincyaw/kernel').AuthoringClientOpen, received: (event: import('@lincyaw/kernel').AuthoringClientEvent) => void, failed: () => void) => AuthoringClientChannel
182
+ export interface AuthoringWindowChannel {
183
+ publish(connectionId: string, report: import('@lincyaw/kernel').AuthoringWindowReport): Promise<void>
184
+ acknowledge(connectionId: string, report: import('@lincyaw/kernel').AuthoringWindowAcknowledgement): Promise<void>
185
+ close(): void
186
+ }
187
+ export type AuthoringWindowSubscription = (open: import('@lincyaw/kernel').AuthoringWindowOpen, received: (event: import('@lincyaw/kernel').AuthoringWindowEvent) => void, failed: () => void) => AuthoringWindowChannel
172
188
  export interface WorkspaceSubscription {
173
189
  (address: string, event: string, received: (data: string, event?: string) => void, failed?: () => void, ready?: () => void): () => void
174
190
  openAuthoringClient?: AuthoringClientSubscription
191
+ openAuthoringWindow?: AuthoringWindowSubscription
175
192
  }
176
193
 
177
194
  /** A remote host may add its CSRF header without replacing the page's global fetch. */
@@ -188,7 +205,7 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
188
205
  const path = target.pathname.slice(prefix.length)
189
206
  const method = (init?.method ?? 'GET').toUpperCase()
190
207
  if (client.capabilities?.readOnly && !['GET', 'HEAD', 'OPTIONS'].includes(method)
191
- && /^(?:document(?:\/|$)|source(?:\/|$)|project\/|pages\/|history\/|revisions\/|review(?:\/|$))/.test(path)) throw new WorkspaceServerError(403, { error: 'permission-denied' })
208
+ && /^(?:documents?(?:\/|$)|source(?:\/|$)|project\/|pages\/|history\/|revisions\/|review(?:\/|$))/.test(path)) throw new WorkspaceServerError(403, { error: 'permission-denied' })
192
209
  if (path === 'telemetry' || (path === 'diagnostics' || path === 'diagnostics/authoring') && method === 'POST') return fetch(address, { credentials: 'same-origin', ...init })
193
210
  const document = target.searchParams.get('document') ?? undefined
194
211
  const requestId = ++requestSequence
@@ -328,7 +345,9 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
328
345
  }
329
346
  const projectIntents = new Map<string, { id: string, plan?: ProjectPlan }>()
330
347
  return client = {
348
+ subscribeAgentActivity: (received, failed) => subscribe(url('agent-activity/events', ''), 'agent-activity', received, failed),
331
349
  ...subscription?.openAuthoringClient ? { openAuthoringClient: subscription.openAuthoringClient } : {},
350
+ ...subscription?.openAuthoringWindow ? { openAuthoringWindow: subscription.openAuthoringWindow } : {},
332
351
  ...subscription ? { subscribePreviewEvents: ((target, received) => {
333
352
  const address = new URL(base, globalThis.document.baseURI)
334
353
  for (const [key, value] of Object.entries(target)) if (key !== 'topic') address.searchParams.set(key, value)
@@ -341,7 +360,7 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
341
360
  if (operation.op === 'delete' && (!planned || JSON.stringify(planned.operation) !== JSON.stringify(operation))) throw new Error('project-deletion-plan-required')
342
361
  const key = JSON.stringify(operation)
343
362
  let intent = projectIntents.get(key)
344
- if (!intent) { intent = { id: crypto.randomUUID() }; projectIntents.set(key, intent) }
363
+ if (!intent) { intent = { id: randomUUID() }; projectIntents.set(key, intent) }
345
364
  while (projectIntents.size > 64) projectIntents.delete(projectIntents.keys().next().value!)
346
365
  try {
347
366
  intent.plan ??= planned
@@ -354,17 +373,24 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
354
373
  throw error
355
374
  }
356
375
  },
376
+ importDocuments: (files, signal) => {
377
+ const body = new FormData()
378
+ body.set('paths', JSON.stringify(files.map(file => file.webkitRelativePath || file.name)))
379
+ for (const file of files) body.append('files', file, file.name)
380
+ return call(url('documents/import'), { method: 'POST', body, signal })
381
+ },
382
+ migrateWorkspace: () => call(url('workspace/migrate'), { method: 'POST' }),
357
383
  readSource: (document, path) => call(url('source', document, { path })),
358
384
  saveSource: (document, path, content, base, message) => post(url('source', document), { path, content, base, ...message ? { message } : {} }),
359
385
  saveSourceTransaction: (document, changes, message) => post(url('source/transaction', document), { changes, ...message ? { message } : {} }),
360
386
  readIr,
361
- readDocument: document => call(url('document', document)),
387
+ readDocument: (document, signal) => call(url('document', document), { signal }),
362
388
  readAuthoringCapabilities: (document, signal) => call(url('document/capabilities', document), { signal }),
363
389
  planDocumentAction: (document, request, signal) => post(url('document/action/plan', document), request, signal),
364
390
  readDocumentActionPlan: (document, reference, signal) => call(url('document/action/plan', document, { planId: reference.planId, digest: reference.digest }), { signal }),
365
391
  applyDocumentAction: (document, reference, signal) => post(url('document/action/apply', document), reference, signal),
366
392
  documentAssetURL: (document, asset) => url('document/asset', document, { asset }),
367
- changeDocument: (document, change) => post(url('document/change', document), change),
393
+ changeDocument: (document, change, signal) => post(url('document/change', document), change, signal),
368
394
  importDocumentImage: (document, file, change, signal) => {
369
395
  const body = new FormData()
370
396
  body.set('change', JSON.stringify(change)); body.set('file', file)
@@ -389,6 +415,9 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
389
415
  subscribeDocument: (document, changed, failed) => subscribe(url('document/events', document), 'document', changed, failed),
390
416
  readPageDeletion: (document, section) => call(url('pages/delete', document, { section })),
391
417
  deletePage: (document, request) => post(url('pages/delete', document), request),
418
+ readMcpSettings: signal => call(url('mcp-settings'), { signal }),
419
+ changeMcpSettings: (change, signal) => post(url('mcp-settings'), change, signal),
420
+ exportMcpSettings: (revision, signal) => post(url('mcp-settings'), { action: 'export', revision }, signal),
392
421
  readSpeechSettings: signal => call(url('speech-settings'), { signal }),
393
422
  changeSpeechSettings: (change, signal) => post(url('speech-settings'), change, signal),
394
423
  readVoiceCatalog: (document, engine, lang, signal) => call(url('voice-catalog', document, { ...engine ? { engine } : {}, ...lang ? { lang } : {} }), { signal }),
@@ -433,20 +462,20 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
433
462
  })
434
463
  return workbenchInfo
435
464
  },
436
- readFocus: document => call(url('focus', document)),
465
+ readFocus: (document, signal) => call(url('focus', document), { signal }),
437
466
  writeFocus: (document, focus) => post(url('focus'), { document, focus }),
438
467
  subscribeReview: (document, update) => subscribe(url('review', document), 'review', update),
439
468
  acceptReview: (document, body) => post(url('review/accept', document), body),
440
469
  rejectReview: (document, paths) => post(url('review/reject', document), paths ? { paths } : {}),
441
470
  restoreReview: (document, step) => post(url('review/restore', document), { step }),
442
- readChanges: document => call(url('changes', document)),
471
+ readChanges: (document, signal) => call(url('changes', document), { signal }),
443
472
  commitChanges: (document, message, paths) => post(url('changes/commit', document), { message, ...paths ? { paths } : {} }),
444
473
  discardChanges: (document, paths) => post(url('changes/discard', document), paths ? { paths } : {}),
445
474
  readJobs: document => call(url('jobs', document)),
446
475
  startJob: (document, target, source) => post(url('jobs', document), { target, source } satisfies StartJobRequest),
447
476
  cancelJob: (document, id) => post(url('jobs/cancel', document), { id }),
448
477
  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) })),
478
+ readRevisions: (document, query = {}, signal) => call(url('revisions', document, { query: JSON.stringify(query) }), { signal }),
450
479
  readHistoryFile: (document, query) => call(url('history/file', document, { query: JSON.stringify(query) })),
451
480
  revertRevision: (document, request) => post(url('revisions/revert', document), request),
452
481
  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
- }