From 32f505430056b4899220847c6201922a3c95b01b Mon Sep 17 00:00:00 2001 From: Qijun Date: Sun, 4 Oct 2026 00:49:48 -0700 Subject: [PATCH] feat: follow links between notes in the reader [[Page]], [[Page#^name]], [[Page#Heading]], [[paper.pdf#page=12]] and #[[tag]] now read as links. A link opens the note its page names and shows the place it names: the named block or heading scrolled to the top, or the PDF page. A page shared by several notes offers them to choose from; a page no note has yet stays greyed out. ^name is hidden. remarkLinks, in the links package, turns links into buttons that carry what was written and marks each named block and heading with the name a link uses, following the same naming rule as the index, now shared as namingsAmong. Places are found by name rather than line, since the reader rewrites display math before it renders. A link asks the workspace to reveal a place in a file and opens it; the file's reader shows the place once and clears the request. In Markdown the place is held as the reading position, so images that load later do not carry it away and a restored position does not take it back. --- packages/links/package.json | 2 + packages/links/src/index.ts | 2 + packages/links/src/parse.ts | 63 +++++++---- packages/links/src/remark.test.ts | 106 ++++++++++++++++++ packages/links/src/remark.ts | 94 ++++++++++++++++ pnpm-lock.yaml | 6 + .../src/features/reader/csv-reader.test.tsx | 5 +- .../src/features/reader/docx-reader.test.tsx | 5 +- .../features/reader/markdown-reader/index.tsx | 70 +++++++++++- .../markdown-reader/markdown-reader.test.tsx | 75 ++++++++++++- .../reader/markdown-reader/style.module.scss | 66 +++++++++++ .../markdown-reader/use-flow-position.ts | 64 +++++++---- .../reader/markdown-reader/wiki-link.tsx | 90 +++++++++++++++ .../web/src/features/reader/pdf-reader.tsx | 14 ++- .../links-navigation.integration.test.tsx | 61 ++++++++++ .../web/src/shell/workspace-context.tsx | 53 ++++++++- ui-packages/web/src/shell/workspace-store.ts | 12 ++ 17 files changed, 734 insertions(+), 54 deletions(-) create mode 100644 packages/links/src/remark.test.ts create mode 100644 packages/links/src/remark.ts create mode 100644 ui-packages/web/src/features/reader/markdown-reader/wiki-link.tsx create mode 100644 ui-packages/web/src/shell/links-navigation.integration.test.tsx diff --git a/packages/links/package.json b/packages/links/package.json index 887cf7b..14d9ceb 100644 --- a/packages/links/package.json +++ b/packages/links/package.json @@ -12,12 +12,14 @@ }, "dependencies": { "@types/mdast": "^4.0.4", + "mdast-util-to-hast": "^13.2.1", "remark-gfm": "^4.0.1", "remark-math": "^6.0.0", "remark-parse": "^11.0.0", "unified": "^11.0.5" }, "devDependencies": { + "@types/hast": "^3.0.5", "typescript": "^7.0.2", "vitest": "^5.0.0" } diff --git a/packages/links/src/index.ts b/packages/links/src/index.ts index ab8a9ec..3f50e2a 100644 --- a/packages/links/src/index.ts +++ b/packages/links/src/index.ts @@ -11,6 +11,7 @@ export { export { NameBlockError, nameBlock } from './name-block' export { formatNode, + headingKey, isNotePath, type NodeKind, type NodeRef, @@ -31,3 +32,4 @@ export { parseNote, parseTarget, } from './parse' +export { remarkLinks } from './remark' diff --git a/packages/links/src/parse.ts b/packages/links/src/parse.ts index 6d14e79..361298d 100644 --- a/packages/links/src/parse.ts +++ b/packages/links/src/parse.ts @@ -1,4 +1,4 @@ -import type { Heading, Parent, PhrasingContent, Root, RootContent, Text } from 'mdast' +import type { Heading, Paragraph, Parent, PhrasingContent, Root, RootContent, Text } from 'mdast' import { descendants, linesOf, type Node, parser, plainText, splitFrontmatter } from './markdown' // Where a link points: a page by name, and optionally a named block, a heading or a PDF page in @@ -32,12 +32,12 @@ export type ParsedNote = { const contextLength = 200 export const nameSyntax = '[A-Za-z0-9-]+' -const trailingName = new RegExp(`\\s\\^(${nameSyntax})$`) +export const trailingName = new RegExp(`\\s\\^(${nameSyntax})$`) export const standaloneName = new RegExp(`^\\^(${nameSyntax})$`) // [[...]], ![[...]] for an embed, #[[...]] for a tag. A fresh expression each time, since a global // one carries its position from one search to the next. -const linkPattern = () => /(!?)(#?)\[\[([^[\]\n]+)\]\]/g +export const linkPattern = () => /(!?)(#?)\[\[([^[\]\n]+)\]\]/g // The inside of [[...]]: a page, then #^block, #page=N or #heading, then |label. export const parseTarget = (raw: string): { target: LinkTarget; label?: string } => { @@ -130,11 +130,20 @@ const headingsIn = (root: Root, source: readonly string[]): ParsedHeading[] => { }) } -// Blocks named among one parent's children. A name ending a paragraph or heading names it; one -// ending the first paragraph of a list item names the item; a paragraph that is only ^name names -// the block before it, which is how a table, code block or quote is named. -const blocksAmong = (parent: Parent, headings: readonly ParsedHeading[]): ParsedBlock[] => - parent.children.flatMap((child, index): ParsedBlock[] => { +// A ^name and what it names. A name ending a paragraph or heading names it; one ending the first +// paragraph of a list item names the item; a paragraph that is only ^name names the block before +// it, which is how a table, code block or quote is named. mark is the paragraph or heading that +// holds the name, so a reader can hide it: its trailing ^name, or all of it when it stands alone. +export type Naming = { + name: string + kind: BlockKind + owner: RootContent + mark: Paragraph | Heading + alone: boolean +} + +export const namingsAmong = (parent: Parent): Naming[] => + parent.children.flatMap((child, index): Naming[] => { if (child.type === 'paragraph') { const alone = standaloneName.exec(plainText(child).trim())?.[1] const previous = parent.children[index - 1] @@ -143,8 +152,9 @@ const blocksAmong = (parent: Parent, headings: readonly ParsedHeading[]): Parsed { name: alone, kind: previous.type === 'paragraph' ? 'paragraph' : 'other', - lines: linesOf(previous), - text: compact(plainText(previous)), + owner: previous, + mark: child, + alone: true, }, ] const name = nameAtEnd(child) @@ -154,22 +164,29 @@ const blocksAmong = (parent: Parent, headings: readonly ParsedHeading[]): Parsed { name, kind: item ? 'item' : 'paragraph', - lines: linesOf(item ? (parent as Node) : child), - text: compact(withoutName(plainText(child))), + owner: item ? (parent as RootContent) : child, + mark: child, + alone: false, }, ] } - if (child.type === 'heading') { - const name = nameAtEnd(child) - const [start] = linesOf(child) - const section = headings.find(heading => heading.lines[0] === start) - return name && section - ? [{ name, kind: 'heading', lines: section.lines, text: section.title }] - : [] - } - return [] + const name = child.type === 'heading' ? nameAtEnd(child) : undefined + return child.type === 'heading' && name + ? [{ name, kind: 'heading', owner: child, mark: child, alone: false }] + : [] }) +// A named block covers its owner's lines, and a heading its whole section. +const blockOf = (naming: Naming, headings: readonly ParsedHeading[]): ParsedBlock[] => { + const { name, kind, owner, mark, alone } = naming + if (kind === 'heading') { + const section = headings.find(heading => heading.lines[0] === linesOf(owner)[0]) + return section ? [{ name, kind, lines: section.lines, text: section.title }] : [] + } + const text = alone ? plainText(owner) : withoutName(plainText(mark)) + return [{ name, kind, lines: linesOf(owner), text: compact(text) }] +} + // One Markdown note's headings, named blocks and links, with one-based source lines. Code and // inline code are left alone, since only text nodes are read. export const parseNote = (input: string): ParsedNote => { @@ -185,7 +202,9 @@ export const parseNote = (input: string): ParsedNote => { return { ...(name ? { name } : {}), headings, - blocks: parents.flatMap(parent => blocksAmong(parent, headings)), + blocks: parents.flatMap(parent => + namingsAmong(parent).flatMap(naming => blockOf(naming, headings)), + ), links: nodes .filter((node): node is Text => node.type === 'text') .flatMap(text => linksIn(text, source)), diff --git a/packages/links/src/remark.test.ts b/packages/links/src/remark.test.ts new file mode 100644 index 0000000..abab10b --- /dev/null +++ b/packages/links/src/remark.test.ts @@ -0,0 +1,106 @@ +import type { Element, Root as HastRoot, Nodes } from 'hast' +import type { Root } from 'mdast' +import { toHast } from 'mdast-util-to-hast' +import remarkGfm from 'remark-gfm' +import remarkMath from 'remark-math' +import remarkParse from 'remark-parse' +import { unified } from 'unified' +import { describe, expect, it } from 'vitest' +import { parseNote } from './parse' +import { remarkLinks } from './remark' + +const processor = unified().use(remarkParse).use(remarkGfm).use(remarkMath).use(remarkLinks) + +// The elements a reader would render, as HTML-like text with only the attributes links add. +const kept = ['dataLink', 'dataKind', 'dataBlock', 'dataHeading'] +const html = (node: Nodes): string => { + if (node.type === 'text') return node.value + if (node.type !== 'element' && node.type !== 'root') return '' + const children = node.children.map(html).join('') + if (node.type === 'root') return children.trim() + const attributes = kept + .filter(key => node.properties[key] !== undefined) + .map(key => ` ${key}="${String(node.properties[key])}"`) + .join('') + return `<${node.tagName}${attributes}>${children}` +} + +const hastOf = (source: string) => + toHast(processor.runSync(processor.parse(source)) as Root) as HastRoot + +const render = (...lines: string[]) => html(hastOf(lines.join('\n'))).replace(/\n/g, '') + +const elements = (node: Nodes): Element[] => + node.type === 'element' || node.type === 'root' + ? [...(node.type === 'element' ? [node] : []), ...node.children.flatMap(elements)] + : [] + +describe('rendering links', () => { + it('turns links, labels, tags, embeds and PDF pages into buttons that know their target', () => { + expect( + render('See [[RAG]], [[RAG#^def|定义]], #[[agents]], ![[RAG#Later]], [[p.pdf#page=3]].'), + ).toBe( + '

See , ' + + ', ' + + ', ' + + ', ' + + '.

', + ) + }) + + it('leaves code, inline code, Markdown links and links within the page alone', () => { + expect(render('`[[A]]` [see [[B]]](https://x.org) [[#Local]]', '', '```', '[[C]]', '```')).toBe( + '

[[A]] see [[B]] [[#Local]]

[[C]]\n
'.replace( + /\n/g, + '', + ), + ) + }) +}) + +describe('rendering names', () => { + const source = [ + '## Methods ^methods', + '', + 'Retrieval first. ^def', + '', + '- Sparse retrieval ^sparse', + ' - with BM25', + '', + '| A |', + '| - |', + '| x |', + '', + '^table', + ] + + it('hides each name and marks the element it names', () => { + expect(render(...source)).toBe( + '

Methods

' + + '

Retrieval first.

' + + '' + + '' + + '
A
x
', + ) + }) + + it('marks exactly the blocks the index knows by name', () => { + const tree = hastOf(source.join('\n')) + const marked = elements(tree).flatMap(element => + element.properties.dataBlock ? [String(element.properties.dataBlock)] : [], + ) + + expect(marked.sort()).toEqual( + parseNote(source.join('\n')) + .blocks.map(block => block.name) + .sort(), + ) + }) + + it('gives headings the key a link to them uses', () => { + expect(render('# Retrieval Strategy', '', '## 检索 [[RAG]]')).toBe( + '

Retrieval Strategy

' + + '

检索

', + ) + }) +}) diff --git a/packages/links/src/remark.ts b/packages/links/src/remark.ts new file mode 100644 index 0000000..6668b5d --- /dev/null +++ b/packages/links/src/remark.ts @@ -0,0 +1,94 @@ +import type { Link, Parent, Root, RootContent, Text } from 'mdast' +import type {} from 'mdast-util-to-hast' +import { descendants, type Node, plainText } from './markdown' +import { headingKey } from './names' +import { linkPattern, namingsAmong, parseTarget, trailingName } from './parse' + +// What the reader is given to work with, on the element a node becomes. +const setProperty = (node: Node, key: string, value: string) => { + node.data = { ...node.data, hProperties: { ...node.data?.hProperties, [key]: value } } +} + +// Names are marks for links to find, not text to read: the element a name names carries it as +// data-block, and the ^name itself is hidden. +const hideNames = (root: Root) => { + const parents = [root, ...descendants(root)].filter( + (node): node is Parent & Node => 'children' in node, + ) + const namings = parents.flatMap(parent => + namingsAmong(parent).map(naming => ({ parent, naming })), + ) + for (const { parent, naming } of namings) { + setProperty(naming.owner, 'dataBlock', naming.name) + if (naming.alone) { + parent.children = parent.children.filter(child => child !== naming.mark) + continue + } + const last = naming.mark.children.at(-1) + if (last?.type === 'text') last.value = last.value.replace(trailingName, '') + } +} + +// A heading carries its title as a link would spell it, so [[Page#Title]] finds it. +const markHeadings = (root: Root) => { + for (const node of descendants(root)) + if (node.type === 'heading') setProperty(node, 'dataHeading', headingKey(plainText(node))) +} + +// A link becomes a button holding what was written, so a click can follow it once the library +// knows where it leads. It is a link node so Markdown keeps it inline; the empty url is not used. +const linkNode = (raw: string, embed: boolean, tag: boolean): Link => { + const { label } = parseTarget(raw) + const written = (raw.split('|')[0] ?? raw).trim() + const shown = label ?? written + return { + type: 'link', + url: '', + children: [{ type: 'text', value: tag ? `#${shown}` : shown }], + data: { + hName: 'button', + hProperties: { + type: 'button', + dataLink: raw, + dataKind: embed ? 'embed' : tag ? 'tag' : 'link', + }, + }, + } +} + +// Text split around its links. [[#heading]] names no page, so it stays text, as it does in the +// index. +const splitLinks = (text: Text): (Text | Link)[] => { + const pieces: (Text | Link)[] = [] + let from = 0 + for (const match of text.value.matchAll(linkPattern())) { + const raw = match[3] ?? '' + if (!parseTarget(raw).target.page) continue + if (match.index > from) + pieces.push({ type: 'text', value: text.value.slice(from, match.index) }) + pieces.push(linkNode(raw, match[1] === '!', match[2] === '#')) + from = match.index + match[0].length + } + if (from === 0) return [text] + if (from < text.value.length) pieces.push({ type: 'text', value: text.value.slice(from) }) + return pieces +} + +// Text inside a Markdown link stays text, as a link inside a link cannot be followed. +const linkText = (parent: Parent) => { + parent.children = parent.children.flatMap((child): RootContent[] => { + if (child.type === 'text') return splitLinks(child) + if ('children' in child && child.type !== 'link' && child.type !== 'linkReference') + linkText(child) + return [child] + }) as Parent['children'] +} + +// The reader's view of a note's links and names, as remark plugin: [[...]], #[[...]] and ![[...]] +// become buttons that know their target, named blocks and headings carry the names links use, +// and ^name is hidden. Code and inline code are left alone, since only text nodes are read. +export const remarkLinks = () => (root: Root) => { + hideNames(root) + markHeadings(root) + linkText(root) +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index af3c78d..c9fbfae 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,9 @@ importers: '@types/mdast': specifier: ^4.0.4 version: 4.0.4 + mdast-util-to-hast: + specifier: ^13.2.1 + version: 13.2.1 remark-gfm: specifier: ^4.0.1 version: 4.0.1 @@ -30,6 +33,9 @@ importers: specifier: ^11.0.5 version: 11.0.5 devDependencies: + '@types/hast': + specifier: ^3.0.5 + version: 3.0.5 typescript: specifier: ^7.0.2 version: 7.0.2 diff --git a/ui-packages/web/src/features/reader/csv-reader.test.tsx b/ui-packages/web/src/features/reader/csv-reader.test.tsx index a8a9eed..3074d89 100644 --- a/ui-packages/web/src/features/reader/csv-reader.test.tsx +++ b/ui-packages/web/src/features/reader/csv-reader.test.tsx @@ -3,7 +3,10 @@ import { describe, expect, it, vi } from 'vitest' import type { StoredFileMetadata } from '../../core/files' import { CsvReader } from './csv-reader' -vi.mock('../../shell/workspace-context', () => ({ useReaderBinding: vi.fn() })) +vi.mock('../../shell/workspace-context', () => ({ + useReaderBinding: vi.fn(), + useReveal: () => ({ reveal: null, shown: vi.fn() }), +})) const file: StoredFileMetadata = { id: 'sightings', diff --git a/ui-packages/web/src/features/reader/docx-reader.test.tsx b/ui-packages/web/src/features/reader/docx-reader.test.tsx index 33f6a21..e4e5774 100644 --- a/ui-packages/web/src/features/reader/docx-reader.test.tsx +++ b/ui-packages/web/src/features/reader/docx-reader.test.tsx @@ -5,7 +5,10 @@ import type { DocxConversion } from '../../core/docx' import type { StoredFileMetadata } from '../../core/files' import { DocxReader } from './docx-reader' -vi.mock('../../shell/workspace-context', () => ({ useReaderBinding: vi.fn() })) +vi.mock('../../shell/workspace-context', () => ({ + useReaderBinding: vi.fn(), + useReveal: () => ({ reveal: null, shown: vi.fn() }), +})) const mocks = vi.hoisted(() => ({ convert: vi.fn() })) // Only the conversion is stubbed, so adding an export to the module cannot break this file. diff --git a/ui-packages/web/src/features/reader/markdown-reader/index.tsx b/ui-packages/web/src/features/reader/markdown-reader/index.tsx index db4f7ce..48c7a7e 100644 --- a/ui-packages/web/src/features/reader/markdown-reader/index.tsx +++ b/ui-packages/web/src/features/reader/markdown-reader/index.tsx @@ -1,8 +1,19 @@ +import { remarkLinks } from '@gamma-reader/links' import { PanelLeft } from 'lucide-react' -import { type ReactNode, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { + type ComponentProps, + type ReactNode, + useCallback, + useLayoutEffect, + useMemo, + useRef, + useState, +} from 'react' +import type { ExtraProps } from 'react-markdown' import { Markdown, type MarkdownExtensions } from '../../../components/markdown' import { normalizeMath } from '../../../core/markdown-math' -import { useReaderBinding } from '../../../shell/workspace-context' +import { useReaderBinding, useReveal } from '../../../shell/workspace-context' +import type { RevealTarget } from '../../../shell/workspace-store' import { createMarkdownImageResolver } from '../markdown-image-resolver' import { readViewport } from '../reader-viewport' import type { TextReaderProps } from '../text-file-reader' @@ -11,6 +22,7 @@ import { MarkdownOutline } from './outline' import type { MarkdownReadingPreferences } from './reading-preferences' import styles from './style.module.scss' import { useFlowPosition } from './use-flow-position' +import { WikiLink } from './wiki-link' const embeddedOutlineMinimumWidth = 640 @@ -28,6 +40,35 @@ const activeHeadingFrom = (elements: readonly HTMLElement[], scroll: HTMLElement ) } +// The rendered element a reveal names: a block by its name, a heading by its key. +const revealed = (article: HTMLElement, target: RevealTarget) => { + const [attribute, value] = + 'block' in target + ? ['block', target.block] + : 'heading' in target + ? ['heading', target.heading] + : [] + if (!attribute) return undefined + return [...article.querySelectorAll(`[data-${attribute}]`)].find( + element => element.dataset[attribute] === value, + ) +} + +// Links render as buttons that remarkLinks marks with what was written; any other button is kept. +const LinkButton = ({ node: _node, children, ...props }: ComponentProps<'button'> & ExtraProps) => { + const data = props as Record + const raw = data['data-link'] + return typeof raw === 'string' ? ( + + {children} + + ) : ( + + ) +} + export const MarkdownReader = ({ document, content, @@ -59,6 +100,13 @@ export const MarkdownReader = ({ }), [document, files, imageResolver], ) + const extensions = useMemo( + () => ({ + components: { ...markdownOptions?.components, button: LinkButton }, + remarkPlugins: [...(markdownOptions?.remarkPlugins ?? []), remarkLinks], + }), + [markdownOptions], + ) const closeOutline = useCallback(() => setOutlineOpen(false), []) const binding = useMemo( () => ({ @@ -79,7 +127,7 @@ export const MarkdownReader = ({ return () => observer.disconnect() }, [markdown]) - const recordPosition = useFlowPosition({ + const position = useFlowPosition({ rootRef, scrollRef: previewScrollRef, contentRef: articleRef, @@ -88,6 +136,16 @@ export const MarkdownReader = ({ onPositionChange, }) + // A link that led here asked for a place in this note; it is shown once the note is on screen. + const { reveal, shown } = useReveal(document.id) + useLayoutEffect(() => { + const article = articleRef.current + if (!reveal || !active || !article) return + const element = revealed(article, reveal.target) + if (element) position.show(element) + shown(reveal) + }, [active, position, reveal, shown]) + useLayoutEffect(() => { if (!markdown || !articleRef.current || !previewScrollRef.current) return const elements = [...articleRef.current.querySelectorAll('h1, h2, h3, h4, h5, h6')] @@ -102,7 +160,7 @@ export const MarkdownReader = ({ if (!markdown) return (
-
+
{content}
@@ -167,7 +225,7 @@ export const MarkdownReader = ({ ref={previewScrollRef} onScroll={event => { if (!active) return - recordPosition() + position.record() setActiveHeadingId(activeHeadingFrom(headingElements.current, event.currentTarget)) }} > @@ -184,7 +242,7 @@ export const MarkdownReader = ({ : undefined } > - +
diff --git a/ui-packages/web/src/features/reader/markdown-reader/markdown-reader.test.tsx b/ui-packages/web/src/features/reader/markdown-reader/markdown-reader.test.tsx index 251fe2f..1a32321 100644 --- a/ui-packages/web/src/features/reader/markdown-reader/markdown-reader.test.tsx +++ b/ui-packages/web/src/features/reader/markdown-reader/markdown-reader.test.tsx @@ -1,3 +1,4 @@ +import { buildGraph, type LinkGraph } from '@gamma-reader/links' import { fireEvent, render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { beforeEach, describe, expect, it, vi } from 'vitest' @@ -6,7 +7,19 @@ import { parseMarkdownHeadings } from './heading-model' import { MarkdownReader } from './index' import { StandardMarkdownReader } from './standard-reader' -vi.mock('../../../shell/workspace-context', () => ({ useReaderBinding: vi.fn() })) +const links = vi.hoisted(() => ({ + graph: null as LinkGraph | null, + openLink: vi.fn(), + reveal: null as { fileId: string; target: { block: string } } | null, + shown: vi.fn(), +})) + +vi.mock('../../../shell/workspace-context', () => ({ + useReaderBinding: vi.fn(), + useLinkGraph: () => links.graph, + useOpenLink: () => links.openLink, + useReveal: () => ({ reveal: links.reveal, shown: links.shown }), +})) const document: StoredFileMetadata = { id: 'guide', @@ -32,6 +45,10 @@ const renderReader = (content: string) => describe('Markdown file reader', () => { beforeEach(() => { + links.graph = null + links.reveal = null + links.openLink.mockReset() + links.shown.mockReset() HTMLElement.prototype.scrollIntoView = vi.fn() Range.prototype.getClientRects = () => [new DOMRect(100, 100, 160, 24)] as unknown as DOMRectList @@ -115,3 +132,59 @@ describe('Markdown file reader', () => { expect(screen.getByRole('article').parentElement).toHaveAttribute('data-reading-theme', 'paper') }) }) + +describe('links in a Markdown note', () => { + const shared = (id: string, path: string): StoredFileMetadata => ({ ...document, id, path }) + const library = [document, shared('one', 'one/Shared.md'), shared('two', 'two/Shared.md')] + + beforeEach(() => { + links.graph = buildGraph(library, new Map()) + links.reveal = null + links.openLink.mockReset() + links.shown.mockReset() + }) + + const renderNote = (content: string) => + render( + undefined} + />, + ) + + it('opens the note a link names, at the place it names, and hides names', async () => { + const user = userEvent.setup({ delay: null }) + renderNote('See [[guide#^def|the definition]]. ^def') + + expect(screen.queryByText(/\^def/)).not.toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'the definition' })) + + expect(links.openLink).toHaveBeenCalledWith({ page: 'guide', block: 'def' }, 'guide') + }) + + it('leaves a page with no note inert and offers the notes that share a name', async () => { + const user = userEvent.setup({ delay: null }) + renderNote('[[Nowhere]] and [[Shared]]') + + await user.click(screen.getByRole('button', { name: 'Nowhere' })) + expect(screen.getByRole('button', { name: 'Nowhere' })).toHaveAttribute( + 'title', + 'No note named Nowhere yet.', + ) + expect(links.openLink).not.toHaveBeenCalled() + + await user.click(screen.getByRole('button', { name: 'Shared' })) + await user.click(screen.getByRole('button', { name: 'two/Shared.md' })) + expect(links.openLink).toHaveBeenCalledWith({ page: 'Shared' }, 'two') + }) + + it('shows the block a link asked for and says it was shown', () => { + links.reveal = { fileId: 'guide', target: { block: 'def' } } + renderNote('# Guide\n\nRetrieval first. ^def') + + expect(links.shown).toHaveBeenCalledWith(links.reveal) + }) +}) diff --git a/ui-packages/web/src/features/reader/markdown-reader/style.module.scss b/ui-packages/web/src/features/reader/markdown-reader/style.module.scss index d096f85..2f6d950 100644 --- a/ui-packages/web/src/features/reader/markdown-reader/style.module.scss +++ b/ui-packages/web/src/features/reader/markdown-reader/style.module.scss @@ -362,3 +362,69 @@ animation: none; } } + +// A [[link]] reads as a link within the text, though it is a button that opens a note. +.wikiLink { + display: inline; + padding: 0; + border: 0; + background: none; + color: var(--accent); + font: inherit; + text-align: inherit; + text-decoration: underline; + text-decoration-style: dotted; + text-underline-offset: 0.2em; + cursor: pointer; + + &[aria-disabled='true'] { + cursor: default; + } +} + +.tag { + text-decoration: none; +} + +.virtual { + color: var(--muted); +} + +.linkChoices { + z-index: 20; + width: min(360px, calc(100vw - 16px)); + max-height: var(--radix-popover-content-available-height); + padding: 4px; + overflow-y: auto; + border: 1px solid var(--line); + border-radius: 6px; + background: var(--surface); + box-shadow: 0 2px 8px rgb(0 0 0 / 12%); + font-size: 12px; + + ul { + margin: 0; + padding: 0; + list-style: none; + } + + button { + width: 100%; + padding: 8px; + overflow: hidden; + border: 0; + border-radius: 3px; + background: transparent; + color: inherit; + font: inherit; + text-align: left; + text-overflow: ellipsis; + white-space: nowrap; + + &:hover, + &:focus-visible { + background: var(--selected); + color: var(--accent); + } + } +} diff --git a/ui-packages/web/src/features/reader/markdown-reader/use-flow-position.ts b/ui-packages/web/src/features/reader/markdown-reader/use-flow-position.ts index 8932286..4045bdb 100644 --- a/ui-packages/web/src/features/reader/markdown-reader/use-flow-position.ts +++ b/ui-packages/web/src/features/reader/markdown-reader/use-flow-position.ts @@ -1,4 +1,4 @@ -import { type RefObject, useLayoutEffect, useRef } from 'react' +import { type RefObject, useCallback, useLayoutEffect, useRef } from 'react' import { type BlockBox, type FlowPosition, @@ -55,48 +55,74 @@ export const useFlowPosition = ({ defaultPosition?.kind === 'flow' ? defaultPosition : null, ) const restoring = useRef(false) + const release = useRef<(() => void) | null>(null) // Images, formulas and diagrams finish after the text, pushing it down, so the place is applied // again whenever the content changes size — until the reader does anything, from which point // the position is theirs. - useLayoutEffect(() => { - const root = rootRef.current - const scroll = scrollRef.current - const content = contentRef.current - if (!active || !root || !scroll || !content) return - const target = place.current - if (!target) { - scroll.scrollTop = 0 - return - } + const hold = useCallback((root: HTMLElement, scroll: HTMLElement, content: HTMLElement) => { + release.current?.() const apply = () => { + const target = place.current + if (!target) return const blocks = blocksOf(content) scroll.scrollTop = flowScrollTop(target, blocks.length, measure(blocks, scroll)) } const observer = new ResizeObserver(apply) - const release = () => { + const stop = () => { restoring.current = false observer.disconnect() readerInput.forEach(name => { - root.removeEventListener(name, release) + root.removeEventListener(name, stop) }) + if (release.current === stop) release.current = null } restoring.current = true apply() observer.observe(content) readerInput.forEach(name => { - root.addEventListener(name, release, { passive: true }) + root.addEventListener(name, stop, { passive: true }) }) - return release - }, [active, contentRef, rootRef, scrollRef]) + release.current = stop + }, []) - // Browsers deliver scroll at most once a frame, and finding the block takes a handful of reads. - return () => { + useLayoutEffect(() => { + const root = rootRef.current const scroll = scrollRef.current const content = contentRef.current - if (!active || restoring.current || !scroll || !content) return + if (!active || !root || !scroll || !content) return + if (!place.current) { + scroll.scrollTop = 0 + return + } + hold(root, scroll, content) + return () => release.current?.() + }, [active, contentRef, hold, rootRef, scrollRef]) + + const placeAt = (scroll: HTMLElement, content: HTMLElement) => { const blocks = blocksOf(content) place.current = flowAnchorAt(blocks.length, measure(blocks, scroll), scroll.scrollTop) onPositionChange(place.current) } + + return { + // Browsers deliver scroll at most once a frame, and finding the block takes a handful of reads. + record: () => { + const scroll = scrollRef.current + const content = contentRef.current + if (!active || restoring.current || !scroll || !content) return + placeAt(scroll, content) + }, + // Brings an element to the top and holds it there as the reading place, as a restored place + // is held, so content that settles afterwards does not carry it away. + show: (element: HTMLElement) => { + const root = rootRef.current + const scroll = scrollRef.current + const content = contentRef.current + if (!root || !scroll || !content) return + scroll.scrollTop = pageTop(element) - pageTop(scroll) + placeAt(scroll, content) + hold(root, scroll, content) + }, + } } diff --git a/ui-packages/web/src/features/reader/markdown-reader/wiki-link.tsx b/ui-packages/web/src/features/reader/markdown-reader/wiki-link.tsx new file mode 100644 index 0000000..850cdff --- /dev/null +++ b/ui-packages/web/src/features/reader/markdown-reader/wiki-link.tsx @@ -0,0 +1,90 @@ +import { parseTarget } from '@gamma-reader/links' +import * as Popover from '@radix-ui/react-popover' +import { type ReactNode, useState } from 'react' +import { useLinkGraph, useOpenLink } from '../../../shell/workspace-context' +import styles from './style.module.scss' + +type WikiLinkProps = { raw: string; kind: string; children: ReactNode } + +// A [[link]] as the reader shows it. Its page is found by name in the link graph: one file opens +// at the place the link names, several are offered to choose from, and none leaves it inert, as +// a page that is only linked has nothing to open yet. +export const WikiLink = ({ raw, kind, children }: WikiLinkProps) => { + const graph = useLinkGraph() + const openLink = useOpenLink() + const [choosing, setChoosing] = useState(false) + const { target } = parseTarget(raw) + const resolution = graph?.resolve(target) + const page = graph?.node({ page: target.page }) + const owners = page?.kind === 'page' ? page.files : [] + const className = `${styles.wikiLink} ${kind === 'tag' ? styles.tag : ''}` + + if (!resolution) + return ( + + ) + if (resolution.kind === 'virtual') + return ( + + ) + if (resolution.kind === 'file') + return ( + + ) + + return ( + + + + + + +
    + {owners.map(file => ( +
  • + +
  • + ))} +
+
+
+
+ ) +} diff --git a/ui-packages/web/src/features/reader/pdf-reader.tsx b/ui-packages/web/src/features/reader/pdf-reader.tsx index e5bebb8..d930300 100644 --- a/ui-packages/web/src/features/reader/pdf-reader.tsx +++ b/ui-packages/web/src/features/reader/pdf-reader.tsx @@ -1,8 +1,8 @@ -import { useRef, useState } from 'react' +import { useEffect, useRef, useState } from 'react' import { PdfReader as DocumentPdfReader, type PdfReaderHandle } from '../../components/pdf-reader' import type { StoredFileMetadata } from '../../core/files' import type { ReadingPositionProps } from '../../core/reading-position' -import { useReaderBinding } from '../../shell/workspace-context' +import { useReaderBinding, useReveal } from '../../shell/workspace-context' import { usePdfReadingTheme } from './pdf-reading-preferences' import { readViewport } from './reader-viewport' @@ -22,6 +22,16 @@ export const PdfReader = ({ defaultPosition?.kind === 'page' ? defaultPosition.page : 1, ) const [theme, setTheme] = usePdfReadingTheme() + // A link such as [[paper.pdf#page=12]] that led here opens at its page. + const { reveal, shown } = useReveal(document.id) + useEffect(() => { + if (!reveal) return + if ('page' in reveal.target) { + setPageNumber(reveal.target.page) + onPositionChange({ kind: 'page', page: reveal.target.page }) + } + shown(reveal) + }, [onPositionChange, reveal, shown]) useReaderBinding( { fileId: document.id, diff --git a/ui-packages/web/src/shell/links-navigation.integration.test.tsx b/ui-packages/web/src/shell/links-navigation.integration.test.tsx new file mode 100644 index 0000000..2156d7c --- /dev/null +++ b/ui-packages/web/src/shell/links-navigation.integration.test.tsx @@ -0,0 +1,61 @@ +import { render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom' +import { beforeEach, describe, expect, it } from 'vitest' +import { writeStoredTextFile } from '../data/file-store' +import { testProject } from '../test/project' +import { Workbench } from './workbench' + +beforeEach(() => { + Range.prototype.getClientRects = () => [new DOMRect(0, 0, 100, 20)] as unknown as DOMRectList +}) + +const Navigation = () => { + const location = useLocation() + const navigate = useNavigate() + return ( + <> + {decodeURIComponent(location.pathname)} + + + ) +} + +const article = () => screen.getByRole('tabpanel').querySelector('article') as HTMLElement + +describe('following links between notes', () => { + it('opens the linked note at the named block, and Back returns to the note before', async () => { + await writeStoredTextFile('notes/Reading.md', '# Reading\n\nSee [[Retrieval#^first|why]].') + await writeStoredTextFile( + 'notes/Retrieval.md', + '# Retrieval\n\nIntro.\n\nRetrieval comes first. ^first\n\n- An item ^item', + ) + const user = userEvent.setup({ delay: null }) + render( + + + + , + ) + + // A link can be followed once the library is indexed and knows where it leads. + const link = await screen.findByRole('button', { name: 'why' }) + await waitFor(() => expect(link).toHaveAttribute('title', 'notes/Retrieval.md')) + await user.click(link) + + const route = screen.getByLabelText('Current route') + await waitFor(() => expect(route).toHaveTextContent('/files/notes/Retrieval.md')) + const named = await waitFor(() => { + const element = article().querySelector('[data-block="first"]') + expect(element).not.toBeNull() + return element as HTMLElement + }) + expect(named).toHaveTextContent('Retrieval comes first.') + expect(within(article()).queryByText(/\^first|\^item/)).not.toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Back' })) + await waitFor(() => expect(route).toHaveTextContent('/files/notes/Reading.md')) + }) +}) diff --git a/ui-packages/web/src/shell/workspace-context.tsx b/ui-packages/web/src/shell/workspace-context.tsx index 7e600d8..8a8d1ca 100644 --- a/ui-packages/web/src/shell/workspace-context.tsx +++ b/ui-packages/web/src/shell/workspace-context.tsx @@ -1,3 +1,4 @@ +import { headingKey, type LinkTarget } from '@gamma-reader/links' import { createContext, type ReactNode, @@ -10,6 +11,7 @@ import { useRef, } from 'react' import { useStore } from 'zustand' +import { createStore } from 'zustand/vanilla' import type { UpdateStoredTextFileResult } from '../data/file-store' import { getStoredFile } from '../data/file-store' import type { @@ -17,10 +19,16 @@ import type { WorkspaceFileMover, WorkspaceTextWriter, } from '../features/agent/local-tools' +import type { NoteIndexState } from '../features/links/note-index' import type { NoteIndexStore } from '../features/links/use-note-index' import type { Workspace } from './use-workspace' import { type ReaderBinding, useWorkspaceTools } from './use-workspace-tools' -import { sourceDirty, type WorkspaceActions, type WorkspaceStore } from './workspace-store' +import { + type RevealTarget, + sourceDirty, + type WorkspaceActions, + type WorkspaceStore, +} from './workspace-store' type WorkspaceContextValue = { tools: LocalTools @@ -28,9 +36,23 @@ type WorkspaceContextValue = { actions: WorkspaceActions register: (binding: ReaderBinding) => () => void saveSource: (fileId: string, overwrite?: boolean) => Promise<'saved' | 'conflict' | 'failed'> + noteIndex: NoteIndexStore + openLink: (target: LinkTarget, fileId: string) => void } const WorkspaceContext = createContext(null) +// A workspace without a link index, where links lead nowhere yet. +const withoutIndex = createStore(() => ({ graph: null, progress: null })) + +const placeOf = (target: LinkTarget): RevealTarget | null => + target.block + ? { block: target.block } + : target.heading + ? { heading: headingKey(target.heading) } + : target.pdfPage + ? { page: target.pdfPage } + : null + export const WorkspaceProvider = ({ workspace, rootRef, @@ -55,6 +77,10 @@ export const WorkspaceProvider = ({ }) => { const { actions, store } = workspace const readers = useRef(new Map()) + const openDocument = useRef(workspace.openDocument) + useLayoutEffect(() => { + openDocument.current = workspace.openDocument + }, [workspace.openDocument]) const tools = useWorkspaceTools({ workspace, rootRef, @@ -121,6 +147,15 @@ export const WorkspaceProvider = ({ }, [actions, store, updateTextFile], ) + // Opens the file a link leads to, showing the place it names, if any, once the file is read. + const openLink = useCallback( + (target: LinkTarget, fileId: string) => { + const place = placeOf(target) + if (place) actions.reveal(fileId, place) + openDocument.current(fileId) + }, + [actions], + ) const value = useMemo( () => ({ store, @@ -134,8 +169,10 @@ export const WorkspaceProvider = ({ }, tools, saveSource, + noteIndex: noteIndex ?? withoutIndex, + openLink, }), - [actions, saveSource, store, tools], + [actions, noteIndex, openLink, saveSource, store, tools], ) return {children} } @@ -179,3 +216,15 @@ export const useReaderBinding = (binding: ReaderBinding, active: boolean) => { const { register } = useWorkspaceContext() useLayoutEffect(() => (active ? register(binding) : undefined), [active, binding, register]) } + +// The link graph as it stands, null until the library is first indexed. +export const useLinkGraph = () => useStore(useWorkspaceContext().noteIndex, state => state.graph) + +export const useOpenLink = () => useWorkspaceContext().openLink + +// The place a link asked this file's reader to show, if any, and how to say it was shown. +export const useReveal = (fileId: string) => { + const { store, actions } = useWorkspaceContext() + const reveal = useStore(store, state => (state.reveal?.fileId === fileId ? state.reveal : null)) + return { reveal, shown: actions.clearReveal } +} diff --git a/ui-packages/web/src/shell/workspace-store.ts b/ui-packages/web/src/shell/workspace-store.ts index 7e7656c..b57fa30 100644 --- a/ui-packages/web/src/shell/workspace-store.ts +++ b/ui-packages/web/src/shell/workspace-store.ts @@ -17,10 +17,16 @@ export type SourceDraft = { saveError: string | null } +// A place in a file that a link asked to show: a named block, a heading by its key, or a PDF +// page. The file's reader shows it once and clears it. +export type RevealTarget = { block: string } | { heading: string } | { page: number } +export type Reveal = { fileId: string; target: RevealTarget } + export type WorkspaceState = { tabs: string[] sourceDrafts: Record positions: Record + reveal: Reveal | null } export type WorkspaceActions = { @@ -35,6 +41,8 @@ export type WorkspaceActions = { reloadIncomingSource: (fileId: string) => void forgetSource: (fileId: string) => void setPosition: (fileId: string, position: ReadingPosition) => void + reveal: (fileId: string, target: RevealTarget) => void + clearReveal: (reveal: Reveal) => void } export const sourceDirty = (draft: SourceDraft | undefined) => @@ -59,6 +67,7 @@ export const createWorkspaceStore = ( tabs, sourceDrafts: {}, positions, + reveal: null, })) export type WorkspaceStore = ReturnType @@ -199,5 +208,8 @@ export const createWorkspaceActions = (store: WorkspaceStore): WorkspaceActions }), setPosition: (fileId, position) => set(state => ({ positions: { ...state.positions, [fileId]: position } })), + reveal: (fileId, target) => set({ reveal: { fileId, target } }), + // Only the reveal that was shown is cleared, not a newer one asked for meanwhile. + clearReveal: reveal => set(state => (state.reveal === reveal ? { reveal: null } : state)), } }