@lincyaw/workbench 0.2.0-rc.23 → 0.2.0-rc.25
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.
- package/package.json +4 -4
- package/src/authoring-client.ts +3 -3
- package/src/component-property-drafts.ts +4 -4
- package/src/components.tsx +0 -23
- package/src/document-drafts.ts +3 -3
- package/src/document-editor/BlockNoteSurface.tsx +2 -1
- package/src/document-editor/ComponentPropertiesDialog.tsx +3 -3
- package/src/document-editor/DocumentComments.tsx +2 -1
- package/src/document-editor/DocumentEditor.tsx +2 -2
- package/src/document-editor/DocumentStepNarration.tsx +2 -1
- package/src/document-editor/NewCommentDrafts.tsx +3 -2
- package/src/document-editor/comment-drafts.ts +4 -4
- package/src/document-editor/comments.ts +3 -3
- package/src/document-editor/file-input.ts +2 -2
- package/src/document-editor/narration-schema.tsx +3 -2
- package/src/document-editor/projection.ts +2 -2
- package/src/document-editor/rich-text.ts +3 -2
- package/src/document-editor/table-identities.ts +2 -1
- package/src/document-session.ts +3 -3
- package/src/history.ts +2 -2
- package/src/index.ts +0 -3
- package/src/messages.ts +0 -2
- package/src/panels/DocumentView.tsx +1 -3
- package/src/panels/ExportPanel.tsx +1 -6
- package/src/panels/PreviewPanel.tsx +1 -4
- package/src/panels/ProductionCaptionTiming.tsx +3 -3
- package/src/panels/ProductionMediaClips.tsx +2 -1
- package/src/panels/ProductionRecordingRange.tsx +2 -2
- package/src/panels/ProductionTranscription.tsx +2 -1
- package/src/panels/SourceDocumentPanel.tsx +1 -4
- package/src/panels/TranscriptionAdoption.tsx +4 -4
- package/src/places.ts +1 -36
- package/src/styles.css +1 -31
- package/src/workbench.ts +13 -28
- package/src/workspace-client.ts +2 -1
- package/src/assistant-mascot.ts +0 -62
- package/src/mascot-preference.ts +0 -37
- package/src/panels/ChangeTrail.tsx +0 -79
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/workbench",
|
|
3
|
-
"version": "0.2.0-rc.
|
|
3
|
+
"version": "0.2.0-rc.25",
|
|
4
4
|
"description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -54,8 +54,8 @@
|
|
|
54
54
|
"@tiptap/pm": "3.32.0",
|
|
55
55
|
"katex": "0.18.10",
|
|
56
56
|
"react-resizable-panels": "4.14.5",
|
|
57
|
-
"@lincyaw/
|
|
58
|
-
"@lincyaw/
|
|
57
|
+
"@lincyaw/design": "1.0.0-rc.26",
|
|
58
|
+
"@lincyaw/kernel": "1.0.0-rc.26"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
61
|
"react": "^18.3.1",
|
|
@@ -66,6 +66,6 @@
|
|
|
66
66
|
"@types/react-dom": "18.3.7",
|
|
67
67
|
"react": "^18.3.1",
|
|
68
68
|
"react-dom": "^18.3.1",
|
|
69
|
-
"@lincyaw/compiler": "1.0.0-rc.
|
|
69
|
+
"@lincyaw/compiler": "1.0.0-rc.26"
|
|
70
70
|
}
|
|
71
71
|
}
|
package/src/authoring-client.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { authoringClientResultFits } from '@lincyaw/kernel'
|
|
1
|
+
import { authoringClientResultFits, randomUUID } from '@lincyaw/kernel'
|
|
2
2
|
import type { AuthoringClientActionResult, AuthoringClientEvent, AuthoringClientSnapshot, CanonicalSource } from '@lincyaw/kernel'
|
|
3
3
|
import type { Workbench } from './workbench.ts'
|
|
4
4
|
import type { AuthoringClientChannel } from './workspace-client.ts'
|
|
@@ -13,7 +13,7 @@ type Attachment = { directory: string, identity: string, epoch: string, channel:
|
|
|
13
13
|
export function connectAuthoringClient(workbench: Workbench): () => void {
|
|
14
14
|
const open = workbench.client.openAuthoringClient
|
|
15
15
|
if (!open) return () => {}
|
|
16
|
-
const clientId =
|
|
16
|
+
const clientId = randomUUID()
|
|
17
17
|
let closed = false, revision = 0, sequence = 0
|
|
18
18
|
let attached: Attachment | undefined
|
|
19
19
|
let lastSignature: string | undefined, lastContent: object | undefined
|
|
@@ -120,7 +120,7 @@ export function connectAuthoringClient(workbench: Workbench): () => void {
|
|
|
120
120
|
if (!value) { detach(); return }
|
|
121
121
|
if (attached && (attached.directory !== state.document || attached.identity !== source.identity)) detach()
|
|
122
122
|
if (!attached) {
|
|
123
|
-
const epoch =
|
|
123
|
+
const epoch = randomUUID()
|
|
124
124
|
// Callbacks run after the channel has been installed; the socket implementation is asynchronous.
|
|
125
125
|
const owner = { directory: state.document, identity: source.identity, epoch } as Attachment
|
|
126
126
|
owner.channel = open(state.document, { clientId, epoch, snapshot: value }, event => { void received(owner, event) }, () => {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isRecord } from '@lincyaw/kernel'
|
|
1
|
+
import { isRecord, randomUUID } from '@lincyaw/kernel'
|
|
2
2
|
import type { CanonicalSource, ClientComponentDraftReference, JsonObject } from '@lincyaw/kernel'
|
|
3
3
|
import { DocumentDraftStore } from './document-draft-store.ts'
|
|
4
4
|
import type { DraftStoreCommit } from './document-draft-store.ts'
|
|
@@ -50,7 +50,7 @@ export class ComponentPropertyDrafts {
|
|
|
50
50
|
readonly #revisions = new Map<string, number>()
|
|
51
51
|
readonly #settling = new Map<string, number>()
|
|
52
52
|
#agentReader?: { identity: string, memberId: string, store: DocumentDraftStore }
|
|
53
|
-
readonly #writerOwner =
|
|
53
|
+
readonly #writerOwner = randomUUID()
|
|
54
54
|
#revision = 0
|
|
55
55
|
#closed = false
|
|
56
56
|
readonly #leave = (event: BeforeUnloadEvent) => {
|
|
@@ -149,7 +149,7 @@ export class ComponentPropertyDrafts {
|
|
|
149
149
|
if (this.#closed) throw new Error('component-draft-closed')
|
|
150
150
|
const key = targetKey(target), previous = this.#entries.get(key)
|
|
151
151
|
if (!previous && this.#entries.size >= 512) throw new Error('component-draft-limit')
|
|
152
|
-
const record: ComponentPropertyDraft = { format: 1, id: previous?.record.id ??
|
|
152
|
+
const record: ComponentPropertyDraft = { format: 1, id: previous?.record.id ?? randomUUID(), revision: (previous?.record.revision ?? 0) + 1,
|
|
153
153
|
target: structuredClone(target), source: structuredClone(value.source), definitionId: value.definitionId, baseline: structuredClone(value.baseline), value: structuredClone(value.value),
|
|
154
154
|
reset: Boolean(value.reset), composing: Boolean(value.composing), updatedAt: new Date().toISOString() }
|
|
155
155
|
const entry: Entry = previous ?? { record, store: new DocumentDraftStore(scope(target), undefined, { owner: this.#writerOwner, family: 'component' }), failed: false, origins: [] }
|
|
@@ -213,7 +213,7 @@ export class ComponentPropertyDrafts {
|
|
|
213
213
|
try { value = JSON.parse(raw) } catch { return false }
|
|
214
214
|
if (!valid(value, target) || backup.key !== keyOf(value)) return false
|
|
215
215
|
guard?.()
|
|
216
|
-
const record: ComponentPropertyDraft = { ...structuredClone(value), id:
|
|
216
|
+
const record: ComponentPropertyDraft = { ...structuredClone(value), id: randomUUID(), revision: 1, composing: false, updatedAt: new Date().toISOString() }
|
|
217
217
|
const fork = JSON.stringify(record)
|
|
218
218
|
if (fork.length > MAX_CHARS) return false
|
|
219
219
|
const operation = store.put(keyOf(record), fork)
|
package/src/components.tsx
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import type { IconName } from '@lincyaw/design'
|
|
2
|
-
import { mountMascot } from '@lincyaw/design/mascot'
|
|
3
|
-
import type { MascotAction } from '@lincyaw/design/mascot'
|
|
4
2
|
import * as Dialog from '@radix-ui/react-dialog'
|
|
5
3
|
import * as DropdownMenu from '@radix-ui/react-dropdown-menu'
|
|
6
4
|
import * as Popover from '@radix-ui/react-popover'
|
|
@@ -11,7 +9,6 @@ import { forwardRef, useEffect, useId, useMemo, useRef, useState } from 'react'
|
|
|
11
9
|
import type { ComponentProps, CSSProperties, InputHTMLAttributes, ReactNode, Ref, SelectHTMLAttributes, TextareaHTMLAttributes } from 'react'
|
|
12
10
|
import { Group as ResizableGroup, Panel as ResizablePanel, Separator as ResizableSeparator } from 'react-resizable-panels'
|
|
13
11
|
import { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
|
|
14
|
-
import { useMascotEnabled } from './mascot-preference.ts'
|
|
15
12
|
import type { ControlDensity } from './base-controls.tsx'
|
|
16
13
|
export { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
|
|
17
14
|
export type { ButtonVariant, ControlDensity } from './base-controls.tsx'
|
|
@@ -413,26 +410,6 @@ export function PmNotice({ tone = 'neutral', children }: { tone?: 'neutral' | 'a
|
|
|
413
410
|
return <div className={cls('pm-ui-notice', tone !== 'neutral' && `pm-ui-notice--${tone}`)} role={tone === 'danger' ? 'alert' : 'status'}>{children}</div>
|
|
414
411
|
}
|
|
415
412
|
|
|
416
|
-
/** The Presmium kitten acting out what the assistant or a long task is doing. It is decoration: the text beside it
|
|
417
|
-
* says the same thing for everyone, so it is hidden from assistive technology. Nothing shows when the author turned
|
|
418
|
-
* the kitten off in Settings. */
|
|
419
|
-
export function PmMascot(props: { action: MascotAction, size?: 'small' | 'regular' }) {
|
|
420
|
-
return useMascotEnabled() ? <MascotPlayer {...props} /> : null
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
function MascotPlayer({ action, size = 'regular' }: { action: MascotAction, size?: 'small' | 'regular' }) {
|
|
424
|
-
const ref = useRef<HTMLSpanElement>(null)
|
|
425
|
-
const player = useRef<ReturnType<typeof mountMascot>>(undefined)
|
|
426
|
-
const first = useRef(action)
|
|
427
|
-
useEffect(() => {
|
|
428
|
-
const mounted = mountMascot(ref.current!, first.current)
|
|
429
|
-
player.current = mounted
|
|
430
|
-
return () => mounted.stop()
|
|
431
|
-
}, [])
|
|
432
|
-
useEffect(() => { player.current?.set(action) }, [action])
|
|
433
|
-
return <span ref={ref} className={cls('pm-ui-mascot', size === 'small' && 'pm-ui-mascot--sm')} data-pm-mascot={action} aria-hidden="true" />
|
|
434
|
-
}
|
|
435
|
-
|
|
436
413
|
export interface RangeProps {
|
|
437
414
|
label: string
|
|
438
415
|
value: number
|
package/src/document-drafts.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isRecord, validateDocument } from '@lincyaw/kernel'
|
|
1
|
+
import { isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
|
|
2
2
|
import type { TeachingDocument } from '@lincyaw/kernel'
|
|
3
3
|
import { DocumentDraftStore } from './document-draft-store.ts'
|
|
4
4
|
import type { DraftStoreCommit } from './document-draft-store.ts'
|
|
@@ -52,7 +52,7 @@ async function tokenOf(raw: string): Promise<string> {
|
|
|
52
52
|
|
|
53
53
|
/** Strictly committed document backups, with old localStorage copies identified as unconfirmed rescue material. */
|
|
54
54
|
export class DocumentDrafts {
|
|
55
|
-
readonly #owner =
|
|
55
|
+
readonly #owner = randomUUID()
|
|
56
56
|
readonly #owned = new Map<string, { identity: string, revision: number, raw: string }>()
|
|
57
57
|
#store?: DocumentDraftStore
|
|
58
58
|
#identity?: string
|
|
@@ -113,7 +113,7 @@ export class DocumentDrafts {
|
|
|
113
113
|
const owned = previous && this.#owned.get(previous.id)
|
|
114
114
|
if (previous && (!owned || owned.identity !== identity || previous.owner !== this.#owner || previous.revision !== owned.revision)) return
|
|
115
115
|
const changed = previous && store.conflicted(keyOf(identity, previous.id))
|
|
116
|
-
const record: StoredDocumentDraft = { ...draft, format: 2, identity, id: !changed && previous ? previous.id :
|
|
116
|
+
const record: StoredDocumentDraft = { ...draft, format: 2, identity, id: !changed && previous ? previous.id : randomUUID(), owner: this.#owner, revision: changed ? 1 : (owned?.revision ?? 0) + 1, updatedAt: Date.now() }
|
|
117
117
|
if (!Number.isSafeInteger(record.revision)) return
|
|
118
118
|
try { const raw = JSON.stringify(record); return raw.length <= MAX_CHARS ? { record, raw } : undefined }
|
|
119
119
|
catch { return }
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { forwardRef, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
|
2
2
|
import type { ForwardRefExoticComponent, ReactNode, RefAttributes } from 'react'
|
|
3
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
3
4
|
import { filterSuggestionItems } from '@blocknote/core'
|
|
4
5
|
import { BlockNoteView, components } from '@blocknote/mantine'
|
|
5
6
|
import { AddCommentButton, BasicTextStyleButton, BlockNoteViewEditor, BlockTypeSelect, ComponentsContext, CreateLinkButton, FormattingToolbar, FormattingToolbarController, getDefaultReactSlashMenuItems, LinkToolbarController, NestBlockButton, RenderInPortalElement, SideMenuController, SuggestionMenuController, TableCellMergeButton, TableHandlesController, TextAlignButton, UnnestBlockButton, useBlockNoteEditor, useCreateBlockNote, useEditorState } from '@blocknote/react'
|
|
@@ -206,7 +207,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
|
|
|
206
207
|
onItemClick: () => current.current.animationRequest?.request(editor),
|
|
207
208
|
}] : []), {
|
|
208
209
|
title: t.page, aliases: slashAliases('pageAliases'), group: t.document,
|
|
209
|
-
onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId:
|
|
210
|
+
onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: randomUUID() }, content: t.untitledPage }], current, 'after') },
|
|
210
211
|
}], query)} />
|
|
211
212
|
{props.children}
|
|
212
213
|
</NewCommentDraftProvider></BlockNoteViewEditor>
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
|
2
|
-
import { applyDocumentComponentAction, effectiveComponentParameters, isRecord, validateDocumentParameters } from '@lincyaw/kernel'
|
|
2
|
+
import { applyDocumentComponentAction, effectiveComponentParameters, isRecord, randomUUID, validateDocumentParameters } from '@lincyaw/kernel'
|
|
3
3
|
import type { CanonicalSource, DocumentComponentAction, DocumentParameterValidation, JsonObject, TeachingDocument } from '@lincyaw/kernel'
|
|
4
4
|
import { PmButton, PmDialog, PmNotice, PmSelect } from '../components.tsx'
|
|
5
5
|
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
@@ -17,7 +17,7 @@ function fresh(document: TeachingDocument, source: CanonicalSource, target: Comp
|
|
|
17
17
|
const block = document.blocks[target.blockId]
|
|
18
18
|
if (block?.type !== 'component') throw new Error('component-block-missing')
|
|
19
19
|
const value = effectiveComponentParameters(document, block.id, target.stepId).parameters
|
|
20
|
-
return { format: 1, id:
|
|
20
|
+
return { format: 1, id: randomUUID(), revision: 0, target, source, definitionId: block.definitionId, baseline: value, value,
|
|
21
21
|
composing: false, reset: false, updatedAt: new Date().toISOString() }
|
|
22
22
|
}
|
|
23
23
|
function message(error: unknown, t: ComponentPropertyMessages): string {
|
|
@@ -164,7 +164,7 @@ export function ComponentPropertiesDialog({ identity, blockId, stepId, onClose }
|
|
|
164
164
|
const submit = async (action: DocumentComponentAction, submitted?: ComponentPropertyDraft) => {
|
|
165
165
|
if (!canonical || !source?.version || !clean || current.current.busy) return
|
|
166
166
|
const expected = { identity, version: source.version, fingerprint: source.fingerprint! }, signature = JSON.stringify([canonical, action])
|
|
167
|
-
if (!intent.current || intent.current.signature !== signature || intent.current.draft !== submitted) intent.current = { signature, draft: submitted, id:
|
|
167
|
+
if (!intent.current || intent.current.signature !== signature || intent.current.draft !== submitted) intent.current = { signature, draft: submitted, id: randomUUID() }
|
|
168
168
|
const captured = intent.current, controller = new AbortController(), submittedKey = key
|
|
169
169
|
flight.current = controller; current.current.busy = true; setBusy(true); setError(undefined)
|
|
170
170
|
try {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
|
2
2
|
import type { FocusEvent, ReactNode } from 'react'
|
|
3
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
3
4
|
import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
|
|
4
5
|
import { components } from '@blocknote/mantine'
|
|
5
6
|
import { FloatingThreadController, getReferenceText, Thread, useBlockNoteEditor, useCreateBlockNote, useEditorState, useExtension, useExtensionState, useThreads } from '@blocknote/react'
|
|
@@ -174,7 +175,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
|
|
|
174
175
|
return value
|
|
175
176
|
}, [props.editor, drafts])
|
|
176
177
|
const rich = useMemo(() => ({ current: record.rich }), [record])
|
|
177
|
-
const composerId = useRef(
|
|
178
|
+
const composerId = useRef(randomUUID())
|
|
178
179
|
const state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState))
|
|
179
180
|
useLayoutEffect(() => {
|
|
180
181
|
if (!context || !threadId) return
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useEffect, useMemo, useRef } from 'react'
|
|
2
2
|
import type { Transaction } from '@tiptap/pm/state'
|
|
3
3
|
import { closeHistory } from '@tiptap/pm/history'
|
|
4
|
-
import { allocateDocumentPage } from '@lincyaw/kernel'
|
|
4
|
+
import { allocateDocumentPage, randomUUID } from '@lincyaw/kernel'
|
|
5
5
|
import type { Member, TeachingDocument } from '@lincyaw/kernel'
|
|
6
6
|
import type { Locale } from '../messages.ts'
|
|
7
7
|
import { BlockNoteSurface } from './BlockNoteSurface.tsx'
|
|
@@ -189,7 +189,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
|
|
|
189
189
|
const next = after ? blocks.slice(index + 1).find(block => block.type === 'presmiumPage') : undefined
|
|
190
190
|
const latest = current.current.getDocument ? current.current.getDocument() : current.current.document
|
|
191
191
|
if (!latest) throw new Error('page-context-changed')
|
|
192
|
-
const creation = allocateDocumentPage(latest, () =>
|
|
192
|
+
const creation = allocateDocumentPage(latest, () => randomUUID())
|
|
193
193
|
projection.createdPages.set(creation.sectionId, creation)
|
|
194
194
|
try {
|
|
195
195
|
value.transact(transaction => {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { useRef, useState } from 'react'
|
|
2
2
|
import type { NarrationNode, TeachingDocument } from '@lincyaw/kernel'
|
|
3
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
3
4
|
import { PmIconButton } from '../components.tsx'
|
|
4
5
|
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
5
6
|
import { isAgentChanging } from '../workbench.ts'
|
|
@@ -30,7 +31,7 @@ function NarrationField({ identity, reset, blockId, stepId, slot, narrationId, c
|
|
|
30
31
|
// Reserving an identity does not create an entity. The first actual input commits it.
|
|
31
32
|
const [reservedId] = useState(() => {
|
|
32
33
|
const pending = workbench.pendingDocumentField(blockId, identity)
|
|
33
|
-
return narrationId ?? (pending?.stepId === stepId ? pending.narrationId : undefined) ??
|
|
34
|
+
return narrationId ?? (pending?.stepId === stepId ? pending.narrationId : undefined) ?? randomUUID()
|
|
34
35
|
})
|
|
35
36
|
const id = narrationId ?? reservedId
|
|
36
37
|
const target = () => narrationId ?? workbench.getDocument(identity)?.steps[stepId]?.narrationIds[slot] ?? id
|
|
@@ -5,6 +5,7 @@ import { components } from '@blocknote/mantine'
|
|
|
5
5
|
import { ComponentsContext, FloatingComposer, PositionPopover, useBlockNoteEditor, useComponentsContext, useCreateBlockNote, useDictionary, useEditorState, useExtension, useExtensionState } from '@blocknote/react'
|
|
6
6
|
import type { ComponentProps } from '@blocknote/react'
|
|
7
7
|
import type { BlockNoteEditor } from '@blocknote/core'
|
|
8
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
8
9
|
import { TextSelection } from '@tiptap/pm/state'
|
|
9
10
|
import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
|
|
10
11
|
import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
|
|
@@ -60,7 +61,7 @@ export function NewCommentDraftProvider({ children }: { children?: ReactNode })
|
|
|
60
61
|
&& editor.prosemirrorState.doc === native.doc && editor.prosemirrorState.selection === native.selection && comments.store.state === extensionState
|
|
61
62
|
&& (!binding || latest.current === binding && binding.input === input && binding.record === record && !binding.composing)
|
|
62
63
|
if (record && !await drafts.confirm(record) || !owns()) return
|
|
63
|
-
const nextTarget = { ...target, intentId:
|
|
64
|
+
const nextTarget = { ...target, intentId: randomUUID() }, next = await drafts.recover(candidate, nextTarget, version)
|
|
64
65
|
store.beforeAction?.()
|
|
65
66
|
if (!next || !owns()) return
|
|
66
67
|
const positions = store.newDraftPositions(nextTarget, editor)
|
|
@@ -185,7 +186,7 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
|
|
|
185
186
|
})
|
|
186
187
|
return () => { stop(); stopEnter(); if (original && guarded && !props.editor.prosemirrorView.isDestroyed && props.editor.getExtension(CommentEditorSubmitExtension) === guarded) props.editor.replaceExtension(guarded, original) }
|
|
187
188
|
}, [binding, drafts, props.editor])
|
|
188
|
-
const composerId = useRef(
|
|
189
|
+
const composerId = useRef(randomUUID())
|
|
189
190
|
useLayoutEffect(() => {
|
|
190
191
|
if (!binding || !drafts || !context) return
|
|
191
192
|
return drafts.registerComposer({ id: composerId.current, target: binding.target,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { documentCommentTargets, isRecord, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
|
|
1
|
+
import { documentCommentTargets, isRecord, randomUUID, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
|
|
2
2
|
import type { DocumentComment, DocumentThread, RichTextNode, TeachingDocument } from '@lincyaw/kernel'
|
|
3
3
|
import { DocumentDraftStore } from '../document-draft-store.ts'
|
|
4
4
|
import type { DraftStoreResult } from '../document-draft-store.ts'
|
|
@@ -77,7 +77,7 @@ function valid(value: unknown, scope: string): value is CommentDraftRecord {
|
|
|
77
77
|
/** Native composer backups use the document backup owner's strict transactions, never the source writer. */
|
|
78
78
|
export class CommentDrafts {
|
|
79
79
|
readonly #scope: string
|
|
80
|
-
readonly #owner =
|
|
80
|
+
readonly #owner = randomUUID()
|
|
81
81
|
#reader?: DocumentDraftStore
|
|
82
82
|
readonly #listeners = new Set<() => void>()
|
|
83
83
|
readonly #writing = new Map<string, Writing>()
|
|
@@ -240,7 +240,7 @@ export class CommentDrafts {
|
|
|
240
240
|
const known = previous && this.#writing.get(previous.id)
|
|
241
241
|
if (previous && (known && known.record.revision !== previous.revision || previous.owner !== this.#owner)) return
|
|
242
242
|
const branched = known?.store.conflicted(keyOf(this.#scope, known.record.id))
|
|
243
|
-
const record: CommentDraftRecord = { format: 1, scope: this.#scope, id: !branched && known ? known.record.id :
|
|
243
|
+
const record: CommentDraftRecord = { format: 1, scope: this.#scope, id: !branched && known ? known.record.id : randomUUID(), owner: this.#owner,
|
|
244
244
|
revision: !branched && known ? known.record.revision + 1 : 1, updatedAt: Date.now(), target: structuredClone(target), version, content: structuredClone(content), composing }
|
|
245
245
|
return this.#put(record, !branched ? known : undefined)
|
|
246
246
|
}
|
|
@@ -323,7 +323,7 @@ export class CommentDrafts {
|
|
|
323
323
|
const value: unknown = JSON.parse(raw)
|
|
324
324
|
if (!valid(value, this.#scope) || value.revision !== reference.revision || !sameCommentDraftTarget(value.target, target) || !this.#validContent(value) || this.#closed) return
|
|
325
325
|
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
326
|
-
const record: CommentDraftRecord = { ...value, target: isNewCommentDraft(target) ? structuredClone(target) : value.target, id:
|
|
326
|
+
const record: CommentDraftRecord = { ...value, target: isNewCommentDraft(target) ? structuredClone(target) : value.target, id: randomUUID(), owner: this.#owner, revision: 1, updatedAt: Date.now(), version, composing: false, pending: undefined }
|
|
327
327
|
const store = new DocumentDraftStore(this.#scope, undefined, { family: 'comment', owner: this.#owner }), next = JSON.stringify(record)
|
|
328
328
|
if (next.length > MAX_CHARS || !await store.create(keyOf(this.#scope, record.id), next) || this.#closed) { store.close(); if (!this.#closed) { this.#admissionFailure = true; this.#pending() }; return }
|
|
329
329
|
try { operation?.signal?.throwIfAborted(); operation?.guard?.() } catch (error) { store.close(); throw error }
|
|
@@ -4,7 +4,7 @@ import type { BlockNoteEditor } from '@blocknote/core'
|
|
|
4
4
|
import type { CommentData, ThreadData } from '@blocknote/core/comments'
|
|
5
5
|
import { AddMarkStep, RemoveMarkStep } from '@tiptap/pm/transform'
|
|
6
6
|
import { Plugin } from '@tiptap/pm/state'
|
|
7
|
-
import { applyDocumentCommentAction, hasRole, LOCAL_AUTHOR, validateDocumentCommentAnchor } from '@lincyaw/kernel'
|
|
7
|
+
import { applyDocumentCommentAction, hasRole, LOCAL_AUTHOR, randomUUID, validateDocumentCommentAnchor } from '@lincyaw/kernel'
|
|
8
8
|
import type { DocumentComment, DocumentCommentAction, DocumentThread, Member, RichTextNode, TeachingDocument } from '@lincyaw/kernel'
|
|
9
9
|
import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
|
|
10
10
|
import type { RichProjection } from './rich-text.ts'
|
|
@@ -96,7 +96,7 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
96
96
|
if (!thread || thread.deletedAt || thread.createdAt !== target.threadCreatedAt || target.commentId && (!comment || comment.deletedAt || comment.createdAt !== target.commentCreatedAt)) return 'unavailable'
|
|
97
97
|
return comment && target.baseline !== commentDraftBaseline(comment) ? 'changed' : 'current'
|
|
98
98
|
}
|
|
99
|
-
newDraftTarget(editor: NativeDocumentEditor, intentId =
|
|
99
|
+
newDraftTarget(editor: NativeDocumentEditor, intentId = randomUUID()): NewCommentDraftTarget {
|
|
100
100
|
this.beforeAction?.()
|
|
101
101
|
const target: NewCommentDraftTarget = { kind: 'create', intentId, documentId: this.#document.id }
|
|
102
102
|
const selection = editor.prosemirrorState.selection
|
|
@@ -162,7 +162,7 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
162
162
|
#content(comment: NewComment): RichTextNode[] { return nativeRichTextToProduct(comment.body as DocumentEditorBlock[], this.#rich) }
|
|
163
163
|
#act(action: DocumentCommentAction, nativeBody?: unknown) {
|
|
164
164
|
this.beforeAction?.()
|
|
165
|
-
const answer = applyDocumentCommentAction(this.#canonical, action, { member: this.member, now: new Date().toISOString(), allocate: () =>
|
|
165
|
+
const answer = applyDocumentCommentAction(this.#canonical, action, { member: this.member, now: new Date().toISOString(), allocate: () => randomUUID() })
|
|
166
166
|
if (answer.effect.changed) {
|
|
167
167
|
this.#replace(answer.threads, answer.effect.commentId && nativeBody !== undefined ? { id: answer.effect.commentId, body: nativeBody } : undefined)
|
|
168
168
|
this.#notify()
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createExtension, getBlockInfoNearPos, getNodeId } from '@blocknote/core'
|
|
2
2
|
import { FileHandler } from '@tiptap/extension-file-handler'
|
|
3
|
-
import { DOCUMENT_IMAGE_MEDIA_TYPES } from '@lincyaw/kernel'
|
|
3
|
+
import { DOCUMENT_IMAGE_MEDIA_TYPES, randomUUID } from '@lincyaw/kernel'
|
|
4
4
|
import { isObservedWorkspaceFailure, WorkspaceServerError } from '../workspace-client.ts'
|
|
5
5
|
import type { NativeDocumentEditor } from './schema.tsx'
|
|
6
6
|
|
|
@@ -34,7 +34,7 @@ export const imageFileInput = createExtension(({ editor, options }: { editor: Na
|
|
|
34
34
|
const state = editor.prosemirrorState, info = getBlockInfoNearPos(state, position)
|
|
35
35
|
const anchor = editor.getBlock(getNodeId(info.block.node, state.doc))
|
|
36
36
|
if (!anchor) throw new Error('document-file-position')
|
|
37
|
-
const blocks = accepted.map(file => ({ id:
|
|
37
|
+
const blocks = accepted.map(file => ({ id: randomUUID(), type: 'image' as const, props: { name: file.name } }))
|
|
38
38
|
const before = anchor.type !== 'presmiumPage' && position <= (info.contentStart ?? info.block.beforePos)
|
|
39
39
|
const inserted = editor.insertBlocks(blocks, anchor, before ? 'before' : 'after')
|
|
40
40
|
pending = inserted.map((block, index) => ({ file: accepted[index]!, id: block.id }))
|
|
@@ -6,6 +6,7 @@ import { Extension } from '@tiptap/core'
|
|
|
6
6
|
import { Plugin } from '@tiptap/pm/state'
|
|
7
7
|
import { Fragment, Slice } from '@tiptap/pm/model'
|
|
8
8
|
import type { Node } from '@tiptap/pm/model'
|
|
9
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
9
10
|
import { PmButton, PmDialog, PmInput } from '../components.tsx'
|
|
10
11
|
import type { Locale } from '../messages.ts'
|
|
11
12
|
|
|
@@ -56,7 +57,7 @@ const cueIdentities = createExtension({
|
|
|
56
57
|
const copied = (fragment: Fragment): Fragment => {
|
|
57
58
|
const nodes: Node[] = []
|
|
58
59
|
fragment.forEach(node => nodes.push(node.type.name === 'narrationAtom' && node.attrs.kind === 'cue'
|
|
59
|
-
? node.type.create({ ...node.attrs, cueId:
|
|
60
|
+
? node.type.create({ ...node.attrs, cueId: randomUUID() }, node.content, node.marks)
|
|
60
61
|
: node.isLeaf ? node : node.copy(copied(node.content))))
|
|
61
62
|
return Fragment.fromArray(nodes)
|
|
62
63
|
}
|
|
@@ -67,7 +68,7 @@ const cueIdentities = createExtension({
|
|
|
67
68
|
state.doc.descendants((node, position) => {
|
|
68
69
|
if (node.type.name !== 'narrationAtom' || node.attrs.kind !== 'cue') return
|
|
69
70
|
const id = node.attrs.cueId as string
|
|
70
|
-
if (!id || seen.has(id)) transaction.setNodeMarkup(position, undefined, { ...node.attrs, cueId:
|
|
71
|
+
if (!id || seen.has(id)) transaction.setNodeMarkup(position, undefined, { ...node.attrs, cueId: randomUUID() })
|
|
71
72
|
else seen.add(id)
|
|
72
73
|
})
|
|
73
74
|
return transaction.docChanged ? transaction : null
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING } from '@lincyaw/kernel'
|
|
1
|
+
import { documentPageDefaults, DOCUMENT_PAGE_DEFAULT_TIMING, randomUUID } from '@lincyaw/kernel'
|
|
2
2
|
import type { DocumentBlock, DocumentPageIds, NarrationNode, RichTextNode, Section, TeachingDocument, TextBlock } from '@lincyaw/kernel'
|
|
3
3
|
import { productInlineToNative } from './inline.ts'
|
|
4
4
|
import { captureRichBaseline, createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
|
|
@@ -17,7 +17,7 @@ export interface DocumentProjection extends RichProjection {
|
|
|
17
17
|
componentConfiguration: Map<string, string>
|
|
18
18
|
}
|
|
19
19
|
export type NativePageCreation = DocumentPageIds
|
|
20
|
-
const newId = () =>
|
|
20
|
+
const newId = () => randomUUID()
|
|
21
21
|
export const pageId = (sectionId: string) => `page:${sectionId}`
|
|
22
22
|
function plain(nodes: readonly { type: string, text?: string, children?: readonly unknown[] }[]): string {
|
|
23
23
|
return nodes.map(node => node.type === 'text' ? node.text ?? '' : node.type === 'break' ? '\n' : node.children ? plain(node.children as Parameters<typeof plain>[0]) : '').join('')
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { InlineNode, JsonValue, ListItemNode, RichTextNode, TableNode } from '@lincyaw/kernel'
|
|
2
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
2
3
|
import type { TableCellProps } from '@blocknote/core'
|
|
3
4
|
import { nativeInlineToProduct, nativeTextStyleToProduct, productInlineToNative, productTextStyleToNative } from './inline.ts'
|
|
4
5
|
import type { InlineProjectionContext, NativeInline } from './inline.ts'
|
|
@@ -27,12 +28,12 @@ export interface RichProjection extends InlineProjectionContext {
|
|
|
27
28
|
tables: Map<string, { id: string, cells: string[] }[]>
|
|
28
29
|
}
|
|
29
30
|
export function createRichProjection(): RichProjection {
|
|
30
|
-
return { rich: new Map(), baseline: new Map(), tables: new Map(), opaqueInline: new Map(), newInlineId: () =>
|
|
31
|
+
return { rich: new Map(), baseline: new Map(), tables: new Map(), opaqueInline: new Map(), newInlineId: () => randomUUID() }
|
|
31
32
|
}
|
|
32
33
|
export function captureRichBaseline(blocks: readonly DocumentEditorBlock[], context: RichProjection): void {
|
|
33
34
|
for (const block of blocks) { context.baseline.set(block.id, JSON.stringify(block)); captureRichBaseline(block.children, context) }
|
|
34
35
|
}
|
|
35
|
-
const id = () =>
|
|
36
|
+
const id = () => randomUUID()
|
|
36
37
|
const atom = (node: RichTextNode): DocumentEditorInput => ({ id: node.id, type: 'presmiumAtom', props: { entityId: node.id, kind: `rich:${node.type}`, label: node.type === 'extension' ? fallbackText(node.fallback) : fallbackText(node) } })
|
|
37
38
|
|
|
38
39
|
/** The projection records structural identities; the saved document owns all content. */
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createExtension, getBlockInfoNearPos, getNodeId } from '@blocknote/core'
|
|
2
2
|
import { Extension } from '@tiptap/core'
|
|
3
3
|
import { Plugin } from '@tiptap/pm/state'
|
|
4
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
4
5
|
import type { NativeDocumentEditor } from './schema.tsx'
|
|
5
6
|
import type { RichProjection } from './rich-text.ts'
|
|
6
7
|
|
|
@@ -24,7 +25,7 @@ export const tableIdentityExtension = createExtension({
|
|
|
24
25
|
after.doc.descendants((node, position) => {
|
|
25
26
|
if (!TYPES.includes(node.type.name)) return
|
|
26
27
|
let id = node.attrs[ATTR] as string | null
|
|
27
|
-
if (!id || used.has(id)) { id =
|
|
28
|
+
if (!id || used.has(id)) { id = randomUUID(); transaction.setNodeMarkup(position, undefined, { ...node.attrs, [ATTR]: id }) }
|
|
28
29
|
used.add(id)
|
|
29
30
|
})
|
|
30
31
|
if (transaction.steps.length) return transaction.setMeta('addToHistory', false)
|
package/src/document-session.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { hasRole, validateDocument } from '@lincyaw/kernel'
|
|
1
|
+
import { hasRole, randomUUID, validateDocument } from '@lincyaw/kernel'
|
|
2
2
|
import type { DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, DocumentIssue, Member, TeachingDocument } from '@lincyaw/kernel'
|
|
3
3
|
import { WorkspaceServerError } from './workspace-client.ts'
|
|
4
4
|
import type { WorkspaceClient } from './workspace-client.ts'
|
|
@@ -288,7 +288,7 @@ export class DocumentSession {
|
|
|
288
288
|
else if (slot.timer !== undefined) return
|
|
289
289
|
if (this.#readOnly(slot) || slot.flight || slot.assetFlight || !slot.state.dirty || slot.state.composing || slot.state.restored || slot.state.error || !slot.state.content || !slot.state.version) return
|
|
290
290
|
slot.read++
|
|
291
|
-
const flight = { id:
|
|
291
|
+
const flight = { id: randomUUID(), input: slot.input, content: structuredClone(slot.state.content), baseVersion: slot.state.version, hash: undefined as string | undefined }
|
|
292
292
|
slot.flight = flight
|
|
293
293
|
slot.state = { ...slot.state, saving: true }; this.#emit(slot)
|
|
294
294
|
try {
|
|
@@ -406,7 +406,7 @@ export class DocumentSession {
|
|
|
406
406
|
const before = structuredClone(slot.state.content), input = slot.input, version = slot.state.version
|
|
407
407
|
let request = this.#imageImports.get(file)
|
|
408
408
|
if (!request || request.identity !== identity || request.version !== version) {
|
|
409
|
-
request = { identity, version, id:
|
|
409
|
+
request = { identity, version, id: randomUUID() }
|
|
410
410
|
this.#imageImports.set(file, request)
|
|
411
411
|
}
|
|
412
412
|
const read = ++slot.read
|
package/src/history.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { errorMessage } from '@lincyaw/kernel'
|
|
1
|
+
import { errorMessage, randomUUID } from '@lincyaw/kernel'
|
|
2
2
|
import type { RevertResult, ReviewChange, ReviewSnapshot, ReviewUpdate } from '@lincyaw/kernel'
|
|
3
3
|
import type { WorkbenchStore } from './workbench.ts'
|
|
4
4
|
import { WorkspaceServerError } from './workspace-client.ts'
|
|
@@ -129,7 +129,7 @@ export class DocumentHistory {
|
|
|
129
129
|
#change(which: 'undo' | 'redo' | 'revertRevision', expect: string | undefined): Promise<boolean> {
|
|
130
130
|
const binding = this.#store.state.history?.historyBinding
|
|
131
131
|
if (!binding || !expect) return Promise.resolve(false)
|
|
132
|
-
const request = { id:
|
|
132
|
+
const request = { id: randomUUID(), ...binding, expect }
|
|
133
133
|
return this.#run(dir => this.#client[which](dir, request))
|
|
134
134
|
}
|
|
135
135
|
|
package/src/index.ts
CHANGED
|
@@ -26,9 +26,6 @@ export { HistoryPanel } from './panels/HistoryPanel.tsx'
|
|
|
26
26
|
export type { HistoryPanelProps, HistoryRevisionAction } from './panels/HistoryPanel.tsx'
|
|
27
27
|
export { HomePanel } from './panels/HomePanel.tsx'
|
|
28
28
|
export { WorkbenchApprovals } from './approvals.tsx'
|
|
29
|
-
export { assistantMascotAction, useAssistantMascot } from './assistant-mascot.ts'
|
|
30
|
-
export type { AssistantActivity } from './assistant-mascot.ts'
|
|
31
|
-
export { mascotEnabled, setMascotEnabled, useMascotEnabled } from './mascot-preference.ts'
|
|
32
29
|
export { PreviewPanel } from './panels/PreviewPanel.tsx'
|
|
33
30
|
export { SpeechSettingsPanel } from './panels/SpeechSettingsPanel.tsx'
|
|
34
31
|
export { SPEECH_SETTINGS_MESSAGES } from './speech-settings-messages.ts'
|
package/src/messages.ts
CHANGED
|
@@ -330,7 +330,6 @@ const zh = {
|
|
|
330
330
|
'history-result-no-longer-current': '之前的结果已不是当前版本,请查看最新的历史。',
|
|
331
331
|
'authoring-review-required': '有修改等待你审阅,请先接受或放弃。',
|
|
332
332
|
} as Record<string, string>,
|
|
333
|
-
agentWorking: 'AI 正在修改文稿…',
|
|
334
333
|
agentWaiting: (n: number) => `AI 修改了 ${n} 处内容,要接受这些修改吗?`,
|
|
335
334
|
accept: '接受',
|
|
336
335
|
reject: '拒绝',
|
|
@@ -700,7 +699,6 @@ const en: WorkbenchMessages = {
|
|
|
700
699
|
'history-result-no-longer-current': 'The earlier result is no longer the current version. Review the latest history.',
|
|
701
700
|
'authoring-review-required': 'Changes are waiting for your review. Accept or discard them first.',
|
|
702
701
|
},
|
|
703
|
-
agentWorking: 'The AI is editing the document…',
|
|
704
702
|
agentWaiting: (n: number) => `The AI changed ${n} file${n === 1 ? '' : 's'}. Accept the changes?`,
|
|
705
703
|
accept: 'Accept',
|
|
706
704
|
reject: 'Reject',
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
|
2
2
|
import type { ReactNode, RefObject } from 'react'
|
|
3
|
-
import { PmButton, PmDialog, PmIconButton,
|
|
3
|
+
import { PmButton, PmDialog, PmIconButton, PmMenu, PmNotice, PmSkeleton, PmSortableList, PmToolbar, PmToolbarButton } from '../components.tsx'
|
|
4
4
|
import { useMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
5
5
|
import { failureReason, timeAgo } from '../messages.ts'
|
|
6
6
|
import { SHORTCUTS } from '../shortcuts.ts'
|
|
@@ -409,10 +409,8 @@ function DocumentNotices() {
|
|
|
409
409
|
const askFailure = useWorkbenchState(state => (state.pointer ? undefined : state.askFailure))
|
|
410
410
|
return (
|
|
411
411
|
<div className="pmw-notices">
|
|
412
|
-
{review?.running && <PmNotice tone="accent"><PmMascot size="small" action={review.changes.length > 0 ? 'write' : 'read'} />{t.agentWorking}</PmNotice>}
|
|
413
412
|
{review && !review.running && review.changes.length > 0 && (
|
|
414
413
|
<PmNotice tone="accent">
|
|
415
|
-
<PmMascot size="small" action="ask" />
|
|
416
414
|
<span>{t.agentWaiting(review.changes.length)}</span>
|
|
417
415
|
<span className="pmw-notice__actions">
|
|
418
416
|
<PmButton small onClick={() => void workbench.rejectReview()}>{t.reject}</PmButton>
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { useEffect, useState } from 'react'
|
|
2
|
-
import type { CSSProperties } from 'react'
|
|
3
2
|
import type { CompileJob, OutputTarget } from '@lincyaw/kernel'
|
|
4
3
|
import type { IconName } from '@lincyaw/design'
|
|
5
|
-
import { PmBadge, PmButton, PmDialog, PmEmpty, PmIcon, PmIconButton,
|
|
4
|
+
import { PmBadge, PmButton, PmDialog, PmEmpty, PmIcon, PmIconButton, PmNotice } from '../components.tsx'
|
|
6
5
|
import { useMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
7
6
|
import { failureReason, timeAgo } from '../messages.ts'
|
|
8
7
|
|
|
@@ -105,10 +104,6 @@ function JobItem({ job, label, current, onPlay }: { job: CompileJob, label: stri
|
|
|
105
104
|
</p>
|
|
106
105
|
{job.state === 'running' && progress && (
|
|
107
106
|
<div className="pmw-job__progress">
|
|
108
|
-
{/* the kitten runs along the bar to how far the job has come; with no total yet it walks at the start */}
|
|
109
|
-
<span className="pmw-job__runner" style={{ '--pmw-job-done': progress.total ? Math.min(1, (progress.done ?? 0) / progress.total) : 0 } as CSSProperties}>
|
|
110
|
-
<PmMascot size="small" action={progress.total ? 'run' : 'walk'} />
|
|
111
|
-
</span>
|
|
112
107
|
<progress max={progress.total ?? 1} value={progress.total ? progress.done ?? 0 : undefined} aria-label={label} />
|
|
113
108
|
<span>{t.jobProgress(t.jobPhases[progress.phase] ?? t.outputLabels[progress.phase] ?? progress.phase, progress.done, progress.total)}</span>
|
|
114
109
|
</div>
|
|
@@ -6,7 +6,6 @@ import { PmButton, PmNotice } from '../components.tsx'
|
|
|
6
6
|
import { useMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
7
7
|
import { slideAspect } from '../workbench.ts'
|
|
8
8
|
import { failureReason } from '../messages.ts'
|
|
9
|
-
import { PreviewChangeTrail } from './ChangeTrail.tsx'
|
|
10
9
|
|
|
11
10
|
/**
|
|
12
11
|
* The open document as its readers see it (the web form or the slides), with the tools for what the author points at.
|
|
@@ -29,7 +28,6 @@ export function PreviewPanel({ active = true, onPresentationAction, presentation
|
|
|
29
28
|
const reload = useWorkbenchState(state => state.previewReload)
|
|
30
29
|
const aspect = useWorkbenchState(state => (state.previewRenderer === 'slides' ? slideAspect(state.ir) : undefined))
|
|
31
30
|
const container = useRef<HTMLDivElement>(null)
|
|
32
|
-
const stage = useRef<HTMLDivElement>(null)
|
|
33
31
|
const pool = useRef<ReturnType<typeof createPreviewPool>>()
|
|
34
32
|
const [loads, setLoads] = useState(0)
|
|
35
33
|
const [{ ready, mismatch, identityFailure, handshakeFailure, canvasGate }, setStatus] = useState<PreviewFrameStatus>({ ready: false })
|
|
@@ -70,9 +68,8 @@ export function PreviewPanel({ active = true, onPresentationAction, presentation
|
|
|
70
68
|
{failure && <PmNotice tone="danger"><span>{t.previewFailed(failureReason(t, failure))}</span><PmButton small onClick={() => workbench.retryPreview()}>{t.retry}</PmButton></PmNotice>}
|
|
71
69
|
{(!ready || !snapshotMatches) && !failure && !handshakeFailure && !(renderer === 'slides' && preview && !preview.slides) && <p className="pmw-muted pmw-preview__loading">{presentation && ready && !snapshotMatches && !preparing ? t.presentationOutdated : address ? t.previewLoading : t.previewPreparing}</p>}
|
|
72
70
|
{renderer === 'slides' && preview && !preview.slides && <p className="pmw-muted pmw-preview__loading">{t.noSlides}</p>}
|
|
73
|
-
<div
|
|
71
|
+
<div className="pmw-preview__stage">
|
|
74
72
|
<div ref={container} className="pmw-preview__frames" data-renderer={renderer} data-pending-snapshot={!snapshotMatches || undefined} data-presentation-gated={presentation && canvasGate || undefined} style={aspect === undefined ? undefined : { '--pmw-slide-aspect': aspect } as CSSProperties} />
|
|
75
|
-
{!presentation && <PreviewChangeTrail stage={stage} frames={container} />}
|
|
76
73
|
</div>
|
|
77
74
|
</section>
|
|
78
75
|
)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useEffect, useRef, useState } from 'react'
|
|
2
|
-
import { CAPTION_TIMING_MAX_SEGMENTS, captionSourceFingerprint, captionTimingProblem, stepCaptionText } from '@lincyaw/kernel'
|
|
2
|
+
import { CAPTION_TIMING_MAX_SEGMENTS, captionSourceFingerprint, captionTimingProblem, randomUUID, stepCaptionText } from '@lincyaw/kernel'
|
|
3
3
|
import type { CaptionTiming, CaptionTimingSource, DocumentCaptionTimingAction, ProductionPlan } from '@lincyaw/kernel'
|
|
4
4
|
import { PmButton, PmCard, PmDialog, PmInput, PmNotice } from '../components.tsx'
|
|
5
5
|
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
@@ -23,7 +23,7 @@ function lineRows(text: string): Row[] {
|
|
|
23
23
|
else if (ranges.length && !text.slice(ranges.at(-1)!.from, ranges.at(-1)!.to).trim()) ranges[ranges.length - 1]!.to = to
|
|
24
24
|
else ranges.push({ from, to })
|
|
25
25
|
}
|
|
26
|
-
return ranges.map(range => ({ ...range, id:
|
|
26
|
+
return ranges.map(range => ({ ...range, id: randomUUID(), start: '', end: '' }))
|
|
27
27
|
}
|
|
28
28
|
function valueOf(draft: Draft): CaptionTiming | undefined {
|
|
29
29
|
if (!draft.basis.available || !draft.basis.playbackFingerprint || draft.basis.durationMs === undefined) return
|
|
@@ -72,7 +72,7 @@ export function ProductionCaptionTiming({ identity, stepId, plan, current, loadi
|
|
|
72
72
|
const action: DocumentCaptionTimingAction = automatic ? { type: 'caption.timing.reset', stepId } : { type: 'caption.timing.set', stepId, value: value! }
|
|
73
73
|
request.current = controller; setBusy(true); setFailure(undefined)
|
|
74
74
|
try {
|
|
75
|
-
const answer = await workbench.applyDocumentCaptionTiming(action,
|
|
75
|
+
const answer = await workbench.applyDocumentCaptionTiming(action, randomUUID(), expected, controller.signal)
|
|
76
76
|
needsRefresh.current = true
|
|
77
77
|
if (!alive.current || workbench.getState().authoring?.identity !== identity) return
|
|
78
78
|
const ownsInput = drafts.current.get(target) === sent
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { useEffect, useRef, useState } from 'react'
|
|
2
2
|
import type { DocumentChangeAnswer, MediaClip, ProductionAssetInspection, ProductionBinding, TeachingDocument } from '@lincyaw/kernel'
|
|
3
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
3
4
|
import { MediaClipEditor } from '../MediaClipEditor.tsx'
|
|
4
5
|
import type { MediaClipDraft } from '../MediaClipEditor.tsx'
|
|
5
6
|
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
@@ -18,7 +19,7 @@ interface Props {
|
|
|
18
19
|
disabled: boolean
|
|
19
20
|
onChanged(): void
|
|
20
21
|
}
|
|
21
|
-
const newDraft = (version: string, stepId: string): MediaClipDraft => ({ version, clip: { id: `clip_${
|
|
22
|
+
const newDraft = (version: string, stepId: string): MediaClipDraft => ({ version, clip: { id: `clip_${randomUUID().replaceAll('-', '')}`, assetId: '', sourceRange: { startMs: 0, endMs: 0 }, attachment: { stepId, offsetMs: 0 }, volume: 1, muted: false } })
|
|
22
23
|
const fromClip = (version: string, clip: MediaClip): MediaClipDraft => ({ version, clip: structuredClone(clip), baseClip: structuredClone(clip) })
|
|
23
24
|
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
|
|
24
25
|
const draftKey = (clipId?: string) => clipId === undefined ? 'new' : `clip:${clipId}`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useEffect, useId, useRef, useState } from 'react'
|
|
2
|
-
import { recordingSourceRange } from '@lincyaw/kernel'
|
|
2
|
+
import { randomUUID, recordingSourceRange } from '@lincyaw/kernel'
|
|
3
3
|
import type { DocumentRecordingAdoption, ProductionAssetInspection, TimeRange, VoiceSource } from '@lincyaw/kernel'
|
|
4
4
|
import { PmButton, PmInput, PmNotice } from '../components.tsx'
|
|
5
5
|
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
@@ -81,7 +81,7 @@ export function ProductionRecordingRange({ identity, sectionId, stepId, active,
|
|
|
81
81
|
const controller = new AbortController(), proposed = { startMs: start!, endMs: end! }
|
|
82
82
|
const previous = sent.current?.request
|
|
83
83
|
const change: DocumentRecordingAdoption = previous && previous.source.version === source.version && previous.stepId === stepId && previous.assetId === voice.assetId && previous.sha256 === inspected.sha256 && same(previous.sourceRange, proposed)
|
|
84
|
-
? previous : { id:
|
|
84
|
+
? previous : { id: randomUUID(), source: { documentId: source.content.id, version: source.version, fingerprint: source.fingerprint }, stepId, assetId: voice.assetId, sha256: inspected.sha256, sourceRange: proposed }
|
|
85
85
|
const stored = drafts.current.get(key) ?? draft
|
|
86
86
|
drafts.current.set(key, stored); sent.current = { key, draft: stored, request: change }; request.current = controller
|
|
87
87
|
setBusy(true); setFailure(undefined)
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
|
2
2
|
import type { DocumentTranscriptionRequest, TeachingDocument, TranscriptionCapabilities, TranscriptionListAnswer, TranscriptionRevision, TranscriptionTask } from '@lincyaw/kernel'
|
|
3
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
3
4
|
import { PmBadge, PmButton, PmCard, PmDialog, PmField, PmIconButton, PmNotice, PmSelect } from '../components.tsx'
|
|
4
5
|
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
5
6
|
import { documentTranscriptionSession } from '../transcription-session.ts'
|
|
@@ -94,7 +95,7 @@ export function ProductionTranscription({ identity, directory, document, section
|
|
|
94
95
|
try {
|
|
95
96
|
const expected = { identity, version: now.version }, audio = await workbench.inspectDocumentAudio(assetId, expected, controller.signal)
|
|
96
97
|
if (!current() || controller.signal.aborted) return
|
|
97
|
-
const request: DocumentTranscriptionRequest = { intent: `transcription_${
|
|
98
|
+
const request: DocumentTranscriptionRequest = { intent: `transcription_${randomUUID()}`, source: { documentId: now.content.id, version: now.version, fingerprint: now.fingerprint }, assetId, audioSha256: audio.inspection.sha256, engine, lang: now.content.metadata.lang, confirmed: true }
|
|
98
99
|
await session.start(request, () => workbench.startDocumentTranscription(request, expected))
|
|
99
100
|
} catch (error) { if (current() && !controller.signal.aborted) setFailure(transcriptionFailure(error, locale)) }
|
|
100
101
|
finally { if (inspectionRequest.current === controller) { inspectionRequest.current = undefined; if (current()) setInspecting(false) } }
|
|
@@ -10,7 +10,6 @@ import { nativeEditingCursor } from '../document-editor/selection.ts'
|
|
|
10
10
|
import { hasBlockPreview } from '../document-editor/projection.ts'
|
|
11
11
|
import type { NativeDocumentEditor } from '../document-editor/schema.tsx'
|
|
12
12
|
import { isAgentChanging } from '../workbench.ts'
|
|
13
|
-
import { EditorChangeTrail } from './ChangeTrail.tsx'
|
|
14
13
|
|
|
15
14
|
/** Source editing is available before the first successful runtime compilation. */
|
|
16
15
|
export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore }: { commentsPortal?: HTMLElement | null, onCommentDraftRestore?(): void }) {
|
|
@@ -26,7 +25,6 @@ export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore }: {
|
|
|
26
25
|
const navigation = useWorkbenchState(state => state.documentNavigation)
|
|
27
26
|
const readOnly = useWorkbenchState(state => state.mode !== 'editing' || workbench.client.capabilities?.readOnly === true || Boolean(state.authoring?.member && !hasRole(state.authoring.member, 'editor')) || Boolean(state.authoring?.loading) || isAgentChanging(state))
|
|
28
27
|
const container = useRef<HTMLElement>(null)
|
|
29
|
-
const sheet = useRef<HTMLDivElement>(null)
|
|
30
28
|
const consumedNavigation = useRef<string>()
|
|
31
29
|
const bodyEditor = useRef<NativeDocumentEditor>()
|
|
32
30
|
const editingPosition = useRef<{ nativeBlockId: string, sectionId: string, position: number, editor: NativeDocumentEditor, identity: string, reset: number | undefined }>()
|
|
@@ -176,8 +174,7 @@ export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore }: {
|
|
|
176
174
|
{source?.issues.length ? <div className="pmw-source-document__diagnostics"><PmNotice tone="warn"><details><summary>{messages.diagnostics(source.issues.length)}</summary><ul>{source.issues.map((issue, index) => <li key={`${issue.path}:${index}`}><code>{issue.path}</code> {issue.message}</li>)}</ul></details></PmNotice></div> : null}
|
|
177
175
|
{!source?.content || !source.identity ? source?.loading
|
|
178
176
|
? <div className="pmw-source-document__sheet pmw-source-document__sheet--loading"><PmSkeleton label={messages.loading} /></div>
|
|
179
|
-
: <PmNotice tone="warn"><span>{messages.unavailable}</span><span className="pmw-notice__actions"><PmButton small onClick={() => void workbench.retryDocument()}>{t.retry}</PmButton></span></PmNotice> : <div
|
|
180
|
-
<EditorChangeTrail sheet={sheet} />
|
|
177
|
+
: <PmNotice tone="warn"><span>{messages.unavailable}</span><span className="pmw-notice__actions"><PmButton small onClick={() => void workbench.retryDocument()}>{t.retry}</PmButton></span></PmNotice> : <div className="pmw-source-document__sheet">
|
|
181
178
|
<DocumentEditor acknowledged={sourceAcknowledged()} getDocumentAcknowledged={sourceAcknowledged} onCommentDraftRestore={onCommentDraftRestore} commentDrafts={workbench.documentCommentDrafts(source.identity)} identity={source.identity} document={source.content} version={source.version} member={source.member} getDocument={() => workbench.getDocument(source.identity)}
|
|
182
179
|
getDocumentVersion={() => { const current = workbench.getState().authoring; return current && current.identity === source.identity && current.reset === source.reset ? current.version : undefined }} reset={source.reset} locale={locale} readOnly={readOnly}
|
|
183
180
|
uploadImage={(file, signal) => workbench.importDocumentImage(file, source.identity!, signal)}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { useEffect, useMemo, useRef, useState } from 'react'
|
|
2
|
-
import { prepareTranscriptionAdoption } from '@lincyaw/kernel'
|
|
2
|
+
import { prepareTranscriptionAdoption, randomUUID } from '@lincyaw/kernel'
|
|
3
3
|
import type { CanonicalSource, NarrationNode, TeachingDocument, TranscriptionRevision, TranscriptionAdoptionDraft, TranscriptionAdoptionPart, TranscriptionAdoptionPlan } from '@lincyaw/kernel'
|
|
4
4
|
import { PmBadge, PmButton, PmDialog, PmField, PmNotice, PmSelect, PmTextarea } from '../components.tsx'
|
|
5
5
|
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
@@ -14,7 +14,7 @@ const ordered = (value: unknown): unknown => Array.isArray(value) ? value.map(or
|
|
|
14
14
|
const same = (a: unknown, b: unknown) => JSON.stringify(ordered(a)) === JSON.stringify(ordered(b))
|
|
15
15
|
const displayed = (nodes: readonly NarrationNode[]) => nodes.map(node => node.type === 'text' ? node.text : node.type === 'pronunciation' ? node.display : '').join('')
|
|
16
16
|
function restore(key: string): { draft: Draft, failed: boolean } {
|
|
17
|
-
const fallback = () => ({ draft: { id:
|
|
17
|
+
const fallback = () => ({ draft: { id: randomUUID(), revision: 0, discarded: [], shared: 'fork' as const }, failed: false })
|
|
18
18
|
try {
|
|
19
19
|
const raw = localStorage.getItem(key)
|
|
20
20
|
if (!raw) return fallback()
|
|
@@ -83,7 +83,7 @@ function AdoptionTarget({ identity, candidate, document, sectionId, stepId, disa
|
|
|
83
83
|
const now = workbench.getState().authoring
|
|
84
84
|
if (disabled || reviewing || applying || composing || !sourceReady || !now?.version || !now.fingerprint || parsed.invalid) return
|
|
85
85
|
pause()
|
|
86
|
-
if (latest.current.baseVersion && latest.current.baseVersion !== now.version) change({ id:
|
|
86
|
+
if (latest.current.baseVersion && latest.current.baseVersion !== now.version) change({ id: randomUUID(), baseVersion: now.version })
|
|
87
87
|
else if (!latest.current.baseVersion) change({ baseVersion: now.version })
|
|
88
88
|
const value = latest.current, request = ++generation.current, normalized = content()
|
|
89
89
|
const retainsOriginal = references.length > 1 && value.shared === 'fork'
|
|
@@ -104,7 +104,7 @@ function AdoptionTarget({ identity, candidate, document, sectionId, stepId, disa
|
|
|
104
104
|
try {
|
|
105
105
|
const answer = await workbench.adoptDocumentTranscription({ planId, source: sent.source, candidate: sent.candidate, draftRevision: sent.draftRevision }, { identity, version: sent.source.version })
|
|
106
106
|
if (latest.current.id === sent.changeId && latest.current.revision === sent.draftRevision) {
|
|
107
|
-
const next: Draft = { ...latest.current, id:
|
|
107
|
+
const next: Draft = { ...latest.current, id: randomUUID(), revision: 0, discarded: [], baseVersion: answer.version, applied: true }
|
|
108
108
|
latest.current = next; setDraft(next)
|
|
109
109
|
try { localStorage.setItem(key, JSON.stringify(next)); setStorageFailed(false) } catch { setStorageFailed(true) }
|
|
110
110
|
}
|
package/src/places.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { irBlocks } from '@lincyaw/kernel'
|
|
2
|
-
import type { IRDocument, PreviewAnchor, ReviewChange, SourcePos
|
|
2
|
+
import type { IRDocument, PreviewAnchor, ReviewChange, SourcePos } from '@lincyaw/kernel'
|
|
3
3
|
|
|
4
4
|
const CHANGED_PLACES = 100
|
|
5
5
|
|
|
@@ -65,38 +65,3 @@ export function changedPlaces(doc: IRDocument, changes: readonly ReviewChange[])
|
|
|
65
65
|
}
|
|
66
66
|
return [...places.values()].slice(0, CHANGED_PLACES)
|
|
67
67
|
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* The places that differ between two versions of a document: each block whose content changed or that is new (with
|
|
71
|
-
* its page), each page whose title changed or that is new, and the block of each step whose narration or settings
|
|
72
|
-
* changed, at most CHANGED_PLACES.
|
|
73
|
-
*/
|
|
74
|
-
export function changedBlocks(before: TeachingDocument, after: TeachingDocument): PreviewAnchor[] {
|
|
75
|
-
const places: PreviewAnchor[] = []
|
|
76
|
-
const visit = (section: string, ids: readonly string[]) => {
|
|
77
|
-
for (const id of ids) {
|
|
78
|
-
const block = after.blocks[id]
|
|
79
|
-
if (!block) continue
|
|
80
|
-
if (JSON.stringify(block) !== JSON.stringify(before.blocks[id])) places.push({ section, block: id })
|
|
81
|
-
if ('children' in block && Array.isArray(block.children)) visit(section, block.children as string[])
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
for (const id of after.sectionOrder) {
|
|
85
|
-
const section = after.sections[id]
|
|
86
|
-
if (!section) continue
|
|
87
|
-
if (before.sections[id]?.title !== section.title) places.push({ section: id })
|
|
88
|
-
visit(id, section.children)
|
|
89
|
-
}
|
|
90
|
-
// A changed step, or a changed narration of it, shows at the block the step plays (else at its page).
|
|
91
|
-
const seen = new Set(places.map(place => `${place.section}\0${place.block ?? ''}`))
|
|
92
|
-
for (const step of Object.values(after.steps)) {
|
|
93
|
-
const narrated = step.narrationIds.some(id => JSON.stringify(after.narrations[id]) !== JSON.stringify(before.narrations[id]))
|
|
94
|
-
if (!narrated && JSON.stringify(step) === JSON.stringify(before.steps[step.id])) continue
|
|
95
|
-
// the component the step plays, where its narration shows, else any block it shows
|
|
96
|
-
const block = step.visuals.find(visual => after.blocks[visual.blockId]?.type === 'component')?.blockId ?? step.visuals.find(visual => visual.visible)?.blockId ?? step.visuals[0]?.blockId
|
|
97
|
-
const place = { section: step.sectionId, ...block ? { block } : {} }
|
|
98
|
-
const key = `${place.section}\0${place.block ?? ''}`
|
|
99
|
-
if (!seen.has(key)) { seen.add(key); places.push(place) }
|
|
100
|
-
}
|
|
101
|
-
return places.slice(0, CHANGED_PLACES)
|
|
102
|
-
}
|
package/src/styles.css
CHANGED
|
@@ -824,17 +824,6 @@
|
|
|
824
824
|
accent-color: var(--pm-color-accent);
|
|
825
825
|
}
|
|
826
826
|
|
|
827
|
-
/* The kitten above the bar, as far along it as the job has come (`--pmw-job-done`, 0 to 1), never past its ends. */
|
|
828
|
-
.pmw-job__runner {
|
|
829
|
-
display: block;
|
|
830
|
-
margin-left: calc((100% - var(--pm-size-mascot-sm)) * var(--pmw-job-done));
|
|
831
|
-
line-height: 0;
|
|
832
|
-
}
|
|
833
|
-
|
|
834
|
-
.pmw-job__runner:empty {
|
|
835
|
-
display: none;
|
|
836
|
-
}
|
|
837
|
-
|
|
838
827
|
.pmw-job__error {
|
|
839
828
|
margin: 0;
|
|
840
829
|
color: var(--pm-color-danger);
|
|
@@ -936,7 +925,7 @@
|
|
|
936
925
|
.pmw-source-document__recovery-actions { display: flex; flex-wrap: wrap; gap: var(--pm-space-2); }
|
|
937
926
|
.pmw-source-document__diagnostics { margin-block-end: var(--pm-space-3); }
|
|
938
927
|
/* Its end margin is the editor's own end area, which fills the rest of the sheet and takes the presses below the last block. */
|
|
939
|
-
.pmw-source-document__sheet {
|
|
928
|
+
.pmw-source-document__sheet { display: flex; flex-direction: column; max-width: var(--pm-sheet-width); min-height: 100%; margin-inline: auto; padding-block-start: var(--pm-space-4); background: var(--pm-color-surface); box-shadow: var(--pm-shadow-page); }
|
|
940
929
|
/* Opening: the page's own margins, so that the placeholder lines sit where the text will. */
|
|
941
930
|
.pmw-source-document__sheet--loading { box-sizing: border-box; padding: var(--pm-space-10) var(--pm-space-12); }
|
|
942
931
|
.pmw-voice__filters { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--pm-space-3); }
|
|
@@ -1009,22 +998,3 @@
|
|
|
1009
998
|
.pmw-approvals .pmw-muted { margin: 0; }
|
|
1010
999
|
.pmw-approvals__detail { max-height: 30vh; margin: 0; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
1011
1000
|
.pmw-approvals__actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: var(--pm-space-2); }
|
|
1012
|
-
|
|
1013
|
-
/* The kitten walking over the preview to the blocks the AI changed: its ground line meets the block's lower left. */
|
|
1014
|
-
.pmw-change-trail {
|
|
1015
|
-
position: absolute;
|
|
1016
|
-
top: 0;
|
|
1017
|
-
left: 0;
|
|
1018
|
-
z-index: 1;
|
|
1019
|
-
pointer-events: none;
|
|
1020
|
-
transform: translate(calc(var(--pmw-trail-x) - 45%), calc(var(--pmw-trail-y) - 89%));
|
|
1021
|
-
transition: transform var(--pm-duration-walk) linear, opacity var(--pm-duration-slow);
|
|
1022
|
-
}
|
|
1023
|
-
|
|
1024
|
-
.pmw-change-trail[data-phase='done'] {
|
|
1025
|
-
opacity: 0.9;
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
.pmw-change-trail__facing[data-facing='left'] {
|
|
1029
|
-
transform: scaleX(-1);
|
|
1030
|
-
}
|
package/src/workbench.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { applyDocumentCaptionTiming } from '@lincyaw/kernel'
|
|
1
|
+
import { applyDocumentCaptionTiming, randomUUID } from '@lincyaw/kernel'
|
|
2
2
|
import type { DocumentCaptionTimingAction } from '@lincyaw/kernel'
|
|
3
3
|
import { reconcileCaptionTiming } from './caption-timing.ts'
|
|
4
4
|
import type { ProjectOperation, ProjectPlan } from '@lincyaw/kernel'
|
|
@@ -49,7 +49,7 @@ import { DocumentJobs } from './jobs.ts'
|
|
|
49
49
|
import { VoiceoverJobs } from './voiceover-jobs.ts'
|
|
50
50
|
import { contentText, localeOf, MESSAGES } from './messages.ts'
|
|
51
51
|
import type { AgentPlace, Locale } from './messages.ts'
|
|
52
|
-
import {
|
|
52
|
+
import { changedPlaces, findPlaceAtLine, findPlaceSource } from './places.ts'
|
|
53
53
|
import { OperationLog } from './telemetry.ts'
|
|
54
54
|
import type { OperationValue } from './telemetry.ts'
|
|
55
55
|
import { PreviewPlayback } from './preview-playback.ts'
|
|
@@ -169,10 +169,6 @@ export interface WorkbenchState {
|
|
|
169
169
|
isRepairingDiagnostics: boolean
|
|
170
170
|
diagnosticsRepairFailure?: string
|
|
171
171
|
pointer?: Pointer
|
|
172
|
-
/** Where the blocks the AI just changed are in the preview, for the kitten to walk to; `id` is new for each change. */
|
|
173
|
-
changeTrail?: { id: number, rects: PreviewRect[] }
|
|
174
|
-
/** The places the AI just changed, for the kitten in the editor to walk to; `id` is new for each change. */
|
|
175
|
-
changedPlaces?: { id: number, targets: PreviewAnchor[] }
|
|
176
172
|
save: SaveState
|
|
177
173
|
/** What the conversation's agent is told the author points at. */
|
|
178
174
|
focus: FocusReport[]
|
|
@@ -337,7 +333,6 @@ export class Workbench {
|
|
|
337
333
|
#pendingReveal?: PreviewAnchor
|
|
338
334
|
/** The AI's changes to show on the document once the preview has them. */
|
|
339
335
|
#pendingFlash?: ReviewChange[]
|
|
340
|
-
#trail = 0
|
|
341
336
|
#lastPosition?: string
|
|
342
337
|
#awaitingView?: WebView
|
|
343
338
|
/** The forms asked for ahead of the author (`web:<dir>`, `slides:<dir>`), and the wait before asking for the slides. */
|
|
@@ -424,12 +419,6 @@ export class Workbench {
|
|
|
424
419
|
&& previous?.identity === authoring.identity && Boolean(previous?.version && authoring.version)
|
|
425
420
|
&& (previous?.version !== authoring.version || previous?.fingerprint !== authoring.fingerprint)
|
|
426
421
|
if (!authoring.dirty && previous?.dirty || acknowledgedSourceChanged) { void this.#history.read(authoring.directory); void this.loadDocuments() }
|
|
427
|
-
// The source changed under an author with nothing unsaved while the AI holds a review: the AI changed it. The
|
|
428
|
-
// editor's kitten walks to the blocks whose content differs.
|
|
429
|
-
if (acknowledgedSourceChanged && !previous?.dirty && !previous?.saving && this.#state.review && previous?.content && authoring.content) {
|
|
430
|
-
const targets = changedBlocks(previous.content, authoring.content)
|
|
431
|
-
if (targets.length) this.#set({ changedPlaces: { id: ++this.#trail, targets } })
|
|
432
|
-
}
|
|
433
422
|
})
|
|
434
423
|
this.#diagnostics = new DocumentDiagnostics(this.client, store)
|
|
435
424
|
this.#jobs = new DocumentJobs(this.client, store)
|
|
@@ -571,7 +560,7 @@ export class Workbench {
|
|
|
571
560
|
}
|
|
572
561
|
|
|
573
562
|
planDocumentOperation(operation: ProjectOperation): Promise<ProjectPlan> {
|
|
574
|
-
return this.client.planProjectChange({ id:
|
|
563
|
+
return this.client.planProjectChange({ id: randomUUID(), operation })
|
|
575
564
|
}
|
|
576
565
|
|
|
577
566
|
operateDocument(operation: ProjectOperation, planned?: ProjectPlan): Promise<OperationAnswer> {
|
|
@@ -804,7 +793,6 @@ export class Workbench {
|
|
|
804
793
|
this.#pendingFlash = undefined
|
|
805
794
|
const targets = changedPlaces(ir.doc, changes)
|
|
806
795
|
if (targets.length === 0) return
|
|
807
|
-
this.#trail++
|
|
808
796
|
this.#broadcast({ type: 'flash', targets })
|
|
809
797
|
this.#record('ai.change.shown', { 'presmium.places': targets.map(target => [target.section, target.block].filter(Boolean).join(':')).join('\n') })
|
|
810
798
|
}
|
|
@@ -1414,7 +1402,7 @@ export class Workbench {
|
|
|
1414
1402
|
let request: { identity: string, version: string, id: string } | undefined
|
|
1415
1403
|
const answer = await this.#writeDocumentMedia(expected, async directory => {
|
|
1416
1404
|
const existing = this.#audioImports.get(file), first = !existing || existing.identity !== expected.identity
|
|
1417
|
-
request = first ? { identity: expected.identity, version: expected.version, id:
|
|
1405
|
+
request = first ? { identity: expected.identity, version: expected.version, id: randomUUID() } : existing!
|
|
1418
1406
|
this.#audioImports.set(file, request)
|
|
1419
1407
|
try { return await this.client.importDocumentAudio(directory, file, { id: request.id, baseDocumentVersion: request.version }, signal) }
|
|
1420
1408
|
catch (error) {
|
|
@@ -1483,13 +1471,13 @@ export class Workbench {
|
|
|
1483
1471
|
async applyDocumentMediaClip(clip: MediaClip, expected: { identity: string, version: string, binding: ProductionBinding }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
|
|
1484
1472
|
this.#mediaSource(expected)
|
|
1485
1473
|
if (!this.#state.productionPlan || !sameProductionBinding(this.#state.productionPlan.binding, expected.binding) || !this.#productionSourceCurrent(expected.binding)) throw new Error('production-source-changed')
|
|
1486
|
-
const id =
|
|
1474
|
+
const id = randomUUID(), value = structuredClone(clip)
|
|
1487
1475
|
const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, binding: expected.binding, clip: value }, signal), signal)
|
|
1488
1476
|
if (answer.changeId !== id) throw new Error('production-source-changed')
|
|
1489
1477
|
return answer
|
|
1490
1478
|
}
|
|
1491
1479
|
async removeDocumentMediaClip(clipId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
|
|
1492
|
-
const id =
|
|
1480
|
+
const id = randomUUID()
|
|
1493
1481
|
const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, removeClipId: clipId }, signal), signal)
|
|
1494
1482
|
if (answer.changeId !== id) throw new Error('production-source-changed')
|
|
1495
1483
|
return answer
|
|
@@ -1639,7 +1627,7 @@ export class Workbench {
|
|
|
1639
1627
|
const existing = target !== undefined && Object.hasOwn(document.narrations, target) ? document.narrations[target] : undefined
|
|
1640
1628
|
if (existing && !step.narrationIds.includes(existing.id)) throw new Error('document-narration-target')
|
|
1641
1629
|
if (!existing && !meaningful) return undefined
|
|
1642
|
-
const id = target ??
|
|
1630
|
+
const id = target ?? randomUUID()
|
|
1643
1631
|
if (!id || id.length > 200 || /[\u0000-\u001f]/.test(id) || ['__proto__', 'constructor', 'prototype'].includes(id)) throw new Error('document-narration-target')
|
|
1644
1632
|
if (!existing && (document.id === id || [document.sections, document.blocks, document.steps, document.assets, document.definitions].some(map => Object.hasOwn(map, id)))) throw new Error('document-narration-target')
|
|
1645
1633
|
if (existing && JSON.stringify(existing.content) === JSON.stringify(content)) return id
|
|
@@ -1856,7 +1844,7 @@ export class Workbench {
|
|
|
1856
1844
|
if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity) throw new Error('page-context-changed')
|
|
1857
1845
|
const page = document.sections[section]
|
|
1858
1846
|
if (!page) throw new Error('page-boundary')
|
|
1859
|
-
const copy = duplicateDocumentPage(document, section, contentText(document.metadata.lang).copyTitle(page.title), () =>
|
|
1847
|
+
const copy = duplicateDocumentPage(document, section, contentText(document.metadata.lang).copyTitle(page.title), () => randomUUID())
|
|
1860
1848
|
copied = copy.section
|
|
1861
1849
|
Object.assign(document, copy.document)
|
|
1862
1850
|
if (generation === this.#documentSelectionGeneration) this.#pendingDocumentFocus = { documentId: document.id, nodeId: `page:${copied}`, generation, afterSave: true }
|
|
@@ -1892,8 +1880,8 @@ export class Workbench {
|
|
|
1892
1880
|
if (this.#state.authoring?.version !== plan.source.version) throw new Error('revision-conflict')
|
|
1893
1881
|
const current = pageDeletion(document, plan.document, plan.source.version, plan.section)
|
|
1894
1882
|
if (!current.allowed) throw new Error(current.reason)
|
|
1895
|
-
Object.assign(document, removeDocumentPage(document, plan.section, () =>
|
|
1896
|
-
this.#set({ position: { section: document.sectionOrder[0]!, step: 0, trail: [], view: 'document' }, documentNavigation: { section: document.sectionOrder[0]!, request:
|
|
1883
|
+
Object.assign(document, removeDocumentPage(document, plan.section, () => randomUUID()))
|
|
1884
|
+
this.#set({ position: { section: document.sectionOrder[0]!, step: 0, trail: [], view: 'document' }, documentNavigation: { section: document.sectionOrder[0]!, request: randomUUID() } })
|
|
1897
1885
|
})
|
|
1898
1886
|
}
|
|
1899
1887
|
createPage(after = this.#state.position?.section): boolean {
|
|
@@ -1905,7 +1893,7 @@ export class Workbench {
|
|
|
1905
1893
|
this.#set({ pageEditFailure: undefined })
|
|
1906
1894
|
const created = commands.insertPage(after, contentText(source.content.metadata.lang).newPage)
|
|
1907
1895
|
this.#pendingDocumentField = undefined; this.#pendingDocumentSelection = undefined; this.#pendingDocumentFocus = undefined
|
|
1908
|
-
this.#set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request:
|
|
1896
|
+
this.#set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request: randomUUID() } })
|
|
1909
1897
|
// The default title is selected: the author's first words name the page, and Enter goes on to its body.
|
|
1910
1898
|
this.#focusDocumentNode(editor, `page:${created.sectionId}`, true)
|
|
1911
1899
|
return true
|
|
@@ -2042,7 +2030,7 @@ export class Workbench {
|
|
|
2042
2030
|
/** Shows a section in the preview: from the navigation pane, the section to read or the slide to show. */
|
|
2043
2031
|
goToSection(section: string): void {
|
|
2044
2032
|
if (this.#state.webView === 'document' && this.#state.authoring?.content?.sections[section]) {
|
|
2045
|
-
this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request:
|
|
2033
|
+
this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request: randomUUID() } }); return
|
|
2046
2034
|
}
|
|
2047
2035
|
this.goToStep(section, this.#selectedSteps.get(`${this.#state.document}\0${section}`) ?? 0)
|
|
2048
2036
|
}
|
|
@@ -2056,7 +2044,7 @@ export class Workbench {
|
|
|
2056
2044
|
const visible = (index: number) => Boolean(section.stepOrder[index] && effectiveComponentParameters(document, blockId, section.stepOrder[index]).visual?.visible)
|
|
2057
2045
|
const step = visible(current) ? current : Math.max(0, section.stepOrder.findIndex((_, index) => visible(index)))
|
|
2058
2046
|
this.#set({ position: { section: sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined,
|
|
2059
|
-
documentNavigation: { section: sectionId, block: blockId, request:
|
|
2047
|
+
documentNavigation: { section: sectionId, block: blockId, request: randomUUID() } })
|
|
2060
2048
|
}
|
|
2061
2049
|
|
|
2062
2050
|
observeDocumentSection(section: string): void {
|
|
@@ -2289,9 +2277,6 @@ export class Workbench {
|
|
|
2289
2277
|
} else if (this.#state.pointer?.quote) this.point(undefined)
|
|
2290
2278
|
break
|
|
2291
2279
|
}
|
|
2292
|
-
case 'flashed':
|
|
2293
|
-
if (this.#trail) this.#set({ changeTrail: { id: this.#trail, rects: report.rects } })
|
|
2294
|
-
break
|
|
2295
2280
|
case 'rect':
|
|
2296
2281
|
if (this.#state.pointer) this.#set({ pointer: { ...this.#state.pointer, rect: report.rect ?? undefined, obstacles: report.obstacles } })
|
|
2297
2282
|
break
|
package/src/workspace-client.ts
CHANGED
|
@@ -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 =
|
|
@@ -341,7 +342,7 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
|
|
|
341
342
|
if (operation.op === 'delete' && (!planned || JSON.stringify(planned.operation) !== JSON.stringify(operation))) throw new Error('project-deletion-plan-required')
|
|
342
343
|
const key = JSON.stringify(operation)
|
|
343
344
|
let intent = projectIntents.get(key)
|
|
344
|
-
if (!intent) { intent = { id:
|
|
345
|
+
if (!intent) { intent = { id: randomUUID() }; projectIntents.set(key, intent) }
|
|
345
346
|
while (projectIntents.size > 64) projectIntents.delete(projectIntents.keys().next().value!)
|
|
346
347
|
try {
|
|
347
348
|
intent.plan ??= planned
|
package/src/assistant-mascot.ts
DELETED
|
@@ -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
|
-
}
|
package/src/mascot-preference.ts
DELETED
|
@@ -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
|
-
}
|