mirror of
https://github.com/larvit/adf-codec.git
synced 2026-11-19 14:45:44 +01:00
Read Jira wiki markup into ADF with jiraWikiToAdf
This commit is contained in:
@@ -364,9 +364,11 @@ const riddenBlocks: [string, AdfNode][] = [
|
||||
['a blockquote holding no content', { type: 'blockquote' }],
|
||||
['a code block holding another attribute', { attrs: { language: 'java', title: 'a' }, content: [text('x')], type: 'codeBlock' }],
|
||||
['a code block of a marked text', { attrs: { language: 'java' }, content: [text('x', { type: 'strong' })], type: 'codeBlock' }],
|
||||
['a code block of an empty text', { attrs: { language: 'java' }, content: [text('')], type: 'codeBlock' }],
|
||||
['a code block of no content', { attrs: { language: 'java' }, type: 'codeBlock' }],
|
||||
['a code block of two texts', { attrs: { language: 'java' }, content: [text('x'), text('y', { type: 'strong' })], type: 'codeBlock' }],
|
||||
['a code block whose language is no string', { attrs: { language: 5 }, content: [text('x')], type: 'codeBlock' }],
|
||||
['a heading holding an empty content', { attrs: { level: 1 }, content: [], type: 'heading' }],
|
||||
['a list holding a list item and a paragraph', { content: [item(paragraph(text('a'))), paragraph(text('b'))], type: 'bulletList' }],
|
||||
['a list holding a paragraph', { content: [paragraph(text('a'))], type: 'bulletList' }],
|
||||
['a list item holding a localId', list('bulletList', { attrs: { localId: 'i1' }, content: [paragraph(text('a'))], type: 'listItem' })],
|
||||
@@ -381,7 +383,9 @@ const riddenBlocks: [string, AdfNode][] = [
|
||||
['a table row holding a cell and a paragraph', { attrs: plainTable, content: [{ content: [cell('tableCell', text('a')), paragraph(text('b'))], type: 'tableRow' }], type: 'table' }],
|
||||
['a table row holding a localId', { attrs: plainTable, content: [{ attrs: { localId: 'r1' }, content: [cell('tableCell', text('a'))], type: 'tableRow' }], type: 'table' }],
|
||||
['a table row holding a paragraph', { attrs: plainTable, content: [{ content: [paragraph(text('a'))], type: 'tableRow' }], type: 'table' }],
|
||||
['a table whose cell holds a paragraph of an empty content', table(plainTable, [{ content: [{ content: [], type: 'paragraph' }], type: 'tableCell' }])],
|
||||
['an image of a stored file with a URL', image({ type: 'file', url: 'https://example.com/a.png' })],
|
||||
['an image whose URL holds no ://', image({ type: 'external', url: 'a.png' })],
|
||||
['an image whose URL is no string', image({ type: 'external', url: 5 })],
|
||||
['an image whose alt ends in whitespace', image({ ...external, alt: 'A cat ' })],
|
||||
['an image whose alt is no string', image({ ...external, alt: 5 })],
|
||||
@@ -502,6 +506,10 @@ for (const [name, node] of riddenInlines) {
|
||||
})
|
||||
}
|
||||
|
||||
test('carries a text holding nothing', () => {
|
||||
assert.equal(wiki(paragraph(text('a'), text('', { type: 'strong' }))), `a${inline('{"marks":[{"type":"strong"}],"text":"","type":"text"}')}`)
|
||||
})
|
||||
|
||||
test('refuses a carry past 500 levels in a list by the path of the first', () => {
|
||||
let value: AdfAttributes[string] = 1
|
||||
for (let level = 0; level < largestNesting - 1; level += 1) value = [value]
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { AdfMark, AdfNode } from '../../adf/document.ts'
|
||||
import { escapedText } from './text-escaping.ts'
|
||||
import { holdsOnlyAttributes, identicalMark, identicalMarks, isSpellableText, nodeAttrs, nodeMarks } from '../../adf/document.ts'
|
||||
import { inlineCarry } from '../carry.ts'
|
||||
import { spellableColour, spellableTitle, spellableUrl } from '../spellings.ts'
|
||||
import { success, type ConvertErrorPath, type Result } from '../../result.ts'
|
||||
|
||||
// `carried`: whether any node of the line rides the carry.
|
||||
@@ -18,8 +19,6 @@ type SpelledMark = { delimiters: Delimiters; mark: AdfMark }
|
||||
type Token = { checked: boolean; kind: 'atom' | 'close' | 'open'; text: string }
|
||||
|
||||
const characterDelimiters: ReadonlyMap<string, string> = new Map([['em', '_'], ['strike', '-'], ['strong', '*'], ['underline', '+']])
|
||||
const spellableUrl = /^[^\s[\]{}|\\]+$/
|
||||
const spellableColour = /^#[0-9a-f]{6}$/i
|
||||
|
||||
// spec/wiki.md, Inline and Marks.
|
||||
export function inlineLine(nodes: readonly AdfNode[], path: ConvertErrorPath, inCell: boolean): Result<Line> {
|
||||
@@ -53,7 +52,7 @@ function atom(node: AdfNode, nodes: readonly AdfNode[], index: number, inCell: b
|
||||
const spelled = spelledMarks(marks)
|
||||
const previous = nodes[index - 1]
|
||||
const joinsPrevious = previous?.type === 'text' && identicalMarks(nodeMarks(previous), marks)
|
||||
if (!isSpellableText(node) || joinsPrevious || spelled === undefined) return { marks, spelled: undefined }
|
||||
if (!isSpellableText(node) || text === '' || joinsPrevious || spelled === undefined) return { marks, spelled: undefined }
|
||||
const href = hrefSpelling(node, nodes, index)
|
||||
if (href !== undefined) return { marks: marks.slice(0, -1), spelled: { marks: spelled.slice(0, -1), text: href } }
|
||||
const escaped = escapedText(text, index === 0, index === nodes.length - 1, inCell)
|
||||
@@ -108,7 +107,7 @@ function linkDelimiters(attrs: Readonly<Record<string, unknown>>): Delimiters |
|
||||
const { href, title, ...others } = attrs
|
||||
if (Object.keys(others).length > 0 || typeof href !== 'string' || !spellableUrl.test(href)) return undefined
|
||||
if (title === undefined) return { checked: false, close: `|${href}]`, open: '[' }
|
||||
return typeof title === 'string' && /^[^\s[\]{}|\\](?:[^[\]{}|\\\r\n]*[^\s[\]{}|\\])?$/.test(title) ? { checked: false, close: `|${href}|${title}]`, open: '[' } : undefined
|
||||
return typeof title === 'string' && spellableTitle.test(title) ? { checked: false, close: `|${href}|${title}]`, open: '[' } : undefined
|
||||
}
|
||||
|
||||
// Runs of nodes sharing at least their outermost mark, each spelled or carried as a whole.
|
||||
|
||||
@@ -16,7 +16,8 @@ const panelMacro = 2
|
||||
|
||||
const lists = ['bulletList', 'orderedList']
|
||||
const spellableAlt = /^[^\s!|,\\[\]{}](?:[^!|,\\[\]{}\r\n]*[^\s!|,\\[\]{}])?$/
|
||||
const spellableImageUrl = /^[^\s!|\\[\]{}]+$/
|
||||
// Jira reads an address holding no `://` as an attachment's name.
|
||||
const spellableImageUrl = /^[^\s!|\\[\]{}]*:\/\/[^\s!|\\[\]{}]*$/
|
||||
|
||||
// spec/wiki.md, Blocks: each block wiki markup spells, found after its children, since a block rides where one it holds does. A stack rather than recursion (docs/decisions.md §Nothing recurses unbounded).
|
||||
export function spelledBlocks(content: readonly AdfNode[]): Result<Map<AdfNode, Spelling>> {
|
||||
@@ -93,6 +94,7 @@ function leafSpelling(node: AdfNode, path: ConvertErrorPath, inCell: boolean): R
|
||||
function paragraphSpelling(node: AdfNode, path: ConvertErrorPath, inCell: boolean): Result<Spelling | undefined> {
|
||||
if (!holdsExactly(node, {})) return success(undefined)
|
||||
if (node.content === undefined) return success({ blank: true, macros: 0, text: ' ' })
|
||||
if (node.content.length === 0) return success(undefined)
|
||||
const line = inlineLine(node.content, path, inCell)
|
||||
if (!line.ok) return line
|
||||
return success({ blank: node.content.every((child) => child.type === 'text') && /^\s*$/u.test(node.content.map(({ text }) => text).join('')), macros: 0, text: line.value.line })
|
||||
@@ -117,7 +119,7 @@ function codeText(node: AdfNode): string | undefined {
|
||||
const [text, ...others] = nodeContent(node)
|
||||
const code = text?.text
|
||||
if (!holdsOnlyAttributes(node, ['language']) || typeof language !== 'string' || text === undefined || code === undefined || others.length > 0 || !isUnmarkedSpellableText(text)) return undefined
|
||||
if (code.includes('{code}') || code.includes('{noformat}')) return undefined
|
||||
if (code === '' || code.includes('{code}') || code.includes('{noformat}')) return undefined
|
||||
if (language === '') return `{noformat}\n${code}\n{noformat}`
|
||||
return codeLanguages.includes(language) ? `{code:${language}}\n${code}\n{code}` : undefined
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { AdfNode } from '../../adf/document.ts'
|
||||
import type { ConvertFault, Read } from '../../result.ts'
|
||||
import { carriedNesting, carriedNode, carriedValue } from '../../adf/carried-json.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
|
||||
// `inline`: the macro says `display=inline`.
|
||||
export type AdfMacro = { end: number; inline: boolean; node: AdfNode }
|
||||
|
||||
const closer = '{adf}'
|
||||
const holder = 'an {adf} macro'
|
||||
const opener = /\{adf(?::([^}\n]*))?\}/y
|
||||
|
||||
// spec/wiki.md, The carry: `undefined` where no `{adf}` macro opens at `at`. The macro closes before `end`.
|
||||
export function readAdfMacro(wiki: string, at: number, end: number): Read<AdfMacro> | undefined {
|
||||
opener.lastIndex = at
|
||||
const opened = opener.exec(wiki)
|
||||
if (opened === null) return undefined
|
||||
const start = opener.lastIndex
|
||||
const close = wiki.indexOf(closer, start)
|
||||
if (close === -1 || close + closer.length > end) return { fault: refusal('closes with {adf}: this one is left open') }
|
||||
const value = carriedValue(wiki.slice(start, close), holder, refusal("holds one ADF node's JSON: this is no JSON"))
|
||||
if (value.fault !== undefined) return value
|
||||
const bounded = carriedNesting(value.value, largestNesting)
|
||||
if (bounded.fault !== undefined) return bounded
|
||||
const node = carriedNode(bounded.value, holder)
|
||||
if (node.fault !== undefined) return node
|
||||
return { value: { end: close + closer.length, inline: opened[1] === 'display=inline', node: node.value } }
|
||||
}
|
||||
|
||||
function refusal(message: string): ConvertFault {
|
||||
return { code: 'unsupported-node-shape', message: `${holder} ${message}` }
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
// CSS Color Module Level 4, §6.1 Named Colors: each name's hex code.
|
||||
export const colourNames: Readonly<Record<string, string>> = {
|
||||
aliceblue: '#f0f8ff',
|
||||
antiquewhite: '#faebd7',
|
||||
aqua: '#00ffff',
|
||||
aquamarine: '#7fffd4',
|
||||
azure: '#f0ffff',
|
||||
beige: '#f5f5dc',
|
||||
bisque: '#ffe4c4',
|
||||
black: '#000000',
|
||||
blanchedalmond: '#ffebcd',
|
||||
blue: '#0000ff',
|
||||
blueviolet: '#8a2be2',
|
||||
brown: '#a52a2a',
|
||||
burlywood: '#deb887',
|
||||
cadetblue: '#5f9ea0',
|
||||
chartreuse: '#7fff00',
|
||||
chocolate: '#d2691e',
|
||||
coral: '#ff7f50',
|
||||
cornflowerblue: '#6495ed',
|
||||
cornsilk: '#fff8dc',
|
||||
crimson: '#dc143c',
|
||||
cyan: '#00ffff',
|
||||
darkblue: '#00008b',
|
||||
darkcyan: '#008b8b',
|
||||
darkgoldenrod: '#b8860b',
|
||||
darkgray: '#a9a9a9',
|
||||
darkgreen: '#006400',
|
||||
darkgrey: '#a9a9a9',
|
||||
darkkhaki: '#bdb76b',
|
||||
darkmagenta: '#8b008b',
|
||||
darkolivegreen: '#556b2f',
|
||||
darkorange: '#ff8c00',
|
||||
darkorchid: '#9932cc',
|
||||
darkred: '#8b0000',
|
||||
darksalmon: '#e9967a',
|
||||
darkseagreen: '#8fbc8f',
|
||||
darkslateblue: '#483d8b',
|
||||
darkslategray: '#2f4f4f',
|
||||
darkslategrey: '#2f4f4f',
|
||||
darkturquoise: '#00ced1',
|
||||
darkviolet: '#9400d3',
|
||||
deeppink: '#ff1493',
|
||||
deepskyblue: '#00bfff',
|
||||
dimgray: '#696969',
|
||||
dimgrey: '#696969',
|
||||
dodgerblue: '#1e90ff',
|
||||
firebrick: '#b22222',
|
||||
floralwhite: '#fffaf0',
|
||||
forestgreen: '#228b22',
|
||||
fuchsia: '#ff00ff',
|
||||
gainsboro: '#dcdcdc',
|
||||
ghostwhite: '#f8f8ff',
|
||||
gold: '#ffd700',
|
||||
goldenrod: '#daa520',
|
||||
gray: '#808080',
|
||||
green: '#008000',
|
||||
greenyellow: '#adff2f',
|
||||
grey: '#808080',
|
||||
honeydew: '#f0fff0',
|
||||
hotpink: '#ff69b4',
|
||||
indianred: '#cd5c5c',
|
||||
indigo: '#4b0082',
|
||||
ivory: '#fffff0',
|
||||
khaki: '#f0e68c',
|
||||
lavender: '#e6e6fa',
|
||||
lavenderblush: '#fff0f5',
|
||||
lawngreen: '#7cfc00',
|
||||
lemonchiffon: '#fffacd',
|
||||
lightblue: '#add8e6',
|
||||
lightcoral: '#f08080',
|
||||
lightcyan: '#e0ffff',
|
||||
lightgoldenrodyellow: '#fafad2',
|
||||
lightgray: '#d3d3d3',
|
||||
lightgreen: '#90ee90',
|
||||
lightgrey: '#d3d3d3',
|
||||
lightpink: '#ffb6c1',
|
||||
lightsalmon: '#ffa07a',
|
||||
lightseagreen: '#20b2aa',
|
||||
lightskyblue: '#87cefa',
|
||||
lightslategray: '#778899',
|
||||
lightslategrey: '#778899',
|
||||
lightsteelblue: '#b0c4de',
|
||||
lightyellow: '#ffffe0',
|
||||
lime: '#00ff00',
|
||||
limegreen: '#32cd32',
|
||||
linen: '#faf0e6',
|
||||
magenta: '#ff00ff',
|
||||
maroon: '#800000',
|
||||
mediumaquamarine: '#66cdaa',
|
||||
mediumblue: '#0000cd',
|
||||
mediumorchid: '#ba55d3',
|
||||
mediumpurple: '#9370db',
|
||||
mediumseagreen: '#3cb371',
|
||||
mediumslateblue: '#7b68ee',
|
||||
mediumspringgreen: '#00fa9a',
|
||||
mediumturquoise: '#48d1cc',
|
||||
mediumvioletred: '#c71585',
|
||||
midnightblue: '#191970',
|
||||
mintcream: '#f5fffa',
|
||||
mistyrose: '#ffe4e1',
|
||||
moccasin: '#ffe4b5',
|
||||
navajowhite: '#ffdead',
|
||||
navy: '#000080',
|
||||
oldlace: '#fdf5e6',
|
||||
olive: '#808000',
|
||||
olivedrab: '#6b8e23',
|
||||
orange: '#ffa500',
|
||||
orangered: '#ff4500',
|
||||
orchid: '#da70d6',
|
||||
palegoldenrod: '#eee8aa',
|
||||
palegreen: '#98fb98',
|
||||
paleturquoise: '#afeeee',
|
||||
palevioletred: '#db7093',
|
||||
papayawhip: '#ffefd5',
|
||||
peachpuff: '#ffdab9',
|
||||
peru: '#cd853f',
|
||||
pink: '#ffc0cb',
|
||||
plum: '#dda0dd',
|
||||
powderblue: '#b0e0e6',
|
||||
purple: '#800080',
|
||||
rebeccapurple: '#663399',
|
||||
red: '#ff0000',
|
||||
rosybrown: '#bc8f8f',
|
||||
royalblue: '#4169e1',
|
||||
saddlebrown: '#8b4513',
|
||||
salmon: '#fa8072',
|
||||
sandybrown: '#f4a460',
|
||||
seagreen: '#2e8b57',
|
||||
seashell: '#fff5ee',
|
||||
sienna: '#a0522d',
|
||||
silver: '#c0c0c0',
|
||||
skyblue: '#87ceeb',
|
||||
slateblue: '#6a5acd',
|
||||
slategray: '#708090',
|
||||
slategrey: '#708090',
|
||||
snow: '#fffafa',
|
||||
springgreen: '#00ff7f',
|
||||
steelblue: '#4682b4',
|
||||
tan: '#d2b48c',
|
||||
teal: '#008080',
|
||||
thistle: '#d8bfd8',
|
||||
tomato: '#ff6347',
|
||||
turquoise: '#40e0d0',
|
||||
violet: '#ee82ee',
|
||||
wheat: '#f5deb3',
|
||||
white: '#ffffff',
|
||||
whitesmoke: '#f5f5f5',
|
||||
yellow: '#ffff00',
|
||||
yellowgreen: '#9acd32',
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import type { AdfMark, AdfNode } from '../../adf/document.ts'
|
||||
import type { ConvertFault } from '../../result.ts'
|
||||
import { colourNames } from './colour-names.ts'
|
||||
import { identicalMarks } from '../../adf/document.ts'
|
||||
import { readAdfMacro } from './adf-macro.ts'
|
||||
import { smileyEmoji, smileys, spellableColour, spellableTitle, spellableUrl } from '../spellings.ts'
|
||||
|
||||
// `end`: where the reading stopped, a cell's closing `|` or the line's end.
|
||||
export type InlineRead = { end: number; fault?: undefined; nodes: AdfNode[] } | { fault: ConvertFault }
|
||||
|
||||
// A link whose text is being read: `close` is the `|` ending the text, `end` follows its `]`, and `floor` is its place in `opened`, below which no delimiter closes.
|
||||
type Link = { close: number; end: number; floor: number }
|
||||
|
||||
// An opening delimiter no closer has met: `at` is where its content starts, and `piece` holds its characters, which stay text unless it closes.
|
||||
type Opened = { at: number; key: string; mark: AdfMark; piece: Piece }
|
||||
|
||||
// `marks`: outermost first; `node`: a node no mark reaches and no text joins.
|
||||
type Piece = { marks: AdfMark[]; node: AdfNode | undefined; text: string }
|
||||
|
||||
type Role = 'close' | 'either' | 'open'
|
||||
|
||||
// `run`: the piece the next plain character joins.
|
||||
type Scan = { end: number; inCell: boolean; link: Link | undefined; opened: Opened[]; pieces: Piece[]; run: Piece | undefined; start: number; wiki: string }
|
||||
|
||||
const address = /https?:\/\/[^\s)'"<>!|[\]{}\\]*/y
|
||||
const anchorMacro = /\{anchor(?::[^}\n]*)?\}/y
|
||||
const characterMarks: ReadonlyMap<string, AdfMark> = new Map([
|
||||
['*', { type: 'strong' }],
|
||||
['+', { type: 'underline' }],
|
||||
['^', { attrs: { type: 'sup' }, type: 'subsup' }],
|
||||
['_', { type: 'em' }],
|
||||
['~', { attrs: { type: 'sub' }, type: 'subsup' }],
|
||||
])
|
||||
const colourMacro = /\{color(?::([^}\n]*))?\}/y
|
||||
const keepsBackslash = /[\p{L}\p{N}\s:;.,]/u
|
||||
const plain = /[^\n\\*_\-+^~{}?[|:;(h]+/y
|
||||
const space = /\s/u
|
||||
const strike: AdfMark = { type: 'strike' }
|
||||
const word = /[\p{L}\p{N}]/u
|
||||
|
||||
// spec/wiki.md, Inline and Marks: the nodes of `wiki` from `start` to `end`, or in a cell to the `|` closing it.
|
||||
export function readInline(wiki: string, start: number, end: number, inCell: boolean): InlineRead {
|
||||
const scan: Scan = { end, inCell, link: undefined, opened: [], pieces: [], run: undefined, start, wiki }
|
||||
let at = start
|
||||
while (at < end) {
|
||||
if (scan.link?.close === at) at = closeLink(scan, scan.link)
|
||||
else if (inCell && scan.link === undefined && wiki.charAt(at) === '|') break
|
||||
else {
|
||||
const next = readPiece(scan, at)
|
||||
if (typeof next !== 'number') return next
|
||||
at = next
|
||||
}
|
||||
}
|
||||
return { end: at, nodes: nodesOf(scan.pieces) }
|
||||
}
|
||||
|
||||
function readPiece(scan: Scan, at: number): number | { fault: ConvertFault } {
|
||||
const { end, wiki } = scan
|
||||
plain.lastIndex = at
|
||||
if (plain.test(wiki)) {
|
||||
const stop = Math.min(plain.lastIndex, end)
|
||||
literal(scan, wiki.slice(at, stop))
|
||||
return stop
|
||||
}
|
||||
const character = wiki.charAt(at)
|
||||
const mark = characterMarks.get(character)
|
||||
if (mark !== undefined) return delimiter(scan, at, character, character, mark, 'either')
|
||||
switch (character) {
|
||||
case '-':
|
||||
return dash(scan, at)
|
||||
case '?':
|
||||
return wiki.startsWith('??', at) ? delimiter(scan, at, '??', '??', { type: 'em' }, 'either') : plainCharacter(scan, at)
|
||||
case '[':
|
||||
return bracket(scan, at)
|
||||
case '\\':
|
||||
return escape(scan, at)
|
||||
case 'h':
|
||||
return bareAddress(scan, at)
|
||||
case '{':
|
||||
return brace(scan, at)
|
||||
case '}':
|
||||
return wiki.startsWith('}}', at) ? delimiter(scan, at, '}}', '{{', { type: 'code' }, 'close') : plainCharacter(scan, at)
|
||||
case '(':
|
||||
case ':':
|
||||
case ';':
|
||||
return smiley(scan, at)
|
||||
default:
|
||||
return plainCharacter(scan, at)
|
||||
}
|
||||
}
|
||||
|
||||
function plainCharacter(scan: Scan, at: number): number {
|
||||
literal(scan, scan.wiki.charAt(at))
|
||||
return at + 1
|
||||
}
|
||||
|
||||
function literal(scan: Scan, text: string): void {
|
||||
if (scan.run === undefined) scan.run = push(scan, { marks: [], node: undefined, text })
|
||||
else scan.run.text += text
|
||||
}
|
||||
|
||||
function push(scan: Scan, piece: Piece): Piece {
|
||||
scan.pieces.push(piece)
|
||||
scan.run = undefined
|
||||
return piece
|
||||
}
|
||||
|
||||
// spec/wiki.md, Marks: a delimiter opens or closes beside whitespace, punctuation or the line's edge, around a run that neither starts nor ends with whitespace.
|
||||
function delimiter(scan: Scan, at: number, spelled: string, key: string, mark: AdfMark, role: Role): number {
|
||||
const after = at + spelled.length
|
||||
const previous = pointBefore(scan, at)
|
||||
const next = pointAt(scan, after)
|
||||
const opener = openedIndex(scan, key)
|
||||
const opened = scan.opened[opener]
|
||||
if (role !== 'open' && opened !== undefined && opened.at < at && previous !== undefined && !space.test(previous) && (next === undefined || !word.test(next))) close(scan, opened, opener)
|
||||
else if (role !== 'close' && (previous === undefined || !word.test(previous)) && next !== undefined && !space.test(next)) open(scan, after, spelled, key, mark)
|
||||
else literal(scan, spelled)
|
||||
return after
|
||||
}
|
||||
|
||||
// The nearest opener of its kind closes; an older one of that kind stays text.
|
||||
function open(scan: Scan, at: number, spelled: string, key: string, mark: AdfMark): void {
|
||||
const older = openedIndex(scan, key)
|
||||
if (older !== -1) scan.opened.splice(older, 1)
|
||||
scan.opened.push({ at, key, mark, piece: push(scan, { marks: [], node: undefined, text: spelled }) })
|
||||
}
|
||||
|
||||
function close(scan: Scan, { mark, piece }: Opened, opener: number): void {
|
||||
piece.text = ''
|
||||
for (let index = scan.pieces.length - 1; scan.pieces[index] !== piece && index >= 0; index -= 1) {
|
||||
const marked = scan.pieces[index]
|
||||
if (marked !== undefined && marked.node === undefined) marked.marks.unshift(mark)
|
||||
}
|
||||
scan.opened.length = opener
|
||||
scan.run = undefined
|
||||
}
|
||||
|
||||
function openedIndex(scan: Scan, key: string): number {
|
||||
for (let index = scan.opened.length - 1; index > (scan.link?.floor ?? -1); index -= 1) if (scan.opened[index]?.key === key) return index
|
||||
return -1
|
||||
}
|
||||
|
||||
function closeLink(scan: Scan, link: Link): number {
|
||||
const opened = scan.opened[link.floor]
|
||||
scan.link = undefined
|
||||
if (opened !== undefined) close(scan, opened, link.floor)
|
||||
return link.end
|
||||
}
|
||||
|
||||
// spec/wiki.md, What only the reader reads: `--` and `---` between whitespace or the line's edges are dashes, and no run of hyphens strikes.
|
||||
function dash(scan: Scan, at: number): number {
|
||||
const { end, wiki } = scan
|
||||
let after = at + 1
|
||||
while (after < end && wiki.charAt(after) === '-') after += 1
|
||||
if (after === at + 1) return delimiter(scan, at, '-', '-', strike, 'either')
|
||||
const previous = pointBefore(scan, at)
|
||||
const next = pointAt(scan, after)
|
||||
const parted = (previous === undefined || space.test(previous)) && (next === undefined || space.test(next))
|
||||
literal(scan, parted && after - at <= 3 ? (after - at === 3 ? '—' : '–') : wiki.slice(at, after))
|
||||
return after
|
||||
}
|
||||
|
||||
// `\\` is a hardBreak, and any other backslash drops before what Jira lets it protect.
|
||||
function escape(scan: Scan, at: number): number {
|
||||
const next = pointAt(scan, at + 1)
|
||||
if (next === '\\') {
|
||||
push(scan, { marks: [], node: { type: 'hardBreak' }, text: '' })
|
||||
return at + 2
|
||||
}
|
||||
if (next === undefined || keepsBackslash.test(next) || (next === '|' && scan.inCell && scan.link === undefined)) return plainCharacter(scan, at)
|
||||
literal(scan, next)
|
||||
return at + 1 + next.length
|
||||
}
|
||||
|
||||
function smiley(scan: Scan, at: number): number {
|
||||
for (const spelled of smileys) {
|
||||
const emoji = smileyEmoji[spelled]
|
||||
const next = pointAt(scan, at + spelled.length)
|
||||
if (emoji === undefined || !scan.wiki.startsWith(spelled, at) || at + spelled.length > scan.end || (next !== undefined && word.test(next))) continue
|
||||
const { id, shortName } = emoji
|
||||
const text = /^[0-9a-f]+$/.test(id) ? String.fromCodePoint(Number.parseInt(id, 16)) : shortName
|
||||
push(scan, { marks: [], node: { attrs: { id, shortName, text }, type: 'emoji' }, text: '' })
|
||||
return at + spelled.length
|
||||
}
|
||||
return plainCharacter(scan, at)
|
||||
}
|
||||
|
||||
function brace(scan: Scan, at: number): number | { fault: ConvertFault } {
|
||||
const { end, wiki } = scan
|
||||
const macro = readAdfMacro(wiki, at, end)
|
||||
if (macro?.fault !== undefined) return { fault: macro.fault }
|
||||
if (macro !== undefined) {
|
||||
push(scan, { marks: [], node: macro.value.node, text: '' })
|
||||
return macro.value.end
|
||||
}
|
||||
if (wiki.startsWith('{{', at)) return delimiter(scan, at, '{{', '{{', { type: 'code' }, 'open')
|
||||
anchorMacro.lastIndex = at
|
||||
if (anchorMacro.test(wiki)) return anchorMacro.lastIndex
|
||||
colourMacro.lastIndex = at
|
||||
const colour = colourMacro.exec(wiki)
|
||||
return colour === null ? plainCharacter(scan, at) : colourDelimiter(scan, at, colour[0], colour[1])
|
||||
}
|
||||
|
||||
// `{color}` reads beside anything, a letter included.
|
||||
function colourDelimiter(scan: Scan, at: number, spelled: string, named: string | undefined): number {
|
||||
const after = at + spelled.length
|
||||
const opener = openedIndex(scan, 'color')
|
||||
const opened = scan.opened[opener]
|
||||
const name = named?.toLowerCase() ?? ''
|
||||
const color = named !== undefined && spellableColour.test(named) ? named : Object.hasOwn(colourNames, name) ? colourNames[name] : undefined
|
||||
if (named === undefined && opened !== undefined && opened.at < at) close(scan, opened, opener)
|
||||
else if (color !== undefined) open(scan, after, spelled, 'color', { attrs: { color }, type: 'textColor' })
|
||||
else return plainCharacter(scan, at)
|
||||
return after
|
||||
}
|
||||
|
||||
// A link's brackets close on its line, and hold no other `[`.
|
||||
function bracket(scan: Scan, at: number): number {
|
||||
const { end, wiki } = scan
|
||||
const bars: number[] = []
|
||||
let close = at + 1
|
||||
for (; close < end && wiki.charAt(close) !== ']'; close += 1) {
|
||||
const character = wiki.charAt(close)
|
||||
if (character === '[') return plainCharacter(scan, at)
|
||||
if (character === '\\') close += 1
|
||||
else if (character === '|') bars.push(close)
|
||||
}
|
||||
if (close >= end || scan.link !== undefined || bars.length > 2) return plainCharacter(scan, at)
|
||||
const [first, second] = bars
|
||||
if (first === undefined) return bracketed(scan, at, wiki.slice(at + 1, close))
|
||||
const href = wiki.slice(first + 1, second ?? close)
|
||||
const title = second === undefined ? undefined : wiki.slice(second + 1, close)
|
||||
if (!spellableUrl.test(href) || (title !== undefined && !spellableTitle.test(title))) return plainCharacter(scan, at)
|
||||
const mark: AdfMark = { attrs: title === undefined ? { href } : { href, title }, type: 'link' }
|
||||
if (first === at + 1) {
|
||||
push(scan, { marks: [mark], node: undefined, text: href })
|
||||
return close + 1
|
||||
}
|
||||
scan.opened.push({ at: at + 1, key: 'link', mark, piece: push(scan, { marks: [], node: undefined, text: '' }) })
|
||||
scan.link = { close: first, end: close + 1, floor: scan.opened.length - 1 }
|
||||
return at + 1
|
||||
}
|
||||
|
||||
// `[~accountid:<id>]` and `[<href>]`.
|
||||
function bracketed(scan: Scan, at: number, held: string): number {
|
||||
const id = held.startsWith('~accountid:') ? held.slice('~accountid:'.length) : undefined
|
||||
if (id !== undefined && spellableUrl.test(id)) push(scan, { marks: [], node: { attrs: { accessLevel: '', id }, type: 'mention' }, text: '' })
|
||||
else if (!held.startsWith('~') && spellableUrl.test(held)) push(scan, { marks: [{ attrs: { href: held }, type: 'link' }], node: undefined, text: held })
|
||||
else return plainCharacter(scan, at)
|
||||
return at + held.length + 2
|
||||
}
|
||||
|
||||
// spec/wiki.md, What only the reader reads: a bare address, less the punctuation ending it.
|
||||
function bareAddress(scan: Scan, at: number): number {
|
||||
address.lastIndex = at
|
||||
const href = scan.link === undefined ? address.exec(scan.wiki)?.[0].replace(/[.,;?]+$/, '') : undefined
|
||||
if (href === undefined || href.endsWith('://')) return plainCharacter(scan, at)
|
||||
push(scan, { marks: [{ attrs: { href }, type: 'link' }], node: undefined, text: href })
|
||||
return at + href.length
|
||||
}
|
||||
|
||||
function nodesOf(pieces: readonly Piece[]): AdfNode[] {
|
||||
const nodes: AdfNode[] = []
|
||||
let previous: { marks: readonly AdfMark[]; node: AdfNode } | undefined
|
||||
for (const { marks, node, text } of pieces) {
|
||||
if (node !== undefined) {
|
||||
nodes.push(node)
|
||||
previous = undefined
|
||||
} else if (text !== '') {
|
||||
if (previous !== undefined && identicalMarks(previous.marks, marks)) previous.node.text = `${previous.node.text ?? ''}${text}`
|
||||
else {
|
||||
previous = { marks, node: marks.length === 0 ? { text, type: 'text' } : { marks: marks.map(copied), text, type: 'text' } }
|
||||
nodes.push(previous.node)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
function copied({ attrs, type }: AdfMark): AdfMark {
|
||||
return attrs === undefined ? { type } : { attrs: { ...attrs }, type }
|
||||
}
|
||||
|
||||
// Whole code points, so a letter outside the Basic Multilingual Plane reads as a letter.
|
||||
function pointAt({ end, wiki }: Scan, index: number): string | undefined {
|
||||
const point = index < end ? wiki.codePointAt(index) : undefined
|
||||
return point === undefined ? undefined : String.fromCodePoint(point)
|
||||
}
|
||||
|
||||
function pointBefore({ start, wiki }: Scan, index: number): string | undefined {
|
||||
if (index <= start) return undefined
|
||||
const pair = index - 2 >= start ? wiki.slice(index - 2, index) : ''
|
||||
return /^[\ud800-\udbff][\udc00-\udfff]$/.test(pair) ? pair : wiki.charAt(index - 1)
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import type { AdfAttributes, AdfMark, AdfNode } from '../../adf/document.ts'
|
||||
import { adfToLosslessJiraWiki, jiraWikiToAdf } from '../../index.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
|
||||
type Case = { name: string; reads: AdfNode[]; wiki: string }
|
||||
|
||||
function read(wiki: string): AdfNode[] | string {
|
||||
const result = jiraWikiToAdf(wiki)
|
||||
if (!result.ok) return `${result.error.code} at line ${result.error.position.line}, offset ${result.error.position.offset}`
|
||||
return result.value.content ?? 'a document holding no content key'
|
||||
}
|
||||
|
||||
function node(type: string, attrs: AdfAttributes | undefined, ...content: AdfNode[]): AdfNode {
|
||||
return { ...(attrs === undefined ? {} : { attrs }), ...(content.length === 0 ? {} : { content }), type }
|
||||
}
|
||||
|
||||
function paragraph(...content: AdfNode[]): AdfNode {
|
||||
return node('paragraph', undefined, ...content)
|
||||
}
|
||||
|
||||
function text(value: string, ...marks: AdfMark[]): AdfNode {
|
||||
return marks.length === 0 ? { text: value, type: 'text' } : { marks, text: value, type: 'text' }
|
||||
}
|
||||
|
||||
function line(...content: AdfNode[]): AdfNode[] {
|
||||
return [paragraph(...content)]
|
||||
}
|
||||
|
||||
function item(...content: AdfNode[]): AdfNode {
|
||||
return node('listItem', undefined, ...content)
|
||||
}
|
||||
|
||||
function bullets(...items: AdfNode[]): AdfNode {
|
||||
return node('bulletList', undefined, ...items)
|
||||
}
|
||||
|
||||
function ordered(...items: AdfNode[]): AdfNode {
|
||||
return node('orderedList', { order: 1 }, ...items)
|
||||
}
|
||||
|
||||
function table(...rows: AdfNode[][]): AdfNode {
|
||||
return node('table', { isNumberColumnEnabled: false, layout: 'default' }, ...rows.map((cells) => node('tableRow', undefined, ...cells)))
|
||||
}
|
||||
|
||||
function cell(...content: AdfNode[]): AdfNode {
|
||||
return node('tableCell', undefined, paragraph(...content))
|
||||
}
|
||||
|
||||
function header(...content: AdfNode[]): AdfNode {
|
||||
return node('tableHeader', undefined, paragraph(...content))
|
||||
}
|
||||
|
||||
function code(language: string, value?: string): AdfNode {
|
||||
return node('codeBlock', { language }, ...(value === undefined ? [] : [text(value)]))
|
||||
}
|
||||
|
||||
function image(url: string, alt?: string): AdfNode {
|
||||
return node('mediaSingle', { layout: 'center' }, node('media', { ...(alt === undefined ? {} : { alt }), type: 'external', url }))
|
||||
}
|
||||
|
||||
function emoji(shortName: string, id: string, shown: string): AdfNode {
|
||||
return node('emoji', { id, shortName, text: shown })
|
||||
}
|
||||
|
||||
function link(href: string, title?: string): AdfMark {
|
||||
return { attrs: title === undefined ? { href } : { href, title }, type: 'link' }
|
||||
}
|
||||
|
||||
function colour(color: string): AdfMark {
|
||||
return { attrs: { color }, type: 'textColor' }
|
||||
}
|
||||
|
||||
const breakNode: AdfNode = { type: 'hardBreak' }
|
||||
const em: AdfMark = { type: 'em' }
|
||||
const strike: AdfMark = { type: 'strike' }
|
||||
const strong: AdfMark = { type: 'strong' }
|
||||
const underline: AdfMark = { type: 'underline' }
|
||||
const codeMark: AdfMark = { type: 'code' }
|
||||
const sub: AdfMark = { attrs: { type: 'sub' }, type: 'subsup' }
|
||||
const sup: AdfMark = { attrs: { type: 'sup' }, type: 'subsup' }
|
||||
const rule: AdfNode = { type: 'rule' }
|
||||
const status: AdfNode = { attrs: { color: 'red', text: 'x' }, type: 'status' }
|
||||
const statusMacro = '{adf:display=inline}{"attrs":{"color":"red","text":"x"},"type":"status"}{adf}'
|
||||
const smile = emoji(':slight_smile:', '1f642', '🙂')
|
||||
|
||||
const blocks: Case[] = [
|
||||
{ name: 'the empty string as a document of no blocks', reads: [], wiki: '' },
|
||||
{ name: 'blank lines alone as a document of no blocks', reads: [], wiki: '\n \n\n' },
|
||||
{ name: 'a line as a paragraph', reads: line(text('a b')), wiki: 'a b' },
|
||||
{ name: 'a line feed in a paragraph as a hardBreak', reads: line(text('a'), breakNode, text('b')), wiki: 'a\nb' },
|
||||
{ name: 'blank lines as parting paragraphs, however many', reads: [paragraph(text('a')), paragraph(text('b'))], wiki: 'a\n\n\n\nb' },
|
||||
{ name: 'whitespace at a line\'s edges as nothing, a carriage return included', reads: line(text('a'), breakNode, text('b')), wiki: ' a \r\n\tb ' },
|
||||
{ name: 'h1. to h6. as a heading of that level', reads: [node('heading', { level: 1 }, text('a')), node('heading', { level: 6 }, text('b'))], wiki: 'h1. a\n\nh6. b' },
|
||||
{ name: 'a heading as one line, the next line a paragraph', reads: [node('heading', { level: 2 }, text('a')), paragraph(text('b'))], wiki: 'h2. a\nb' },
|
||||
{ name: 'a heading holding no text as a heading holding no content', reads: [node('heading', { level: 3 })], wiki: 'h3. ' },
|
||||
{ name: 'h7. and H1. as text', reads: [paragraph(text('h7. a')), paragraph(text('H1. a'))], wiki: 'h7. a\n\nH1. a' },
|
||||
{ name: 'bq. as a blockquote of one paragraph, the next line a paragraph', reads: [node('blockquote', undefined, paragraph(text('a'))), paragraph(text('b'))], wiki: 'bq. a\nb' },
|
||||
{ name: '{quote} as a blockquote of its blocks', reads: [node('blockquote', undefined, paragraph(text('a')), paragraph(text('b')))], wiki: '{quote}\na\n\nb\n{quote}' },
|
||||
{ name: 'a {quote} holding nothing as a blockquote of an empty paragraph', reads: [node('blockquote', undefined, paragraph())], wiki: '{quote}\n{quote}' },
|
||||
{ name: 'a {quote} left open as closing at the end', reads: [node('blockquote', undefined, paragraph(text('a')))], wiki: '{quote}\na' },
|
||||
{ name: 'a {quote} inside a line as text', reads: [node('blockquote', undefined, paragraph(text('a{quote} b')))], wiki: '{quote}a{quote} b' },
|
||||
{ name: 'a bq. inside a {quote}', reads: [node('blockquote', undefined, node('blockquote', undefined, paragraph(text('a'))))], wiki: '{quote}\nbq. a\n{quote}' },
|
||||
{ name: '---- as a rule, longer runs too', reads: [rule, rule], wiki: '----\n\n------' },
|
||||
{ name: 'a rule between lines as parting two paragraphs', reads: [paragraph(text('a')), rule, paragraph(text('b'))], wiki: 'a\n----\nb' },
|
||||
{ name: '* and # items as lists', reads: [bullets(item(paragraph(text('a'))), item(paragraph(text('b')))), ordered(item(paragraph(text('c'))))], wiki: '* a\n* b\n\n# c' },
|
||||
{ name: '- items as a bulletList', reads: [bullets(item(paragraph(text('a'))), item(paragraph(text('b'))))], wiki: '- a\n- b' },
|
||||
{ name: 'one more marker per level, nested lists mixed', reads: [bullets(item(paragraph(text('a')), ordered(item(paragraph(text('b')))), bullets(item(paragraph(text('c'))))), item(paragraph(text('d'))))], wiki: '* a\n*# b\n** c\n* d' },
|
||||
{ name: 'a list of the other kind with no blank line as a second list', reads: [ordered(item(paragraph(text('a')))), bullets(item(paragraph(text('b'))))], wiki: '# a\n* b' },
|
||||
{ name: 'a line after an item as a hardBreak in the item\'s paragraph', reads: [bullets(item(paragraph(text('a'), breakNode, text('b'))))], wiki: '* a\nb' },
|
||||
{ name: 'a marker two levels deeper as an item holding an empty paragraph between', reads: [bullets(item(paragraph(text('a')), bullets(item(paragraph(), bullets(item(paragraph(text('b'))))))))], wiki: '* a\n*** b' },
|
||||
{ name: 'a marker with no space or no text as text', reads: [paragraph(text('*a')), paragraph(text('*'))], wiki: '*a\n\n* ' },
|
||||
{ name: 'a list after a paragraph line', reads: [paragraph(text('a')), bullets(item(paragraph(text('b'))))], wiki: 'a\n* b' },
|
||||
{ name: 'a blank line as parting two lists of one kind', reads: [bullets(item(paragraph(text('a')))), bullets(item(paragraph(text('b'))))], wiki: '* a\n\n* b' },
|
||||
{ name: '{noformat} as a codeBlock of language ""', reads: [code('', 'a\n\n b')], wiki: '{noformat}\na\n\n b\n{noformat}' },
|
||||
{ name: '{code:<language>} in lowercase, {code} as java', reads: [code('python', 'x'), code('java', 'y')], wiki: '{code:Python}\nx\n{code}\n\n{code}\ny\n{code}' },
|
||||
{ name: 'a {code} dropping its title and borderStyle', reads: [code('sql', 'x'), code('java', 'y')], wiki: '{code:sql|title=T|borderStyle=solid}\nx\n{code}\n\n{code:title=T}\ny\n{code}' },
|
||||
{ name: 'a code text whole, markup, carriage returns and edge blanks included', reads: [code('', ' *a* \r\n{quote}\n')], wiki: '{noformat}\n *a* \r\n{quote}\n\n{noformat}' },
|
||||
{ name: 'a {code} holding nothing as a codeBlock holding no content', reads: [code('java')], wiki: '{code}\n{code}' },
|
||||
{ name: 'a {code} left open as closing at the end', reads: [code('java', 'a')], wiki: '{code}\na' },
|
||||
{ name: 'an image alone on its line as a mediaSingle', reads: [image('http://a.b/c.png')], wiki: '!http://a.b/c.png!' },
|
||||
{ name: 'an image\'s alt, dropping thumbnail, align and the other parameters', reads: [image('http://a.b/c.png', 'hi there'), image('http://a.b/c.png')], wiki: '!http://a.b/c.png|alt=hi there, width=30!\n\n!http://a.b/c.png|thumbnail!' },
|
||||
{ name: 'an image between lines as parting two paragraphs', reads: [paragraph(text('a')), image('ftp://a.b/c.png'), paragraph(text('b'))], wiki: 'a\n!ftp://a.b/c.png!\nb' },
|
||||
{ name: '!name.ext! as its text', reads: line(text('!name.ext!')), wiki: '!name.ext!' },
|
||||
{ name: 'a panel by its bgColor, compared without case', reads: [node('panel', { panelType: 'error' }, paragraph(text('a'))), node('panel', { panelType: 'note' }, paragraph(text('b')))], wiki: '{panel:bgColor=#FFEBE6}\na\n{panel}\n\n{panel:bgColor=#eae6ff}\nb\n{panel}' },
|
||||
{ name: '{panel} and any other bgColor as info', reads: [node('panel', { panelType: 'info' }, paragraph(text('a'))), node('panel', { panelType: 'info' }, paragraph(text('b')))], wiki: '{panel}\na\n{panel}\n\n{panel:bgColor=red|borderStyle=dashed}\nb\n{panel}' },
|
||||
{ name: 'a panel\'s title as its first paragraph in strong', reads: [node('panel', { panelType: 'success' }, paragraph(text('T *t*', strong)), paragraph(text('a')))], wiki: '{panel:title=T *t*|bgColor=#e3fcef}\na\n{panel}' },
|
||||
{ name: 'a panel holding a list and a quote', reads: [node('panel', { panelType: 'info' }, bullets(item(paragraph(text('a')))), node('blockquote', undefined, paragraph(text('b'))))], wiki: '{panel}\n* a\n{quote}\nb\n{quote}\n{panel}' },
|
||||
{ name: 'a {panel} holding parameters inside a panel as text', reads: [node('panel', { panelType: 'info' }, paragraph(text('{panel:title=x}'), breakNode, text('a')))], wiki: '{panel}\n{panel:title=x}\na\n{panel}' },
|
||||
{ name: 'a table row per line, || a tableHeader and | a tableCell', reads: [table([header(text('h')), header(text('i'))], [cell(text('a')), cell(text('b'))])], wiki: '||h||i||\n|a|b|' },
|
||||
{ name: 'a space-only cell as an empty paragraph, and a cell\'s edge blanks as nothing', reads: [table([cell(text('a')), cell()])], wiki: '| a | |' },
|
||||
{ name: 'a row its last delimiter leaves open', reads: [table([cell(text('a')), cell(text('b'))])], wiki: '|a|b' },
|
||||
{ name: 'a header after a cell in one row', reads: [table([cell(text('a')), header(text('b'))])], wiki: '|a||b|' },
|
||||
{ name: 'a line after a table as a paragraph', reads: [table([cell(text('a'))]), paragraph(text('b|c|'))], wiki: '|a|\nb|c|' },
|
||||
{ name: 'an escaped | as ending its cell, the backslash kept', reads: [table([cell(text('a\\')), cell(text('b'))])], wiki: '|a\\|b|' },
|
||||
{ name: 'a link, a mark and a carry inside a cell', reads: [table([cell(text('a', strong)), cell(text('x', link('http://y.z'))), cell(status)])], wiki: `|*a*|[x|http://y.z]|${statusMacro}|` },
|
||||
{ name: '{adf:display=block} as its node', reads: [rule, node('expand', { title: 'a|b' }, paragraph(text('{')))], wiki: '{adf:display=block}\n{"type":"rule"}\n{adf}\n\n{adf:display=block}\n{"attrs":{"title":"a|b"},"content":[{"content":[{"text":"\\u007b","type":"text"}],"type":"paragraph"}],"type":"expand"}\n{adf}' },
|
||||
{ name: 'an {adf} macro in any JSON spelling, with no display or no line feeds', reads: [rule, rule], wiki: '{adf}{ "type" : "rule" }{adf}\n{adf:display=block}{"type":"rule"}{adf}' },
|
||||
{ name: 'a block carry\'s JSON holding line feeds', reads: [rule, paragraph(text('a'))], wiki: '{adf:display=block}\n{\n"type":\n"rule"}\n{adf} a' },
|
||||
{ name: 'a block of a type this version doesn\'t know', reads: [node('futureBlock', { a: 1 })], wiki: '{adf:display=block}\n{"attrs":{"a":1},"type":"futureBlock"}\n{adf}' },
|
||||
]
|
||||
|
||||
const inline: Case[] = [
|
||||
{ name: '\\\\ as a hardBreak', reads: line(text('a'), breakNode, text('b'), breakNode, breakNode), wiki: 'a\\\\b\\\\\\\\' },
|
||||
{ name: '\\X as X, markup or not', reads: line(text('*a* [a] {a} a|b - (y) :) !a! #')), wiki: '\\*a\\* \\[a\\] \\{a\\} a\\|b \\- \\(y) :\\) \\!a! \\#' },
|
||||
{ name: 'a backslash before :, ;, ., a comma, a letter or a digit as itself', reads: line(text('\\a \\1 \\: \\; \\. \\, \\')), wiki: '\\a \\1 \\: \\; \\. \\, \\' },
|
||||
{ name: '\\\\ as a hardBreak before \\X reads X', reads: line(breakNode, text('*')), wiki: '\\\\\\*' },
|
||||
{ name: 'each character mark', reads: line(text('a', strong), text(' '), text('b', em), text(' '), text('c', strike), text(' '), text('d', underline), text(' '), text('e', codeMark)), wiki: '*a* _b_ -c- +d+ {{e}}' },
|
||||
{ name: '??x?? as em, ^x^ as sup and ~x~ as sub', reads: line(text('a b', em), text(' '), text('c', sup), text(' '), text('d', sub)), wiki: '??a b?? ^c^ ~d~' },
|
||||
{ name: 'marks nested outermost first', reads: line(text('a ', strong), text('b', strong, em), text(' c', strong)), wiki: '*a _b_ c*' },
|
||||
{ name: 'a mark outside a code mark, and inside one', reads: line(text('a', strong, codeMark), text(' '), text('b', codeMark, strong)), wiki: '*{{a}}* {{*b*}}' },
|
||||
{ name: 'a delimiter beside a letter or digit outside, or whitespace inside, as text', reads: line(text('a*b*c x^2^ * a * *a *b')), wiki: 'a*b*c x^2^ * a * *a *b' },
|
||||
{ name: 'a delimiter beside punctuation as a mark', reads: line(text('('), text('a', strong), text('). '), text('b', em), text(',')), wiki: '(*a*). _b_,' },
|
||||
{ name: 'a mark inside a word\'s own delimiter characters', reads: line(text('a_b', em), text(' '), text('a-b', strike), text(' '), text('a*b', strong)), wiki: '_a_b_ -a-b- *a*b*' },
|
||||
{ name: 'the nearest opener of a type as the one a closer takes', reads: line(text('*a '), text('b', strong), text(' c* *'), text('d', strong), text('*')), wiki: '*a *b* c* **d**' },
|
||||
{ name: 'a mark as ending with its line', reads: line(text('*a'), breakNode, text('b*')), wiki: '*a\nb*' },
|
||||
{ name: 'a mark crossing another as the first to close, the other text', reads: line(text('a _b', strong), text(' c_')), wiki: '*a _b* c_' },
|
||||
{ name: 'a mark around a hardBreak as marking the text alone', reads: line(text('a', strong), breakNode, text('b', strong)), wiki: '*a\\\\b*' },
|
||||
{ name: '{color} by hex code, as written', reads: line(text('a', colour('#FF0000')), text('b')), wiki: '{color:#FF0000}a{color}b' },
|
||||
{ name: '{color} by CSS name as its hex code, compared without case', reads: line(text('a', colour('#ff0000')), text(' '), text('b', colour('#00008b'))), wiki: '{color:red}a{color} {color:DarkBlue}b{color}' },
|
||||
{ name: 'a {color} of no CSS name, and one left open, as text', reads: line(text('{color:nonsense}a{color} {color:red}b')), wiki: '{color:nonsense}a{color} {color:red}b' },
|
||||
{ name: 'a colour inside a mark and around one', reads: line(text('a', strong, colour('#0000ff')), text(' '), text('b', colour('#ff0000'), strong), text(' c', colour('#ff0000'))), wiki: '*{color:blue}a{color}* {color:red}*b* c{color}' },
|
||||
{ name: '[text|href] and [text|href|title] as a link', reads: line(text('a b', link('http://x.y')), text(' '), text('c', link('#d', 'T t'))), wiki: '[a b|http://x.y] [c|#d|T t]' },
|
||||
{ name: '[href] as a link whose text is its href', reads: line(text('http://x.y', link('http://x.y')), text(' '), text('#anchor', link('#anchor')), text(' '), text('^name.ext', link('^name.ext'))), wiki: '[http://x.y] [#anchor] [^name.ext]' },
|
||||
{ name: 'a link holding no text as its href', reads: line(text('http://x.y', link('http://x.y'))), wiki: '[|http://x.y]' },
|
||||
{ name: 'a mark inside a link and around one', reads: line(text('a', link('http://x.y'), strong), text(' '), text('b', strong, link('http://x.y'))), wiki: '[*a*|http://x.y] *[b|http://x.y]*' },
|
||||
{ name: 'an escaped bracket and | in a link\'s text', reads: line(text('a]|b', link('http://x.y'))), wiki: '[a\\]\\|b|http://x.y]' },
|
||||
{ name: 'brackets holding no link as text', reads: line(text('[] [a b] [a|b c] [a|b|c|d] [a')), wiki: '[] [a b] [a|b c] [a|b|c|d] [a' },
|
||||
{ name: 'a link as ending with its line', reads: line(text('[a'), breakNode, text('b|'), text('http://x.y', link('http://x.y')), text(']')), wiki: '[a\nb|http://x.y]' },
|
||||
{ name: '[~accountid:<id>] as a mention', reads: line(node('mention', { accessLevel: '', id: 'abc:1-2' })), wiki: '[~accountid:abc:1-2]' },
|
||||
{ name: '[~name] and an accountid holding nothing as text', reads: line(text('[~name] [~accountid:]')), wiki: '[~name] [~accountid:]' },
|
||||
{ name: 'a bare address as a link, up to whitespace', reads: line(text('See '), text('http://a.b/c?d=1,2', link('http://a.b/c?d=1,2')), text(' and '), text('https://e.f', link('https://e.f'))), wiki: 'See http://a.b/c?d=1,2 and https://e.f' },
|
||||
{ name: 'a bare address less the punctuation ending it', reads: line(text('('), text('http://a.b/c', link('http://a.b/c')), text('). '), text('http://a.b/c:', link('http://a.b/c:')), text(' '), text('http://a.b', link('http://a.b')), text('!?')), wiki: '(http://a.b/c). http://a.b/c: http://a.b!?' },
|
||||
{ name: 'an address of another scheme or case, and a scheme alone, as text', reads: line(text('ftp://a.b HTTP://a.b http://')), wiki: 'ftp://a.b HTTP://a.b http://' },
|
||||
{ name: 'an image inside a line as text, its address a link', reads: line(text('a !'), text('http://a.b/c.png', link('http://a.b/c.png')), text('! b')), wiki: 'a !http://a.b/c.png! b' },
|
||||
{ name: '{adf:display=inline} as its node', reads: line(text('a '), status, text(' b')), wiki: `a ${statusMacro} b` },
|
||||
{ name: 'a carried text as a node of its own beside text of its marks', reads: line(text('a'), text('b'), text('c')), wiki: 'a{adf:display=inline}{"text":"b","type":"text"}{adf}c' },
|
||||
{ name: '{anchor} as nothing', reads: [paragraph(text('a b'))], wiki: '{anchor:top}a {anchor}b\n\n{anchor:x}' },
|
||||
{ name: 'a macro this version doesn\'t know as text', reads: line(text('{foo} {foo:a=b}x{foo}')), wiki: '{foo} {foo:a=b}x{foo}' },
|
||||
{ name: '-- and --- between blanks or line edges as dashes', reads: line(text('– a – b a--b a — b a---b ---- —')), wiki: '-- a -- b a--b a --- b a---b ---- ---' },
|
||||
{ name: 'a smiley as its emoji wherever no letter or digit follows', reads: line(text('x'), smile, text(' f'), emoji(':cross_mark:', 'atlassian-cross_mark', ':cross_mark:'), text(' a:Pb :)x '), emoji(':smiley:', '1f603', '😃'), text('.')), wiki: 'x:) f(x) a:Pb :)x :D.' },
|
||||
{ name: 'each star and flag smiley', reads: line(emoji(':yellow_star:', 'atlassian-yellow_star', ':yellow_star:'), emoji(':yellow_star:', 'atlassian-yellow_star', ':yellow_star:'), emoji(':red_star:', 'atlassian-red_star', ':red_star:'), emoji(':flag_off:', 'atlassian-flag_off', ':flag_off:'), emoji(':flag_on:', 'atlassian-flag_on', ':flag_on:')), wiki: '(*)(*y)(*r)(flagoff)(flag)' },
|
||||
{ name: 'a smiley inside a mark, unmarked', reads: line(text('a', strong), smile), wiki: '*a:)*' },
|
||||
]
|
||||
|
||||
for (const { name, reads, wiki } of [...blocks, ...inline]) {
|
||||
test(`reads ${name}`, () => {
|
||||
assert.deepEqual(read(wiki), reads)
|
||||
})
|
||||
}
|
||||
|
||||
const smileys: [string, string, string, string][] = [
|
||||
[':)', ':slight_smile:', '1f642', '🙂'],
|
||||
[':(', ':disappointed:', '1f61e', '😞'],
|
||||
[':P', ':stuck_out_tongue:', '1f61b', '😛'],
|
||||
[':D', ':smiley:', '1f603', '😃'],
|
||||
[';)', ':wink:', '1f609', '😉'],
|
||||
['(y)', ':thumbsup:', '1f44d', '👍'],
|
||||
['(n)', ':thumbsdown:', '1f44e', '👎'],
|
||||
['(i)', ':info:', 'atlassian-info', ':info:'],
|
||||
['(/)', ':check_mark:', 'atlassian-check_mark', ':check_mark:'],
|
||||
['(x)', ':cross_mark:', 'atlassian-cross_mark', ':cross_mark:'],
|
||||
['(!)', ':warning:', 'atlassian-warning', ':warning:'],
|
||||
['(+)', ':plus:', 'atlassian-plus', ':plus:'],
|
||||
['(-)', ':minus:', 'atlassian-minus', ':minus:'],
|
||||
['(?)', ':question:', 'atlassian-question_mark', ':question:'],
|
||||
['(on)', ':light_bulb_on:', 'atlassian-light_bulb_on', ':light_bulb_on:'],
|
||||
['(off)', ':light_bulb_off:', 'atlassian-light_bulb_off', ':light_bulb_off:'],
|
||||
['(*)', ':yellow_star:', 'atlassian-yellow_star', ':yellow_star:'],
|
||||
['(*y)', ':yellow_star:', 'atlassian-yellow_star', ':yellow_star:'],
|
||||
['(*r)', ':red_star:', 'atlassian-red_star', ':red_star:'],
|
||||
['(*g)', ':green_star:', 'atlassian-green_star', ':green_star:'],
|
||||
['(*b)', ':blue_star:', 'atlassian-blue_star', ':blue_star:'],
|
||||
['(flag)', ':flag_on:', 'atlassian-flag_on', ':flag_on:'],
|
||||
['(flagoff)', ':flag_off:', 'atlassian-flag_off', ':flag_off:'],
|
||||
]
|
||||
|
||||
for (const [smiley, shortName, id, shown] of smileys) {
|
||||
test(`reads the smiley ${smiley} as ${shortName}`, () => {
|
||||
assert.deepEqual(read(`a ${smiley}`), line(text('a '), emoji(shortName, id, shown)))
|
||||
})
|
||||
}
|
||||
|
||||
test('reads the carry of a document holding no content key as that document', () => {
|
||||
assert.deepEqual(jiraWikiToAdf('{adf:display=block}\n{"type":"doc","version":1}\n{adf}'), { ok: true, value: { type: 'doc', version: 1 } })
|
||||
})
|
||||
|
||||
const refusals: { name: string; refusal: string; wiki: string }[] = [
|
||||
{ name: 'an {adf} macro holding invalid JSON', refusal: 'unsupported-node-shape at line 3, offset 3', wiki: 'a\n\n{adf:display=block}\nnot json\n{adf}' },
|
||||
{ name: 'an inline {adf} macro holding invalid JSON', refusal: 'unsupported-node-shape at line 2, offset 2', wiki: 'a\nb {adf:display=inline}{bad{adf}' },
|
||||
{ name: 'an {adf} macro holding JSON that is no node', refusal: 'unsupported-node-shape at line 1, offset 0', wiki: '{adf:display=block}\n[1]\n{adf}' },
|
||||
{ name: 'an {adf} macro left open', refusal: 'unsupported-node-shape at line 1, offset 0', wiki: '{adf:display=block}\n{"type":"rule"}' },
|
||||
{ name: 'an inline {adf} macro closing on a later line', refusal: 'unsupported-node-shape at line 1, offset 0', wiki: 'a {adf:display=inline}{"type":\n"status"}{adf}' },
|
||||
{ name: 'an inline {adf} macro left open', refusal: 'unsupported-node-shape at line 1, offset 0', wiki: '|a {adf:display=inline}{"type":"status"}|' },
|
||||
{ name: 'a carried node nesting deeper than its position leaves', refusal: 'unsupported-nesting-depth at line 1, offset 0', wiki: `{adf:display=block}\n{"attrs":{"a":${'['.repeat(largestNesting + 1)}${']'.repeat(largestNesting + 1)}},"type":"x"}\n{adf}` },
|
||||
{ name: `a list nesting deeper than ${largestNesting} levels`, refusal: 'unsupported-nesting-depth at line 2, offset 4', wiki: `* a\n${'*'.repeat(largestNesting + 1)} b` },
|
||||
]
|
||||
|
||||
for (const { name, refusal, wiki } of refusals) {
|
||||
test(`refuses ${name}`, () => {
|
||||
assert.equal(read(wiki), refusal)
|
||||
})
|
||||
}
|
||||
|
||||
test('refuses what is not a string', () => {
|
||||
const result = jiraWikiToAdf(JSON.parse('7'))
|
||||
assert.equal(result.ok ? 'read' : result.error.code, 'not-a-string')
|
||||
})
|
||||
|
||||
test(`reads a list nesting ${largestNesting} levels`, () => {
|
||||
const result = jiraWikiToAdf(`${'*'.repeat(largestNesting)} a`)
|
||||
assert.equal(result.ok, true)
|
||||
})
|
||||
|
||||
const roundTrips: { name: string; wiki: string }[] = [
|
||||
{ name: 'a quote holding a panel holding a list', wiki: '{quote}\n{panel:bgColor=#deebff}\n* a\n*# b\n{panel}\n\nc\n{quote}' },
|
||||
{ name: 'a table of marked cells and an empty one', wiki: '||*a*||[b|http://x.y|T]||\n| |{color:#ff0000}c{color}|' },
|
||||
{ name: 'escaped markup', wiki: '\\*a\\* \\[b\\] :\\) \\(y) c\\!d' },
|
||||
{ name: 'a code block and an image', wiki: '{code:sql}\nselect *\n\nfrom a\n{code}\n\n!http://a.b/c.png|alt=d e!' },
|
||||
{ name: 'nested marks sharing their outermost', wiki: '*a _b_* -c-\\\\[~accountid:d]' },
|
||||
]
|
||||
|
||||
for (const { name, wiki } of roundTrips) {
|
||||
test(`reads ${name} to the document that writes it`, () => {
|
||||
const result = jiraWikiToAdf(wiki)
|
||||
const written = result.ok ? adfToLosslessJiraWiki(result.value) : result
|
||||
assert.equal(written.ok ? written.value : written.error.code, wiki)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import type { AdfDocument, AdfNode } from '../../adf/document.ts'
|
||||
import type { ConvertFault, ParseError, Result } from '../../result.ts'
|
||||
import { largestNesting } from '../../nesting.ts'
|
||||
import { notAString } from '../../not-a-string.ts'
|
||||
import { panelColours } from '../spellings.ts'
|
||||
import { positioned, success } from '../../result.ts'
|
||||
import { readAdfMacro } from './adf-macro.ts'
|
||||
import { readInline } from './inline.ts'
|
||||
import { withinEngineLimits } from '../../length-bound.ts'
|
||||
|
||||
// An open `{quote}` or `{panel}`, or the document: `content` is its node's own array.
|
||||
type Container = { content: AdfNode[]; kind: 'document' | 'panel' | 'quote' }
|
||||
|
||||
type Fault = { fault: ConvertFault }
|
||||
|
||||
// One open list per marker of the last item's line: `item` is the content of its last item, `list` its items.
|
||||
type Level = { item: AdfNode[]; list: AdfNode[]; marker: string }
|
||||
|
||||
// `end`: the line's end, less its whitespace; `next`: where the line after it starts.
|
||||
type Line = { end: number; next: number; start: number; text: string }
|
||||
|
||||
// `paragraph`: the content a following text line joins after a hardBreak; `rows`: the rows a following row line joins.
|
||||
type Reading = { containers: Container[]; levels: Level[]; paragraph: AdfNode[] | undefined; rows: AdfNode[] | undefined; wiki: string }
|
||||
|
||||
const codeMacro = /\{(code|noformat)(?::([^}\n]*))?\}/y
|
||||
const documentCarry = '{adf:display=block}\n{"type":"doc","version":1}\n{adf}'
|
||||
const image = /^!([^\s!|]+)(?:\|([^!]*))?!$/
|
||||
const itemMarker = /^([*#]+|-) +/
|
||||
const lineWord = /^(?:bq|h([1-6]))\.\s*/
|
||||
const panelMacro = /\{panel(?::([^}\n]*))?\}/y
|
||||
const quoteMacro = '{quote}'
|
||||
const space = /\s/u
|
||||
|
||||
export function jiraWikiToAdf(wiki: string): Result<AdfDocument, ParseError> {
|
||||
return positioned(withinEngineLimits(() => readWiki(wiki)), { line: 1, offset: 0 })
|
||||
}
|
||||
|
||||
function readWiki(wiki: string): Result<AdfDocument> {
|
||||
if (typeof wiki !== 'string') return notAString(wiki, 'Jira wiki markup')
|
||||
if (wiki === documentCarry) return success({ type: 'doc', version: 1 })
|
||||
const root: Container = { content: [], kind: 'document' }
|
||||
const reading: Reading = { containers: [root], levels: [], paragraph: undefined, rows: undefined, wiki }
|
||||
let at = 0
|
||||
while (at < wiki.length) {
|
||||
const feed = wiki.indexOf('\n', at)
|
||||
const next = feed === -1 ? wiki.length : feed + 1
|
||||
const held = wiki.slice(at, next)
|
||||
const start = at + held.length - held.trimStart().length
|
||||
const text = held.trim()
|
||||
const read = text === '' ? closeBlocks(reading, next) : readLine(reading, { end: start + text.length, next, start, text })
|
||||
if (typeof read !== 'number') return { error: { ...read.fault, path: [], position: lineStart(wiki, start) }, ok: false }
|
||||
at = read
|
||||
}
|
||||
closeContainers(reading, 1)
|
||||
return success({ content: root.content, type: 'doc', version: 1 })
|
||||
}
|
||||
|
||||
// spec/wiki.md, Blocks: reads the block or the line at `line.start`, and returns where reading goes on.
|
||||
function readLine(reading: Reading, line: Line): Fault | number {
|
||||
const { next, start, text } = line
|
||||
const macro = readMacro(reading, line)
|
||||
if (macro !== undefined) return macro
|
||||
const worded = lineWord.exec(text)
|
||||
if (worded !== null) return readWordedLine(reading, line, start + worded[0].length, worded[1])
|
||||
if (/^-{4,}$/.test(text)) return pushBlock(reading, { type: 'rule' }, next)
|
||||
const marker = itemMarker.exec(text)
|
||||
if (marker !== null) return readItem(reading, line, marker[1]?.replace('-', '*') ?? '', start + marker[0].length)
|
||||
if (text.startsWith('|')) {
|
||||
const row = readRow(reading, line)
|
||||
if (row !== undefined) return row
|
||||
}
|
||||
const [, url, held] = image.exec(text) ?? []
|
||||
if (url?.includes('://') === true) return pushBlock(reading, { attrs: { layout: 'center' }, content: [media(url, held)], type: 'mediaSingle' }, next)
|
||||
return readTextLine(reading, line)
|
||||
}
|
||||
|
||||
// A macro opens and closes a block only at its line's start, and reads as text anywhere else; `undefined` where none stands there.
|
||||
function readMacro(reading: Reading, { start, text }: Line): Fault | number | undefined {
|
||||
const { containers, wiki } = reading
|
||||
if (!text.startsWith('{')) return undefined
|
||||
const carried = readAdfMacro(wiki, start, wiki.length)
|
||||
if (carried?.fault !== undefined) return { fault: carried.fault }
|
||||
if (carried !== undefined) return carried.value.inline ? undefined : pushBlock(reading, carried.value.node, carried.value.end)
|
||||
codeMacro.lastIndex = start
|
||||
const code = codeMacro.exec(wiki)
|
||||
if (code !== null) return readCode(reading, codeMacro.lastIndex, code[1] ?? '', code[2])
|
||||
if (text.startsWith(quoteMacro)) {
|
||||
const open = containers.findIndex(({ kind }) => kind === 'quote')
|
||||
if (open === -1) openContainer(reading, 'quote', { type: 'blockquote' })
|
||||
else closeContainers(reading, open)
|
||||
return start + quoteMacro.length
|
||||
}
|
||||
panelMacro.lastIndex = start
|
||||
const panel = panelMacro.exec(wiki)
|
||||
const open = containers.findIndex(({ kind }) => kind === 'panel')
|
||||
if (panel === null || (open !== -1 && panel[1] !== undefined)) return undefined
|
||||
if (open === -1) openPanel(reading, parameters(panel[1] ?? '', '|'))
|
||||
else closeContainers(reading, open)
|
||||
return panelMacro.lastIndex
|
||||
}
|
||||
|
||||
// The text stands between the macros whole, less the line feed after the opening one and the line feed before the closing one.
|
||||
function readCode(reading: Reading, from: number, name: string, held: string | undefined): number {
|
||||
const { wiki } = reading
|
||||
const closer = `{${name}}`
|
||||
const close = wiki.indexOf(closer, from)
|
||||
const end = close === -1 ? wiki.length : close
|
||||
const start = from + (wiki.startsWith('\n', from) ? 1 : 0)
|
||||
const text = wiki.slice(start, Math.max(start, end - (wiki.startsWith('\n', end - 1) ? 1 : 0)))
|
||||
const [first = ''] = (held ?? '').split('|')
|
||||
const language = name === 'noformat' ? '' : first === '' || first.includes('=') ? 'java' : first.trim().toLowerCase()
|
||||
return pushBlock(reading, { attrs: { language }, ...(text === '' ? {} : { content: [{ text, type: 'text' }] }), type: 'codeBlock' }, close === -1 ? wiki.length : close + closer.length)
|
||||
}
|
||||
|
||||
function openPanel(reading: Reading, held: ReadonlyMap<string, string>): void {
|
||||
const colour = held.get('bgColor')?.toLowerCase()
|
||||
const panelType = Object.entries(panelColours).find(([, spelled]) => spelled === colour)?.[0] ?? 'info'
|
||||
const title = held.get('title') ?? ''
|
||||
const content = openContainer(reading, 'panel', { attrs: { panelType }, type: 'panel' })
|
||||
if (title !== '') content.push({ content: [{ marks: [{ type: 'strong' }], text: title, type: 'text' }], type: 'paragraph' })
|
||||
}
|
||||
|
||||
function openContainer(reading: Reading, kind: Container['kind'], node: AdfNode): AdfNode[] {
|
||||
const content: AdfNode[] = []
|
||||
pushBlock(reading, { ...node, content }, 0)
|
||||
reading.containers.push({ content, kind })
|
||||
return content
|
||||
}
|
||||
|
||||
// Closes every container from `open` on: one holding nothing holds an empty paragraph.
|
||||
function closeContainers(reading: Reading, open: number): void {
|
||||
closeBlocks(reading, 0)
|
||||
for (const { content } of reading.containers.splice(open)) if (content.length === 0) content.push({ type: 'paragraph' })
|
||||
}
|
||||
|
||||
// `h1.` to `h6.` and `bq.`, each one line.
|
||||
function readWordedLine(reading: Reading, { end, next }: Line, from: number, level: string | undefined): Fault | number {
|
||||
const inline = readInline(reading.wiki, from, end, false)
|
||||
if (inline.fault !== undefined) return inline
|
||||
const content = inline.nodes.length === 0 ? {} : { content: inline.nodes }
|
||||
const node: AdfNode = level === undefined ? { content: [{ ...content, type: 'paragraph' }], type: 'blockquote' } : { attrs: { level: Number(level) }, ...content, type: 'heading' }
|
||||
return pushBlock(reading, node, next)
|
||||
}
|
||||
|
||||
// A marker per level: the levels the line shares with the item before it stay open, and a level it skips holds an item of an empty paragraph.
|
||||
function readItem(reading: Reading, { end, next }: Line, markers: string, from: number): Fault | number {
|
||||
const { levels } = reading
|
||||
if (markers.length > largestNesting) return { fault: { code: 'unsupported-nesting-depth', message: `lists nest deeper than ${largestNesting} levels` } }
|
||||
const inline = readInline(reading.wiki, from, end, false)
|
||||
if (inline.fault !== undefined) return inline
|
||||
let shared = 0
|
||||
while (shared < markers.length && levels[shared]?.marker === markers.charAt(shared)) shared += 1
|
||||
if (shared === 0) closeBlocks(reading, 0)
|
||||
levels.length = shared
|
||||
for (let depth = shared; depth < markers.length; depth += 1) {
|
||||
const list: AdfNode[] = []
|
||||
const marker = markers.charAt(depth)
|
||||
const holder = depth === 0 ? blocksOf(reading) : levels[depth - 1]?.item
|
||||
holder?.push(marker === '#' ? { attrs: { order: 1 }, content: list, type: 'orderedList' } : { content: list, type: 'bulletList' })
|
||||
levels.push({ item: depth < markers.length - 1 ? pushItem(list, { type: 'paragraph' }) : [], list, marker })
|
||||
}
|
||||
const level = levels[markers.length - 1]
|
||||
if (level === undefined) return next
|
||||
level.item = pushItem(level.list, inline.nodes.length === 0 ? { type: 'paragraph' } : { content: inline.nodes, type: 'paragraph' })
|
||||
reading.paragraph = inline.nodes.length === 0 ? undefined : inline.nodes
|
||||
return next
|
||||
}
|
||||
|
||||
function pushItem(list: AdfNode[], paragraph: AdfNode): AdfNode[] {
|
||||
const item = [paragraph]
|
||||
list.push({ content: item, type: 'listItem' })
|
||||
return item
|
||||
}
|
||||
|
||||
// spec/wiki.md, Blocks: a row is one line, and each `|` or `||` opens a cell, the last one closing the row; `undefined` where the line holds no cell.
|
||||
function readRow(reading: Reading, { end, next, start }: Line): Fault | number | undefined {
|
||||
const { wiki } = reading
|
||||
const cells: AdfNode[] = []
|
||||
let at = start
|
||||
while (at < end) {
|
||||
const header = wiki.startsWith('||', at)
|
||||
let from = at + (header ? 2 : 1)
|
||||
if (from >= end) break
|
||||
while (space.test(wiki.charAt(from))) from += 1
|
||||
const inline = readInline(wiki, from, end, true)
|
||||
if (inline.fault !== undefined) return inline
|
||||
const nodes = trimmedEnd(inline.nodes)
|
||||
cells.push({ content: [nodes.length === 0 ? { type: 'paragraph' } : { content: nodes, type: 'paragraph' }], type: header ? 'tableHeader' : 'tableCell' })
|
||||
at = inline.end
|
||||
}
|
||||
if (cells.length === 0) return undefined
|
||||
if (reading.rows === undefined) {
|
||||
const rows: AdfNode[] = []
|
||||
pushBlock(reading, { attrs: { isNumberColumnEnabled: false, layout: 'default' }, content: rows, type: 'table' }, 0)
|
||||
reading.rows = rows
|
||||
}
|
||||
reading.rows.push({ content: cells, type: 'tableRow' })
|
||||
return next
|
||||
}
|
||||
|
||||
// A cell's text ends before the whitespace its closing `|` follows.
|
||||
function trimmedEnd(nodes: AdfNode[]): AdfNode[] {
|
||||
const last = nodes.at(-1)
|
||||
if (last?.type !== 'text' || last.text === undefined || last.attrs !== undefined) return nodes
|
||||
const text = last.text.trimEnd()
|
||||
return text === '' ? nodes.slice(0, -1) : [...nodes.slice(0, -1), { ...last, text }]
|
||||
}
|
||||
|
||||
function media(url: string, held: string | undefined): AdfNode {
|
||||
const alt = parameters(held ?? '', ',').get('alt') ?? ''
|
||||
return { attrs: { ...(alt === '' ? {} : { alt }), type: 'external', url }, type: 'media' }
|
||||
}
|
||||
|
||||
// A text line joins the paragraph before it, or its item's, after a hardBreak.
|
||||
function readTextLine(reading: Reading, { end, next, start }: Line): Fault | number {
|
||||
const inline = readInline(reading.wiki, start, end, false)
|
||||
if (inline.fault !== undefined) return inline
|
||||
if (inline.nodes.length === 0) return next
|
||||
if (reading.paragraph === undefined) {
|
||||
pushBlock(reading, { content: inline.nodes, type: 'paragraph' }, 0)
|
||||
reading.paragraph = inline.nodes
|
||||
return next
|
||||
}
|
||||
reading.paragraph.push({ type: 'hardBreak' })
|
||||
for (const node of inline.nodes) reading.paragraph.push(node)
|
||||
return next
|
||||
}
|
||||
|
||||
// Ends the open paragraph, list and table, then stands the block in the innermost open container.
|
||||
function pushBlock(reading: Reading, node: AdfNode, next: number): number {
|
||||
closeBlocks(reading, next)
|
||||
blocksOf(reading)?.push(node)
|
||||
return next
|
||||
}
|
||||
|
||||
function closeBlocks(reading: Reading, next: number): number {
|
||||
reading.levels.length = 0
|
||||
reading.paragraph = undefined
|
||||
reading.rows = undefined
|
||||
return next
|
||||
}
|
||||
|
||||
function blocksOf({ containers }: Reading): AdfNode[] | undefined {
|
||||
return containers.at(-1)?.content
|
||||
}
|
||||
|
||||
// `key=value` parameters, a parameter holding no `=` under the key it is.
|
||||
function parameters(held: string, separator: string): Map<string, string> {
|
||||
const read = new Map<string, string>()
|
||||
for (const parameter of held.split(separator)) {
|
||||
const [key = '', ...value] = parameter.split('=')
|
||||
read.set(key.trim(), value.join('=').trim())
|
||||
}
|
||||
return read
|
||||
}
|
||||
|
||||
function lineStart(wiki: string, index: number): { line: number; offset: number } {
|
||||
let line = 1
|
||||
let offset = 0
|
||||
for (let next = wiki.indexOf('\n'); next >= 0 && next < index; next = wiki.indexOf('\n', next + 1)) {
|
||||
line += 1
|
||||
offset = next + 1
|
||||
}
|
||||
return { line, offset }
|
||||
}
|
||||
+35
-26
@@ -41,29 +41,38 @@ export const panelColours: Readonly<Record<string, string>> = {
|
||||
warning: '#fffae6',
|
||||
}
|
||||
|
||||
// spec/wiki.md, What only the reader reads: each smiley Jira reads as an emoji.
|
||||
export const smileys: readonly string[] = [
|
||||
'(!)',
|
||||
'(*)',
|
||||
'(*b)',
|
||||
'(*g)',
|
||||
'(*r)',
|
||||
'(*y)',
|
||||
'(+)',
|
||||
'(-)',
|
||||
'(/)',
|
||||
'(?)',
|
||||
'(flag)',
|
||||
'(flagoff)',
|
||||
'(i)',
|
||||
'(n)',
|
||||
'(off)',
|
||||
'(on)',
|
||||
'(x)',
|
||||
'(y)',
|
||||
':(',
|
||||
':)',
|
||||
':D',
|
||||
':P',
|
||||
';)',
|
||||
]
|
||||
// spec/wiki.md, Marks: what `{color}` and a link's href and title spell.
|
||||
export const spellableColour = /^#[0-9a-f]{6}$/i
|
||||
|
||||
export const spellableTitle = /^[^\s[\]{}|\\](?:[^[\]{}|\\\r\n]*[^\s[\]{}|\\])?$/
|
||||
|
||||
export const spellableUrl = /^[^\s[\]{}|\\]+$/
|
||||
|
||||
// spec/wiki.md, What only the reader reads: each smiley Jira reads as an emoji, with the emoji's id and shortName.
|
||||
export const smileyEmoji: Readonly<Record<string, { id: string; shortName: string }>> = {
|
||||
'(!)': { id: 'atlassian-warning', shortName: ':warning:' },
|
||||
'(*)': { id: 'atlassian-yellow_star', shortName: ':yellow_star:' },
|
||||
'(*b)': { id: 'atlassian-blue_star', shortName: ':blue_star:' },
|
||||
'(*g)': { id: 'atlassian-green_star', shortName: ':green_star:' },
|
||||
'(*r)': { id: 'atlassian-red_star', shortName: ':red_star:' },
|
||||
'(*y)': { id: 'atlassian-yellow_star', shortName: ':yellow_star:' },
|
||||
'(+)': { id: 'atlassian-plus', shortName: ':plus:' },
|
||||
'(-)': { id: 'atlassian-minus', shortName: ':minus:' },
|
||||
'(/)': { id: 'atlassian-check_mark', shortName: ':check_mark:' },
|
||||
'(?)': { id: 'atlassian-question_mark', shortName: ':question:' },
|
||||
'(flag)': { id: 'atlassian-flag_on', shortName: ':flag_on:' },
|
||||
'(flagoff)': { id: 'atlassian-flag_off', shortName: ':flag_off:' },
|
||||
'(i)': { id: 'atlassian-info', shortName: ':info:' },
|
||||
'(n)': { id: '1f44e', shortName: ':thumbsdown:' },
|
||||
'(off)': { id: 'atlassian-light_bulb_off', shortName: ':light_bulb_off:' },
|
||||
'(on)': { id: 'atlassian-light_bulb_on', shortName: ':light_bulb_on:' },
|
||||
'(x)': { id: 'atlassian-cross_mark', shortName: ':cross_mark:' },
|
||||
'(y)': { id: '1f44d', shortName: ':thumbsup:' },
|
||||
':(': { id: '1f61e', shortName: ':disappointed:' },
|
||||
':)': { id: '1f642', shortName: ':slight_smile:' },
|
||||
':D': { id: '1f603', shortName: ':smiley:' },
|
||||
':P': { id: '1f61b', shortName: ':stuck_out_tongue:' },
|
||||
';)': { id: '1f609', shortName: ':wink:' },
|
||||
}
|
||||
|
||||
export const smileys: readonly string[] = Object.keys(smileyEmoji)
|
||||
|
||||
Reference in New Issue
Block a user