import type MarkdownIt from 'markdown-it'; import type Core from 'markdown-it/lib/parser_core'; import type StateCore from 'markdown-it/lib/rules_core/state_core'; import type Token from 'markdown-it/lib/token'; // eslint-disable-next-line no-useless-escape export const pattern = /^\[(X|\s|\_|\-)\]\s(.*)/i; export const CheckboxTokenType = { Checkbox: 'checkbox', CheckboxOpen: 'checkbox_open', CheckboxClose: 'checkbox_close', CheckboxInput: 'checkbox_input', CheckboxLabel: 'checkbox_label', CheckboxLabelOpen: 'checkbox_label_open', CheckboxLabelClose: 'checkbox_label_close', } as const; type ParsedCheckbox = { tokens: Token[]; content: string; startLine: number; endLine: number; checked: boolean; }; type ContentLine = { tokens: Token[]; content: string; }; function matchOpenToken(tokens: Token[], i: number) { if (tokens[i].type !== 'paragraph_open' || tokens[i + 1].type !== 'inline') { return false; } const firstInline = tokens[i + 1].children?.[0]; return firstInline?.type === 'text' && pattern.test(firstInline.content); } export type CheckboxOptions = { idPrefix?: string; divClass?: string; /** @default true */ disabled?: boolean; }; export const checkboxReplace = function (_md: MarkdownIt, opts?: CheckboxOptions): Core.RuleCore { let lastId = 0; const defaults: Required = { divClass: 'checkbox', idPrefix: 'checkbox', disabled: true, }; const options = Object.assign(defaults, opts); const createTokens = function (state: StateCore, checkbox: ParsedCheckbox): Token[] { let token: Token; const nodes: Token[] = []; /** *
*/ token = new state.Token(CheckboxTokenType.CheckboxOpen, 'div', 1); token.block = true; token.map = [checkbox.startLine, checkbox.endLine]; token.attrs = [['class', options.divClass]]; nodes.push(token); /** * */ const id = options.idPrefix + lastId; lastId += 1; token = new state.Token(CheckboxTokenType.CheckboxInput, 'input', 0); token.block = true; token.map = [checkbox.startLine, checkbox.endLine]; token.attrs = [ ['type', 'checkbox'], ['id', id], ]; if (options.disabled) { token.attrSet('disabled', ''); } if (checkbox.checked === true) { token.attrSet('checked', 'true'); } nodes.push(token); /** *