mirror of
https://github.com/larvit/adf-codec.git
synced 2026-11-18 14:15:44 +01:00
Ship adfToHtml: semantic HTML for the CommonMark blocks and marks, an adf-carry element for the rest
This commit is contained in:
@@ -44,7 +44,7 @@ test('refuses a value that is not an ADF document, naming the check it failed',
|
||||
assert.equal(markdown(adfToLosslessMarkdown({ type: 'doc', version: Number.NaN })), 'not-an-adf-document: an ADF document holds a version number: found NaN')
|
||||
})
|
||||
|
||||
const tooLong = 'unsupported-node-shape: the markdown for this document, or for a directive\'s plain CommonMark, would be longer than 536870888 characters, the longest this library writes'
|
||||
const tooLong = 'unsupported-node-shape: the markdown or HTML for this document, or a directive\'s plain CommonMark, would be longer than 536870888 characters, the longest this library writes'
|
||||
|
||||
// A code block of 300 lines; two of these together fall some 1000 characters short of V8's longest string, so only what their spelling adds passes it.
|
||||
function nearlyHalfTheBound(): AdfNode {
|
||||
|
||||
@@ -12,7 +12,7 @@ import { flavourClaims } from '../flavour.ts'
|
||||
import { holdsNullCharacter, isBlankLine, isThematicBreak, markerInterruptsParagraph } from '../commonmark/grammar.ts'
|
||||
import { languageSlot, type LanguageSlot } from '../code-language.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
import { longestMarkdown, tooLong, withinEngineLimits, withinLongest } from '../length-bound.ts'
|
||||
import { longestOutput, tooLong, withinEngineLimits, withinLongest } from '../../length-bound.ts'
|
||||
import { spellBlockDirectiveOpener } from '../directive/block-spelling.ts'
|
||||
import { spellDirectiveCloser, spellDirectiveOpener } from '../directive/syntax.ts'
|
||||
import { tryImage } from './image.ts'
|
||||
@@ -55,7 +55,7 @@ export function writeMarkdown(document: AdfDocument, writtenAs: WrittenAs): Resu
|
||||
if (document.version !== 1) return failure('unsupported-document-version', `no markdown spelling carries ADF version ${document.version}`, [])
|
||||
if (document.content === undefined) return success(`${documentSpelling}\n`)
|
||||
// Every character of text is spelled at least once, so this much text cannot fit, and none of it is spelled.
|
||||
if (heldTextLength(document.content) > longestMarkdown) return tooLong()
|
||||
if (heldTextLength(document.content) > longestOutput) return tooLong()
|
||||
const walk = walkBlocks(document.content, [], 0, { ...writtenAs, memo: undefined })
|
||||
if (!walk.ok) return walk
|
||||
const text = joinBlocks(walk.value.blocks, 'document')
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
import type { AdfNode } from '../../adf/document.ts'
|
||||
import type { WrittenFlavour } from '../flavour.ts'
|
||||
import { centeredImage, externalMedia } from '../external-image.ts'
|
||||
import { linkDefinition } from '../mark-spellings.ts'
|
||||
import { nodeAttrs, nodeContent, nodeMarks } from '../../adf/document.ts'
|
||||
import { serializeCanonicalJson } from '../../canonical-json.ts'
|
||||
import { plainImage } from '../../adf/external-image.ts'
|
||||
import { targetDefinition } from '../mark-spellings.ts'
|
||||
import { tryImageLine } from './inline-line.ts'
|
||||
|
||||
export function tryImage(node: AdfNode, flavour: WrittenFlavour): string | undefined {
|
||||
const [media] = nodeContent(node)
|
||||
if (media === undefined) return undefined
|
||||
const { alt, url } = nodeAttrs(media)
|
||||
if (typeof url !== 'string' || (alt !== undefined && typeof alt !== 'string')) return undefined
|
||||
const [mark] = nodeMarks(media)
|
||||
const link = mark === undefined ? undefined : linkDefinition(nodeAttrs(mark))
|
||||
const read = centeredImage([externalMedia(alt ?? '', url, link)])
|
||||
return serializeCanonicalJson(node, 'compact') === serializeCanonicalJson(read, 'compact') ? tryImageLine(alt, url, flavour, link) : undefined
|
||||
const image = plainImage(node)
|
||||
if (image === undefined) return undefined
|
||||
const { alt, link, url } = image
|
||||
return tryImageLine(alt, url, flavour, link === undefined ? undefined : targetDefinition(link))
|
||||
}
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
import type { AdfNode } from '../adf/document.ts'
|
||||
import type { LinkDefinition } from './commonmark/link-syntax.ts'
|
||||
import { linkMark } from './mark-spellings.ts'
|
||||
|
||||
// spec/flavour.md, The CommonMark image: `` reads to `centeredImage([externalMedia(alt, url)])`, the only shape `adfToLosslessMarkdown` writes as ``.
|
||||
export function centeredImage(content: AdfNode[]): AdfNode {
|
||||
return { attrs: { layout: 'center' }, content, type: 'mediaSingle' }
|
||||
}
|
||||
|
||||
// `` builds no `alt`, so a media holding an empty one takes the directive form.
|
||||
export function externalMedia(alt: string, url: string, link?: LinkDefinition): AdfNode {
|
||||
const media: AdfNode = { attrs: alt === '' ? { type: 'external', url } : { alt, type: 'external', url }, type: 'media' }
|
||||
return link === undefined ? media : { ...media, marks: [linkMark(link)] }
|
||||
}
|
||||
|
||||
// The ` (image)` after a link for an image inside it, as the readers build it (spec/flavour.md, The CommonMark image) and `adfToPortableMarkdown` writes it; `link` builds the linked word `image`.
|
||||
export function imageAside(link: (text: string) => AdfNode[]): AdfNode[] {
|
||||
return [{ text: ' (', type: 'text' }, ...link('image'), { text: ')', type: 'text' }]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { AdfNode } from '../adf/document.ts'
|
||||
|
||||
// The ` (image)` after a link for an image inside it, as the readers build it (spec/flavour.md, The CommonMark image) and `adfToPortableMarkdown` writes it; `link` builds the linked word `image`.
|
||||
export function imageAside(link: (text: string) => AdfNode[]): AdfNode[] {
|
||||
return [{ text: ' (', type: 'text' }, ...link('image'), { text: ')', type: 'text' }]
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import type { Result } from '../result.ts'
|
||||
import { joinedWithin, tooLong, withinEngineLimits, withinLongest } from './length-bound.ts'
|
||||
import { success } from '../result.ts'
|
||||
|
||||
function thrown(name: string, message: string): () => Result<string> {
|
||||
return () => {
|
||||
const error = new Error(message)
|
||||
error.name = name
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
test('joins pieces up to the bound, and builds nothing past it', () => {
|
||||
assert.deepEqual(joinedWithin(['a', 'b']), success('ab'))
|
||||
const half = 'a'.repeat(2 ** 28)
|
||||
assert.deepEqual(joinedWithin([half, half]), tooLong())
|
||||
})
|
||||
|
||||
test('passes a text within the bound', () => {
|
||||
assert.deepEqual(withinLongest('x'), success('x'))
|
||||
})
|
||||
|
||||
test('refuses a string past the bound as too long on every engine, and any other engine limit as engine-limit', () => {
|
||||
assert.deepEqual(withinEngineLimits(thrown('RangeError', 'Invalid string length')), tooLong())
|
||||
assert.deepEqual(withinEngineLimits(thrown('InternalError', 'allocation size overflow')), tooLong())
|
||||
assert.deepEqual(withinEngineLimits(thrown('RangeError', 'Out of memory')), {
|
||||
error: { code: 'engine-limit', message: 'the conversion passed a limit of this JavaScript engine on a string, array, Map or Set, or ran it out of memory (Out of memory)', path: [] },
|
||||
ok: false,
|
||||
})
|
||||
const code = (message: string): string | undefined => {
|
||||
const refused = withinEngineLimits(thrown('RangeError', message))
|
||||
return refused.ok ? undefined : refused.error.code
|
||||
}
|
||||
assert.equal(code('Invalid array length'), 'engine-limit')
|
||||
assert.equal(code('Array buffer allocation failed'), 'engine-limit')
|
||||
assert.equal(code('Map maximum size exceeded'), 'engine-limit')
|
||||
assert.equal(code('Set maximum size exceeded'), 'engine-limit')
|
||||
assert.equal(code('invalid array length'), 'engine-limit')
|
||||
assert.deepEqual(
|
||||
withinEngineLimits(() => {
|
||||
throw 'out of memory'
|
||||
}),
|
||||
{ error: { code: 'engine-limit', message: 'the conversion passed a limit of this JavaScript engine on a string, array, Map or Set, or ran it out of memory (out of memory)', path: [] }, ok: false },
|
||||
)
|
||||
assert.deepEqual(
|
||||
withinEngineLimits(() => success('x')),
|
||||
{ ok: true, value: 'x' },
|
||||
)
|
||||
})
|
||||
|
||||
test('lets a stack overflow or any other throw through', () => {
|
||||
assert.throws(() => withinEngineLimits(thrown('RangeError', 'Maximum call stack size exceeded')))
|
||||
assert.throws(() => withinEngineLimits(thrown('TypeError', 'a bug')))
|
||||
assert.throws(() =>
|
||||
withinEngineLimits(() => {
|
||||
throw 'a string'
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -1,54 +0,0 @@
|
||||
import { failure, success, type Result } from '../result.ts'
|
||||
|
||||
// V8's longest string, refused on every engine so a document converts alike everywhere (docs/decisions.md §Markdown past V8's longest string is refused on every engine).
|
||||
export const longestMarkdown = 2 ** 29 - 24
|
||||
|
||||
// Measured on Firefox 155, Node 24 and Bun 1.4; SpiderMonkey's `invalid array length` is taken from its js.msg. SpiderMonkey's overflow and V8's string overflow both mean a string past longestMarkdown; the others name an engine's own limit or its memory running short.
|
||||
const pastLongestString = ['InternalError: allocation size overflow', 'RangeError: Invalid string length']
|
||||
const pastEngineLimit = [
|
||||
'RangeError: Array buffer allocation failed',
|
||||
'RangeError: Invalid array length',
|
||||
'RangeError: Map maximum size exceeded',
|
||||
'RangeError: Out of memory',
|
||||
'RangeError: Set maximum size exceeded',
|
||||
'RangeError: invalid array length',
|
||||
]
|
||||
|
||||
export function tooLong<T>(): Result<T> {
|
||||
return failure('unsupported-node-shape', `the markdown for this document, or for a directive's plain CommonMark, would be longer than ${longestMarkdown} characters, the longest this library writes`, [])
|
||||
}
|
||||
|
||||
export function withinLongest(text: string): Result<string> {
|
||||
return text.length > longestMarkdown ? tooLong() : success(text)
|
||||
}
|
||||
|
||||
export function joinedWithin(pieces: Iterable<string>): Result<string> {
|
||||
const kept: string[] = []
|
||||
let length = 0
|
||||
for (const piece of pieces) {
|
||||
length += piece.length
|
||||
if (length > longestMarkdown) return tooLong()
|
||||
kept.push(piece)
|
||||
}
|
||||
return success(kept.join(''))
|
||||
}
|
||||
|
||||
// Any concatenation can pass an engine's longest string or array; wrap every call that builds one.
|
||||
export function withinEngineLimits<T>(convert: () => Result<T>): Result<T> {
|
||||
try {
|
||||
return convert()
|
||||
} catch (error) {
|
||||
// SpiderMonkey throws a bare string where it finds no memory for a buffer (measured on Firefox 155).
|
||||
if (error === 'out of memory') return engineLimit(error)
|
||||
if (!(error instanceof Error)) throw error
|
||||
const thrown = `${error.name}: ${error.message}`
|
||||
if (pastLongestString.includes(thrown)) return tooLong()
|
||||
// A stack overflow is a bug (docs/decisions.md §Nothing recurses unbounded), so it stays a throw.
|
||||
if (!pastEngineLimit.includes(thrown)) throw error
|
||||
return engineLimit(error.message)
|
||||
}
|
||||
}
|
||||
|
||||
function engineLimit<T>(thrown: string): Result<T> {
|
||||
return failure('engine-limit', `the conversion passed a limit of this JavaScript engine on a string, array, Map or Set, or ran it out of memory (${thrown})`, [])
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { escapeUnbalanced, spellLinkTarget } from './commonmark/link-syntax.ts'
|
||||
import { holdsDirectivePrefix, spellAttributes, spellVocabulary } from './directive/syntax.ts'
|
||||
import { holdsEntityReference } from './commonmark/entity-references.ts'
|
||||
import { isAutolink } from './commonmark/grammar.ts'
|
||||
import { isMarkType, markAttributes } from '../adf/mark-attributes.ts'
|
||||
import { isMarkType, linkTarget, linkTargetMark, markAttributes, type LinkTarget } from '../adf/mark-attributes.ts'
|
||||
import { spellEmptyKeys } from './directive/empty-keys.ts'
|
||||
import { vocabularyPairs } from '../adf/attribute-vocabulary.ts'
|
||||
|
||||
@@ -37,16 +37,21 @@ export function markSpelling(type: string): MarkSpelling | undefined {
|
||||
return { attributes, kind: spelling.kind }
|
||||
}
|
||||
|
||||
export function linkMark({ destination, title }: LinkDefinition): AdfMark {
|
||||
return { attrs: title === undefined ? { href: destination } : { href: destination, title }, type: 'link' }
|
||||
export function linkMark(definition: LinkDefinition): AdfMark {
|
||||
return linkTargetMark(definitionTarget(definition))
|
||||
}
|
||||
|
||||
export function definitionTarget({ destination, title }: LinkDefinition): LinkTarget {
|
||||
return title === undefined ? { href: destination } : { href: destination, title }
|
||||
}
|
||||
|
||||
export function linkDefinition(attrs: AdfAttributes): LinkDefinition | undefined {
|
||||
const destination = linkHref(attrs)
|
||||
const title = attrs['title']
|
||||
if (destination === undefined) return undefined
|
||||
if (title === undefined) return { destination }
|
||||
return typeof title === 'string' ? { destination, title } : undefined
|
||||
const target = linkTarget(attrs)
|
||||
return target === undefined ? undefined : targetDefinition(target)
|
||||
}
|
||||
|
||||
export function targetDefinition({ href, title }: LinkTarget): LinkDefinition {
|
||||
return title === undefined ? { destination: href } : { destination: href, title }
|
||||
}
|
||||
|
||||
export function linkHref(attrs: AdfAttributes): string | undefined {
|
||||
|
||||
@@ -2,14 +2,14 @@ import type { AdfNode } from '../adf/document.ts'
|
||||
import type { DirectiveSpan } from './directive/syntax.ts'
|
||||
import type { JsonSpelling } from '../canonical-json.ts'
|
||||
import type { JsonValue } from '../json-value.ts'
|
||||
import { canonicalJsonPieces, spellsCanonicalJson } from '../canonical-json.ts'
|
||||
import { carriedJson } from '../adf/carried-json.ts'
|
||||
import { spellsCanonicalJson } from '../canonical-json.ts'
|
||||
import { directiveEscape, malformedDirective, readSoleStringAttribute, spellAttributes, spellDirectiveOpener, spellInlineLeafDirective, spellStringAttribute, unsupportedNodeShape } from './directive/syntax.ts'
|
||||
import { failure, success, type ConvertErrorPath, type Read, type Result } from '../result.ts'
|
||||
import { success, type ConvertErrorPath, type Read, type Result } from '../result.ts'
|
||||
import { fencedCodeBlock } from './commonmark/backtick-runs.ts'
|
||||
import { infoStringCarries } from './commonmark/grammar.ts'
|
||||
import { isAdfNode } from '../adf/document.ts'
|
||||
import { isJsonValue, nestingDepth, overNested } from '../json-value.ts'
|
||||
import { joinedWithin } from './length-bound.ts'
|
||||
import { overNested } from '../json-value.ts'
|
||||
import { largestNesting } from '../nesting.ts'
|
||||
import { parseJsonText } from '../json-text.ts'
|
||||
|
||||
@@ -54,16 +54,6 @@ export function readCarriedInline(span: DirectiveSpan): Read<AdfNode> | undefine
|
||||
return readCarriedJson(spelled.value, 'compact', largestNesting)
|
||||
}
|
||||
|
||||
function carriedJson(node: AdfNode, spelled: object, spelling: JsonSpelling, path: ConvertErrorPath, levels: number): Result<{ headroom: number; json: string }> {
|
||||
const headroom = levels - nestingDepth(node)
|
||||
if (!isJsonValue(spelled) || headroom < 0) {
|
||||
return failure('unsupported-nesting-depth', `a carried node's JSON nests deeper than the ${levels} levels its position leaves`, path)
|
||||
}
|
||||
// Two-space JSON indents each value by its depth, so a short compact value can spell past the bound: join only up to it.
|
||||
const json = joinedWithin(canonicalJsonPieces(spelled, spelling))
|
||||
return json.ok ? success({ headroom, json: json.value }) : json
|
||||
}
|
||||
|
||||
// `type` is the one the fence's info string names, `undefined` for the inline carry.
|
||||
function readCarriedJson(raw: string, spelling: JsonSpelling, levels: number, type?: string): Read<AdfNode> {
|
||||
const wayOut = type === undefined ? directiveEscape : fenceEscape(type)
|
||||
|
||||
@@ -5,8 +5,9 @@ import type { EmphasisPairing } from '../commonmark/emphasis-matching.ts'
|
||||
import type { InlineSource, InlineToken } from '../inline-tokens.ts'
|
||||
import type { LineContainer } from '../line-container.ts'
|
||||
import type { LinkDefinition } from '../commonmark/link-syntax.ts'
|
||||
import { centeredImage, externalMedia, imageAside } from '../external-image.ts'
|
||||
import { commonMarkLink, linkDefinition, linkHref, linkMark } from '../mark-spellings.ts'
|
||||
import { centeredImage, externalMedia } from '../../adf/external-image.ts'
|
||||
import { imageAside } from '../image-aside.ts'
|
||||
import { commonMarkLink, definitionTarget, linkDefinition, linkHref, linkMark } from '../mark-spellings.ts'
|
||||
import { decodeTextEscapes, trimTrailingSpace } from '../commonmark/grammar.ts'
|
||||
import { failure, faulted, success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
import { flavourClaims } from '../flavour.ts'
|
||||
@@ -318,7 +319,7 @@ function imageLink(definition: LinkDefinition): ImageLink {
|
||||
function mediaSingle({ alt, definition, link }: Image): AdfNode {
|
||||
const { title } = definition
|
||||
const caption: AdfNode[] = title === undefined || title === '' ? [] : [{ content: [{ text: title, type: 'text' }], type: 'caption' }]
|
||||
return centeredImage([externalMedia(alt, definition.destination, link), ...caption])
|
||||
return centeredImage([externalMedia(alt, definition.destination, link === undefined ? undefined : definitionTarget(link)), ...caption])
|
||||
}
|
||||
|
||||
// ADF holds no empty text node and a hard break takes no link, so the destination text carries the link ahead of the text's hard breaks; an empty destination leaves the breaks alone.
|
||||
|
||||
@@ -364,7 +364,7 @@ test('refuses a blockquote directive whose CommonMark spelling would pass V8\'s
|
||||
const fence = `\`\`\`\n${`${'a'.repeat(894_782)}\n`.repeat(300)}\`\`\`\n`
|
||||
assert.equal(
|
||||
content(losslessMarkdownToAdf(`!adf:blockquote\n${fence}\n${fence}!adf:/blockquote\n`)),
|
||||
'unsupported-node-shape: the markdown for this document, or for a directive\'s plain CommonMark, would be longer than 536870888 characters, the longest this library writes',
|
||||
'unsupported-node-shape: the markdown or HTML for this document, or a directive\'s plain CommonMark, would be longer than 536870888 characters, the longest this library writes',
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ import { parseInlineContent } from './inline-content.ts'
|
||||
import { readBlockDirectiveNode } from '../directive/node-reading.ts'
|
||||
import { spellStringAttribute, unsupportedNodeShape } from '../directive/syntax.ts'
|
||||
import { spellsEmpty } from '../directive/empty-keys.ts'
|
||||
import { withinEngineLimits } from '../length-bound.ts'
|
||||
import { withinEngineLimits } from '../../length-bound.ts'
|
||||
|
||||
// A flavour's own reading of a quote, and of a bullet list into one or more blocks; `path` is the container's, `index` the list's place among the container's blocks.
|
||||
export type FlavourBlockReaders = {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { AdfDocument, AdfNode } from '../../adf/document.ts'
|
||||
import { adfDocumentFault, heldTextLength, nodeAttrs, nodeContent, nodeMarks } from '../../adf/document.ts'
|
||||
import { blockNodeModel, isTaskItem } from '../../adf/block-nodes.ts'
|
||||
import { centeredImage, externalMedia } from '../external-image.ts'
|
||||
import { centeredImage, externalMedia } from '../../adf/external-image.ts'
|
||||
import { commonMarkSpelling, largestListMarker, writeMarkdown, type SpellingMemo } from '../emit/adf-to-markdown.ts'
|
||||
import { failure, faulted, success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
import { flavourClaims } from '../flavour.ts'
|
||||
@@ -9,8 +9,8 @@ import { inlineLeaves, isBlockNodeType, oneLine, portableLink, reduceInline, wri
|
||||
import { inlineNodeModel } from '../../adf/inline-nodes.ts'
|
||||
import { languageSlot } from '../code-language.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
import { linkDefinition } from '../mark-spellings.ts'
|
||||
import { longestMarkdown, tooLong, withinEngineLimits } from '../length-bound.ts'
|
||||
import { linkTarget } from '../../adf/mark-attributes.ts'
|
||||
import { longestOutput, tooLong, withinEngineLimits } from '../../length-bound.ts'
|
||||
import { portableWriting } from './block-spelling.ts'
|
||||
import { splitTaskList } from './task-list.ts'
|
||||
import { taskMarker } from './conventions.ts'
|
||||
@@ -63,7 +63,7 @@ export function reduceToPortable(document: AdfDocument): Result<AdfDocument> {
|
||||
if (fault !== undefined) return faulted(fault, [])
|
||||
if (document.version !== 1) return failure('unsupported-document-version', `no markdown spelling carries ADF version ${document.version}`, [])
|
||||
// Measured on the caller's text, edge whitespace and all: `toEditorNormal`'s merge could build past the bound.
|
||||
if (heldTextLength(nodeContent(document)) > longestMarkdown) return tooLong()
|
||||
if (heldTextLength(nodeContent(document)) > longestOutput) return tooLong()
|
||||
// Two documents the editor holds equal write the same portable markdown (docs/decisions.md §Equality is deep).
|
||||
const blocks = reduceBlocks(nodeContent(toEditorNormal(document)), { depth: 0, memo: new Map(), path: [] })
|
||||
if (!blocks.ok) {
|
||||
@@ -367,5 +367,5 @@ function reduceMedia(media: AdfNode, reduction: Reduction): Result<AdfNode[]> {
|
||||
const alt = typeof held === 'string' ? oneLine(held).trim() : ''
|
||||
const mark = nodeMarks(media).find(({ type }) => type === 'link')
|
||||
const link = mark === undefined ? undefined : portableLink(mark, 'paragraph')
|
||||
return success([centeredImage([externalMedia(alt, writableHref(url), link === undefined ? undefined : linkDefinition(nodeAttrs(link)))])])
|
||||
return success([centeredImage([externalMedia(alt, writableHref(url), link === undefined ? undefined : linkTarget(nodeAttrs(link)))])])
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@ import type { AdfAttributes, AdfMark, AdfNode } from '../../adf/document.ts'
|
||||
import type { LineContainer } from '../line-container.ts'
|
||||
import type { MarkRun } from '../emit/line-escaping.ts'
|
||||
import { blockNodeModel } from '../../adf/block-nodes.ts'
|
||||
import { cardUrl, shownText, visibleText } from '../../adf/shown-text.ts'
|
||||
import { codeTextMarkTypes } from '../../adf/inline-nodes.ts'
|
||||
import { failure, success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
import { imageAside } from '../external-image.ts'
|
||||
import { imageAside } from '../image-aside.ts'
|
||||
import { joinsWhenEditorNormal, sameMarkWhenEditorNormal } from './editor-normal.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
import { mergeAdjacentText, nodeAttrs, nodeContent, nodeMarks } from '../../adf/document.ts'
|
||||
@@ -47,50 +48,38 @@ function nodeLeaves(node: AdfNode, container: LineContainer, path: ConvertErrorP
|
||||
const attrs = nodeAttrs(node)
|
||||
if (node.type === 'text') return success(textLeaves(node.text, marks, container))
|
||||
if (node.type === 'hardBreak') return success([lineBreak(container)])
|
||||
if (node.type === 'date') return success(textLeaves(isoDate(attrs['timestamp']), marks, container))
|
||||
if (node.type === 'emoji') return success(textLeaves(nonEmpty(attrs['text']) ?? attrs['shortName'], marks, container))
|
||||
if (['date', 'emoji', 'mention', 'status'].includes(node.type)) return success(textLeaves(shownText(node), marks, container))
|
||||
if (node.type === 'placeholder') return success([])
|
||||
if (node.type === 'mention') return success(textLeaves(nonEmpty(attrs['text']) ?? idMention(attrs['id']), marks, container))
|
||||
if (node.type === 'status') return success(textLeaves(attrs['text'], marks, container))
|
||||
if (['extension', 'inlineExtension'].includes(node.type)) return success(textLeaves(nonEmpty(attrs['text']), marks, container, noteName(attrs['extensionKey']) ?? 'extension'))
|
||||
if (['extension', 'inlineExtension'].includes(node.type)) return success(textLeaves(shownText(node), marks, container, noteName(attrs['extensionKey']) ?? 'extension'))
|
||||
if (node.type === 'syncBlock') return success(noteLeaves('synced block'))
|
||||
if (['media', 'mediaInline'].includes(node.type)) return success(mediaLeaves(attrs, marks, container))
|
||||
if (['blockCard', 'embedCard', 'inlineCard'].includes(node.type)) return success(cardLeaves(attrs, marks, container))
|
||||
const own = textLeaves(node.text ?? (['expand', 'nestedExpand'].includes(node.type) ? attrs['title'] : undefined), marks, container)
|
||||
if (['blockCard', 'embedCard', 'inlineCard'].includes(node.type)) return success(cardLeaves(node, marks, container))
|
||||
const own = textLeaves(node.text ?? shownText(node), marks, container)
|
||||
const held = inlineLeaves(nodeContent(node), container, path, depth + 1)
|
||||
if (!held.ok) return held
|
||||
return success(own.length > 0 && held.value.length > 0 ? [...own, textLeaf(' ', []), ...held.value] : [...own, ...held.value])
|
||||
}
|
||||
|
||||
function cardLeaves(attrs: Readonly<AdfAttributes>, marks: readonly AdfMark[], container: LineContainer): AdfNode[] {
|
||||
const data = attrs['data']
|
||||
const held = typeof data === 'object' && data !== null && !Array.isArray(data) ? data : {}
|
||||
const url = nonEmpty(attrs['url'])
|
||||
const heldUrl = nonEmpty(held['url'])
|
||||
const name = nonEmpty(held['name'])
|
||||
const href = url ?? heldUrl
|
||||
if (href === undefined) return textLeaves(name, marks, container, 'link card')
|
||||
return linkedLeaves(url ?? name ?? href, href, marks, container)
|
||||
function cardLeaves(card: AdfNode, marks: readonly AdfMark[], container: LineContainer): AdfNode[] {
|
||||
const href = cardUrl(card)
|
||||
if (href === undefined) return textLeaves(shownText(card), marks, container, 'link card')
|
||||
return linkedLeaves(shownText(card) ?? href, href, marks, container)
|
||||
}
|
||||
|
||||
function linkedLeaves(text: string, href: string, marks: readonly AdfMark[], container: LineContainer): AdfNode[] {
|
||||
return textLeaves(text, [...marks.filter((mark) => mark.type !== 'link'), { attrs: { href }, type: 'link' }], container)
|
||||
}
|
||||
|
||||
function idMention(id: unknown): string | undefined {
|
||||
return typeof id === 'string' && id !== '' ? `@${id}` : undefined
|
||||
}
|
||||
|
||||
// An image standing inline is a link to it: the reader builds no node for an inline image, reading it as its alt text linked, and inside a link as the link's text, then (image).
|
||||
function mediaLeaves(attrs: Readonly<AdfAttributes>, marks: readonly AdfMark[], container: LineContainer): AdfNode[] {
|
||||
const alt = nonEmpty(attrs['alt'])
|
||||
const url = nonEmpty(attrs['url'])
|
||||
const alt = visibleText(attrs['alt'])
|
||||
const url = visibleText(attrs['url'])
|
||||
if (attrs['type'] !== 'external' || url === undefined) return textLeaves(alt, marks, container, 'image')
|
||||
const link = marks.find((mark) => mark.type === 'link')
|
||||
const href = link === undefined ? undefined : nodeAttrs(link)['href']
|
||||
if (typeof href !== 'string') return linkedLeaves(alt ?? url, url, marks, container)
|
||||
if (href === url) return textLeaves(alt ?? url, marks, container)
|
||||
return [...textLeaves(alt ?? nonEmpty(href) ?? url, marks, container), ...imageAside((text) => linkedLeaves(text, url, marks, container))]
|
||||
return [...textLeaves(alt ?? visibleText(href) ?? url, marks, container), ...imageAside((text) => linkedLeaves(text, url, marks, container))]
|
||||
}
|
||||
|
||||
function noteLeaves(name: string): AdfNode[] {
|
||||
@@ -98,25 +87,13 @@ function noteLeaves(name: string): AdfNode[] {
|
||||
}
|
||||
|
||||
function noteName(value: unknown): string | undefined {
|
||||
return nonEmpty(value) === undefined ? undefined : oneLine(String(value)).trim()
|
||||
return visibleText(value) === undefined ? undefined : oneLine(String(value)).trim()
|
||||
}
|
||||
|
||||
export function oneLine(text: string): string {
|
||||
return text.replace(/[\r\u0000]/g, '').replace(/\n/g, ' ')
|
||||
}
|
||||
|
||||
function nonEmpty(value: unknown): string | undefined {
|
||||
return typeof value === 'string' && oneLine(value).trim() !== '' ? value : undefined
|
||||
}
|
||||
|
||||
function isoDate(timestamp: unknown): string | undefined {
|
||||
const milliseconds = typeof timestamp === 'string' && /^-?\d+$/.test(timestamp) ? Number(timestamp) : Number.NaN
|
||||
const date = new Date(milliseconds)
|
||||
if (Number.isNaN(date.getTime())) return undefined
|
||||
const iso = date.toISOString()
|
||||
return iso.slice(0, iso.indexOf('T'))
|
||||
}
|
||||
|
||||
function lineBreak(container: LineContainer): AdfNode {
|
||||
return container === 'paragraph' ? { type: 'hardBreak' } : textLeaf(' ', [])
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { mintTaskIds } from './task-ids.ts'
|
||||
import { parseInlineContent } from '../parse/inline-content.ts'
|
||||
import { pathTo, splitTaskList } from './task-list.ts'
|
||||
import { positioned, success } from '../../result.ts'
|
||||
import { withinEngineLimits } from '../length-bound.ts'
|
||||
import { withinEngineLimits } from '../../length-bound.ts'
|
||||
|
||||
type Paragraph = Extract<Block, { kind: 'paragraph' }>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user