import * as Mdast from "mdast-util-from-markdown" ; import { markdownLineEnding } from "micromark-util-character" ; import { codes } from "micromark-util-symbol/codes.js" ; import * as Micromark from "micromark-util-types" ; import { Processor } from "unified" ; import processor from "../processor" ; import { clozeNodeType , ClozePromptNode } from "./index" ; const clozeToken = "clozePrompt" ; const clozeMarkerToken = "clozePromptMarker" ; const clozeChunkToken = "clozePromptChunk" ; const micromarkClozeExtension = { text : { [ codes . leftCurlyBrace ] : { tokenize } } , } ; function tokenize ( this , effects , ok , nok ) { const self = this ; const eventStart = this . events . length + 3 ; let balance = 1 ; return atOpeningBrace ; function atOpeningBrace ( code ) { effects . enter ( clozeToken ) ; effects . enter ( clozeMarkerToken ) ; effects . consume ( code ) ; effects . exit ( clozeMarkerToken ) ; effects . enter ( clozeChunkToken ) ; return inside ; } function inside ( code ) { if ( code === codes . eof || markdownLineEnding ( code ) ) { return nok ; } else if ( code === codes . rightCurlyBrace ) { effects . exit ( clozeChunkToken ) ; return atClosingBrace ( code ) ; } else if ( code === codes . leftCurlyBrace ) { effects . consume ( code ) ; balance ++ ; return inside ; } else { effects . consume ( code ) ; return inside ; } } function atClosingBrace ( code ) { balance -- ; if ( balance ) { effects . enter ( clozeChunkToken ) ; effects . consume ( code ) ; return inside ; } else { effects . enter ( clozeMarkerToken ) ; effects . consume ( code ) ; effects . exit ( clozeMarkerToken ) ; effects . exit ( clozeToken ) ; return ok ; } } } export default function clozePlugin ( this ) { const data = this . data ( ) ; if ( ! data . toMarkdownExtensions ) { data . toMarkdownExtensions = [ ] ; } ( data . toMarkdownExtensions as any [ ] ) . push ( { handlers : { [ clozeNodeType ] : clozePromptCompiler , } , } ) ; if ( ! data . micromarkExtensions ) { data . micromarkExtensions = [ ] ; } ( data . micromarkExtensions as any [ ] ) . push ( micromarkClozeExtension ) ; if ( ! data . fromMarkdownExtensions ) { data . fromMarkdownExtensions = [ ] ; } ( data . fromMarkdownExtensions as any [ ] ) . push ( { enter : { [ clozeToken ] : enterClozeNode , [ clozeChunkToken ] : enterClozeNodeData , } , exit : { [ clozeToken ] : exitClozeNode , [ clozeChunkToken ] : exitClozeNodeData , } , } ) ; } function enterClozeNode ( this , token ) { this . enter ( { type : clozeNodeType , children : [ ] } as any , token ) ; } function exitClozeNode ( this , token ) { this . exit ( token ) ; } function enterClozeNodeData ( this , token ) { this . config . enter . data . call ( this , token ) ; } function exitClozeNodeData ( this , token ) { this . config . exit . data . call ( this , token ) ; } function clozePromptCompiler ( node ) { const result = processor . stringify ( { ... node , type : "emphasis" } ) as string ; return `{${ result . slice ( 1 , - 2 ) }}` ; }