/
surface_selection.js
412 lines (389 loc) · 12.3 KB
/
surface_selection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
var OO = require('../basics/oo');
var Document = require('../document');
var _ = require('../basics/helpers');
var Range = Document.Range;
var Coordinate = Document.Coordinate;
/**
* A class that maps DOM selections to model selections.
*
* There are some difficulties with mapping model selections:
* 1. DOM selections can not model discontinuous selections, such as TableSelections or MultiSelections.
* 2. Not all positions reachable via ContentEditable can be mapped to model selections. For instance,
* there are extra positions before and after non-editable child elements.
* 3. Some native cursor behaviors need to be overidden, such as for navigating tables.
*
* @class SurfaceSelection
* @constructor
* @param {Element} rootElement
* @module Surface
*/
function SurfaceSelection(rootElement, doc, container) {
this.element = rootElement;
this.doc = doc;
this.container = container;
this.state = new SurfaceSelection.State();
}
SurfaceSelection.Prototype = function() {
function compareNodes(node1, node2) {
var cmp = node1.compareDocumentPosition(node2);
if (cmp&window.document.DOCUMENT_POSITION_FOLLOWING) {
return -1;
} else if (cmp&window.document.DOCUMENT_POSITION_PRECEDING) {
return 1;
} else {
return 0;
}
}
// input methods:
// - mouse down (setting cursor with mouse)
// - keyboard cursor movement
// - expand:
// - mouse dragging
// - cursor movement with shift
// workflow for mapping from DOM to model:
// 1. extract coordinates
// 2. fixup coordinates
// 3. create a model selection
this._pullState = function(anchorNode, anchorOffset, focusNode, focusOffset, collapsed, options) {
options = options || {};
if (!focusNode || !anchorNode) {
this.state = null;
return;
}
// console.log('###', anchorNode, anchorOffset, focusNode, focusOffset);
var start, end;
if (collapsed) {
start = this.getModelCoordinate(anchorNode, anchorOffset, options);
end = start;
} else {
start = this.getModelCoordinate(anchorNode, anchorOffset, options);
end = this.getModelCoordinate(focusNode, focusOffset, options);
}
// the selection is reversed when the focus propertyEl is before
// the anchor el or the computed charPos is in reverse order
var reverse = false;
if (!collapsed && focusNode && anchorNode) {
var cmp = compareNodes(end.el, start.el);
reverse = ( cmp < 0 || (cmp === 0 && end.offset < start.offset) );
}
if (reverse) {
var tmp = end;
end = start;
start = tmp;
}
// console.log('### extracted selection:', start, end, reverse);
this.state = new SurfaceSelection.State(collapsed, reverse, start, end);
};
this.getModelCoordinate = function(node, offset, options) {
var current = node;
var propertyEl = null;
while(current) {
// if available extract a path fragment
if (current.dataset && current.dataset.path) {
propertyEl = current;
break;
}
// edge case: when a node is empty then then the given DOM node
// is the node element and with offset=0
if ($(current).is('.content-node') && offset === 0) {
var $propertyEl = $(current).find('[data-path]');
if ($propertyEl.length) {
return new SurfaceSelection.Coordinate($propertyEl[0], 0);
}
}
current = current.parentNode;
}
if (!propertyEl) {
return this.searchForCoordinate(node, offset, options);
}
var charPos = this._computeCharPosition(propertyEl, node, offset);
return new SurfaceSelection.Coordinate(propertyEl, charPos);
};
this._computeCharPosition = function(propertyEl, endNode, offset) {
var charPos = 0;
// This works with endNode being a TextNode
function _getPosition(node) {
if (endNode === node) {
charPos += offset;
return true;
}
if (node.nodeType === window.Node.TEXT_NODE) {
charPos += node.textContent.length;
} else if (node.nodeType === window.Node.ELEMENT_NODE) {
// external nodes have a length of 1
// they are attached to an invisible character
// but may have a custom rendering
if ($(node).data('external')) {
charPos += 1;
return false;
}
for (var childNode = node.firstChild; childNode; childNode = childNode.nextSibling) {
if (_getPosition(childNode)) {
return true;
}
}
}
return false;
}
// count characters recursively
// by sum up the length of all TextNodes
// and counting external nodes by 1.
function _countCharacters(el) {
var type = el.nodeType;
if (type === window.Node.TEXT_NODE) {
return el.textContent.length;
} else if (type === window.Node.ELEMENT_NODE) {
if ($(el).data('external')) {
return 1;
} else {
var count = 0;
for (var childNode = el.firstChild; childNode; childNode = childNode.nextSibling) {
count += _countCharacters(childNode);
}
return count;
}
}
return 0;
}
var found = false;
// HACK: edge case which occurs when the last element
// is not content-editable (i.e., external)
// then the anchor node is the property element itself
if (endNode === propertyEl) {
var child = propertyEl.firstChild;
for (var i = 0; i < offset; i++) {
if (!child) {
break;
}
charPos += _countCharacters(child);
child = child.nextSibling;
}
found = true;
} else {
found = _getPosition(propertyEl);
}
if (!found) {
console.error('Could not find char position.');
return 0;
}
// console.log('charPos', charPos);
return charPos;
};
/**
* Look up model coordinate by doing a search
* on all available property elements.
*/
this.searchForCoordinate = function(node, offset, options) {
var elements = this.element.querySelectorAll('*[data-path]');
var idx, idx1, idx2, cmp1, cmp2;
idx1 = 0;
idx2 = elements.length-1;
cmp1 = compareNodes(elements[idx1], node);
cmp2 = compareNodes(elements[idx2], node);
while(true) {
var l = idx2-idx1+1;
if (cmp2 < 0) {
idx = idx2;
break;
} else if (cmp1 > 0) {
idx = idx1;
break;
} else if (l<=2) {
idx = idx2;
break;
}
var pivotIdx = idx1 + Math.floor(l/2);
var pivotCmp = compareNodes(elements[pivotIdx], node);
if (pivotCmp < 0) {
idx1 = pivotIdx;
cmp1 = pivotCmp;
} else {
idx2 = pivotIdx;
cmp2 = pivotCmp;
}
}
var charPos;
if (options.direction === "left") {
idx = Math.max(0, idx-1);
charPos = elements[idx].textContent.length;
} else if (cmp2<0) {
charPos = elements[idx].textContent.length;
} else {
charPos = 0;
}
return new SurfaceSelection.Coordinate(elements[idx], charPos);
};
this._getSelection = function(anchorNode, anchorOffset, focusNode, focusOffset, collapsed) {
this._pullState(anchorNode, anchorOffset, focusNode, focusOffset, collapsed);
// console.log('#### selection state', this.state);
if (!this.state) {
return Document.nullSelection;
}
var doc = this.doc;
var start = this.state.start;
var end = this.state.end;
var node1, node2, parent1, parent2, row1, col1, row2, col2;
var range = new Range(
new Coordinate(start.path, start.offset),
new Coordinate(end.path, end.offset)
);
if (_.isEqual(start.path, end.path)) {
return doc.createSelection({
type: 'property',
path: start.path,
startOffset: start.offset,
endOffset: end.offset,
reverse: this.state.reverse
});
} else {
node1 = doc.get(start.path[0]);
node2 = doc.get(end.path[0]);
parent1 = node1.getRoot();
parent2 = node2.getRoot();
if (parent1.type === "table" && parent1.id === parent2.id) {
// HACK making sure that the table matrix has been computed
parent1.getMatrix();
row1 = node1.rowIdx;
col1 = node1.colIdx;
row2 = node2.rowIdx;
col2 = node2.colIdx;
return doc.createSelection({
type: 'table',
tableId: parent1.id,
startRow: row1,
startCol: col1,
endRow: row2,
endCol: col2
});
} else {
return doc.createSelection({
type: 'container',
containerId: this.container.id,
startPath: range.start.path,
startOffset: range.start.offset,
endPath: range.end.path,
endOffset: range.end.offset,
reverse: this.state.reverse
});
}
}
};
this.getSelection = function() {
var wSel = window.getSelection();
var sel = this._getSelection(wSel.anchorNode, wSel.anchorOffset, wSel.focusNode, wSel.focusOffset, wSel.collapsed);
// console.log('### selection', sel.toString());
return sel;
};
var _findDomPosition = function(element, offset) {
if (element.nodeType === document.TEXT_NODE) {
var l = element.textContent.length;
if (l < offset) {
return {
node: null,
offset: offset-l
};
} else {
return {
node: element,
offset: offset,
boundary: (l === offset)
};
}
} else if (element.nodeType === document.ELEMENT_NODE) {
if ($(element).data('external')) {
return {
node: null,
offset: offset-1
};
}
// edge case: if the element itself is empty and offset===0
if (!element.firstChild && offset === 0) {
return {
node: element,
offset: 0
};
}
for (var child = element.firstChild; child; child = child.nextSibling) {
var pos = _findDomPosition(child, offset);
if (pos.node) {
return pos;
} else {
// not found in this child; then pos.offset contains the translated offset
offset = pos.offset;
}
}
}
return {
node: null,
offset: offset
};
};
this._getDomPosition = function(path, offset) {
var selector = '*[data-path="'+path.join('.')+'"]';
var componentElement = this.element.querySelector(selector);
if (!componentElement) {
console.warn('Could not find DOM element for path', path);
return null;
}
// console.log('### Found component element', componentElement);
var pos = _findDomPosition(componentElement, offset);
if (pos.node) {
return pos;
} else {
return null;
}
};
this.setSelection = function(sel) {
// console.log('### renderSelection', sel.toString());
var wSel = window.getSelection();
if (sel.isNull() || sel.isTableSelection()) {
return this.clear();
}
var range = sel.getRange();
var startPosition = this._getDomPosition(range.start.path, range.start.offset);
if (!startPosition) {
return this.clear();
}
var endPosition;
if (range.isCollapsed()) {
endPosition = startPosition;
} else {
endPosition = this._getDomPosition(range.end.path, range.end.offset);
}
if (!endPosition) {
return this.clear();
}
// if there is a range then set replace the window selection accordingly
wSel.removeAllRanges();
range = window.document.createRange();
if (sel.isReverse()) {
range.setStart(endPosition.node, endPosition.offset);
wSel.addRange(range);
wSel.extend(startPosition.node, startPosition.offset);
} else {
range.setStart(startPosition.node, startPosition.offset);
range.setEnd(endPosition.node, endPosition.offset);
wSel.addRange(range);
}
this.state = new SurfaceSelection.State(sel.isCollapsed(), sel.isReverse(), range.start, range.end);
};
this.clear = function() {
var sel = window.getSelection();
sel.removeAllRanges();
this.state = null;
};
};
OO.initClass(SurfaceSelection);
SurfaceSelection.State = function(collapsed, reverse, start, end) {
this.collapsed = collapsed;
this.reverse = reverse;
this.start = start;
this.end = end;
Object.freeze(this);
};
SurfaceSelection.Coordinate = function(el, charPos) {
this.el = el;
this.offset = charPos;
this.path = el.dataset.path.split('.');
};
module.exports = SurfaceSelection;