3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-19 14:45:44 +01:00

Answer architecture round 1: 0 🔴, 11 🟡 (0 misread); one line policy, one reduction run, named sweep stages, spelling memo, block text, link options, HTML refusals

This commit is contained in:
2026-11-08 20:30:08 +01:00
committed by Lillem4n
parent 8e6d7efff1
commit e9de121425
20 changed files with 329 additions and 215 deletions
+13 -17
View File
@@ -6,35 +6,31 @@ import { nodeAttrs, nodeContent } from '../adf/document.ts'
import { partsShownText, referenceName, shownImage, shownLink, shownText, shownUrl } from '../adf/shown-text.ts'
import { shownValue } from './escaping.ts'
// The content a carry element shows of one block; `code` the code block holding it, if any.
type ShownBlock = { code: AdfNode | undefined; html: string }
// One object per block a node stands in, so a block's content after a nested block parts from its content before; `code` the code block it is, if any.
type BlockPart = { code: AdfNode | undefined }
type ShownBlock = { html: string; part: BlockPart }
// What a carry element shows of the node it holds, and all `htmlToAdf` accepts there, so a change here breaks reading stored HTML (docs/decisions.md §The formats are API).
export function carryContent(node: AdfNode, tag: 'div' | 'span'): string {
if (tag === 'span') return shownBlocks(node, '<br>').map(({ html }) => html).join('<br>')
return shownBlocks(node, '\n').map(({ code, html }) => (code === undefined ? `<p>${html}</p>` : `<pre><code${languageClass(nodeAttrs(code)['language']) ?? ''}>${html}</code></pre>`)).join('')
return shownBlocks(node, '\n').map(({ html, part: { code } }) => (code === undefined ? `<p>${html}</p>` : `<pre><code${languageClass(nodeAttrs(code)['language']) ?? ''}>${html}</code></pre>`)).join('')
}
// What a carry element shows, block by block, as the writer panels picked it (docs/decisions.md §The HTML dialect).
function shownBlocks(root: AdfNode, codeLineFeed: string): ShownBlock[] {
const shown: ShownBlock[] = []
let current: ShownBlock = { code: undefined, html: '' }
// Each entry holds the code block it stands in, none where another block stands between them; a `null` node ends a block, and what follows stands in that entry's `code`, the code block around the block that ended.
const pending: { code: AdfNode | undefined; node: AdfNode | null }[] = [{ code: undefined, node: root }]
const pending: { node: AdfNode; part: BlockPart }[] = [{ node: root, part: { code: undefined } }]
for (let next = pending.pop(); next !== undefined; next = pending.pop()) {
const { node } = next
const code = node?.type === 'codeBlock' ? node : node !== null && partsShownText(node.type) ? undefined : next.code
if (node === null || partsShownText(node.type)) {
if (current.html !== '') shown.push(current)
current = { code, html: '' }
}
if (node === null) continue
current = { ...current, html: current.html + shownPiece(node, current.code === undefined ? '<br>' : codeLineFeed) }
if (partsShownText(node.type)) pending.push({ code: next.code, node: null })
for (const child of [...nodeContent(node)].reverse()) pending.push({ code, node: child })
const part = partsShownText(node.type) ? { code: node.type === 'codeBlock' ? node : undefined } : next.part
const piece = shownPiece(node, part.code === undefined ? '<br>' : codeLineFeed)
const last = shown.at(-1)
if (last?.part === part) last.html += piece
else shown.push({ html: piece, part })
for (const child of [...nodeContent(node)].reverse()) pending.push({ node: child, part })
}
if (current.html !== '') shown.push(current)
return shown
return shown.filter(({ html }) => html !== '')
}
// The node's own part of what its carry element shows.
+16 -9
View File
@@ -22,13 +22,13 @@ export function dataAttributes(node: AdfNode, vocabulary: AttributeVocabulary, w
return attributes
}
// What `dataAttributes` wrote, its pairs' values unescaped; the caller reads `leading`, an attribute the element writes ahead of them, where it stands first. A pair it does not write in that order is no HTML of the dialect; a name or value no attribute of the node spells is the node's shape, as a directive's is (docs/decisions.md §Which code a cause takes).
export function readDataAttributes(pairs: readonly (readonly [string, string])[], element: string, vocabulary: AttributeVocabulary, written: readonly string[], leading?: string): Read<AdfAttributes> {
// What `dataAttributes` wrote, its pairs' values unescaped. A pair it does not write in that order is no HTML of the dialect; a name or value no attribute of the node spells is the node's shape, as a directive's is (docs/decisions.md §Which code a cause takes).
export function readDataAttributes(pairs: readonly (readonly [string, string])[], element: string, vocabulary: AttributeVocabulary, written: readonly string[]): Read<AdfAttributes> {
const attrs: AdfAttributes = {}
let previous = ''
for (const [name, spelled] of leading !== undefined && pairs[0]?.[0] === leading ? pairs.slice(1) : pairs) {
for (const [name, spelled] of pairs) {
const [key, kind] = dataKey(name, vocabulary, written) ?? []
if (key === undefined || kind === undefined) return { fault: nameFault(name, element, leading, previous) }
if (key === undefined || kind === undefined) return { fault: nameFault(name, element) }
if (key <= previous) return { fault: unmappable(`the data-* attributes stand once each, sorted by the attribute they name: found ${name} after ${dataName(previous)}`) }
const value = dataValue(spelled, kind)
if (value === undefined) return { fault: { code: 'unsupported-node-shape', message: `${name} holds no ${kind} written as compact JSON` } }
@@ -38,6 +38,15 @@ export function readDataAttributes(pairs: readonly (readonly [string, string])[]
return { value: attrs }
}
// As `readDataAttributes`, past `leading`, an attribute the element writes ahead of them, where it stands first; the caller reads `leading`.
export function readDataAttributesAfter(leading: string, pairs: readonly (readonly [string, string])[], element: string, vocabulary: AttributeVocabulary, written: readonly string[]): Read<AdfAttributes> {
const repeated = pairs.findIndex(([name], index) => index > 0 && name === leading)
const data = readDataAttributes(pairs.slice(pairs[0]?.[0] === leading ? 1 : 0, repeated < 0 ? pairs.length : repeated), element, vocabulary, written)
const before = repeated < 0 ? undefined : pairs[repeated - 1]
if (data.fault !== undefined || before === undefined) return data
return { fault: unmappable(`<${element}> takes ${leading} once, before its data-* attributes: found ${leading} after ${before[0]}`) }
}
// The attribute `name` spells, among those the element itself does not write.
function dataKey(name: string, vocabulary: AttributeVocabulary, written: readonly string[]): [string, AttributeKind] | undefined {
return Object.entries(vocabulary).find(([candidate]) => !written.includes(candidate) && dataName(candidate) === name)
@@ -53,11 +62,9 @@ export function dataValue(spelled: string, kind: AttributeKind): JsonValue | und
return value !== undefined && holdsKind(value, kind) && spellsCanonicalJson(value, 'compact', spelled) ? value : undefined
}
// At a `leading`, `previous` is empty only where another `leading` stood first.
function nameFault(name: string, element: string, leading: string | undefined, previous: string): ConvertFault {
if (name.startsWith('data-')) return { code: 'unsupported-node-shape', message: `<${element}> takes no ${name} attribute` }
if (name !== leading) return unmappable(`<${element}> takes no ${name} attribute`)
return unmappable(`<${element}> takes ${name} once, before its data-* attributes: found ${name} after ${previous === '' ? name : dataName(previous)}`)
function nameFault(name: string, element: string): ConvertFault {
const message = `<${element}> takes no ${name} attribute`
return name.startsWith('data-') ? { code: 'unsupported-node-shape', message } : unmappable(message)
}
function unmappable(message: string): ConvertFault {
+11 -5
View File
@@ -18,7 +18,7 @@ import { positioned, success } from '../../result.ts'
import { readAnchorAttributes } from '../anchor-element.ts'
import { readCarry } from './carry-element.ts'
import { readCarryAttributes } from '../carry-attributes.ts'
import { readDataAttributes } from '../data-attributes.ts'
import { readDataAttributes, readDataAttributesAfter } from '../data-attributes.ts'
import { readImageAttributes } from '../image-element.ts'
import { readLanguageClass } from '../language-class.ts'
import { serializeCanonicalJson } from '../../canonical-json.ts'
@@ -242,7 +242,8 @@ function readContainer(html: string, tag: StartTag, type: ContainerType, place:
const at = tag.start + `<${tag.name} start="`.length
return refused('unmappable-html', `an ordered list starts at an integer, written as JavaScript writes it: ${foundAt(html, at)}`, html, at, place)
}
const data = readDataAttributes(tag.attributes, tag.name, blockNodes[type].attributes, ordered ? ['order'] : [], ordered ? 'start' : undefined)
const vocabulary = blockNodes[type].attributes
const data = ordered ? readDataAttributesAfter('start', tag.attributes, tag.name, vocabulary, ['order']) : readDataAttributes(tag.attributes, tag.name, vocabulary, [])
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, tag.start, place)
const node = built(type, order === undefined ? data.value : { order, ...data.value }, [])
const closer = `</${tag.name}>`
@@ -320,9 +321,7 @@ function readItemLine(html: string, index: number, element: string, open: Open):
if (!line.ok) return line
const { end, node } = line.value
if (!html.startsWith(closer, end) && !html.startsWith('\n', end)) {
const lineEnd = `the line ends at ${closer}, or at a line feed before the next block`
// After a line's `</p>`, or before a block or the next item, no inline element can stand.
const stop = line.value.form === 'bare' && !isBlockStart(html, end) && startTagName(html, end) !== element ? misread(html, end, `${lineEnd}, and its text spells < as &lt;`, 'no inline element of the dialect') : { at: end, message: `${lineEnd}: ${foundAt(html, end)}` }
const stop = lineEndRefusal(html, end, line.value.form, element)
return refused('unmappable-html', stop.message, html, stop.at, open.place)
}
const paragraph = asFirstParagraph({ end, node }, line.value.form, html, index, place)
@@ -331,6 +330,13 @@ function readItemLine(html: string, index: number, element: string, open: Open):
return success({ end: end + 1, kind: 'opened', open: { ...open, content: [node] } })
}
function lineEndRefusal(html: string, end: number, form: FirstParagraphForm, element: string): { at: number; message: string } {
const lineEnd = `the line ends at </${element}>, or at a line feed before the next block`
// After a line's `</p>`, or before a block or the next item, no inline element can stand.
if (form !== 'bare' || isBlockStart(html, end) || startTagName(html, end) === element) return { at: end, message: `${lineEnd}: ${foundAt(html, end)}` }
return misread(html, end, `${lineEnd}, and its text spells < as &lt;`, 'no inline element of the dialect')
}
// The paragraph on an item's or cell's line and the form it stands in there, up to its closer or to the line feed before its next block.
function readLineParagraph(html: string, index: number, place: Place): Result<{ end: number; form: FirstParagraphForm; node: AdfNode }, ParseError> {
const tag = readStartTag(html, index)
+3 -2
View File
@@ -1,7 +1,7 @@
import type { AdfNode } from '../../adf/document.ts'
import { foundAt, misspelledText, refused, type Place, type ReadNode, type StartTag } from './source.ts'
import { nodeTypeOfElement } from '../node-element.ts'
import { readDataAttributes } from '../data-attributes.ts'
import { readDataAttributes, readDataAttributesAfter } from '../data-attributes.ts'
import { success } from '../../result.ts'
import { misspelledAt, unescapedValue } from '../escaping.ts'
@@ -13,7 +13,8 @@ export function readNodeElement(html: string, tag: StartTag, place: Place): Read
const [type, model] = found
const name = `<${tag.name} class="${model.class}">`
if (model.leading !== undefined && rest[0]?.[0] !== model.leading.name) return refused('unmappable-html', `${name} holds ${model.leading.name} first, before its data-* attributes: ${foundAt(html, tag.start)}`, html, tag.start, place)
const data = readDataAttributes(rest, `${tag.name} class="${model.class}"`, model.vocabulary, model.written, model.leading?.name)
const element = `${tag.name} class="${model.class}"`
const data = model.leading === undefined ? readDataAttributes(rest, element, model.vocabulary, model.written) : readDataAttributesAfter(model.leading.name, rest, element, model.vocabulary, model.written)
if (data.fault !== undefined) return refused(data.fault.code, data.fault.message, html, tag.start, place)
const closer = `</${tag.name}>`
const stop = html.indexOf('<', tag.end)