Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify SelectionChangeObserver update logic #1095

Merged
merged 3 commits into from
Oct 3, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 4 additions & 34 deletions src/trix/observers/selection_change_observer.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,16 @@
/* eslint-disable
id-length,
*/
import BasicObject from "trix/core/basic_object"

export default class SelectionChangeObserver extends BasicObject {
constructor() {
super(...arguments)
this.update = this.update.bind(this)
this.run = this.run.bind(this)
this.selectionManagers = []
}

start() {
if (!this.started) {
this.started = true
if ("onselectionchange" in document) {
return document.addEventListener("selectionchange", this.update, true)
} else {
return this.run()
}
document.addEventListener("selectionchange", this.update, true)
}
}

Expand All @@ -37,7 +29,7 @@ export default class SelectionChangeObserver extends BasicObject {
}

unregisterSelectionManager(selectionManager) {
this.selectionManagers = this.selectionManagers.filter((s) => s !== selectionManager)
this.selectionManagers = this.selectionManagers.filter((sm) => sm !== selectionManager)
if (this.selectionManagers.length === 0) {
return this.stop()
}
Expand All @@ -48,36 +40,14 @@ export default class SelectionChangeObserver extends BasicObject {
}

update() {
const domRange = getDOMRange()
const caretMove = window.getSelection().type === "Caret"

if (!domRangesAreEqual(domRange, this.domRange) || caretMove) {
this.domRange = domRange
return this.notifySelectionManagersOfSelectionChange()
}
this.notifySelectionManagersOfSelectionChange()
}

reset() {
this.domRange = null
return this.update()
}

// Private

run() {
if (this.started) {
this.update()
return requestAnimationFrame(this.run)
}
this.update()
}
}

const domRangesAreEqual = (left, right) =>
left?.startContainer === right?.startContainer &&
left?.startOffset === right?.startOffset &&
left?.endContainer === right?.endContainer &&
left?.endOffset === right?.endOffset

export const selectionChangeObserver = new SelectionChangeObserver()

export const getDOMSelection = function() {
Expand Down