🎨 Modify the rendering logic of the checkbox

This commit is contained in:
2025-09-21 01:14:33 +08:00
parent d597f379ff
commit e372a0dd7c

View File

@@ -63,12 +63,12 @@ function findCheckboxes(view: EditorView) {
const matchPos = from + match.index const matchPos = from + match.index
const matchEnd = matchPos + match[0].length const matchEnd = matchPos + match[0].length
// 检查前是否有合适的空格或行首 // 检查前是否有 "- " 模式
const beforeChar = matchPos > 0 ? doc.sliceString(matchPos - 1, matchPos) : "" const beforeTwoChars = matchPos >= 2 ? doc.sliceString(matchPos - 2, matchPos) : ""
const afterChar = matchEnd < doc.length ? doc.sliceString(matchEnd, matchEnd + 1) : "" const afterChar = matchEnd < doc.length ? doc.sliceString(matchEnd, matchEnd + 1) : ""
// 只在行首或空格后,且后面跟空格或行尾时才渲染 // 只有当前面是 "- " 且后面跟空格或行尾时才渲染
if ((beforeChar === "" || beforeChar === " " || beforeChar === "\t" || beforeChar === "\n") && if (beforeTwoChars === "- " &&
(afterChar === "" || afterChar === " " || afterChar === "\t" || afterChar === "\n")) { (afterChar === "" || afterChar === " " || afterChar === "\t" || afterChar === "\n")) {
const isChecked = match[1].toLowerCase() === "x" const isChecked = match[1].toLowerCase() === "x"
@@ -76,7 +76,8 @@ function findCheckboxes(view: EditorView) {
widget: new CheckboxWidget(isChecked), widget: new CheckboxWidget(isChecked),
inclusive: false, inclusive: false,
}) })
widgets.push(deco.range(matchPos, matchEnd)) // 替换整个 "- [ ]" 或 "- [x]" 模式,包括前面的 "- "
widgets.push(deco.range(matchPos - 2, matchEnd))
} }
} }
} }
@@ -90,17 +91,23 @@ function findCheckboxes(view: EditorView) {
function toggleCheckbox(view: EditorView, pos: number) { function toggleCheckbox(view: EditorView, pos: number) {
const doc = view.state.doc const doc = view.state.doc
// 查找当前位置附近的复选框模式 // 查找当前位置附近的复选框模式(需要前面有 "- "
for (let offset = -3; offset <= 0; offset++) { for (let offset = -5; offset <= 0; offset++) {
const checkPos = pos + offset const checkPos = pos + offset
if (checkPos >= 0 && checkPos + 3 <= doc.length) { if (checkPos >= 2 && checkPos + 3 <= doc.length) {
// 检查是否有 "- " 前缀
const prefix = doc.sliceString(checkPos - 2, checkPos)
const text = doc.sliceString(checkPos, checkPos + 3).toLowerCase() const text = doc.sliceString(checkPos, checkPos + 3).toLowerCase()
if (prefix === "- ") {
let change let change
if (text === "[x]") { if (text === "[x]") {
change = { from: checkPos, to: checkPos + 3, insert: "[ ]" } // 替换整个 "- [x]" 为 "- [ ]"
change = { from: checkPos - 2, to: checkPos + 3, insert: "- [ ]" }
} else if (text === "[ ]") { } else if (text === "[ ]") {
change = { from: checkPos, to: checkPos + 3, insert: "[x]" } // 替换整个 "- [ ]" 为 "- [x]"
change = { from: checkPos - 2, to: checkPos + 3, insert: "- [x]" }
} }
if (change) { if (change) {
@@ -109,6 +116,7 @@ function toggleCheckbox(view: EditorView, pos: number) {
} }
} }
} }
}
return false return false
} }