Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/links/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
2 changes: 2 additions & 0 deletions packages/links/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export {
export { NameBlockError, nameBlock } from './name-block'
export {
formatNode,
headingKey,
isNotePath,
type NodeKind,
type NodeRef,
Expand All @@ -31,3 +32,4 @@ export {
parseNote,
parseTarget,
} from './parse'
export { remarkLinks } from './remark'
63 changes: 41 additions & 22 deletions packages/links/src/parse.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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 } => {
Expand Down Expand Up @@ -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]
Expand All @@ -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)
Expand All @@ -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 => {
Expand All @@ -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)),
Expand Down
106 changes: 106 additions & 0 deletions packages/links/src/remark.test.ts
Original file line number Diff line number Diff line change
@@ -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}</${node.tagName}>`
}

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(
'<p>See <button dataLink="RAG" dataKind="link">RAG</button>, ' +
'<button dataLink="RAG#^def|定义" dataKind="link">定义</button>, ' +
'<button dataLink="agents" dataKind="tag">#agents</button>, ' +
'<button dataLink="RAG#Later" dataKind="embed">RAG#Later</button>, ' +
'<button dataLink="p.pdf#page=3" dataKind="link">p.pdf#page=3</button>.</p>',
)
})

it('leaves code, inline code, Markdown links and links within the page alone', () => {
expect(render('`[[A]]` [see [[B]]](https://x.org) [[#Local]]', '', '```', '[[C]]', '```')).toBe(
'<p><code>[[A]]</code> <a>see [[B]]</a> [[#Local]]</p><pre><code>[[C]]\n</code></pre>'.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(
'<h2 dataBlock="methods" dataHeading="methods">Methods</h2>' +
'<p dataBlock="def">Retrieval first.</p>' +
'<ul><li dataBlock="sparse">Sparse retrieval<ul><li>with BM25</li></ul></li></ul>' +
'<table dataBlock="table"><thead><tr><th>A</th></tr></thead>' +
'<tbody><tr><td>x</td></tr></tbody></table>',
)
})

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(
'<h1 dataHeading="retrieval strategy">Retrieval Strategy</h1>' +
'<h2 dataHeading="检索 [[rag]]">检索 <button dataLink="RAG" dataKind="link">RAG</button></h2>',
)
})
})
94 changes: 94 additions & 0 deletions packages/links/src/remark.ts
Original file line number Diff line number Diff line change
@@ -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)
}
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion ui-packages/web/src/features/reader/csv-reader.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
5 changes: 4 additions & 1 deletion ui-packages/web/src/features/reader/docx-reader.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading