Skip to content

Commit e212f2e

Browse files
committed
simplify '[before|after]Cursor' as 'aroundCursor'
1 parent 9864196 commit e212f2e

File tree

1 file changed

+17
-27
lines changed

1 file changed

+17
-27
lines changed

codejar.ts

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -237,28 +237,20 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
237237
}
238238
}
239239

240-
function beforeCursor() {
241-
const s = getSelection()
242-
const r0 = s.getRangeAt(0)
243-
const r = document.createRange()
244-
r.selectNodeContents(editor)
245-
r.setEnd(r0.startContainer, r0.startOffset)
246-
return r.toString()
247-
}
248-
249-
function afterCursor() {
250-
const s = getSelection()
251-
const r0 = s.getRangeAt(0)
252-
const r = document.createRange()
253-
r.selectNodeContents(editor)
254-
r.setStart(r0.endContainer, r0.endOffset)
255-
return r.toString()
240+
function aroundCursor() {
241+
let {start, end, dir} = save()
242+
if (dir === '<-') {
243+
[start, end] = [end, start]
244+
}
245+
const text = toString()
246+
const before = text.slice(0, start)
247+
const after = text.slice(end)
248+
return {before, after}
256249
}
257250

258251
function handleNewLine(event: KeyboardEvent) {
259252
if (event.key === 'Enter') {
260-
const before = beforeCursor()
261-
const after = afterCursor()
253+
const {before, after} = aroundCursor()
262254

263255
const [padding] = findPadding(before)
264256
let newLinePadding = padding
@@ -292,7 +284,7 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
292284
if (isLegacy && event.key === 'Enter') {
293285
event.preventDefault()
294286
event.stopPropagation()
295-
if (afterCursor() === '') {
287+
if (aroundCursor().after === '') {
296288
insert('\n ')
297289
const pos = save()
298290
pos.start = --pos.end
@@ -322,7 +314,7 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
322314
if (event.key === 'Tab') {
323315
event.preventDefault()
324316
if (event.shiftKey) {
325-
const before = beforeCursor()
317+
const {before} = aroundCursor()
326318
const [padding, start] = findPadding(before)
327319
if (padding.length > 0) {
328320
const pos = save()
@@ -413,13 +405,11 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
413405
return event.key.toUpperCase()
414406
}
415407

416-
function insert(inserted: string) {
417-
let {start, end} = save()
418-
const text = toString()
419-
const before = text.slice(0, start)
420-
const after = text.slice(end)
421-
editor.textContent = before + inserted + after
422-
start += inserted.length
408+
function insert(text: string) {
409+
let {start} = save()
410+
const {before, after} = aroundCursor()
411+
editor.textContent = before + text + after
412+
start += text.length
423413
restore({start, end: start})
424414
}
425415

0 commit comments

Comments
 (0)