import { scanFence } from "@mdit/helper"; import type { BlockRule } from "@mdit/helper"; import type { Env, StateBlock, Token } from "markdown-it"; import type { AllowedAttributes } from "./utils.js"; import { parseAttributesRange, scanCodeSpan } from "./utils.js"; export interface FieldContext { /** Container name (e.g., "fields", "props") */ name: string; /** Stack tracking the depth of nested field items for proper closing */ depthStack: number[]; } interface FieldStateEnv extends Env { [fieldContextKey]?: FieldContext | undefined; } const fieldContextKey = Symbol("field:context"); interface FieldStateBlock extends StateBlock { env: FieldStateEnv; } const MIN_MARKER_NUM = 3; // Indentation from 0-3 spaces is cosmetic (visual only, does not affect nesting depth). // 4+ spaces triggers standard Markdown code block behavior. const MAX_COSMETIC_INDENT = 3; // Attribute key sanitization: only alphanumeric and hyphens allowed const INVALID_KEY_CHAR_RE = /[^a-zA-Z0-9-]/; /** * Check if an attribute key contains only valid characters for CSS class names. * * 检查属性键是否只包含 CSS 类名的有效字符。 * * @param key - Attribute key / 属性键 * @returns Whether the key is valid / 键是否有效 */ export const isValidAttrKey = (key: string): boolean => key.length > 0 && !INVALID_KEY_CHAR_RE.test(key); /** * Check whether a line starts with a field marker, whose name is a Markdown code span so that the * name never clashes with Markdown syntax, e.g. `@`name``, `@@`a`b``. * * 检查一行是否以字段标记开头,其名字是一个 Markdown 代码片段,因此名字不会与 Markdown 语法冲突,例如 `@`name``、`@@`a`b``。 * * @param state - Block state / 块状态 * @param start - Start position of the line / 行的起始位置 * @param max - End of the line / 行的结束位置 * @returns Marker end position, field name and depth, or `false` / 标记结束位置、字段名与层级,或 `false` */ export const checkFieldMarker = ( state: StateBlock, start: number, max: number, ): false | { end: number; name: string; depth: number } => { if (state.src.charCodeAt(start) !== 64 /* @ */) return false; // Count leading @ chars for depth (depth = count, starting from 1) let depth = 0; let pos = start; while (pos < max && state.src.charCodeAt(pos) === 64 /* @ */) { depth++; pos++; } // The name follows as a code span, and must not be separated from the @ chars if (state.src.charCodeAt(pos) !== 96 /* ` */) return false; const span = scanCodeSpan(state.src, pos, max); if (!span) return false; return { end: span.end, name: span.value, depth }; }; // oxlint-disable max-lines-per-function export const getFieldsRule = (name: string, classPrefix: string): BlockRule => (state: FieldStateBlock, startLine, endLine, silent) => { const start = state.bMarks[startLine] + state.tShift[startLine]; const max = state.eMarks[startLine]; const indent = state.sCount[startLine]; // Check out the first character quickly, // this should filter out most of non-containers if (state.src.charCodeAt(start) !== 58 /* : */) return false; let pos = start + 1; // Check out the rest of the marker string while (pos <= max) { if (state.src.charCodeAt(pos) !== 58 /* : */) break; pos++; } const markerCount = pos - start; if (markerCount < MIN_MARKER_NUM) return false; pos = state.skipSpaces(pos); // check name is matched for (let ii = 0; ii < name.length; ii++) { if (state.src.charCodeAt(pos) !== name.charCodeAt(ii)) return false; pos++; } // Check what follows the name if (pos < max) { const charCode = state.src.charCodeAt(pos); if (!state.md.utils.isSpace(charCode) && charCode !== 35 /* # */) return false; } // Since start is found, we can report success here in validation mode if (silent) return true; let id = ""; let idStart = -1; for (let ii = pos; ii < max; ii++) { if (state.src.charCodeAt(ii) === 35 /* # */) { idStart = ii + 1; break; } } if (idStart !== -1) { let idEnd = idStart; while (idEnd < max && !state.md.utils.isSpace(state.src.charCodeAt(idEnd))) idEnd++; id = state.src.slice(idStart, idEnd); } // Search for closing fence let nextLine = startLine + 1; let autoClosed = false; // Search for the end of the block for ( ; // nextLine should be accessible outside the loop, // unclosed block should be auto closed by end of document. // also block seems to be auto closed by end of parent nextLine < endLine; nextLine++ ) { const nextLineStart = state.bMarks[nextLine] + state.tShift[nextLine]; const nextLineMax = state.eMarks[nextLine]; if (nextLineStart < nextLineMax && state.sCount[nextLine] < indent) { // non-empty line with negative indent should stop the list: // - ::: // test break; } // directives inside fenced code blocks are literal text, skip them const fenceEnd = scanFence(state, nextLine, endLine, indent); if (fenceEnd != null && fenceEnd > nextLine) { nextLine = fenceEnd - 1; continue; } if ( // closing fence should be indented same as opening one state.sCount[nextLine] === indent && // match start state.src.charCodeAt(nextLineStart) === 58 /* : */ ) { // check rest of marker for (pos = nextLineStart + 1; pos <= nextLineMax; pos++) if (state.src.charCodeAt(pos) !== 58 /* : */) break; // closing code fence must be at least as long as the opening one if (pos - nextLineStart >= markerCount) { // make sure tail has spaces only pos = state.skipSpaces(pos); if (pos >= nextLineMax) { // found! autoClosed = true; break; } } } } const oldParentType = state.parentType; const oldLineMax = state.lineMax; const oldBlkIndent = state.blkIndent; const oldContext = state.env[fieldContextKey]; state.parentType = `${name}_field`; // this will prevent lazy continuations from ever going past our end marker state.lineMax = nextLine; // this will update the block indent state.blkIndent = indent; const openToken = state.push(`${name}_fields_open`, "dl", 1); const markup = ":".repeat(markerCount); openToken.markup = markup; openToken.block = true; openToken.info = name; openToken.map = [startLine, nextLine + (autoClosed ? 1 : 0)]; openToken.attrs = [ ["class", `${classPrefix}wrapper ${name}-fields`], ["data-kind", name], ]; if (id) openToken.attrSet("id", id); state.env[fieldContextKey] = { name, depthStack: [] }; state.md.block.tokenize(state, startLine + 1, nextLine); // Close any remaining open field items from the depth stack const depthStack = state.env[fieldContextKey].depthStack; for (let ii = depthStack.length - 1; ii >= 0; ii--) { // Close inner
wrapper before closing parent when backtracking if (ii < depthStack.length - 1 && depthStack[ii + 1] > depthStack[ii]) state.push(`${name}_fields_inner_close`, "dl", -1); state.push(`${name}_field_close`, "div", -1); } state.env[fieldContextKey] = oldContext; const closeToken = state.push(`${name}_fields_close`, "dl", -1); closeToken.block = true; closeToken.markup = ""; state.parentType = oldParentType; state.lineMax = oldLineMax; state.blkIndent = oldBlkIndent; state.line = nextLine + (autoClosed ? 1 : 0); return true; }; // oxlint-enable max-lines-per-function export const getFieldItemRule = ( name: string, allowedAttributes: AllowedAttributes | null, shouldParseAttributes: boolean, ): BlockRule => (state: FieldStateBlock, startLine, endLine, silent) => { const ctx = state.env[fieldContextKey]; if (!ctx || ctx.name !== name) return false; const start = state.bMarks[startLine] + state.tShift[startLine]; const max = state.eMarks[startLine]; const indent = state.sCount[startLine] - state.blkIndent; // 0-3 spaces of indent are cosmetic; 4+ means code block, not a field item. // This guard protects against other plugins that increase blkIndent; // markdown-it's code_block rule normally consumes 4+-space lines first. /* istanbul ignore next -- guard for plugins that raise blkIndent above 3 */ if (indent > MAX_COSMETIC_INDENT) return false; // Must be an @ run immediately followed by a code span, the @ count giving the depth const marker = checkFieldMarker(state, start, max); if (marker === false) return false; if (silent) return true; // Parse attributes (if enabled), filtering out invalid keys const attributes = shouldParseAttributes ? parseAttributesRange(state.src, marker.end, max, allowedAttributes).filter((attr) => isValidAttrKey(attr.attr), ) : []; const currentDepth = marker.depth; // Manage depth stack: close items as needed const depthStack = ctx.depthStack; // Close items that are at the same or deeper depth (sibling or backtrack) let lastClosedDepth = -1; while (depthStack.length > 0 && depthStack[depthStack.length - 1] >= currentDepth) { const closingDepth = depthStack[depthStack.length - 1]; depthStack.pop(); // Close inner
wrapper before closing parent when backtracking if (lastClosedDepth > closingDepth) state.push(`${name}_fields_inner_close`, "dl", -1); state.push(`${name}_field_close`, "div", -1); lastClosedDepth = closingDepth; } // Close outermost inner
wrapper only when backtracking to parent level if (lastClosedDepth > currentDepth && depthStack.length > 0) state.push(`${name}_fields_inner_close`, "dl", -1); // Open inner
wrapper only on first descent to a deeper level const shouldOpenInner = depthStack.length > 0 && currentDepth > depthStack[depthStack.length - 1] && lastClosedDepth !== currentDepth; if (shouldOpenInner) state.push(`${name}_fields_inner_open`, "dl", 1); // Push current depth onto stack depthStack.push(currentDepth); // Search for the end of the item block content let nextLine = startLine + 1; for (; nextLine < endLine; nextLine++) { if (state.isEmpty(nextLine)) continue; // directives inside fenced code blocks are literal text, skip them const fenceEnd = scanFence(state, nextLine, endLine, state.blkIndent); if (fenceEnd != null && fenceEnd > nextLine) { nextLine = fenceEnd - 1; continue; } const nextStart = state.bMarks[nextLine] + state.tShift[nextLine]; const nextMax = state.eMarks[nextLine]; const nextIndent = state.sCount[nextLine] - state.blkIndent; if (nextIndent <= MAX_COSMETIC_INDENT) { // A field container marker (3+ colons) at the container level ends the // item. A single `:` (e.g. definition list syntax) is not a container // marker and must stay inside the item. let colonCount = 0; while ( nextStart + colonCount < nextMax && state.src.charCodeAt(nextStart + colonCount) === 58 /* : */ ) colonCount++; if (colonCount >= MIN_MARKER_NUM) break; // Check if it's a field marker within the cosmetic indent range const nextMarker = checkFieldMarker(state, nextStart, nextMax); // oxlint-disable-next-line typescript/strict-boolean-expressions if (nextMarker) break; } } const tokenOpen = state.push(`${name}_field_open`, "div", 1); tokenOpen.attrSet("data-level", String(currentDepth)); tokenOpen.meta = { name: marker.name, level: currentDepth, attributes }; tokenOpen.map = [startLine, nextLine]; // A field item may be parsed while tokenizing another block container // (e.g. a blockquote or a list item). It cannot extend past that container, // so it must be closed before the container's close token is emitted. const isNestedBlock = state.parentType !== `${name}_field` && state.parentType !== `${name}_field_item`; const oldParentType = state.parentType; const oldLineMax = state.lineMax; state.parentType = `${name}_field_item`; // this will prevent lazy continuations from ever going past our end marker state.lineMax = nextLine; state.md.block.tokenize(state, startLine + 1, nextLine); state.parentType = oldParentType; state.lineMax = oldLineMax; if (isNestedBlock) { state.push(`${name}_field_close`, "div", -1); if (shouldOpenInner) state.push(`${name}_fields_inner_close`, "dl", -1); depthStack.pop(); } // Note: otherwise field_close tokens are NOT pushed here. Closing is handled by: // (1) depth stack cleanup in getFieldsRule when exiting the container, or // (2) sibling/backtrack logic when encountering a field at equal or lower depth. state.line = nextLine; return true; }; interface FieldsScanContext { /** Nesting level of the container opening token / 容器开始 token 的嵌套层级 */ level: number; /** Whether a field item has been found in this container / 容器内是否已找到字段项 */ hasField: boolean; /** Containers hidden before the first field / 第一个字段前被隐藏的容器 */ hiddenContainers: { index: number; type: string }[]; } export const getFieldsScanner = (name: string): ((tokens: Token[]) => void) => { // Hoist the token type strings: the scanner compares them for every token, so building them // inside the loop would allocate a new string per comparison. const fieldsOpenType = `${name}_fields_open`; const fieldsCloseType = `${name}_fields_close`; const fieldsEmptyType = `${name}_fields_empty`; const fieldOpenType = `${name}_field_open`; const fieldCloseType = `${name}_field_close`; const innerOpenType = `${name}_fields_inner_open`; const innerCloseType = `${name}_fields_inner_close`; return (tokens: Token[]) => { // Containers currently open, outermost first. The scanner walks the token array once and // keeps the state of every open container on this stack instead of re-scanning the document // for each `${name}_fields_open` (which was O(containers × tokens) when levels desynced). const activeContexts: FieldsScanContext[] = []; const hideToken = (context: FieldsScanContext, index: number, token: Token): void => { if (token.nesting > 0) context.hiddenContainers.push({ index, type: token.type }); else if (token.nesting < 0 && context.hiddenContainers.length > 0) context.hiddenContainers.pop(); token.type = fieldsEmptyType; token.hidden = true; }; for (let ii = 0; ii < tokens.length; ii++) { const token = tokens[ii]; // A close token belongs to the innermost open container: block tokens are emitted in // document order, so same-name containers pair up like a stack. Popping by token order // instead of comparing `level` means a third-party rule that re-levels (or defers) close // tokens can never leave a container scanning to the end of the document. if (token.type === fieldsCloseType) { activeContexts.pop(); continue; } const contextCount = activeContexts.length; for (let ci = 0; ci < contextCount; ci++) { const context = activeContexts[ci]; if (context.hasField) continue; // Read the type again for every container: an outer container may have hidden (renamed) // the token, and a nested container must observe the renamed type, matching the previous // per-container scan order. const type = token.type; // A nested fields container only increases the nesting depth of the outer containers; // the stack itself records it. if (type === fieldsOpenType) continue; const nestingDepth = contextCount - 1 - ci; // A field item may be nested inside another block, e.g. a blockquote or a list item, so // it is recognized at any depth while no nested fields container is open. if (nestingDepth === 0 && type === fieldOpenType) { for (const hidden of context.hiddenContainers) { const hiddenToken = tokens[hidden.index]; hiddenToken.type = hidden.type; hiddenToken.hidden = false; } context.hiddenContainers.length = 0; context.hasField = true; continue; } // skip processing tokens deep inside other blocks, and hide contents before the first field if (token.level > context.level + 1 || nestingDepth > 0) { hideToken(context, ii, token); continue; } if (type === fieldCloseType || type === innerOpenType || type === innerCloseType) continue; // hide contents before first field hideToken(context, ii, token); } if (token.type === fieldsOpenType) activeContexts.push({ level: token.level, hasField: false, hiddenContainers: [] }); } }; };