import MarkdownIt from "markdown-it" ; import Token from "markdown-it/lib/token" ; function attrSet ( token , name , value ) { const index = token . attrIndex ( name ) ; const attr = [ name , value ] ; if ( index < 0 ) { token . attrPush ( attr ) ; } else if ( token . attrs != null ) { token . attrs [ index ] = attr ; } } function parentToken ( tokens , index ) { const targetLevel = tokens [ index ] . level - 1 ; for ( let i = index - 1 ; i >= 0 ; i -- ) { if ( tokens [ i ] . level === targetLevel ) { return i ; } } return - 1 ; } function isInline ( token ) { return token . type === "inline" ; } function isParagraph ( token ) { return token . type === "paragraph_open" ; } function isListItem ( token ) { return token . type === "list_item_open" ; } function startsWithTodoMarkdown ( token ) { return ( token . content . indexOf ( "[ ] " ) === 0 || token . content . indexOf ( "[x] " ) === 0 || token . content . indexOf ( "[X] " ) === 0 ) ; } function isTodoItem ( tokens , index ) { return ( isInline ( tokens [ index ] ) && isParagraph ( tokens [ index - 1 ] ) && isListItem ( tokens [ index - 2 ] ) && startsWithTodoMarkdown ( tokens [ index ] ) ) ; } const markdownItTasklist = function ( md ) { md . core . ruler . after ( "inline" , "gfm-tasklists" , function ( state ) { const tokens = state . tokens ; for ( let i = 2 ; i < tokens . length ; i ++ ) { if ( isTodoItem ( tokens , i ) ) { const token = tokens [ i ] ; const checked = ! token . content . startsWith ( "[ ]" ) ; if ( token . children != null ) { token . children [ 0 ] . content = token . children [ 0 ] . content . slice ( 3 ) ; } const li = tokens [ i - 2 ] ; attrSet ( li , "class" , "task-list-item" ) ; attrSet ( li , "checked" , checked ? "true" : "false" ) ; if ( li . map != null ) { attrSet ( li , "startline" , li . map [ 0 ] . toString ( ) ) ; attrSet ( li , "endline" , li . map [ 1 ] . toString ( ) ) ; } attrSet ( tokens [ parentToken ( tokens , i - 2 ) ] , "class" , "task-list" ) ; } } return true ; } ) ; } ; export default markdownItTasklist ;