checklistPlugin.js (1345B)
1 import { ViewPlugin } from '@codemirror/view'; 2 import { toggleChecklistLine, isChecklistLine } from './editorUtils.js'; 3 4 export function checklistPlugin(getReadOnly) { 5 return ViewPlugin.fromClass( 6 class { 7 constructor(view) { 8 this.view = view; 9 this.getReadOnly = getReadOnly; 10 this.onMouseDown = this.onMouseDown.bind(this); 11 view.dom.addEventListener('mousedown', this.onMouseDown); 12 } 13 14 onMouseDown(event) { 15 if (this.getReadOnly()) return; 16 17 const pos = this.view.posAtCoords({ x: event.clientX, y: event.clientY }); 18 if (pos == null) return; 19 20 const line = this.view.state.doc.lineAt(pos); 21 if (!isChecklistLine(line.text)) return; 22 23 const bracketStart = line.text.indexOf('['); 24 const bracketEnd = line.text.indexOf(']', bracketStart); 25 if (bracketStart < 0 || bracketEnd < 0) return; 26 27 const clickStart = pos - line.from; 28 if (clickStart < bracketStart || clickStart > bracketEnd + 1) return; 29 30 event.preventDefault(); 31 const nextLine = toggleChecklistLine(line.text); 32 this.view.dispatch({ 33 changes: { from: line.from, to: line.to, insert: nextLine }, 34 }); 35 } 36 37 destroy() { 38 this.view.dom.removeEventListener('mousedown', this.onMouseDown); 39 } 40 }, 41 ); 42 }