Created
July 1, 2024 13:03
-
-
Save goulvench/d005c2c8b3b038ce2278ebaac9a979e2 to your computer and use it in GitHub Desktop.
Enhance Trix with automatic bullet and number lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// app/javascript/trix_auto_list.js | |
/* | |
Turn lines starting with dashes or stars into bullet lists and lines starting with "1. " into numbered lists. | |
Works within nested lists but skips headings, code blocks and pasted text. | |
*/ | |
document.addEventListener("trix-change", function (event) { | |
const editor = event.target.editor | |
const position = editor.getPosition() | |
if ( | |
position < 2 || | |
editor.attributeIsActive("code") || | |
editor.attributeIsActive("heading1") | |
) { | |
return | |
} | |
let text = editor | |
.getDocument() | |
.toString() | |
.substring(position - 4, position) | |
const bullet = /\n[*-] / | |
const number = /\n1\. / | |
let type, | |
offset = null | |
if (position < 4) { | |
text = "\n" + text | |
} | |
if (bullet.test(text)) { | |
offset = 2 | |
type = "bullet" | |
} else if (number.test(text)) { | |
offset = 3 | |
type = "number" | |
} | |
if (type) { | |
editor.recordUndoEntry("autolist") | |
editor.setSelectedRange([position - offset, position]) | |
editor.deleteInDirection("forward") | |
editor.activateAttribute(type) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment