Skip to content

Commit 864dc63

Browse files
committed
feat(switch): improve switch event
1 parent 957b62c commit 864dc63

File tree

2 files changed

+34
-18
lines changed

2 files changed

+34
-18
lines changed

src/cursor.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,26 @@ export default class Cursor {
4545
)
4646
}
4747

48+
isAtLastLine () {
49+
const range = rangy.createRange()
50+
range.selectNodeContents(this.host)
51+
52+
const hostCoords = range.nativeRange.getBoundingClientRect()
53+
const cursorCoords = this.range.nativeRange.getBoundingClientRect()
54+
55+
return hostCoords.bottom === cursorCoords.bottom
56+
}
57+
58+
isAtFirstLine () {
59+
const range = rangy.createRange()
60+
range.selectNodeContents(this.host)
61+
62+
const hostCoords = range.nativeRange.getBoundingClientRect()
63+
const cursorCoords = this.range.nativeRange.getBoundingClientRect()
64+
65+
return hostCoords.top === cursorCoords.top
66+
}
67+
4868
isAtBeginning () {
4969
return parser.isBeginningOfHost(
5070
this.host,

src/dispatcher.js

Lines changed: 14 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -168,14 +168,18 @@ export default class Dispatcher {
168168

169169
const cursor = this.selectionWatcher.getSelection()
170170
if (!cursor || cursor.isSelection) return
171-
// Detect if the browser moved the cursor in the next tick.
172-
// If the cursor stays at its position, fire the switch event.
173-
setTimeout(() => {
174-
var newCursor = this.selectionWatcher.forceCursor()
175-
if (newCursor.equals(cursor)) {
176-
this.notify('switch', element, direction, newCursor)
177-
}
178-
})
171+
172+
if (direction === 'up' && cursor.isAtFirstLine()) {
173+
event.preventDefault()
174+
event.stopPropagation()
175+
this.notify('switch', element, direction, cursor)
176+
}
177+
178+
if (direction === 'down' && cursor.isAtLastLine()) {
179+
event.preventDefault()
180+
event.stopPropagation()
181+
this.notify('switch', element, direction, cursor)
182+
}
179183
}
180184

181185
/**
@@ -204,19 +208,11 @@ export default class Dispatcher {
204208

205209
this.keyboard
206210
.on('up', function (event) {
207-
self.dispatchSwitchEvent(event, this, 'before')
208-
})
209-
210-
.on('left', function (event) {
211-
self.dispatchSwitchEvent(event, this, 'before')
212-
})
213-
214-
.on('right', function (event) {
215-
self.dispatchSwitchEvent(event, this, 'after')
211+
self.dispatchSwitchEvent(event, this, 'up')
216212
})
217213

218214
.on('down', function (event) {
219-
self.dispatchSwitchEvent(event, this, 'after')
215+
self.dispatchSwitchEvent(event, this, 'down')
220216
})
221217

222218
.on('backspace', function (event) {

0 commit comments

Comments
 (0)