3
0
mirror of https://github.com/larvit/adf-codec.git synced 2026-11-18 22:25: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:
2026-10-23 12:50:48 +02:00
committed by Lillem4n
parent 33ef8db768
commit 6fe36d5947
33 changed files with 826 additions and 147 deletions
+17
View File
@@ -0,0 +1,17 @@
import type { AdfNode } from './document.ts'
import type { JsonSpelling } from '../canonical-json.ts'
import { canonicalJsonPieces } from '../canonical-json.ts'
import { failure, success, type ConvertErrorPath, type Result } from '../result.ts'
import { isJsonValue, nestingDepth } from '../json-value.ts'
import { joinedWithin } from '../length-bound.ts'
// `spelled` is the node as the carry holds it, `type` dropped where the format names it apart; `levels` the nesting its position leaves.
export 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
}
+29
View File
@@ -0,0 +1,29 @@
import type { AdfNode } from './document.ts'
import { linkTarget, linkTargetMark, type LinkTarget } from './mark-attributes.ts'
import { nodeAttrs, nodeContent, nodeMarks } from './document.ts'
import { serializeCanonicalJson } from '../canonical-json.ts'
// `alt` undefined where the media holds none: an empty alt builds no `alt`, so a media holding an empty one is no plain image.
export type ExternalImage = { alt: string | undefined; link: LinkTarget | undefined; url: string }
// The plain image, the one shape each format writes as its own image element: a centered `mediaSingle` holding one external `media`, which a link may mark.
export function centeredImage(content: AdfNode[]): AdfNode {
return { attrs: { layout: 'center' }, content, type: 'mediaSingle' }
}
export function externalMedia(alt: string, url: string, link?: LinkTarget): AdfNode {
const media: AdfNode = { attrs: alt === '' ? { type: 'external', url } : { alt, type: 'external', url }, type: 'media' }
return link === undefined ? media : { ...media, marks: [linkTargetMark(link)] }
}
// `undefined` unless the node is exactly the plain image its parts build.
export function plainImage(node: AdfNode): ExternalImage | 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 : linkTarget(nodeAttrs(mark))
const read = centeredImage([externalMedia(alt ?? '', url, link)])
return serializeCanonicalJson(node, 'compact') === serializeCanonicalJson(read, 'compact') ? { alt, link, url } : undefined
}
+15
View File
@@ -1,3 +1,4 @@
import type { AdfAttributes, AdfMark } from './document.ts'
import type { AttributeVocabulary } from './attribute-vocabulary.ts'
export const blockMarkAttributes = {
@@ -26,3 +27,17 @@ export type MarkType = keyof typeof markAttributes
export function isMarkType(type: string): type is MarkType {
return Object.hasOwn(markAttributes, type)
}
export type LinkTarget = { href: string; title?: string }
export function linkTargetMark({ href, title }: LinkTarget): AdfMark {
return { attrs: title === undefined ? { href } : { href, title }, type: 'link' }
}
// `undefined` where `href` is no string, or `title` is there and no string; any other key is the caller's to check.
export function linkTarget(attrs: AdfAttributes): LinkTarget | undefined {
const { href, title } = attrs
if (typeof href !== 'string') return undefined
if (title === undefined) return { href }
return typeof title === 'string' ? { href, title } : undefined
}
+60
View File
@@ -0,0 +1,60 @@
import type { AdfNode } from './document.ts'
import type { JsonValue } from '../json-value.ts'
import { nodeAttrs } from './document.ts'
// The text a node shows in place of itself, read from the attribute holding its content; `undefined` where it holds none.
export function shownText(node: AdfNode): string | undefined {
const attrs = nodeAttrs(node)
switch (node.type) {
case 'blockCard':
case 'embedCard':
case 'inlineCard':
return visibleText(attrs['url']) ?? visibleText(cardData(node)['name']) ?? cardUrl(node)
case 'date':
return isoDate(attrs['timestamp'])
case 'emoji':
return visibleText(attrs['text']) ?? stringValue(attrs['shortName'])
case 'expand':
case 'nestedExpand':
case 'status':
return stringValue(node.type === 'status' ? attrs['text'] : attrs['title'])
case 'extension':
case 'inlineExtension':
return visibleText(attrs['text'])
case 'media':
case 'mediaInline':
return visibleText(attrs['alt']) ?? (attrs['type'] === 'external' ? visibleText(attrs['url']) : undefined)
case 'mention': {
const id = attrs['id']
return visibleText(attrs['text']) ?? (typeof id === 'string' && id !== '' ? `@${id}` : undefined)
}
default:
return undefined
}
}
export function cardUrl(card: AdfNode): string | undefined {
return visibleText(nodeAttrs(card)['url']) ?? visibleText(cardData(card)['url'])
}
// `undefined` where the value is no string or holds only whitespace and null characters.
export function visibleText(value: unknown): string | undefined {
return typeof value === 'string' && /[^\s\0]/.test(value) ? value : undefined
}
function cardData(card: AdfNode): Readonly<Record<string, JsonValue>> {
const data = nodeAttrs(card)['data']
return typeof data === 'object' && data !== null && !Array.isArray(data) ? data : {}
}
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 stringValue(value: unknown): string | undefined {
return typeof value === 'string' ? value : undefined
}