Skip to content

Commit

Permalink
implement and use selectionchange
Browse files Browse the repository at this point in the history
related #1522
  • Loading branch information
jhchen committed Jul 4, 2017
1 parent fbb81f5 commit f269276
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
28 changes: 28 additions & 0 deletions core/emitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,45 @@ import logger from './logger';

let debug = logger('quill:events');

const EVENTS = ['selectionchange'];

EVENTS.forEach(function(eventName) {
document.addEventListener(eventName, (...args) => {
document.querySelectorAll('.ql-container').forEach((node) => {
// TODO use WeakMap
if (node.__quill && node.__quill.emitter) {
node.__quill.emitter.handleDOM(...args);
}
});
});
});

class Emitter extends EventEmitter {
constructor() {
super();
this.listeners = {};
this.on('error', debug.error);
}

emit() {
debug.log.apply(debug, arguments);
super.emit.apply(this, arguments);
}

handleDOM(...args) {
(this.listeners[event.type] || []).forEach(function({ node, handler }) {
if (event.target === node) {
handler(...args);
}
});
}

listenDOM(eventName, node, handler) {
if (!this.listeners[eventName]) {
this.listeners[eventName] = [];
}
this.listeners[eventName].push({ node, handler })
}
}

Emitter.events = {
Expand Down
10 changes: 3 additions & 7 deletions core/selection.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,6 @@ class Selection {
this.cursor = Parchment.create('cursor', this);
// savedRange is last non-null range
this.lastRange = this.savedRange = new Range(0, 0);
['keyup', 'mouseup', 'mouseleave', 'touchend', 'touchleave', 'focus', 'blur'].forEach((eventName) => {
this.root.addEventListener(eventName, () => {
// When range used to be a selection and user click within the selection,
// the range now being a cursor has not updated yet without setTimeout
setTimeout(this.update.bind(this, Emitter.sources.USER), 100);
});
});
this.root.addEventListener('click', (e) => {
const blot = Parchment.find(e.target, true);
const selectedNode = document.querySelector('.ql-embed-selected');
Expand All @@ -51,6 +44,9 @@ class Selection {
e.stopPropagation();
}
});
this.emitter.listenDOM('selectionchange', document, () => {
this.update(Emitter.sources.USER);
});
this.emitter.on(Emitter.events.EDITOR_CHANGE, (type, delta) => {
if (type === Emitter.events.TEXT_CHANGE && delta.length() > 0) {
this.update(Emitter.sources.SILENT);
Expand Down

0 comments on commit f269276

Please sign in to comment.