selection.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import Parchment from 'parchment';
  2. import clone from 'clone';
  3. import equal from 'deep-equal';
  4. import Emitter from './emitter';
  5. import logger from './logger';
  6. let debug = logger('quill:selection');
  7. class Range {
  8. constructor(index, length = 0) {
  9. this.index = index;
  10. this.length = length;
  11. }
  12. }
  13. class Selection {
  14. constructor(scroll, emitter) {
  15. this.emitter = emitter;
  16. this.scroll = scroll;
  17. this.composing = false;
  18. this.mouseDown = false;
  19. this.root = this.scroll.domNode;
  20. this.cursor = Parchment.create('cursor', this);
  21. // savedRange is last non-null range
  22. this.lastRange = this.savedRange = new Range(0, 0);
  23. this.handleComposition();
  24. this.handleDragging();
  25. this.emitter.listenDOM('selectionchange', document, () => {
  26. if (!this.mouseDown) {
  27. setTimeout(this.update.bind(this, Emitter.sources.USER), 1);
  28. }
  29. });
  30. this.emitter.on(Emitter.events.EDITOR_CHANGE, (type, delta) => {
  31. if (type === Emitter.events.TEXT_CHANGE && delta.length() > 0) {
  32. this.update(Emitter.sources.SILENT);
  33. }
  34. });
  35. this.emitter.on(Emitter.events.SCROLL_BEFORE_UPDATE, () => {
  36. if (!this.hasFocus()) return;
  37. let native = this.getNativeRange();
  38. if (native == null) return;
  39. if (native.start.node === this.cursor.textNode) return; // cursor.restore() will handle
  40. // TODO unclear if this has negative side effects
  41. this.emitter.once(Emitter.events.SCROLL_UPDATE, () => {
  42. try {
  43. this.setNativeRange(native.start.node, native.start.offset, native.end.node, native.end.offset);
  44. } catch (ignored) {}
  45. });
  46. });
  47. this.emitter.on(Emitter.events.SCROLL_OPTIMIZE, (mutations, context) => {
  48. if (context.range) {
  49. const { startNode, startOffset, endNode, endOffset } = context.range;
  50. this.setNativeRange(startNode, startOffset, endNode, endOffset);
  51. }
  52. });
  53. this.update(Emitter.sources.SILENT);
  54. }
  55. handleComposition() {
  56. this.root.addEventListener('compositionstart', () => {
  57. this.composing = true;
  58. });
  59. this.root.addEventListener('compositionend', () => {
  60. this.composing = false;
  61. if (this.cursor.parent) {
  62. const range = this.cursor.restore();
  63. if (!range) return;
  64. setTimeout(() => {
  65. this.setNativeRange(range.startNode, range.startOffset, range.endNode, range.endOffset);
  66. }, 1);
  67. }
  68. });
  69. }
  70. handleDragging() {
  71. this.emitter.listenDOM('mousedown', document.body, () => {
  72. this.mouseDown = true;
  73. });
  74. this.emitter.listenDOM('mouseup', document.body, () => {
  75. this.mouseDown = false;
  76. this.update(Emitter.sources.USER);
  77. });
  78. }
  79. focus() {
  80. if (this.hasFocus()) return;
  81. this.root.focus();
  82. this.setRange(this.savedRange);
  83. }
  84. format(format, value) {
  85. if (this.scroll.whitelist != null && !this.scroll.whitelist[format]) return;
  86. this.scroll.update();
  87. let nativeRange = this.getNativeRange();
  88. if (nativeRange == null || !nativeRange.native.collapsed || Parchment.query(format, Parchment.Scope.BLOCK)) return;
  89. if (nativeRange.start.node !== this.cursor.textNode) {
  90. let blot = Parchment.find(nativeRange.start.node, false);
  91. if (blot == null) return;
  92. // TODO Give blot ability to not split
  93. if (blot instanceof Parchment.Leaf) {
  94. let after = blot.split(nativeRange.start.offset);
  95. blot.parent.insertBefore(this.cursor, after);
  96. } else {
  97. blot.insertBefore(this.cursor, nativeRange.start.node); // Should never happen
  98. }
  99. this.cursor.attach();
  100. }
  101. this.cursor.format(format, value);
  102. this.scroll.optimize();
  103. this.setNativeRange(this.cursor.textNode, this.cursor.textNode.data.length);
  104. this.update();
  105. }
  106. getBounds(index, length = 0) {
  107. let scrollLength = this.scroll.length();
  108. index = Math.min(index, scrollLength - 1);
  109. length = Math.min(index + length, scrollLength - 1) - index;
  110. let node, [leaf, offset] = this.scroll.leaf(index);
  111. if (leaf == null) return null;
  112. [node, offset] = leaf.position(offset, true);
  113. let range = document.createRange();
  114. if (length > 0) {
  115. range.setStart(node, offset);
  116. [leaf, offset] = this.scroll.leaf(index + length);
  117. if (leaf == null) return null;
  118. [node, offset] = leaf.position(offset, true);
  119. range.setEnd(node, offset);
  120. return range.getBoundingClientRect();
  121. } else {
  122. let side = 'left';
  123. let rect;
  124. if (node instanceof Text) {
  125. if (offset < node.data.length) {
  126. range.setStart(node, offset);
  127. range.setEnd(node, offset + 1);
  128. } else {
  129. range.setStart(node, offset - 1);
  130. range.setEnd(node, offset);
  131. side = 'right';
  132. }
  133. rect = range.getBoundingClientRect();
  134. } else {
  135. rect = leaf.domNode.getBoundingClientRect();
  136. if (offset > 0) side = 'right';
  137. }
  138. return {
  139. bottom: rect.top + rect.height,
  140. height: rect.height,
  141. left: rect[side],
  142. right: rect[side],
  143. top: rect.top,
  144. width: 0
  145. };
  146. }
  147. }
  148. getNativeRange() {
  149. let selection = document.getSelection();
  150. if (selection == null || selection.rangeCount <= 0) return null;
  151. let nativeRange = selection.getRangeAt(0);
  152. if (nativeRange == null) return null;
  153. let range = this.normalizeNative(nativeRange);
  154. debug.info('getNativeRange', range);
  155. return range;
  156. }
  157. getRange() {
  158. let normalized = this.getNativeRange();
  159. if (normalized == null) return [null, null];
  160. let range = this.normalizedToRange(normalized);
  161. return [range, normalized];
  162. }
  163. hasFocus() {
  164. return document.activeElement === this.root;
  165. }
  166. normalizedToRange(range) {
  167. let positions = [[range.start.node, range.start.offset]];
  168. if (!range.native.collapsed) {
  169. positions.push([range.end.node, range.end.offset]);
  170. }
  171. let indexes = positions.map((position) => {
  172. let [node, offset] = position;
  173. let blot = Parchment.find(node, true);
  174. let index = blot.offset(this.scroll);
  175. if (offset === 0) {
  176. return index;
  177. } else if (blot instanceof Parchment.Container) {
  178. return index + blot.length();
  179. } else {
  180. return index + blot.index(node, offset);
  181. }
  182. });
  183. let end = Math.min(Math.max(...indexes), this.scroll.length() - 1);
  184. let start = Math.min(end, ...indexes);
  185. return new Range(start, end-start);
  186. }
  187. normalizeNative(nativeRange) {
  188. if (!contains(this.root, nativeRange.startContainer) ||
  189. (!nativeRange.collapsed && !contains(this.root, nativeRange.endContainer))) {
  190. return null;
  191. }
  192. let range = {
  193. start: { node: nativeRange.startContainer, offset: nativeRange.startOffset },
  194. end: { node: nativeRange.endContainer, offset: nativeRange.endOffset },
  195. native: nativeRange
  196. };
  197. [range.start, range.end].forEach(function(position) {
  198. let node = position.node, offset = position.offset;
  199. while (!(node instanceof Text) && node.childNodes.length > 0) {
  200. if (node.childNodes.length > offset) {
  201. node = node.childNodes[offset];
  202. offset = 0;
  203. } else if (node.childNodes.length === offset) {
  204. node = node.lastChild;
  205. offset = node instanceof Text ? node.data.length : node.childNodes.length + 1;
  206. } else {
  207. break;
  208. }
  209. }
  210. position.node = node, position.offset = offset;
  211. });
  212. return range;
  213. }
  214. rangeToNative(range) {
  215. let indexes = range.collapsed ? [range.index] : [range.index, range.index + range.length];
  216. let args = [];
  217. let scrollLength = this.scroll.length();
  218. indexes.forEach((index, i) => {
  219. index = Math.min(scrollLength - 1, index);
  220. let node, [leaf, offset] = this.scroll.leaf(index);
  221. [node, offset] = leaf.position(offset, i !== 0);
  222. args.push(node, offset);
  223. });
  224. if (args.length < 2) {
  225. args = args.concat(args);
  226. }
  227. return args;
  228. }
  229. scrollIntoView(scrollingContainer) {
  230. let range = this.lastRange;
  231. if (range == null) return;
  232. let bounds = this.getBounds(range.index, range.length);
  233. if (bounds == null) return;
  234. let limit = this.scroll.length()-1;
  235. let [first, ] = this.scroll.line(Math.min(range.index, limit));
  236. let last = first;
  237. if (range.length > 0) {
  238. [last, ] = this.scroll.line(Math.min(range.index + range.length, limit));
  239. }
  240. if (first == null || last == null) return;
  241. let scrollBounds = scrollingContainer.getBoundingClientRect();
  242. if (bounds.top < scrollBounds.top) {
  243. scrollingContainer.scrollTop -= (scrollBounds.top - bounds.top);
  244. } else if (bounds.bottom > scrollBounds.bottom) {
  245. scrollingContainer.scrollTop += (bounds.bottom - scrollBounds.bottom);
  246. }
  247. }
  248. setNativeRange(startNode, startOffset, endNode = startNode, endOffset = startOffset, force = false) {
  249. debug.info('setNativeRange', startNode, startOffset, endNode, endOffset);
  250. if (startNode != null && (this.root.parentNode == null || startNode.parentNode == null || endNode.parentNode == null)) {
  251. return;
  252. }
  253. let selection = document.getSelection();
  254. if (selection == null) return;
  255. if (startNode != null) {
  256. if (!this.hasFocus()) this.root.focus();
  257. let native = (this.getNativeRange() || {}).native;
  258. if (native == null || force ||
  259. startNode !== native.startContainer ||
  260. startOffset !== native.startOffset ||
  261. endNode !== native.endContainer ||
  262. endOffset !== native.endOffset) {
  263. if (startNode.tagName == "BR") {
  264. startOffset = [].indexOf.call(startNode.parentNode.childNodes, startNode);
  265. startNode = startNode.parentNode;
  266. }
  267. if (endNode.tagName == "BR") {
  268. endOffset = [].indexOf.call(endNode.parentNode.childNodes, endNode);
  269. endNode = endNode.parentNode;
  270. }
  271. let range = document.createRange();
  272. range.setStart(startNode, startOffset);
  273. range.setEnd(endNode, endOffset);
  274. selection.removeAllRanges();
  275. selection.addRange(range);
  276. }
  277. } else {
  278. selection.removeAllRanges();
  279. this.root.blur();
  280. document.body.focus(); // root.blur() not enough on IE11+Travis+SauceLabs (but not local VMs)
  281. }
  282. }
  283. setRange(range, force = false, source = Emitter.sources.API) {
  284. if (typeof force === 'string') {
  285. source = force;
  286. force = false;
  287. }
  288. debug.info('setRange', range);
  289. if (range != null) {
  290. let args = this.rangeToNative(range);
  291. this.setNativeRange(...args, force);
  292. } else {
  293. this.setNativeRange(null);
  294. }
  295. this.update(source);
  296. }
  297. update(source = Emitter.sources.USER) {
  298. let oldRange = this.lastRange;
  299. let [lastRange, nativeRange] = this.getRange();
  300. this.lastRange = lastRange;
  301. if (this.lastRange != null) {
  302. this.savedRange = this.lastRange;
  303. }
  304. if (!equal(oldRange, this.lastRange)) {
  305. if (!this.composing && nativeRange != null && nativeRange.native.collapsed && nativeRange.start.node !== this.cursor.textNode) {
  306. this.cursor.restore();
  307. }
  308. let args = [Emitter.events.SELECTION_CHANGE, clone(this.lastRange), clone(oldRange), source];
  309. this.emitter.emit(Emitter.events.EDITOR_CHANGE, ...args);
  310. if (source !== Emitter.sources.SILENT) {
  311. this.emitter.emit(...args);
  312. }
  313. }
  314. }
  315. }
  316. function contains(parent, descendant) {
  317. try {
  318. // Firefox inserts inaccessible nodes around video elements
  319. descendant.parentNode;
  320. } catch (e) {
  321. return false;
  322. }
  323. // IE11 has bug with Text nodes
  324. // https://connect.microsoft.com/IE/feedback/details/780874/node-contains-is-incorrect
  325. if (descendant instanceof Text) {
  326. descendant = descendant.parentNode;
  327. }
  328. return parent.contains(descendant);
  329. }
  330. export { Range, Selection as default };