1
0
mirror of https://github.com/osmarks/mycorrhiza.git synced 2024-10-30 11:46:16 +00:00

Merge pull request #88 from chekoopa/better-text-actions

Make text decorations toggleable, like Github's
This commit is contained in:
Umar Getagazov 2021-08-22 13:49:13 +07:00 committed by GitHub
commit da90edcb63
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -5,6 +5,11 @@ function placeCursor(position, el = editTextarea) {
el.selectionStart = el.selectionEnd
}
function selectRange(left, right, el = editTextarea) {
el.selectionEnd = right
el.selectionStart = left
}
function getSelectedText(el = editTextarea) {
const [start, end] = [el.selectionStart, el.selectionEnd]
const text = el.value
@ -26,15 +31,35 @@ function textInserter(text, cursorPosition = null, el = editTextarea) {
function selectionWrapper(cursorPosition, prefix, postfix = null, el = editTextarea) {
return function() {
const [start, end] = [el.selectionStart, el.selectionEnd]
let [start, end] = [el.selectionStart, el.selectionEnd]
if (postfix == null) {
postfix = prefix
}
let text = getSelectedText(el)
let result = prefix + text + postfix
let removing = false
let result
if (text.startsWith(prefix) && text.endsWith(postfix)) {
// selection is decorated, so we just cut it
removing = true
result = text.substring(cursorPosition, text.length - cursorPosition)
} else if ( (prefix == el.value.slice(start-cursorPosition, start)) &&
(postfix == el.value.slice(end, end+cursorPosition)) ) {
// selection is surrounded by decorations
removing = true
result = text
start -= cursorPosition
end += cursorPosition
} else {
// no decorations, so we add them
result = prefix + text + postfix
}
el.setRangeText(result, start, end, 'select')
el.focus()
placeCursor(end + cursorPosition)
if (removing) {
selectRange(start, end-cursorPosition*2)
} else {
selectRange(start+cursorPosition, end+cursorPosition)
}
}
}