mirror of
https://github.com/osmarks/mycorrhiza.git
synced 2025-06-02 11:14:05 +00:00
Make text decorations toggleable, like Github's
This commit is contained in:
parent
15415e44ff
commit
ba6a444063
@ -5,6 +5,11 @@ function placeCursor(position, el = editTextarea) {
|
|||||||
el.selectionStart = el.selectionEnd
|
el.selectionStart = el.selectionEnd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function selectRange(left, right, el = editTextarea) {
|
||||||
|
el.selectionEnd = right
|
||||||
|
el.selectionStart = left
|
||||||
|
}
|
||||||
|
|
||||||
function getSelectedText(el = editTextarea) {
|
function getSelectedText(el = editTextarea) {
|
||||||
const [start, end] = [el.selectionStart, el.selectionEnd]
|
const [start, end] = [el.selectionStart, el.selectionEnd]
|
||||||
const text = el.value
|
const text = el.value
|
||||||
@ -26,15 +31,35 @@ function textInserter(text, cursorPosition = null, el = editTextarea) {
|
|||||||
|
|
||||||
function selectionWrapper(cursorPosition, prefix, postfix = null, el = editTextarea) {
|
function selectionWrapper(cursorPosition, prefix, postfix = null, el = editTextarea) {
|
||||||
return function() {
|
return function() {
|
||||||
const [start, end] = [el.selectionStart, el.selectionEnd]
|
let [start, end] = [el.selectionStart, el.selectionEnd]
|
||||||
if (postfix == null) {
|
if (postfix == null) {
|
||||||
postfix = prefix
|
postfix = prefix
|
||||||
}
|
}
|
||||||
let text = getSelectedText(el)
|
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.setRangeText(result, start, end, 'select')
|
||||||
el.focus()
|
el.focus()
|
||||||
placeCursor(end + cursorPosition)
|
if (removing) {
|
||||||
|
selectRange(start, end-cursorPosition*2)
|
||||||
|
} else {
|
||||||
|
selectRange(start+cursorPosition, end+cursorPosition)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user