-
Notifications
You must be signed in to change notification settings - Fork 146
feat(custom-ui): developer citation demo over anchored metadata (SD-3199) #3370
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| import { useEffect, useMemo, useRef, useState } from 'react'; | ||
| import type { SelectionCapture } from 'superdoc/ui'; | ||
| import { useSuperDocUI } from 'superdoc/ui/react'; | ||
| import type { SelectionTarget } from './citations-types'; | ||
| import { useCitations } from './useCitations'; | ||
|
|
||
| interface Props { | ||
| /** Close without posting. */ | ||
| onCancel(): void; | ||
| /** Called after a successful attach so the parent can dismiss / scroll. */ | ||
| onPosted(id: string | null): void; | ||
| } | ||
|
|
||
| /** | ||
| * Inline composer for new citations. Mirrors `CommentComposer`'s | ||
| * capture pattern: freeze the editor selection at mount so focusing | ||
| * the form fields doesn't tear it down. On submit, the captured | ||
| * selection feeds `metadata.attach` via `useCitations.attachAtSelection`. | ||
| */ | ||
| export function CitationComposer({ onCancel, onPosted }: Props) { | ||
| const ui = useSuperDocUI(); | ||
| const { attach } = useCitations(); | ||
| const [citationId, setCitationId] = useState(''); | ||
| const [sourceId, setSourceId] = useState(''); | ||
| const [displayText, setDisplayText] = useState(''); | ||
| const [locator, setLocator] = useState(''); | ||
| const [posting, setPosting] = useState(false); | ||
| const [error, setError] = useState<string | null>(null); | ||
| const citationIdRef = useRef<HTMLInputElement | null>(null); | ||
|
|
||
| // Capture once at mount and hold it. SelectionCapture's quotedText | ||
| // gives us a preview, and the capture's TextTarget feeds attach. | ||
| const captured: SelectionCapture | null = useMemo(() => ui?.selection.capture() ?? null, [ui]); | ||
|
|
||
| useEffect(() => { | ||
| citationIdRef.current?.focus(); | ||
| }, []); | ||
|
|
||
| // `SelectionCapture` is a SelectionSlice; `selectionTarget` is the | ||
| // SelectionTarget shape `metadata.attach` accepts directly. | ||
| const capturedTarget = | ||
| ((captured as unknown as { selectionTarget?: SelectionTarget | null } | null)?.selectionTarget ?? null); | ||
| const canPost = | ||
| !!ui && | ||
| !!captured && | ||
| !posting && | ||
| citationId.trim().length > 0 && | ||
| sourceId.trim().length > 0 && | ||
| displayText.trim().length > 0 && | ||
| capturedTarget !== null; | ||
|
|
||
| const post = () => { | ||
| if (!ui || !canPost || !capturedTarget) return; | ||
| setPosting(true); | ||
| setError(null); | ||
| const result = attach(capturedTarget, { | ||
| citationId: citationId.trim(), | ||
| sourceId: sourceId.trim(), | ||
| displayText: displayText.trim(), | ||
| locator: locator.trim() || undefined, | ||
| }); | ||
| setPosting(false); | ||
| if ('error' in result) { | ||
| setError(result.error); | ||
| return; | ||
| } | ||
| // Restore the editor's visible selection so the user can keep editing. | ||
| if (captured) ui.selection.restore(captured); | ||
| onPosted(result.id); | ||
| }; | ||
|
|
||
| const cancel = () => { | ||
| if (ui && captured) ui.selection.restore(captured); | ||
| onCancel(); | ||
| }; | ||
|
|
||
| return ( | ||
| <div className="composer"> | ||
| <div className="composer-quote"> | ||
| {captured?.quotedText ? <>“{captured.quotedText}”</> : <em>No selection</em>} | ||
| </div> | ||
| <input | ||
| ref={citationIdRef} | ||
| className="composer-input" | ||
| placeholder="Citation ID (your stable id, e.g. cite-7f3a)" | ||
| value={citationId} | ||
| onChange={(e) => setCitationId(e.target.value)} | ||
| onKeyDown={(e) => { | ||
| if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') post(); | ||
| if (e.key === 'Escape') cancel(); | ||
| }} | ||
| /> | ||
| <input | ||
| className="composer-input" | ||
| placeholder="Source ID (record key in your citation DB)" | ||
| value={sourceId} | ||
| onChange={(e) => setSourceId(e.target.value)} | ||
| onKeyDown={(e) => { | ||
| if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') post(); | ||
| if (e.key === 'Escape') cancel(); | ||
| }} | ||
| /> | ||
| <input | ||
| className="composer-input" | ||
| placeholder="Display text (fallback label, e.g. Smith v. Jones, 2024)" | ||
| value={displayText} | ||
| onChange={(e) => setDisplayText(e.target.value)} | ||
| onKeyDown={(e) => { | ||
| if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') post(); | ||
| if (e.key === 'Escape') cancel(); | ||
| }} | ||
| /> | ||
| <input | ||
| className="composer-input" | ||
| placeholder="Locator (optional, e.g. §3.2 or p. 17)" | ||
| value={locator} | ||
| onChange={(e) => setLocator(e.target.value)} | ||
| onKeyDown={(e) => { | ||
| if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') post(); | ||
| if (e.key === 'Escape') cancel(); | ||
| }} | ||
| /> | ||
| {error && <div className="composer-error">{error}</div>} | ||
| <div className="composer-actions"> | ||
| <button onClick={cancel}>Cancel</button> | ||
| <button className="primary" disabled={!canPost} onClick={post}> | ||
| {posting ? 'Saving…' : 'Cite'} | ||
| </button> | ||
| </div> | ||
| </div> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import { useEffect, useMemo, useState } from 'react'; | ||
| import type { ViewportRect } from 'superdoc/ui'; | ||
| import { useSuperDocContentControls, useSuperDocUI } from 'superdoc/ui/react'; | ||
| import { useCitations } from './useCitations'; | ||
|
|
||
| /** | ||
| * Renders absolute-positioned overlay rectangles on every cited span. | ||
| * | ||
| * Two-step lookup. `editor.doc.metadata.*` keys by the metadata id | ||
| * (which is the SDT's `w:tag`); `ui.contentControls.getRect({ id })` | ||
| * keys by the SDT's PM node id (which the painter stamps as | ||
| * `data-sdt-id`). These are different identifiers. The contentControls | ||
| * slice surfaces both per item (`target.nodeId` + `properties.tag`), | ||
| * so we build a tag → nodeId map and translate at measure time. | ||
| * | ||
| * `getRect` returns `rects[]` — one ViewportRect per painted line of a | ||
| * wrapped span — so line-wrapped citations get clean per-line | ||
| * underlines without spilling across the page margin. | ||
| * | ||
| * Scroll and resize trigger a re-measure so the highlights stay glued. | ||
| */ | ||
| type HighlightEntry = { metadataId: string; tooltip: string; rects: ViewportRect[] }; | ||
|
|
||
| type CCItem = { target?: { nodeId?: string }; properties?: { tag?: string } }; | ||
|
|
||
| export function CitationHighlights() { | ||
| const ui = useSuperDocUI(); | ||
| const { citations } = useCitations(); | ||
| const cc = useSuperDocContentControls(); | ||
| const [entries, setEntries] = useState<HighlightEntry[]>([]); | ||
|
|
||
| // tag (= metadata id) → PM node id. Refreshes whenever the slice | ||
| // items array reference changes. | ||
| const tagToNodeId = useMemo(() => { | ||
| const map = new Map<string, string>(); | ||
| for (const item of (cc.items ?? []) as unknown as CCItem[]) { | ||
| const tag = item.properties?.tag; | ||
| const nodeId = item.target?.nodeId; | ||
| if (typeof tag === 'string' && typeof nodeId === 'string') { | ||
| map.set(tag, nodeId); | ||
| } | ||
| } | ||
| return map; | ||
| }, [cc.items]); | ||
|
|
||
| useEffect(() => { | ||
| if (!ui) { | ||
| setEntries([]); | ||
| return; | ||
| } | ||
|
|
||
| const remeasure = () => { | ||
| const next: HighlightEntry[] = []; | ||
| for (const c of citations) { | ||
| const nodeId = tagToNodeId.get(c.id); | ||
| if (!nodeId) continue; | ||
| const result = ui.contentControls.getRect({ id: nodeId }); | ||
| if (!result.success) continue; | ||
| next.push({ | ||
| metadataId: c.id, | ||
| tooltip: `${c.payload.displayText} (${c.payload.citationId})`, | ||
| rects: result.rects, | ||
| }); | ||
| } | ||
| setEntries(next); | ||
| }; | ||
|
|
||
| remeasure(); | ||
| window.addEventListener('scroll', remeasure, true); | ||
| window.addEventListener('resize', remeasure); | ||
| return () => { | ||
| window.removeEventListener('scroll', remeasure, true); | ||
| window.removeEventListener('resize', remeasure); | ||
| }; | ||
| }, [ui, citations, tagToNodeId]); | ||
|
|
||
| return ( | ||
| <div className="citation-highlights" aria-hidden> | ||
| {entries.flatMap((entry) => | ||
| entry.rects.map((rect, i) => ( | ||
| <div | ||
| key={`${entry.metadataId}:${i}`} | ||
| className="citation-highlight" | ||
| data-citation-id={entry.metadataId} | ||
| title={entry.tooltip} | ||
| style={{ | ||
| position: 'fixed', | ||
| left: rect.left, | ||
| top: rect.top, | ||
| width: rect.width, | ||
| height: rect.height, | ||
| }} | ||
| /> | ||
| )), | ||
| )} | ||
| </div> | ||
| ); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
SelectionCapture.selectionTargetcan represent cross-paragraph ranges, butmetadata.attachrejects those targets and throwsINVALID_TARGETin that case. This handler enables posting for any non-nullcapturedTargetand callsattach(...)directly, so selecting text across paragraph boundaries causes an uncaught exception (and leaves the composer in a broken posting state) instead of showing a validation message. Use the existing single-paragraph guard path (attachAtSelection/textTargetToSelectionTarget) or catch and map attach exceptions tosetError.Useful? React with 👍 / 👎.