@lincyaw/workbench 0.2.0-rc.123 → 0.2.0-rc.126

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.123",
3
+ "version": "0.2.0-rc.126",
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": {
@@ -55,8 +55,8 @@
55
55
  "@tiptap/pm": "3.32.0",
56
56
  "katex": "0.18.10",
57
57
  "react-resizable-panels": "4.14.5",
58
- "@lincyaw/design": "1.0.0-rc.122",
59
- "@lincyaw/kernel": "1.0.0-rc.122"
58
+ "@lincyaw/design": "1.0.0-rc.124",
59
+ "@lincyaw/kernel": "1.0.0-rc.124"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "react": "^18.3.1",
@@ -67,6 +67,6 @@
67
67
  "@types/react-dom": "18.3.7",
68
68
  "react": "^18.3.1",
69
69
  "react-dom": "^18.3.1",
70
- "@lincyaw/compiler": "1.0.0-rc.122"
70
+ "@lincyaw/compiler": "1.0.0-rc.124"
71
71
  }
72
72
  }
@@ -2,7 +2,7 @@ import { isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { PresmiumDocument } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from './document-draft-store.ts'
4
4
  import { sha256 as tokenOf } from './sha256.ts'
5
- import type { DraftStoreCommit, DraftStoreOperation } from './document-draft-store.ts'
5
+ import type { DraftStoreCommit, DraftStoreOperation, DraftStoreResult } from './document-draft-store.ts'
6
6
 
7
7
  export interface DocumentDraftReference { id: string, revision: number, token: string }
8
8
  export interface DocumentDraft {
@@ -47,10 +47,13 @@ function documentDraft(value: unknown, documentId: string): DocumentDraft | unde
47
47
  pendingHash: value.pendingHash, composing: value.composing, origins: value.origins }
48
48
  }
49
49
 
50
+ interface ParsedDraft { raw: string, documentId: string, value: StoredDocumentDraft, token?: string }
51
+
50
52
  /** Strictly committed document backups, with old localStorage copies identified as unconfirmed rescue material. */
51
53
  export class DocumentDrafts {
52
54
  readonly #owner = randomUUID()
53
55
  readonly #owned = new Map<string, { identity: string, revision: number, raw: string }>()
56
+ readonly #parsed = new Map<string, ParsedDraft[]>()
54
57
  #store?: DocumentDraftStore
55
58
  #identity?: string
56
59
  #closed = false
@@ -93,25 +96,37 @@ export class DocumentDrafts {
93
96
  signal?.throwIfAborted()
94
97
  try {
95
98
  if (typeof raw !== 'string' || raw.length > MAX_CHARS) throw new Error('document-draft-size')
96
- const value: unknown = JSON.parse(raw)
97
- if (!isRecord(value) || value.format !== 2 || value.identity !== identity || !idRevision(value) || key !== keyOf(identity, value.id)
98
- || typeof value.owner !== 'string' || !value.owner || value.owner.length > 200 || typeof value.updatedAt !== 'number' || !Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0 || Number.isNaN(new Date(value.updatedAt).getTime())) throw new Error('document-draft-data')
99
- const draft = documentDraft(value, documentId)
100
- if (!draft) throw new Error('document-draft-document')
101
- if (draft.baseHash.startsWith('json:')) draft.baseHash = await tokenOf(draft.baseHash.slice(5))
102
- if (draft.pendingHash?.startsWith('json:')) draft.pendingHash = await tokenOf(draft.pendingHash.slice(5))
103
- const token = await tokenOf(raw), marker = settledKey(identity, { id: value.id, revision: value.revision, token })
99
+ const { value, token } = await this.#parse(identity, documentId, key, raw)
100
+ const marker = settledKey(identity, { id: value.id, revision: value.revision, token })
104
101
  if (durable.get(marker) === token) continue
105
102
  if (source === 'rescue' && localStorage.getItem(marker) === token) continue
106
103
  const id = JSON.stringify([value.id, value.revision, token])
107
- if (!records.has(id)) records.set(id, { ...draft, format: 2, identity, id: value.id, owner: value.owner, revision: value.revision, updatedAt: value.updatedAt, token, source,
104
+ if (!records.has(id)) records.set(id, { ...value, token, source,
108
105
  owned: source === 'durable' && value.owner === this.#owner && (this.#owned.get(value.id)?.raw === raw || store.owns(key, raw)) })
109
106
  } catch { signal?.throwIfAborted(); failed = true }
110
107
  }
108
+ for (const key of this.#parsed.keys()) if (key.startsWith(prefix(identity)) && !values.some(value => value.key === key)) this.#parsed.delete(key)
111
109
  signal?.throwIfAborted()
112
110
  return { records: [...records.values()], failed }
113
111
  }
114
112
 
113
+ /** The same stored bytes are parsed and validated once: a long document's backup is read again after each of its writes. Contents are shared, never mutated. */
114
+ async #parse(identity: string, documentId: string, key: string, raw: string): Promise<{ value: StoredDocumentDraft, token: string }> {
115
+ const known = this.#parsed.get(key)?.find(entry => entry.raw === raw && entry.documentId === documentId)
116
+ if (known) return { value: known.value, token: known.token ??= await tokenOf(raw) }
117
+ const value: unknown = JSON.parse(raw)
118
+ if (!isRecord(value) || value.format !== 2 || value.identity !== identity || !idRevision(value) || key !== keyOf(identity, value.id)
119
+ || typeof value.owner !== 'string' || !value.owner || value.owner.length > 200 || typeof value.updatedAt !== 'number' || !Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0 || Number.isNaN(new Date(value.updatedAt).getTime())) throw new Error('document-draft-data')
120
+ const draft = documentDraft(value, documentId)
121
+ if (!draft) throw new Error('document-draft-document')
122
+ if (draft.baseHash.startsWith('json:')) draft.baseHash = await tokenOf(draft.baseHash.slice(5))
123
+ if (draft.pendingHash?.startsWith('json:')) draft.pendingHash = await tokenOf(draft.pendingHash.slice(5))
124
+ const parsed: StoredDocumentDraft = { ...draft, format: 2, identity, id: value.id, owner: value.owner, revision: value.revision, updatedAt: value.updatedAt }
125
+ const token = await tokenOf(raw)
126
+ this.#remember(key, { raw, documentId, value: parsed, token })
127
+ return { value: parsed, token }
128
+ }
129
+
115
130
  #record(identity: string, draft: DocumentDraft, previous?: StoredDocumentDraft): { record: StoredDocumentDraft, raw: string } | undefined {
116
131
  const store = this.#storage(identity)
117
132
  if (!store || !draftShape(draft)) return
@@ -124,14 +139,30 @@ export class DocumentDrafts {
124
139
  catch { return }
125
140
  }
126
141
 
142
+ // Storage holds this tab's committed write while later ones are in flight or waiting, so each key keeps those bytes, newest first.
143
+ #remember(key: string, entry: ParsedDraft): void {
144
+ this.#parsed.set(key, [entry, ...(this.#parsed.get(key) ?? []).filter(known => known.raw !== entry.raw)].slice(0, 8))
145
+ }
146
+ #settled(key: string, raw: string, result: DraftStoreResult): void {
147
+ const entries = this.#parsed.get(key), index = entries?.findIndex(entry => entry.raw === raw) ?? -1
148
+ if (!entries || index < 0) return
149
+ this.#parsed.set(key, result === 'committed' ? entries.slice(0, index + 1) : entries.filter((_, position) => position !== index))
150
+ }
151
+
152
+ // This tab's own bytes come from its open document, so reading them back does not parse them again.
153
+ #own(identity: string, next: { record: StoredDocumentDraft, raw: string }): void {
154
+ this.#owned.set(next.record.id, { identity, revision: next.record.revision, raw: next.raw })
155
+ this.#remember(keyOf(identity, next.record.id), { raw: next.raw, documentId: next.record.content.id, value: next.record })
156
+ }
157
+
127
158
  /** Admission is immediate; only done='committed' confirms a durable backup. */
128
159
  write(identity: string, draft: DocumentDraft, previous?: StoredDocumentDraft): DocumentDraftCommit | undefined {
129
160
  const next = this.#record(identity, draft, previous)
130
161
  if (!next) return
131
162
  const commit = this.#store!.put(keyOf(identity, next.record.id), next.raw)
132
163
  if (!commit) return
133
- this.#owned.set(next.record.id, { identity, revision: next.record.revision, raw: next.raw })
134
- void commit.done.then(() => this.#touch())
164
+ this.#own(identity, next)
165
+ void commit.done.then(result => { this.#settled(keyOf(identity, next.record.id), next.raw, result); this.#touch() })
135
166
  if (previous && previous.id !== next.record.id) this.archive(previous)
136
167
  return { ...commit, record: next.record, clearing: false }
137
168
  }
@@ -139,7 +170,7 @@ export class DocumentDrafts {
139
170
  async fork(identity: string, draft: DocumentDraft, operation?: DraftStoreOperation): Promise<StoredDocumentDraft | undefined> {
140
171
  const next = this.#record(identity, draft)
141
172
  if (!next || !await this.#store!.create(keyOf(identity, next.record.id), next.raw, operation)) return
142
- this.#owned.set(next.record.id, { identity, revision: next.record.revision, raw: next.raw })
173
+ this.#own(identity, next)
143
174
  this.#touch()
144
175
  return next.record
145
176
  }
@@ -1,6 +1,6 @@
1
1
  import * as Popover from '@radix-ui/react-popover'
2
2
  import { cloneElement, forwardRef, memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'
3
- import type { DragEvent, KeyboardEvent, ReactElement, ReactNode } from 'react'
3
+ import type { DragEvent, KeyboardEvent, MouseEvent as ReactMouseEvent, PointerEvent as ReactPointerEvent, ReactElement, ReactNode } from 'react'
4
4
  import { PmButton, PmIcon, PmIconButton } from './base-controls.tsx'
5
5
  import type { MenuItem } from './components.tsx'
6
6
  import { PmMenu } from './components.tsx'
@@ -361,8 +361,9 @@ export interface DocPreview { path: string[], title: string, excerpt: string, me
361
361
 
362
362
  /**
363
363
  * A preview of a reference's target on hover: it opens after the pointer rests 500 ms (or the trigger is focused for as
364
- * long), stays while the pointer crosses to it within 300 ms, and its buttons take the keyboard with Tab. `load` runs
365
- * when it opens; `children` is the trigger.
364
+ * long), stays while the pointer crosses to it within 300 ms, and its buttons take the keyboard with Tab. A touch has
365
+ * no hover: a tap on the trigger opens the card at once instead of activating the trigger, a second tap or one outside
366
+ * closes it. `load` runs when it opens; `children` is the trigger.
366
367
  */
367
368
  export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actions, children }: { label: string, load(): Promise<DocPreview>, loadingLabel: string, failedLabel: string, actions?: ReactNode, children: ReactElement }) {
368
369
  const [open, setOpen] = useState(false)
@@ -373,13 +374,17 @@ export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actio
373
374
  loader.current = load
374
375
  // The preview is read when the pointer arrives, so that it is usually there when the card opens 500 ms later.
375
376
  const reading = useRef<{ promise: Promise<DocPreview>, value?: DocPreview }>()
377
+ // The pointer that pressed the trigger last: a touch taps it open, a mouse or pen keeps hovering and clicking.
378
+ const pressed = useRef<{ touch: boolean, trigger?: Element }>({ touch: false })
379
+ const read = () => {
380
+ if (open || reading.current) return
381
+ const entry: { promise: Promise<DocPreview>, value?: DocPreview } = { promise: loader.current() }
382
+ entry.promise.then(value => { entry.value = value }, () => {})
383
+ reading.current = entry
384
+ }
376
385
  const schedule = (next: boolean) => {
377
386
  clearTimeout(timer.current)
378
- if (next && !open && !reading.current) {
379
- const entry: { promise: Promise<DocPreview>, value?: DocPreview } = { promise: loader.current() }
380
- entry.promise.then(value => { entry.value = value }, () => {})
381
- reading.current = entry
382
- }
387
+ if (next) read()
383
388
  timer.current = setTimeout(() => setOpen(next), next ? PREVIEW_OPEN_DELAY : PREVIEW_CLOSE_DELAY)
384
389
  }
385
390
  useEffect(() => () => clearTimeout(timer.current), [])
@@ -397,9 +402,20 @@ export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actio
397
402
  }, [open])
398
403
  const trigger = cloneElement(children as ReactElement<Record<string, unknown>>, {
399
404
  describedBy: open ? id : undefined,
400
- onPointerEnter: () => schedule(true),
401
- onPointerLeave: () => schedule(false),
402
- onFocus: () => schedule(true),
405
+ onPointerEnter: (event: ReactPointerEvent) => { if (event.pointerType !== 'touch') schedule(true) },
406
+ onPointerLeave: (event: ReactPointerEvent) => { if (event.pointerType !== 'touch') schedule(false) },
407
+ onPointerDown: (event: ReactPointerEvent) => { pressed.current = { touch: event.pointerType === 'touch', trigger: event.currentTarget as Element } },
408
+ // Capturing, so that the trigger's own click (going to the target) does not run.
409
+ onClickCapture: (event: ReactMouseEvent) => {
410
+ if (!pressed.current.touch) return
411
+ pressed.current.touch = false
412
+ event.preventDefault()
413
+ event.stopPropagation()
414
+ clearTimeout(timer.current)
415
+ if (!open) read()
416
+ setOpen(!open)
417
+ },
418
+ onFocus: () => { if (!pressed.current.touch) schedule(true) },
403
419
  onBlur: (event: FocusEvent) => { if (!(event.relatedTarget instanceof Node && document.getElementById(id)?.contains(event.relatedTarget))) schedule(false) },
404
420
  onKeyDownCapture: (event: globalThis.KeyboardEvent) => { if (event.key === 'Escape' && open) { event.stopPropagation(); clearTimeout(timer.current); setOpen(false) } },
405
421
  })
@@ -409,6 +425,7 @@ export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actio
409
425
  <Popover.Portal>
410
426
  <Popover.Content id={id} className="pm-ui-doc-preview pm-ui-floating pm-ui" aria-label={label} side="bottom" align="start" sideOffset={6} collisionPadding={16}
411
427
  onOpenAutoFocus={event => event.preventDefault()} onCloseAutoFocus={event => event.preventDefault()}
428
+ onInteractOutside={event => { if (event.target instanceof Node && pressed.current.trigger?.contains(event.target)) event.preventDefault() }}
412
429
  onPointerEnter={() => clearTimeout(timer.current)} onPointerLeave={() => schedule(false)}
413
430
  onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget as Node)) schedule(false) }}
414
431
  onEscapeKeyDown={event => event.stopPropagation()}>
@@ -516,28 +533,32 @@ export interface BacklinkPlace { id: string, excerpt: string, meta?: string, syn
516
533
  /**
517
534
  * A document that cites this one: its title, then each place with the sentence around it (two lines at most) and what
518
535
  * tells equal sentences apart (`meta`). One place makes the whole card the button; several are a list under the title.
536
+ * With `onPeek`, each place has a second, smaller action at its end (Open on the Side), always shown.
519
537
  */
520
- export function PmBacklinkItem({ title, count, places, syncedLabel, onActivate }: { title: string, count?: string, places: readonly BacklinkPlace[], syncedLabel?: string, onActivate(id: string): void }) {
538
+ export function PmBacklinkItem({ title, count, places, syncedLabel, peekLabel, onActivate, onPeek }: { title: string, count?: string, places: readonly BacklinkPlace[], syncedLabel?: string, peekLabel?: string, onActivate(id: string): void, onPeek?(id: string): void }) {
521
539
  const icon = (place: BacklinkPlace) => <PmIcon name={place.synced ? 'synced' : 'document'} />
522
540
  const label = (place: BacklinkPlace) => place.synced && syncedLabel ? <span className="pm-ui-sr-only">{syncedLabel}</span> : null
541
+ const peek = (place: BacklinkPlace) => onPeek && peekLabel ? <PmIconButton small icon="rail" className="pm-ui-backlink__peek" label={peekLabel} onClick={() => onPeek(place.id)} /> : null
523
542
  if (places.length === 1) {
524
543
  const place = places[0]!
525
- return (
544
+ const card = (
526
545
  <button type="button" className="pm-ui-backlink" title={title} onClick={() => onActivate(place.id)}>
527
546
  <span className="pm-ui-backlink__title">{icon(place)}<span className="pm-ui-backlink__name">{title}</span>{label(place)}</span>
528
547
  {place.excerpt && <span className="pm-ui-backlink__excerpt">{place.excerpt}</span>}
529
548
  {place.meta && <span className="pm-ui-backlink__meta">{place.meta}</span>}
530
549
  </button>
531
550
  )
551
+ const action = peek(place)
552
+ return action ? <div className="pm-ui-backlink__row">{card}{action}</div> : card
532
553
  }
533
554
  return (
534
555
  <div className="pm-ui-backlink" data-group="">
535
556
  <span className="pm-ui-backlink__title" title={title}><PmIcon name="document" /><span className="pm-ui-backlink__name">{title}</span>{count && <span className="pm-ui-backlink__count">{count}</span>}</span>
536
557
  <ul className="pm-ui-backlink__places">{places.map(place => (
537
- <li key={place.id}><button type="button" className="pm-ui-backlink__place" onClick={() => onActivate(place.id)}>
558
+ <li key={place.id} className="pm-ui-backlink__row"><button type="button" className="pm-ui-backlink__place" onClick={() => onActivate(place.id)}>
538
559
  {place.excerpt && <span className="pm-ui-backlink__excerpt">{place.excerpt}</span>}
539
560
  <span className="pm-ui-backlink__meta">{icon(place)}{place.meta}{label(place)}</span>
540
- </button></li>
561
+ </button>{peek(place)}</li>
541
562
  ))}</ul>
542
563
  </div>
543
564
  )
package/src/knowledge.css CHANGED
@@ -195,6 +195,18 @@
195
195
  gap: var(--pm-space-px);
196
196
  }
197
197
 
198
+ .pmw-references__row {
199
+ display: flex;
200
+ align-items: center;
201
+ gap: var(--pm-space-1);
202
+ min-width: 0;
203
+ }
204
+
205
+ .pmw-references__link {
206
+ flex: 1;
207
+ min-width: 0;
208
+ }
209
+
198
210
  .pmw-references__link:not([aria-disabled]) {
199
211
  color: var(--pm-color-accent);
200
212
  }
@@ -1,6 +1,6 @@
1
1
  import { useEffect, useState } from 'react'
2
2
  import type { DocumentCitation, DocumentLinks, OutgoingLink } from '@lincyaw/kernel/contracts'
3
- import { PmBacklinkItem, PmButton, PmIcon, PmNotice, PmSkeleton } from '../components.tsx'
3
+ import { PmBacklinkItem, PmButton, PmIcon, PmIconButton, PmNotice, PmSkeleton } from '../components.tsx'
4
4
  import { useTreeMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
5
5
 
6
6
  type Links = { state: 'loading' } | { state: 'failed' } | { state: 'unavailable' } | { state: 'ready', links: DocumentLinks }
@@ -35,6 +35,8 @@ function groupCitations(citations: readonly DocumentCitation[]): { document: str
35
35
  return [...groups.values()]
36
36
  }
37
37
 
38
+ const placeOf = (citation: DocumentCitation) => ({ document: citation.document, ...citation.section ? { section: citation.section } : {}, block: citation.block })
39
+
38
40
  /** Several references to one target are one row with their count. */
39
41
  function sameTargets(links: readonly OutgoingLink[]): { link: OutgoingLink, count: number }[] {
40
42
  const rows = new Map<string, { link: OutgoingLink, count: number }>()
@@ -51,12 +53,13 @@ function OutgoingItem({ link, count }: { link: OutgoingLink, count: number }) {
51
53
  const t = useTreeMessages()
52
54
  const workbench = useWorkbench()
53
55
  const gone = link.missing || link.trashed
54
- return <li>
56
+ return <li className="pmw-references__row">
55
57
  <button type="button" className="pm-ui-nav-item pmw-references__link" title={link.title} disabled={link.missing} aria-disabled={gone || undefined} onClick={() => void workbench.tree.openPlace(link.target)}>
56
58
  <PmIcon name={link.kind === 'embed' ? 'synced' : 'document'} />
57
59
  <span className="pmw-references__title">{link.title}</span>
58
60
  {gone ? <span className="pm-ui-nav-item__count">{link.missing ? t.missingTarget : t.trashedTarget}</span> : count > 1 && <span className="pm-ui-nav-item__count">{t.placeCount(count)}</span>}
59
61
  </button>
62
+ {!link.missing && <PmIconButton small icon="rail" label={t.openOnSide} onClick={() => workbench.tree.peek(link.target)} />}
60
63
  </li>
61
64
  }
62
65
 
@@ -84,7 +87,7 @@ function ReferencesView({ read }: { read: ReturnType<typeof useDocumentLinks> })
84
87
  <PmBacklinkItem title={group.title} count={group.citations.length > 1 ? t.placeCount(group.citations.length) : undefined} syncedLabel={t.syncedLabel}
85
88
  places={group.citations.map((citation, index) => ({ id: String(index), excerpt: citation.excerpt, synced: citation.kind === 'embed',
86
89
  meta: group.citations.length > 1 ? `${citation.kind === 'embed' ? t.syncedLabel : t.referenceLabel} · ${t.placeIndex(index + 1)}` : undefined }))}
87
- onActivate={id => { const citation = group.citations[Number(id)]!; void workbench.tree.openPlace({ document: citation.document, ...citation.section ? { section: citation.section } : {}, block: citation.block }) }} />
90
+ peekLabel={t.openOnSide} onActivate={id => void workbench.tree.openPlace(placeOf(group.citations[Number(id)]!))} onPeek={id => workbench.tree.peek(placeOf(group.citations[Number(id)]!))} />
88
91
  </li>
89
92
  ))}</ul> : <p className="pmw-muted">{t.noCitations}</p>}
90
93
  </section>