Skip to content

Commit 85fff39

Browse files
committed
simplify '[before|after]Cursor' as 'aroundCursor'
1 parent de81e23 commit 85fff39

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
@@ -229,28 +229,20 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
229229
}
230230
}
231231

232-
function beforeCursor() {
233-
const s = getSelection()
234-
const r0 = s.getRangeAt(0)
235-
const r = document.createRange()
236-
r.selectNodeContents(editor)
237-
r.setEnd(r0.startContainer, r0.startOffset)
238-
return r.toString()
239-
}
240-
241-
function afterCursor() {
242-
const s = getSelection()
243-
const r0 = s.getRangeAt(0)
244-
const r = document.createRange()
245-
r.selectNodeContents(editor)
246-
r.setStart(r0.endContainer, r0.endOffset)
247-
return r.toString()
232+
function aroundCursor() {
233+
let {start, end, dir} = save()
234+
if (dir === '<-') {
235+
[start, end] = [end, start]
236+
}
237+
const text = toString()
238+
const before = text.slice(0, start)
239+
const after = text.slice(end)
240+
return {before, after}
248241
}
249242

250243
function handleNewLine(event: KeyboardEvent) {
251244
if (event.key === 'Enter') {
252-
const before = beforeCursor()
253-
const after = afterCursor()
245+
const {before, after} = aroundCursor()
254246

255247
const [padding] = findPadding(before)
256248
let newLinePadding = padding
@@ -284,7 +276,7 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
284276
if (isLegacy && event.key === 'Enter') {
285277
event.preventDefault()
286278
event.stopPropagation()
287-
if (afterCursor() === '') {
279+
if (aroundCursor().after === '') {
288280
insert('\n ')
289281
const pos = save()
290282
pos.start = --pos.end
@@ -314,7 +306,7 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
314306
if (event.key === 'Tab') {
315307
event.preventDefault()
316308
if (event.shiftKey) {
317-
const before = beforeCursor()
309+
const {before} = aroundCursor()
318310
const [padding, start] = findPadding(before)
319311
if (padding.length > 0) {
320312
const pos = save()
@@ -405,13 +397,11 @@ export function CodeJar(editor: HTMLElement, highlight: (e: HTMLElement, pos?: P
405397
return event.key.toUpperCase()
406398
}
407399

408-
function insert(inserted: string) {
409-
let {start, end} = save()
410-
const text = toString()
411-
const before = text.slice(0, start)
412-
const after = text.slice(end)
413-
editor.textContent = before + inserted + after
414-
start += inserted.length
400+
function insert(text: string) {
401+
let {start} = save()
402+
const {before, after} = aroundCursor()
403+
editor.textContent = before + text + after
404+
start += text.length
415405
restore({start, end: start})
416406
}
417407

0 commit comments

Comments
 (0)