garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/lists.ts

raw

/**
 * Enter in a message box on a list's line, as a notes app has it: the next
 * line starts with the next bullet (`- `, `* `, `+ `, or the next number),
 * indented as this one; Enter on a bullet with nothing after it ends the list,
 * taking the bullet away. `null` when the line is no list item: the box's own
 * new line is right then.
 */
export function continueList(text: string, at: number, end = at): {text: string; at: number} | null {
    const start = text.lastIndexOf('\n', at - 1) + 1
    const line = text.slice(start, at)
    const item = line.match(/^(\s*)([-*+]|(\d+)([.)]))(\s+)(.*)$/)
    if (!item) return null
    const [, indent, bullet, num, sep, gap, rest] = item
    // An empty item: Enter ends the list, leaving the line blank.
    if (!rest.trim() && end === at && !text.slice(at).split('\n')[0].trim())
        return {text: text.slice(0, start) + text.slice(at), at: start}
    const next = `\n${indent}${num ? `${Number(num) + 1}${sep}` : bullet}${gap}`
    return {text: text.slice(0, at) + next + text.slice(end), at: at + next.length}
}