-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTheTerms.vue
1461 lines (1195 loc) · 42 KB
/
TheTerms.vue
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<template>
<div
:style="{
width: width + 'px',
height: height + 'px'
}"
class="terms"
@mousedown.left.exact="onMousedown_div"
>
<span
ref="ruler"
class="ruler term"
/>
<term
v-for="(term, index) in terms"
:key="term.key"
:term="term"
:index="index"
:has-input="index == inputIndex"
:vsm-dictionary="vsmDictionary"
:query-options="queryOptions"
:autofocus="index == inputIndex && autofocus"
:placeholder="terms.length == 1 && placeholder"
:tab-listen-mode="index == inputIndex ? inputTabListenMode : 3"
:fresh-list-delay="freshListDelay"
:max-string-lengths="maxStringLengths"
:has-item-literal="!!(allowClassNull || advancedSearch)"
:custom-item="customItem"
:custom-item-literal="customItemLiteral2"
unselectable="on"
@input="onInput"
@key-esc="onKeyEsc"
@key-bksp="onKeyBksp"
@key-ctrl-enter="onKeyCtrlEnter"
@key-tab="onKeyTab"
@key-alt-up="onKeyAltUp"
@key-alt-down="onKeyAltDown"
@key-ctrl-delete="onKeyCtrlDelete"
@key-ctrl-bksp="onKeyCtrlBksp"
@key-shift-enter="onKeyShiftEnter"
@mouseenter="onMouseenter"
@mouseleave="onMouseleave"
@focus="onFocus"
@blur="onBlur"
@list-open="onListOpen"
@item-select="insertFromMatch"
@item-literal-select="onItemLiteralSelect"
@plain-enter="onPlainEnter"
@mousedown="onMousedown"
@ctrl-mousedown="onCtrlMousedown"
@ctrl-shift-mousedown="onCtrlShiftMousedown"
@alt-mousedown="onAltMousedown"
@click="onClick"
@dblclick="onDblclick"
/>
<div
v-if="dragIndex >= 0"
:style="{
width: terms [dragIndex].width + 'px',
height: terms[dragIndex].height + 'px',
top: terms [dragIndex].y + 'px',
left: terms[dragIndex].x + 'px',
}"
class="term drag-placeholder"
/>
<the-popup
v-if="popupLoc >= 0 && popupLoc < terms.length"
:index="popupLoc"
:term="terms[popupLoc]"
:vsm-dictionary="vsmDictionary"
:sizes="sizes"
:allow-class-null="allowClassNull"
:term-margin="popupTermMargin"
:custom-popup="customPopup"
:term-copy="termCopy"
:term-paste="termPaste"
@mouseenter="onMouseenter_popup"
@mouseleave="onMouseleave"
@edit="onDblclick"
@undo-edit="onKeyEsc"
@toggle-focal="onAltMousedown"
@insert="onInsertBefore"
@remove="onKeyCtrlDelete"
@set-type="onSetType"
@copy="onCopy"
@copy-ref="onCopyRef"
@paste="onPaste"
@mousedown.native.stop="x => x"
/>
</div>
</template>
<script>
import Term from './Term.vue';
import ThePopup from './ThePopup.vue';
import sanitizeHtml from './sanitizeHtml.js';
import to from './termOperations.js';
import stringStyleHtml from 'string-style-html';
const defaultFontSize = 11; // Equals `.vsm-box`'s CSS-value 'font-size'.
export default {
name: 'TheTerms',
components: {
'term': Term,
'the-popup': ThePopup
},
props: {
vsmDictionary: {
type: Object,
required: true
},
queryOptions: {
type: [Object, Boolean],
default: false
},
autofocus: {
type: Boolean,
default: false
},
placeholder: {
type: [String, Boolean],
default: false
},
cycleOnTab: {
type: Boolean,
default: false
},
maxStringLengths: {
type: Object,
required: true
},
freshListDelay: {
type: Number,
default: 0
},
advancedSearch: {
type: [Function, Boolean],
default: false
},
allowClassNull: {
type: Boolean,
default: true
},
origTerms: {
type: Array,
required: true
},
sizes: {
type: Object,
required: true
},
customItem: {
type: [Function, Boolean],
default: false
},
customItemLiteral: {
type: [Function, Boolean],
default: false
},
customTerm: {
type: [Function, Boolean],
default: false
},
customPopup: {
type: [Function, Boolean],
default: false
},
termCopy: {
type: [Function, Boolean],
default: false
},
termPaste: {
type: [Function, Boolean],
default: false
}
},
data: function() { return {
terms: [], // Current state of Terms. Starts as augmented `origTerms`.
padTop: 0, // } These will be computed after 'mounted'.
padRight: 0, // } ". = Inner padding of TheTerms.
padBottom: 0, // } "
padLeft: 0, // } "
bkgrColor: '', // } ". = Background color of TheTerms. Used by TheConns.
termPadBordLR: 0, // } ". = Sum of a Term's inner left+right padding+border.
termMarginHor: 0, // } ". = Maximum of a Term's left and right margin.
termHeight: 0, // } ". Note: it's a value, while termWidth is a function.
inputIndex: 0, // Index of Term that now has the input or vsm-autocomplete.
popupLoc: -1, // Index of Term that now has an associated PopupBox; -1=none.
width: 0, // Width incl padding/border. Is updated by `setTermCoordinates()`.
hasEndTermFocus: false, // Tells if the endTerm currently has the focus.
endSpaceX: 0, // All clicks to the right of this will focus the endTerm.
dragIndex: -1, // When >= 0, it is the index of a currently dragged Term.
enablePopup: true, // Helps to prevent showing ThePopup in an edge case.
timerPopupHide: 0, // = a timer-handle, only while a Popup-hide timer runs.
timerPopupShow: 0, // (Similar).
popupEscListener: false, // Helps hide ThePopup when the user presses Esc.
mayNarrow: false // Prevents making TheTerms less wide.
}; },
computed: {
height() {
return this.termHeight + this.padTop + this.padBottom;
},
inputTabListenMode() {
if (this.cycleOnTab) return 3;
for (var i = 0, a = []; i < this.terms.length; i++) {
if (to.isEditable(this.terms[i])) a.push(i);
}
return (this.inputIndex == a[a.length - 1] ? 0 : 1) +
( this.inputIndex == a[0] ? 0 : 2);
},
/**
* Makes vsm-autocomplete's default item-literal `titleStr` more informative,
* applies a `customItemLiteral` function prop if given, and
* appends HTMLto show `advancedSearch`'s hotkey Shift+Enter, if needed.
*/
customItemLiteral2() {
var f = data => {
// 1) Override vsmAC's `strTitle` for the item-literal.
data.strs.strTitle =
this.advancedSearch ? 'Advanced search' : 'Create new concept';
// 2) If no `customItemLiteral` changes `str`, set an augmented default.
if (!this.customItemLiteral) data.strs.str =
(this.advancedSearch ? 'Search' : 'Create') + ` '${data.strs.str}'`;
// 3) Else, now give `customItemLiteral` control over both str&strTitle.
else data.strs = this.customItemLiteral(data);
return data.strs;
};
// 4) Finally, if advSrch is available then show the hotkey for it, by..
return !this.advancedSearch ? f : ( // ..wrapping the above function..
data => { // ..into a new one.
data.strs = f(data);
data.strs.str += '<span class="hotkey">Shift+Enter</span>';
return data.strs;
}
);
},
popupTermMargin() {
var i = this.popupLoc;
return i < 0 ? {} : {
left: i ? this.termMarginHor : this.padLeft,
right: i < this.terms.length - 1 ? this.termMarginHor : this.padRight
};
}
},
watch: {
origTerms: function() {
this.initForNewTerms();
},
sizes: function() {
this.measureSizes();
this.setTermCoordinates();
this.emitValue('change'); // Ensure that TheConns updates along.
},
customTerm: function() {
this.setTermCoordinates();
this.emitValue('change');
},
hasEndTermFocus: function(val) { // Recalc. endTerm coo.s; may need to widen.
if (val) this.setTermCoordinates(this.terms.length - 1);
}
},
mounted: function() {
this.measureSizes();
this.initForNewTerms();
},
methods: {
//
// --- DIMENSIONS, TERM POSITIONING, and EXTRA TERM PROPERTIES -------------
//
/**
* We make `measureSizes()` access the ruler-element in this separate func.,
* only so that the tests can override it and insert custom functionality.
*/
getRuler() {
return this.$refs.ruler;
},
/**
* This measures some sizes set by CSS, as an initialization step.
*/
measureSizes() {
var style = getComputedStyle(this.$el); // --1-- TheTerms's style.
var num = s => +s.replace(/px$/, '');
var calc = side => num( style['padding-' + side] );
this.padTop = calc('top');
this.padRight = calc('right');
this.padBottom = calc('bottom');
this.padLeft = calc('left');
this.bkgrColor = style['background-color'];
var ruler = this.getRuler();
style = getComputedStyle(ruler); // --2-- Term's style.
calc = side =>
num(style['padding-' + side]) +
num(style['border-' + side + '-width']);
this.termPadBordLR = calc('left') + calc('right');
calc = side => num(style['margin-' + side]);
this.termMarginHor = calc('left') + calc('right');
ruler.innerHTML = 'W'; // Make it not empty, in order to measure height.
this.termHeight = ruler.offsetHeight;
this.sizes.widthScale = this.sizes.widthScale ||
num(style['font-size']) / defaultFontSize || 1;
},
/**
* Calculates (using the DOM) how wide a Term should be made (including
* padding and borders), so that it can contain its label (= the HTML that
* results from its `str` with its `style` applied).
* If needed, the string is hereby trimmed to be only `maxStrWidth` px wide
* (this width excludes Term's padding and borders).
* Notes:
* + Term-width = allocated string-width + Term's padding & borders.
* + If an `editStrWidth` is given, it overrides the given min/max-widths.
* + Text-trimming happens via CSS's `text-overflow:ellipsis`.
* + Instead of using `offsetWidth` which is a rounded-up/down integer,
* we get the full-precision width, and then always round it up.
* Like this, e.g. for a string (that will not be trimmed and) that is
* 70.23px wide, the Term's width will be set so that the contained string
* gets 71px space, and not 70px (which would 'text-overflow'-truncate it).
*/
termWidth(label, minStrWidth, maxStrWidth, editStrWidth = false) {
var f = w => Math.ceil(w * this.sizes.widthScale) + this.termPadBordLR;
var r = this.$refs.ruler;
r.innerHTML = label;
r.style =
editStrWidth ? `width:${f(editStrWidth)}px;` :
(minStrWidth ? `min-width:${f( minStrWidth)}px;` : '') +
(maxStrWidth ? `max-width:${f( maxStrWidth)}px;` : '');
var w = Math.ceil(r.getBoundingClientRect().width); // Not `offsetWidth`.
r.style = '';
return w;
},
initForNewTerms() {
// If dragging was ongoing, abort it. Make that all listeners get detached.
if (this.dragIndex >= 0) window.dispatchEvent(new MouseEvent('mouseup'));
// Hide any ThePopup, and ignore a hover-event that might fire just after..
this.tempDisablePopup(); // ..we could place a new Term under the mouse.
var terms = this.origTerms.map(term => to.prepToReceive(term));
terms.push(to.newEndTerm());
// Determine which Editable Term (or endTerm) gets the only <input>-elem.
for (var i = 0; i < terms.length; i++) {
if (to.isEditable(terms[i])) { this.inputIndex = i; break }
}
this.setTermCoordinates(0, terms);
// Assign all `terms` at once, making all added sub-prop.s Vue-reactive.
this.terms = terms;
this.emitValue('change-init');
},
/**
* (Re-)Calculates coordinates & dimensions for Terms, and related UI-data.
* Can start recalculating from a given `startIndex`, for efficiency.
*/
setTermCoordinates(startIndex = 0, terms) {
terms = terms || this.terms;
startIndex = 0;
var i = startIndex - 1;
var x = startIndex ? (terms[i].x + terms[i].width + this.termMarginHor) :
this.padLeft;
var t, editWidth;
while ((t = terms[++i])) { // == "As long as there are Terms, .."
t.str = t.str || '';
if (t.isEndTerm) {
// Calc. X-coo. of "endTerm's space": starts at endTerm's left margin.
this.endSpaceX = !i ? 0 : x - this.termMarginHor;
editWidth = Math.ceil(this.sizes.widthScale * (this.hasEndTermFocus ?
this.sizes.minEndTermWideWidth : this.sizes.minEndTermWidth) );
var spaceLeft = // Note: part 1 = minWidth, adjusted for not letting..
// // ..TheTerms become less wide, unless permitted.
Math.max(this.sizes.minWidth, this.mayNarrow ? 0 : this.width)
- x - editWidth - this.termPadBordLR - this.padRight;
this.mayNarrow = false;
t.width = editWidth + Math.max(0, spaceLeft) + this.termPadBordLR;
}
else {
editWidth = to.isEditable(t) && // Not Edit-type => false..
(t.editWidth || this.sizes.defaultEditWidth); // .. else => Number.
var maxWidth = t.maxWidth === undefined ? this.sizes.defaultMaxWidth :
t.maxWidth;
t.label = this.termLabel(t, i);
t.width = this.termWidth(t.label, t.minWidth, maxWidth, editWidth);
}
t.height = this.termHeight;
t.x = x;
t.y = this.padTop;
x += t.width + this.termMarginHor;
}
// Also set TheTerms' total width now.
x = x - this.termMarginHor + this.padRight;
if (x != this.width) this.$emit('width', this.width = x);
},
/**
* Calculates the text/HTML `label` for a Term, based on its text-`str`,
* by applying `style` and a `customTerm()` function, if these exist.
* This must be done before measuring the visual width needed for the Term.
*/
termLabel(term, i) {
var strs = { // Use `strs.str`, for uniformity among customization funcs.
str: stringStyleHtml(term.str, term.style)
};
if (this.customTerm && !to.isEditable(term)) strs = this.customTerm(
{ strs, index: i, type: term.type,
term: to.prepToEmit(term),
vsmDictionary: this.vsmDictionary }
);
return sanitizeHtml(strs.str); // Secure the UI against third-party data.
},
//
// --- ENDTERM WIDTH -------------------------------------------------------
//
onFocus(index) {
this.hasEndTermFocus = index == this.terms.length - 1;
},
onBlur(index) {
if (index == this.terms.length - 1) this.hasEndTermFocus = false;
},
//
// --- MOVING THE INPUT between Edit-Terms ---------------------------------
//
/**
* While a user types in an Edit-type Term's input-element, its content
* needs to be continuously saved to the Term's `str` + its derived `label`.
* Because when the input-element moves to another Term, or when Vue updates
* any other HTML/CSS and then automatically re-fills input content based
* on `str` (which is used as initial value, and so also after any refresh),
* then the correct content remains (or is re-placed) in the input-less
* Edit-Term.
*/
onInput(index, str) {
this.hidePopup();
var term = this.terms[index];
term.str = str;
term.label = sanitizeHtml(str);
},
/**
* This will be called with `str` == '' for a Tab-press, or 'shift' for
* a Shift+Tab. Or 'ignore' for Tab at the endTerm, or for Shift+Tab at
* the first Edit-Term. On 'ignore', Term lets the event pass to the browser.
*/
onKeyTab(index, str) {
if (str == 'ignore') return this.hidePopup();
this.moveInputToNextEditTerm(index, str ? -1 : 1);
},
moveInputToNextEditTerm(index, step) {
this.moveInputTo( this.getNextEditTermIndex(index, step) );
},
getNextEditTermIndex(index, step) { // `step`: 1/-1: to right/left.
var n = this.terms.length;
var pos = index;
while (1) { // eslint-disable-line no-constant-condition
pos = (pos + step + n) % n; // Search moving 1 step right/left cyclingly.
if (pos == index || to.isEditable(this.terms[pos])) return pos;
}
},
/**
* When clicking on TheTerms's padding, to the right of the last real Term
* (i.e. on the endTerm's margin), only: move the input to endTerm.
* Else, just move the focus to the current input.
* Note: clicks on ThePopup are ignored via its `@mousedown.native.stop`.
*/
onMousedown_div(event) {
var rect = this.$el.getBoundingClientRect();
var clickX = event.clientX - rect.left;
if (this.endSpaceX <= clickX) this.moveInputTo(this.terms.length - 1);
else this.focusInput();
},
onMousedown(index, event) {
this.hidePopup();
if (to.isEditable(this.terms[index])) this.moveInputTo(index);
else this.initDrag(index, event);
},
/**
* Moves the (only) <input>-elem. or vsmAutocomplete to the Term at `index`,
* if it is an Edit-type term. If not, just re-focuses the current input.
*/
moveInputTo(index, unsel = false) {
this.hidePopup();
if (to.isEditable(this.terms[index])) this.inputIndex = index;
// After Vue removes the old input, adds the new input, and fills it
// with the value it finds in `term.str`: focus the new input.
this.focusInput(unsel);
},
focusInput(unsel = false) {
this.hidePopup(); // Hide ThePopup, if it would be visible.
this.$nextTick(() => { // Wait for Vue to update the DOM.
var input = this.inputElement();
input.focus();
if (unsel) input.selectionStart = input.selectionEnd =
input.value.length;
});
},
inputElement() {
return this.$el.querySelector('.input'); // Non-reactive =>query it.
},
/**
* Moves the input to the endTerm and focus it.
* This function is called by VsmBox, after a click on TheConns's area above
* avoethe endTerm.
*/
moveInputToEndTerm(unsel = false) {
this.moveInputTo(this.terms.length - 1, unsel);
},
//
// --- CHANGING TERM-TYPE --------------------------------------------------
//
/**
* Changes a Term's type to the next one in a cycle (see `to.cycleType`).
*/
onCtrlMousedown(index) {
var term = this.terms[index];
to.cycleType(term, this.allowClassNull, this);
// Make a Ctrl+Clicked Edit-type term always keep or get the <input>.
// Also unselect after maybe multiple Ctrl+Clicks on it. Or if it is
// not an Edit-type term, then just refocus the current input-having Term.
this.moveInputTo(index, true);
if (!term.isEndTerm) this.emitValue();
},
//
// --- SETTING/UNSETTING FOCAL TERM ----------------------------------------
//
/**
* Toggles a Term's state of being 'focal'.
* It ensures that only one Term is focal, and will not make endTerm focal.
*/
onAltMousedown(index) {
var term = this.terms[index];
if (!term.isEndTerm) {
to.makeFocal(term, !term.isFocal, this);
if (term.isFocal) {
this.terms.forEach(t => t == term || to.makeFocal(t, false, this));
}
}
this.moveInputTo(index, true);
if (!term.isEndTerm) this.emitValue();
},
//
// --- EMITTING CHANGE -----------------------------------------------------
//
/**
* Constructs and emits the current, publicly visible state of TheTerms,
* excluding the endTerm. Term-properties are pruned in 'termOperations.js'.
*/
emitValue(eventStr = 'change') {
this.$emit(eventStr, this.terms .slice(0, -1) .map(to.prepToEmit));
},
//
// --- START EDITING TERMS, and CANCELING THE EDITING ----------------------
//
/**
* - On doubleclick on Edit-type Term, shows ThePopup.
* - On doubleclick on non-Edit-type Term, converts it to an Edit-type Term.
*/
onDblclick(index) {
if (to.isEditable(this.terms[index])) this.showPopup(index);
else {
this.makeTermEditable(index);
this.moveInputTo(index); // This also hides a possibly visible ThePopup.
this.setTermCoordinates(index);
this.emitValue();
}
},
/**
* Replaces a non-Edit-type Term by a derived Edit-type Term. It adds a
* `backup` property to the Edit-Term, to enable restoring the original one.
*/
makeTermEditable(index) {
this.$set(this.terms, index, to.createEditTerm(this.terms[index]));
},
/**
* Restores an Edit-type Term that was previously not-Edit-type.
* This function is called after an Esc-press on a plain input,
* or on a vsmAutocomplete-input with closed selection-list.
*/
onKeyEsc(index) {
this.hidePopup();
var term = this.terms[index];
if (to.isEditable(term) && term.backup) {
this.replaceTerm(index, to.createRestoredTerm(term));
}
},
//
// --- BACKSPACE INTO TERM BEFORE, REMOVING, and INSERTING TERM AFTER ------
//
/**
* This is called only on an empty Edit-Term.
* - If on first Term, does nothing.
* - Else, makes the Term before it editable (if needed), and focuses it.
*/
onKeyBksp(index) {
this.hidePopup();
if (!index) return;
// Ensure that endTerm (if that's where we're at) releases its claim to
// wide-width, before moving the input to a new place.
// (Note: we don't use `this.inputElement().blur()`, as in Firefox that
// can let the Backspace-event bubble up and cause a Go-To-Prev.-Page).
this.hasEndTermFocus = false;
index = --this.inputIndex;
var change = !to.isEditable(this.terms[index]);
if (change) this.makeTermEditable(index);
this.focusInput(true);
this.setTermCoordinates(index);
if (change) this.emitValue();
},
/**
* Deletes a Term. Then moves input+focus to right after it (if Edit-Term),
* or else right before it (if Edit-Term), or else the first next Edit-Term.
* If on the endTerm, just resets its type to 'EI'.
*/
onKeyCtrlDelete(index) {
this.hidePopup();
var term = this.terms[index];
if (term.isEndTerm) {
term.str = term.label = '';
to.setType(term, 'EI', this);
this.mayNarrow = true;
this.setTermCoordinates(index);
return this.focusInput();
}
var index2 = to.isEditable(this.terms[index + 1]) ? index :
(index && to.isEditable(this.terms[index - 1])) ? index - 1 :
this.getNextEditTermIndex(index, 1) - 1;
this.deleteTerm(index);
this.moveInputTo(index2, true);
this.setTermCoordinates(index);
this.emitValue();
},
/**
* Deletes the Term before it, if there is one.
* For a lone endTerm, resets it.
*/
onKeyCtrlBksp(index) {
if (index) this.onKeyCtrlDelete(index - 1);
else if (this.terms.length == 1) this.onKeyCtrlDelete(0);
},
deleteTerm(index) {
if (index == this.inputIndex) {
this.inputElement().blur(); // Prevent that detached input emits change!
}
this.terms.splice(index, 1);
},
/**
* Adds a new Edit-Instance Term behind the current Edit-Term and focuses it.
*/
onKeyCtrlEnter(index) {
this.insertEmptyTerm(index);
},
insertEmptyTerm(index, after = 1) { // `after`: 1/0 to insert after/before.
var term = this.terms[index];
var term2 = to.newEditTerm(term.isEndTerm && after);
if (after) to.unsetAsEndTerm(term, this);
else this.hasEndTermFocus = false; // => Release wide-claim, if any.
this.terms.splice(index + after, 0, term2);
this.moveInputTo(index + after); // Update inputIndex, focus at nextTick.
this.setTermCoordinates(index); // Not `index+1`: it may need to update a..
this.emitValue(); // ..former ex-endTerm(@index)'s width.
},
//
// --- MOVING EDIT-TYPE TERMS LEFT/RIGHT, and general moving ---------------
//
onKeyAltUp(index) {
this.moveEditTerm(index, index - 1);
},
onKeyAltDown(index) {
this.moveEditTerm(index, index + 1);
},
/**
* Moves an Edit-type Term to a new position.
* Arg. `to` is the position where the Term will be reinserted in the array
* `this.terms`, after it has been extracted/deleted from the pos. `from`.
*/
moveEditTerm(from, to) {
this.hidePopup();
// Abort if at endTerm, or if less than 2 real terms. (Note: `.length`..
var n = this.terms.length; // ..includes the endTerm).
if (from == n - 1 || n < 3) return;
/* Also make the `to`-index cycle. E.g. these four examples:
(orig. positions at each one's start): 0 1 2 (3), n=4
- Alt+Down on 0: move term at 0 to pos 1: => 1 0 2 (3) (3=endTerm)
- Alt+Down on 2: move term at 2 to pos 0: => 2 0 1 (3) <- cycle right
- Alt+Up on 2: move term at 2 to pos 1: => 0 2 1 (3)
- Alt+Up on 0: move term at 0 to pos 2: => 1 2 0 (3) <- cycle left */
if (to < 0 ) to = n - 2;
else if (to > n - 2) to = 0;
this.moveTerm(from, to, true);
},
/**
* Helper of `moveEditTerm()` and of `initDrag().processMousemove()`.
*/
moveTerm(from, to, inputToTo = false) {
var terms2 = this.terms.slice(0, from).concat(this.terms.slice(from + 1));
terms2.splice(to, 0, this.terms[from]);
if (inputToTo) {
this.inputIndex = to; // (Don't use `moveInputTo()` for moving terms, ..
this.focusInput(); // ..as it'd try backing up the label at old pos).
}
this.setTermCoordinates(Math.min(from, to), terms2);
this.terms = terms2;
this.emitValue();
},
//
// --- ENTERING TERMS (Filling in Edit-Terms) ------------------------------
//
onPlainEnter(index) { // Can be called on ER/EL-type Terms, only.
this.hidePopup();
this.fillInTerm(index, to.createRorLTerm(this.terms[index]));
},
onItemLiteralSelect(index) { // Can be called on EI/EC-type Terms, only.
this.hidePopup();
if (this.advancedSearch) this.launchAdvancedSearch(index);
else if (this.allowClassNull) {
// Pretend an item with id=null was selected. =>Results in classID=null.
this.insertFromMatch(index, { str: this.terms[index].str, id: null });
}
},
onKeyShiftEnter(index) { // Can be called on all Edit-type Terms.
this.hidePopup();
if (this.advancedSearch) this.launchAdvancedSearch(index);
},
launchAdvancedSearch(index) {
var term = this.terms[index];
var qOpt = to.clone(term.queryOptions || {}); // (No merge w `this.que..`).
delete qOpt.sort; // Don't let adv-search use this; according to the spec.
this.$nextTick(() => // Let VsmBox update before calling an external func.
this.advancedSearch(
{ str: term.str,
termType: term.type.replace('E', ''),
vsmDictionary: this.vsmDictionary,
queryOptions: qOpt,
allowClassNull: this.allowClassNull
},
match => this.insertFromMatch(index, match)
));
},
/**
* Creates & fills in a Term, based on a match-object (or similar Object)
* as defined in 'vsm-dictionary' and 'vsm-box''s specs.
*/
insertFromMatch(index, match) {
if (match)
this.fillInTerm(index, to.createTermFromMatch(this.terms[index], match));
},
/**
* Puts the given (already cleanded) non-Edit-Term in place of the Edit-Term
* at `index`, and adds a new endTerm if endTerm was there.
* Aborts if invalid data is given.
*/
fillInTerm(index, term) {
if (! term || !term.str ||
(term.classID === null && !this.allowClassNull && term.type != 'R'))
return;
if (term.isEndTerm) {
to.unsetAsEndTerm(term, this);
this.terms.push(to.newEndTerm());
}
this.replaceTerm(index, term);
},
/**
* Puts the given non-Edit-Term in place of the Edit-Term at `index`.
*/
replaceTerm(index, term) {
this.moveInputToNextEditTerm(index, 1); // Do this before changing type.
this.$set(this.terms, index, term);
this.setTermCoordinates(index);
this.emitValue();
this.tempDisablePopup();
},
//
// --- DRAGGING A TERM -----------------------------------------------------
//
onCtrlShiftMousedown(index, event) {
this.hidePopup();
this.initDrag(index, event);
},
initDrag(index, event) { // Called by `onMousedown()`, see above.
// Calculation of mouse-coordinates of `event`: relative to `term`'s
// top left corner, or the Term's drag-placeholder's top left corner.
// This also works when the page is scrolled, and when the VsmBox has
// any absolute-positioned ancestor-elements.
// + Note: mouse-coo.s `clientX/Y` are relative to a possibly scrolled
// viewport, and so is `getBoundingClientRect()` => cancels out nicely.
// + Note that `term.x/y` change along with changing placeholder position.
var theTerms = this.$el.getBoundingClientRect();
theTerms = { x: ~~theTerms.left, y: ~~theTerms.top };
var mouseCoosRelToTerm = event => {
var term = this.terms[index];
return {
x: event.clientX - theTerms.x - term.x,
y: event.clientY - theTerms.y - term.y
};
};
var dragOffset = mouseCoosRelToTerm(event); // =Mousedown-pos. inside Term.
var threshSqr = Math.pow(this.sizes.termDragThreshold, 2);
var hook = func => { // Hooks/unhooks events to the whole browser window.
func('mousemove', processMousemove);
func('mouseup', processMouseup),
func('blur', stopDrag);
};
// Function for setting/restoring the cursor to 'grabbing' on the whole
// page. Because the mouse may leave the Term and hover other elements.
var origCursor = document.body.style.cursor;
var setGrabCursor = (on = true) => {
document.body.style.cursor = on ? 'grabbing' : origCursor;
};
var processMousemove = event => {
// Get current Term at `index`. (Which can be a different object than at
// last call, if `origTerms` changed. That may happen often, if external
// code responds to VsmBox 'change' events by updating `initialValue`).
var term = this.terms[index];
var loc = mouseCoosRelToTerm(event);
// If not yet dragging (because mousemove-distance threshold not yet
// reached), then check if the mouse is past the threshold now.
// If not, abort; if so, start dragging and make the first move-response.
if (this.dragIndex < 0) {