/** * MarkdownFlow Interactive Block Layered Parser - TypeScript Version * * Uses a three-layer analysis architecture: * Layer 1: ?[] format validation * Layer 2: Variable detection and pattern classification * Layer 3: Specific content parsing */ import { findUnescaped, INTERACTION_CONTENT_SOURCE, splitOnEllipsis, splitOnSingleUnescapedPipe, splitUnescaped, unescapeInteractionText, readInteraction, } from './escaping'; import { normalizeVariableName, readVariableMarker, trimVariablePadding, VARIABLE_REFERENCE_SOURCE, VARIABLE_PADDING_SOURCE, } from './variable-name'; // Interaction input type enumeration export enum InteractionType { TEXT_ONLY = 'text_only', // Pure text input: ?[{{var}}...question] BUTTONS_ONLY = 'buttons_only', // Pure button group: ?[{{var}} option1|option2] BUTTONS_WITH_TEXT = 'buttons_with_text', // Button group + text: ?[{{var}} option1|option2|...question] BUTTONS_MULTI_SELECT = 'buttons_multi_select', // Multi-select buttons: ?[{{var}} A||B] BUTTONS_MULTI_WITH_TEXT = 'buttons_multi_with_text', // Multi-select + text: ?[{{var}} A||B||...question] NON_ASSIGNMENT_BUTTON = 'non_assignment_button', // Non-assignment button: ?[Continue] or ?[Continue|Cancel] } // Pre-compiled regex constants export const COMPILED_REGEXES = { // Layer 1: Basic format validation - matches ?[content] but excludes ?[text](url) format. // The content accepts an escaped delimiter as one unit, so a `\]` inside an option does not // end the interaction. See ./escaping. LAYER1_INTERACTION: new RegExp( `\\?\\[(${INTERACTION_CONTENT_SOURCE})\\](?!\\()` ), // Names use the teaching engine's grammar; only the content after the marker is split into // choices, display/value pairs or a text input. A leading {{name}} binds the answer; // the percent prefix is retained for legacy content only. LAYER2_VARIABLE: new RegExp( `^${VARIABLE_PADDING_SOURCE}%?${VARIABLE_REFERENCE_SOURCE}([\\s\\S]*)$` ), // Layer 3: Split content before and after ... LAYER3_ELLIPSIS: /^(.*?)\.\.\.(.*)/, // Kept for consumers that inspect the exported regex collection. Exact // single-pipe splitting requires context that Safari-safe regexes cannot // express without consuming adjacent text, and now also has to skip a bar // an option escaped, so the parser uses the scanner in ./escaping instead. LAYER3_SINGLE_PIPE_SPLIT: /\|(?!\|)/g, }; // Button interface export interface Button { display: string; value: string; } // Parse result base interface export interface ParseResultBase { type: InteractionType | null; error?: string; } // Variable interaction result interface export interface VariableInteractionResult extends ParseResultBase { type: | InteractionType.TEXT_ONLY | InteractionType.BUTTONS_ONLY | InteractionType.BUTTONS_WITH_TEXT | InteractionType.BUTTONS_MULTI_SELECT | InteractionType.BUTTONS_MULTI_WITH_TEXT; variable: string; buttons?: Button[]; question?: string; isMultiSelect?: boolean; } // Non-assignment interaction result interface (no variable). Supports the // same shapes as variable interactions: buttons (single/multi select), text // input (?[...question]) and buttons + text (?[A|B|...question]). export interface NonAssignmentButtonResult extends ParseResultBase { type: InteractionType.NON_ASSIGNMENT_BUTTON; buttons: Button[]; question?: string; isMultiSelect?: boolean; } // Error result interface export interface ErrorResult extends ParseResultBase { type: null; error: string; } // Parse result union type export type ParseResult = | VariableInteractionResult | NonAssignmentButtonResult | ErrorResult; // remark-compatible output format export interface RemarkCompatibleResult { variableName?: string; buttonTexts?: string[]; buttonValues?: string[]; placeholder?: string; isMultiSelect?: boolean; } // Legacy return data format for backward compatibility export interface LegacyReturnData { variable?: string; buttons?: Button[]; question?: string; isMultiSelect?: boolean; } /** * Layered interaction parser class */ export class InteractionParser { constructor() { // Constructor is intentionally empty - no initialization needed } /** * Main parsing method * * @param content - Raw content of interaction block * @returns Standardized parse result */ parse(content: string): ParseResult { try { // Layer 1: Validate basic format const innerContent = this._layer1ValidateFormat(content); if (innerContent === null) { return this._createErrorResult( `Invalid interaction format: ${content}` ); } // Layer 2: Variable detection and pattern classification const [hasVariable, variableName, remainingContent] = this._layer2DetectVariable(innerContent); // Layer 3: Specific content parsing if (hasVariable && variableName === null) { return this._createErrorResult('Invalid variable name'); } if (hasVariable && variableName) { return this._layer3ParseVariableInteraction( variableName, remainingContent ); } else { return this._layer3ParseDisplayButtons(innerContent); } } catch (error) { return this._createErrorResult( `Parsing error: ${error instanceof Error ? error.message : 'Unknown error'}` ); } } /** * Parse and convert to remark-compatible format * * @param content - Raw content of interaction block * @returns remark-compatible result object */ parseToRemarkFormat(content: string): RemarkCompatibleResult { const result = this.parse(content); if (result.error) { // Compatibility handling when parsing fails return { placeholder: trimVariablePadding(content) }; } // Convert to remark-compatible format const remarkResult: RemarkCompatibleResult = {}; if (result.type === InteractionType.NON_ASSIGNMENT_BUTTON) { // Non-assignment interaction (no variableName in the output) const nonAssignmentResult = result as NonAssignmentButtonResult; if (nonAssignmentResult.buttons.length > 0) { remarkResult.buttonTexts = nonAssignmentResult.buttons.map( b => b.display ); remarkResult.buttonValues = nonAssignmentResult.buttons.map( b => b.value ); } if (nonAssignmentResult.question !== undefined) { remarkResult.placeholder = nonAssignmentResult.question; } if (nonAssignmentResult.isMultiSelect !== undefined) { remarkResult.isMultiSelect = nonAssignmentResult.isMultiSelect; } } else if (result.type !== null) { // Variable interaction const variableResult = result as VariableInteractionResult; remarkResult.variableName = variableResult.variable; if (variableResult.buttons) { remarkResult.buttonTexts = variableResult.buttons.map(b => b.display); remarkResult.buttonValues = variableResult.buttons.map(b => b.value); } if (variableResult.question !== undefined) { remarkResult.placeholder = variableResult.question; } if (variableResult.isMultiSelect !== undefined) { remarkResult.isMultiSelect = variableResult.isMultiSelect; } } return remarkResult; } /** * Layer 1: Validate ?[] format and extract content * * @param content - Raw content * @returns Extracted bracket content, returns null if validation fails */ private _layer1ValidateFormat(content: string): string | null { content = trimVariablePadding(content); const span = readInteraction(content); return span?.complete && span.end === content.length ? span.content : null; } /** * Layer 2: Detect variables and perform pattern classification * * @param innerContent - Content extracted from layer 1 * @returns [hasVariable, variableName, remainingContent] */ private _layer2DetectVariable( innerContent: string ): [boolean, string | null, string] { innerContent = trimVariablePadding(innerContent); const markerStart = innerContent.startsWith('%') ? 1 : 0; if (!innerContent.startsWith('{{', markerStart)) { // No variable, entire content used for display button parsing return [false, null, innerContent]; } const marker = readVariableMarker(innerContent, markerStart); if (!marker) return [true, null, innerContent]; const variableName = normalizeVariableName(marker.rawName); const remainingContent = trimVariablePadding( innerContent.slice(marker.end) ); return [true, variableName, remainingContent]; } /** * Parse the structural shape of interaction content: buttons, optional * `...question` text input, multi-select flag. Shared by the variable and * non-assignment branches, which only differ in how they map the shape * into their result types. * * @param content - Content after the (optional) variable * @returns The parsed content shape */ private _parseContentShape(content: string): { buttons: Button[]; question?: string; isMultiSelect: boolean; hasTextInput: boolean; } { const ellipsis = splitOnEllipsis(content); if (ellipsis) { const beforeEllipsis = trimVariablePadding(ellipsis[0]); const question = trimVariablePadding( unescapeInteractionText(ellipsis[1]) ); if (beforeEllipsis) { // Button group + text input: ?[Button1 | Button2 | ...question] const [buttons, isMultiSelect] = this._parseButtons(beforeEllipsis); return { buttons, question, isMultiSelect, hasTextInput: true }; } // Pure text input: ?[...question] return { buttons: [], question, isMultiSelect: false, hasTextInput: true, }; } if (findUnescaped(content, '|') >= 0) { // Button group: ?[Button1 | Button2] or ?[Button1 || Button2] const [buttons, isMultiSelect] = this._parseButtons(content); return { buttons, isMultiSelect, hasTextInput: false }; } if (content) { // Single button: ?[Button1] or ?[Button1//id1] return { buttons: [this._parseSingleButton(content)], isMultiSelect: false, hasTextInput: false, }; } // Empty content: pure text input with no prompt return { buttons: [], question: '', isMultiSelect: false, hasTextInput: true, }; } /** * Layer 3: Parse variable interaction (variable assignment type) * * @param variableName - Variable name * @param content - Content after variable * @returns Parse result */ private _layer3ParseVariableInteraction( variableName: string, content: string ): VariableInteractionResult { const shape = this._parseContentShape(content); if (shape.hasTextInput) { if (shape.buttons.length > 0) { // Button group + text input: ?[{{var}} Button1 | Button2 | ...question] return { type: shape.isMultiSelect ? InteractionType.BUTTONS_MULTI_WITH_TEXT : InteractionType.BUTTONS_WITH_TEXT, variable: variableName, buttons: shape.buttons, question: shape.question, isMultiSelect: shape.isMultiSelect, }; } // Pure text input: ?[{{var}}...question] or ?[{{var}}] return { type: InteractionType.TEXT_ONLY, variable: variableName, question: shape.question ?? '', isMultiSelect: false, }; } // Button group or single button: ?[{{var}} Button1 | Button2] return { type: shape.isMultiSelect ? InteractionType.BUTTONS_MULTI_SELECT : InteractionType.BUTTONS_ONLY, variable: variableName, buttons: shape.buttons, isMultiSelect: shape.isMultiSelect, }; } /** * Layer 3: Parse non-assignment interactions (no variable). Same shapes as * the variable branch; the answer is not assigned to a variable. * * @param content - Content * @returns Parse result */ private _layer3ParseDisplayButtons( content: string ): NonAssignmentButtonResult { if (!content) { // Empty content: ?[] return { type: InteractionType.NON_ASSIGNMENT_BUTTON, buttons: [{ display: '', value: '' }], }; } const shape = this._parseContentShape(content); const result: NonAssignmentButtonResult = { type: InteractionType.NON_ASSIGNMENT_BUTTON, buttons: shape.buttons, isMultiSelect: shape.isMultiSelect, }; if (shape.hasTextInput) { result.question = shape.question; } return result; } /** * Parse button group with fault tolerance * * @param content - Button content, separated by | or || * @returns [button list, isMultiSelect] */ private _parseButtons(content: string): [Button[], boolean] { if (!content || typeof content !== 'string') { return [[], false]; } const [_separator, isMultiSelect] = this._detectSeparatorType(content); const buttons: Button[] = []; try { // Use different splitting logic based on separator type let buttonTexts: string[]; if (isMultiSelect) { // Multi-select mode: split on ||, preserve single | buttonTexts = splitUnescaped(content, '||'); } else { // Single-select mode: split on single |, but preserve || buttonTexts = splitOnSingleUnescapedPipe(content); } for (const buttonText of buttonTexts) { const trimmed = trimVariablePadding(buttonText); if (trimmed) { const button = this._parseSingleButton(trimmed); buttons.push(button); } } } catch { // Fallback to treating entire content as single button const whole = trimVariablePadding(unescapeInteractionText(content)); return [[{ display: whole, value: whole }], false]; } // For empty content (like just separators), return empty list if ( !buttons.length && (trimVariablePadding(content) === '||' || trimVariablePadding(content) === '|') ) { return [[], isMultiSelect]; } // Ensure at least one button exists (but only if there's actual content) if (!buttons.length && trimVariablePadding(content)) { const whole = trimVariablePadding(unescapeInteractionText(content)); buttons.push({ display: whole, value: whole }); } return [buttons, isMultiSelect]; } /** * Parse single button, supports Button//value format * * @param buttonText - Button text * @returns {display: display text, value: actual value} */ private _parseSingleButton(buttonText: string): Button { buttonText = trimVariablePadding(buttonText); // Detect Button//value format: split at the first "//" with a non-empty // display before it and a non-empty value after it. (indexOf instead of // a lazy/greedy regex, whose backtracking is super-linear.) const separatorIndex = findUnescaped(buttonText, '//'); if (separatorIndex > 0 && separatorIndex + 2 < buttonText.length) { return { display: trimVariablePadding( unescapeInteractionText(buttonText.slice(0, separatorIndex)) ), value: trimVariablePadding( unescapeInteractionText(buttonText.slice(separatorIndex + 2)) ), }; } const resolved = unescapeInteractionText(buttonText); return { display: resolved, value: resolved }; } /** * Detect separator type and whether it's multi-select * * Logic: The first separator type encountered determines the parsing mode: * - If first separator is |, then || is treated as part of the value * - If first separator is ||, then single | is treated as part of the value * * @param content - Button content to analyze * @returns [separator, isMultiSelect] where separator is '|' or '||' */ private _detectSeparatorType(content: string): [string, boolean] { if (!content || typeof content !== 'string') { return ['|', false]; } // Find the position of first single pipe and first double pipe. // A bar an option escaped is not a separator. const singlePipePos = findUnescaped(content, '|'); const doublePipePos = findUnescaped(content, '||'); // If no pipes found if (singlePipePos === -1) { return ['|', false]; } // If no double pipe found, definitely single-select if (doublePipePos === -1) { return ['|', false]; } // Both found - check which comes first // If double pipe comes first or at the same position (which means // the single pipe is part of the double pipe), it's multi-select mode if (doublePipePos <= singlePipePos) { return ['||', true]; } // If single pipe comes first, it's single-select mode return ['|', false]; } /** * Create error result * * @param errorMessage - Error message * @returns Error result */ private _createErrorResult(errorMessage: string): ErrorResult { return { type: null, error: errorMessage, }; } } /** * Convenience function for parsing interaction format * * Supported formats: * 1. ?[{{var}}...question] - Pure text input * 2. ?[{{var}} option1|option2] - Pure button group (supports display//value format) * 3. ?[{{var}} option1|option2|...question] - Button group + text input * 4. ?[{{var}} option1||option2] - Multi-select button group * 5. ?[{{var}} option1||option2||...question] - Multi-select button group + text input * 6. ?[{{var}} single option] - Single button selection * 7. ?[Continue] or ?[Continue|Cancel] - Non-assignment button * * @param content - Raw content of interaction block * @returns [interaction type, parsed data] */ export function parseInteractionFormat( content: string ): [InteractionType, LegacyReturnData] { // Use new layered parser const parser = new InteractionParser(); const result = parser.parse(content); // Handle parse errors if (result.error) { // Compatibility handling when parsing fails return [ InteractionType.TEXT_ONLY, { question: trimVariablePadding(content) }, ]; } // Extract parse result and convert to original return format const interactionType = result.type; // Build return data dictionary for backward compatibility const returnData: LegacyReturnData = {}; if (result.type !== InteractionType.NON_ASSIGNMENT_BUTTON) { const variableResult = result as VariableInteractionResult; if (variableResult.variable !== undefined) { returnData.variable = variableResult.variable; } if (variableResult.buttons !== undefined) { returnData.buttons = variableResult.buttons; } if (variableResult.question !== undefined) { returnData.question = variableResult.question; } if (variableResult.isMultiSelect !== undefined) { returnData.isMultiSelect = variableResult.isMultiSelect; } } else { const buttonResult = result as NonAssignmentButtonResult; if (buttonResult.buttons !== undefined) { returnData.buttons = buttonResult.buttons; } } // Ensure we have a valid interaction type, fallback to TEXT_ONLY if null const finalType = interactionType || InteractionType.TEXT_ONLY; return [finalType, returnData]; } /** * Factory function to create parser instance */ export function createInteractionParser(): InteractionParser { return new InteractionParser(); }