Repository navigation
Expand file tree
/
Copy pathtext.js
More file actions
2642 lines (2468 loc) · 88.3 KB
/
Copy pathtext.js
File metadata and controls
2642 lines (2468 loc) · 88.3 KB
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
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
import app from './../app.js';
import config from './../config.js';
import zoomView from './../libs/zoomView.js';
import Base_tools_class from './../core/base-tools.js';
import Base_selection_class from './../core/base-selection.js';
import Base_layers_class from './../core/base-layers.js';
import GUI_tools_class from './../core/gui/gui-tools.js';
import Helper_class from './../libs/helpers.js';
import Dialog_class from './../libs/popup.js';
import WebFont from 'webfontloader';
import alertify from './../../../node_modules/alertifyjs/build/alertify.min.js';
/**
* TODO
* - Add leading, superscript, subscript
* - Implement text direction (right to left, top to bottom, etc.); currently partial implementation
* - Allow search & add google fonts
* - Enable text layer rotation
* - Undo history
*/
// Default text styling
// WARNING - changing this could break backwards compatibility!
// Defaults aren't saved in text layer in order to reduce data size and increase meta comparison performance.
export const metaDefaults = {
size: 40,
family: 'Arial',
kerning: 0,
leading: 0,
bold: false,
italic: false,
underline: false,
strikethrough: false,
fill_color: '#008800',
stroke_size: 0,
stroke_color: '#000000'
};
// Global map of font name to font metrics information.
const fontMetricsMap = new Map();
const layerEditors = new WeakMap();
const fontLoadPromiseMap = new Map();
const fontLoadMap = new Map();
fontLoadMap.set('Arial', true);
fontLoadMap.set('Courier', true);
fontLoadMap.set('Impact', true);
fontLoadMap.set('Helvetica', true);
fontLoadMap.set('Monospace', true);
fontLoadMap.set('Tahoma', true);
fontLoadMap.set('Times New Roman', true);
fontLoadMap.set('Verdana', true);
function load_font_family({ family, variants }, successCallback) {
if (fontLoadMap.get(family) == null) {
fontLoadMap.set(family, false);
const loadPromise = new Promise((resolve, reject) => {
WebFont.load({
google: {
families: [family + (variants ? ':' + variants.join(',') : '')]
},
fontactive: (family) => {
fontLoadMap.set(family, true);
fontLoadPromiseMap.delete(family);
resolve();
},
fontinactive: (family) => {
alertify.error('Font ' + family + ' could not be loaded.');
fontLoadPromiseMap.delete(family);
reject();
}
});
});
fontLoadPromiseMap.set(family, loadPromise);
}
if (successCallback) {
const loadPromise = fontLoadPromiseMap.get(family);
if (loadPromise) {
loadPromise.then(successCallback);
} else if (fontLoadMap.get(family) == true) {
requestAnimationFrame(() => {
successCallback();
});
}
}
}
/**
* The canvas's native font metrics implementation doesn't really give us enough information...
*/
const kerningTestCanvas = document.createElement('canvas');
kerningTestCanvas.width = 10;
kerningTestCanv
9798
as.height = 10;
kerningTestCanvas.style = 'font-kerning: normal; text-rendering: optimizeLegibility;';
const kerningTestCtx = kerningTestCanvas.getContext('2d');
class Font_metrics_class {
constructor(family, size) {
this.family = family || (family = "Arial");
this.size = parseInt(size) || (size = 12);
this.kerningMap = new Map();
// Preparing container
const line = document.createElement('div');
const body = document.body;
line.style.position = 'absolute';
line.style.whiteSpace = 'nowrap';
line.style.font = size + 'px ' + family;
body.appendChild(line);
// Now we can measure width and height of the letter
const text = '——————————'; // 10 symbols to be more accurate with width
line.innerHTML = text;
this.width = line.offsetWidth / text.length;
this.height = line.offsetHeight;
// Now creating 1px sized item that will be aligned to baseline
// to calculate baseline shift
const baseline = document.createElement('span');
baseline.style.display = 'inline-block';
baseline.style.overflow = 'hidden';
baseline.style.width = '1px';
baseline.style.height = '1px';
line.appendChild(baseline);
// Baseline is important for positioning text on canvas
this.baseline = baseline.offsetTop + baseline.offsetHeight;
document.body.removeChild(line);
}
/**
* Attempts to determine the height of a letter via pixel comparison
* @param {string} letter - The letter to check
* @param {string} [baseline] - Baseline position override
*/
calculate_letter_bounds(letter, baseline) {
baseline = baseline || 'alphabetic'
kerningTestCanvas.width = this.width;
kerningTestCanvas.height = this.height;
kerningTestCtx.clearRect(0, 0, this.width, this.height);
kerningTestCtx.font =
' ' + (this.size) + 'px' +
' ' + this.family;
kerningTestCtx.textAlign = 'left';
kerningTestCtx.textBaseline = baseline;
kerningTestCtx.fillStyle = '#000000';
kerningTestCtx.fillText(letter, 0, baseline === 'alphabetic' ? this.baseline : 0);
const pixels = kerningTestCtx.getImageData(0, 0, this.width, this.height).data;
const pixelLength = pixels.length;
let start = 0;
let end = this.height;
for (let i = 0; i < pixelLength; i += 4) {
if (pixels[i + 3] !== 0) {
start = Math.floor(i / 4 / this.width);
break;
}
}
for (let i = pixelLength - 4; i >= 0; i -= 4) {
if (pixels[i + 3] !== 0) {
end = Math.floor(i / 4 / this.width);
break;
}
}
kerningTestCanvas.width = 10;
kerningTestCanvas.height = 10;
return {
top: start,
bottom: end,
height: end - start
}
}
/**
* Calculate the kerning offset between two letters.
* @param {string} letters - a two character string of the two letters to determine font kerning from. Returns the kerning offset that should be used to draw the 2nd letter.
* @param {object} flags - font style, such as bold or italic
*/
get_kerning_offset(letters, flags = {}) {
let offset = this.kerningMap.get(letters);
if (offset == null) {
kerningTestCtx.font =
' ' + (flags.italic ? 'italic' : '') +
' ' + (flags.bold ? 'bold' : '') +
' ' + (this.size) + 'px' +
' ' + this.family;
offset = kerningTestCtx.measureText(letters).width - (kerningTestCtx.measureText(letters[0]).width + kerningTestCtx.measureText(letters[1]).width);
this.kerningMap.set(letters, offset);
}
return offset;
}
}
/**
* This class's job is to store and modify the internal JSON format of a text layer.
*/
class Text_document_class {
constructor() {
this.lines = [];
this.on_change = null;
// If user edits params while no selection, queue meta insertion for next type.
this.queuedMetaChanges = null;
}
/**
* Returns the number of lines in the document.
*/
get_line_count() {
return this.lines.length;
}
/**
* Returns the length of a given line
* @param {number} lineNumber - The number of the line to get the length of
*/
get_line_character_count(lineNumber) {
return this.get_line_text(lineNumber).length;
}
/**
* Returns the text string at a given line (ignores formatting).
* @param {number} lineNumber - The number of the line to get the text from
*/
get_line_text(lineNumber) {
let lineText = '';
for (let i = 0; i < this.lines[lineNumber].length; i++) {
lineText += this.lines[lineNumber][i].text;
}
return lineText;
}
/**
* Returns the position of the end of the the word at the line/character provided
* @param {number} line - The reference line number (0 indexed)
* @param {number} character - The reference character position (0 indexed)
* @param {boolean} noJump - Dont jump to the next word if at the end of current one
*/
get_word_end_position(line, character, noJump) {
let newLine = line;
let newCharacter = character;
let fullText = this.get_line_text(newLine);
if (character === fullText.length && newLine < this.lines.length - 1) {
if (noJump) {
return { line, character };
}
newLine += 1;
character = 0;
fullText = this.get_line_text(newLine);
}
const text = fullText.slice(character);
if (noJump && text[0] === ' ') {
return { line, character };
}
for (let i = 1; i < text.length; i++) {
if (text[i] === ' ') {
newCharacter = character + i;
break;
}
}
if (newCharacter === character) {
newCharacter = fullText.length + 1;
}
return {
line: newLine,
character: newCharacter
}
}
/**
* Returns the position of the start of the the word at the line/character provided
* @param {number} line - The reference line number (0 indexed)
* @param {number} character - The reference character position (0 indexed)
* @param {boolean} noJump - Dont jump to the next word if at the end of current one
*/
get_word_start_position(line, character, noJump) {
let newLine = line;
let newCharacter = character;
let isWrap = false;
if (character === 0 && newLine > 0) {
if (noJump) {
return { line, character };
}
isWrap = true;
newLine -= 1;
}
const fullText = this.get_line_text(newLine);
if (isWrap) {
character = fullText.length;
}
const text = fullText.slice(0, character);
if (noJump && text[text.length - 1] === ' ') {
return { line, character };
}
for (let i = -1; i >= -text.length; i--) {
if (text[i + text.length - 1] === ' ') {
newCharacter = character + i;
break;
}
}
if (newCharacter === character) {
newCharacter = 0;
}
return {
line: newLine,
character: newCharacter
}
}
/**
* Determine if the metadata (formatting) of two text spans is the same, usually used to determine if the spans can be merged together.
*/
is_same_span_meta(meta1, meta2) {
const meta1Keys = Object.keys(meta1).sort();
const meta2Keys = Object.keys(meta2).sort();
if (meta1Keys.length !== meta2Keys.length) {
return false;
}
for (let i = 0; i < meta1Keys.length; i++) {
if (meta1Keys[i] !== meta2Keys[i]) {
return false;
}
const meta1Value = meta1[meta1Keys[i]];
const meta2Value = meta2[meta2Keys[i]];
if (JSON.stringify(meta1Value) !== JSON.stringify(meta2Value)) {
return false;
}
}
return true;
}
/**
* Inserts a span with empty text in the document at the specified line and character position
* @param {number} line - The line number to insert at (0 indexed)
* @param {number} character - The character position to insert at (0 indexed)
* @param {object} meta - Metadata to associate with span
*/
insert_empty_span(line, character, meta) {
let insertedSpan = null;
const lineDef = this.lines[line];
let newLine = [];
let spanStartCharacter = 0;
let wasInserted = false;
for (let span of lineDef) {
if (!wasInserted && character >= spanStartCharacter && character <= spanStartCharacter + span.text.length) {
let textBefore = span.text.slice(0, character - spanStartCharacter);
let textAfter = span.text.slice(character - spanStartCharacter);
if (textBefore.length > 0) {
newLine.push({
text: textBefore,
meta: JSON.parse(JSON.stringify(span.meta))
});
}
const newMeta = JSON.parse(JSON.stringify(span.meta));
for (let metaKey in meta) {
newMeta[metaKey] = meta[metaKey];
}
insertedSpan = {
text: '',
meta: newMeta
};
newLine.push(insertedSpan);
if (textAfter.length > 0) {
newLine.push({
text: textAfter,
meta: JSON.parse(JSON.stringify(span.meta))
});
}
wasInserted = true;
} else {
newLine.push(span);
}
spanStartCharacter += span.text.length;
}
this.lines[line] = newLine;
return insertedSpan;
}
/**
* Inserts a text string in the document at the specified line and character position
* @param {string} text - The text string to insert
* @param {number} line - The line number to insert at (0 indexed)
* @param {number} character - The character position to insert at (0 indexed)
*/
insert_text(text, line, character) {
let insertedSpan;
if (this.queuedMetaChanges) {
insertedSpan = this.insert_empty_span(line, character, this.queuedMetaChanges);
this.queuedMetaChanges = null;
}
const insertLine = this.lines[line];
const textHasNewline = text.includes('\n');
let characterCount = 0;
let modifyingSpan = null;
let previousSpans = [];
let nextSpans = [];
let newLine = line;
let newCharacter = character;
// Insert text into span at specified line/character
for (let i = 0; i < insertLine.length; i++) {
const span = insertLine[i];
const spanLength = span.text.length;
if (!modifyingSpan && (character > characterCount || character === 0) && character <= characterCount + spanLength) {
if (insertLine[i + 1] && insertLine[i + 1].text === '') {
modifyingSpan = insertLine[i + 1];
} else {
modifyingSpan = span;
}
const textIdx = character - characterCount;
modifyingSpan.text = modifyingSpan.text.slice(0, textIdx) + text + modifyingSpan.text.slice(textIdx);
if (!textHasNewline) {
newCharacter = characterCount + textIdx + text.length;
break;
}
} else if (textHasNewline) {
if (modifyingSpan) {
nextSpans.push(span);
} else {
previousSpans.push(span);
}
}
characterCount += spanLength;
}
// Create new lines if newline character was used
if (textHasNewline && modifyingSpan) {
const modifiedSpans = [];
const textLines = modifyingSpan.text.split('\n');
for (let i = 0; i < textLines.length; i++) {
modifiedSpans.push({
meta: JSON.parse(JSON.stringify(modifyingSpan.meta)),
text: textLines[i]
});
}
this.lines[line] = [...previousSpans, modifiedSpans.shift()];
for (let i = 0; i < modifiedSpans.length; i++) {
if (i === modifiedSpans.length - 1) {
if (!modifiedSpans[i].text && nextSpans.length > 0) {
this.lines.splice(line + i + 1, 0, nextSpans);
} else {
this.lines.splice(line + i + 1, 0, [modifiedSpans[i], ...nextSpans]);
}
newLine = line + i + 1;
newCharacter = text.length - 1 - text.lastIndexOf('\n');
} else {
this.lines.splice(line + i + 1, 0, [modifiedSpans[i]]);
}
}
}
// Notify change
if (this.on_change) {
this.on_change(this.lines);
}
// Return end position
return {
line: newLine,
character: newCharacter
};
}
/**
* Deletes text withing the specified range
* @param {number} startLine - The starting line of the text range
* @param {number} startCharacter - The character position at the starting line of the text range
* @param {number} endLine - The ending line of the text range
* @param {number} endCharacter - The character position at the ending line of the text range
*/
delete_range(startLine, startCharacter, endLine, endCharacter) {
// Check bounds
startLine >= 0 || (startLine = 0);
startCharacter >= 0 || (startCharacter = 0);
endLine < this.lines.length || (endLine = this.lines.length - 1);
const endLineCharacterCount = this.get_line_character_count(endLine);
endCharacter <= endLineCharacterCount || (
endCharacter = endLineCharacterCount
);
// Early return if there's nothing to delete
if (startLine === endLine && startCharacter === endCharacter) {
return {
line: startLine,
character: startCharacter
};
}
// Get spans in start line before range
const beforeSpans = [];
const afterSpans = [];
let characterCount = 0;
let startSpan = null;
let startSpanDeleteIndex = 0;
for (let i = 0; i < this.lines[startLine].length; i++) {
const span = this.lines[startLine][i];
const spanLength = span.text.length;
if (!startSpan && (startCharacter > characterCount || startCharacter === 0) && startCharacter <= characterCount + spanLength) {
startSpan = span;
startSpanDeleteIndex = Math.max(0, startCharacter - characterCount);
break;
}
if (!startSpan) {
beforeSpans.push(span);
}
characterCount += spanLength;
}
// Get spans in end line after range
characterCount = 0;
let endSpan = null;
let endSpanDeleteIndex = 0;
for (let i = 0; i < this.lines[endLine].length; i++) {
const span = this.lines[endLine][i];
const spanLength = span.text.length;
if (!endSpan && (endCharacter > characterCount || endCharacter === 0) && endCharacter <= characterCount + spanLength) {
endSpan = span;
endSpanDeleteIndex = Math.max(0, endCharacter - characterCount);
}
else if (endSpan) {
afterSpans.push(span);
}
characterCount += spanLength;
}
// Merge start and end lines
this.lines[startLine] = [...beforeSpans];
if (startSpan === endSpan || this.is_same_span_meta(startSpan.meta, endSpan.meta)) {
const combinedSpans = {
meta: startSpan.meta,
text: startSpan.text.slice(0, startSpanDeleteIndex) + endSpan.text.slice(endSpanDeleteIndex)
};
if (combinedSpans.text || (beforeSpans.length === 0 && afterSpans.length === 0)) {
this.lines[startLine].push(combinedSpans);
}
} else {
const middleSpans = [];
let isAddedStartSpan = false;
let isAddedEndSpan = false;
if (startSpan) {
startSpan.text = startSpan.text.slice(0, startSpanDeleteIndex);
if (startSpan.text) {
middleSpans.push(startSpan);
isAddedStartSpan = true;
}
}
if (endSpan) {
endSpan.text = endSpan.text.slice(endSpanDeleteIndex)
if (endSpan.text || middleSpans.length === 0) {
middleSpans.push(endSpan);
isAddedEndSpan = true;
}
}
if (isAddedStartSpan && !isAddedEndSpan) {
const afterSpan = afterSpans[0];
if (afterSpan && this.is_same_span_meta(startSpan.meta, afterSpan.meta)) {
afterSpans.shift();
startSpan.text += afterSpan.text;
}
}
else if (isAddedEndSpan && !isAddedStartSpan) {
const beforeSpan = beforeSpans[beforeSpans.length - 1];
if (beforeSpan && this.is_same_span_meta(beforeSpan.meta, endSpan.meta)) {
beforeSpans.pop();
beforeSpan.text += endSpan.text;
}
}
else if (middleSpans.length === 0) {
const beforeSpan = beforeSpans[beforeSpans.length - 1];
const afterSpan = afterSpans[0];
if (beforeSpan && afterSpan && this.is_same_span_meta(beforeSpan.meta, afterSpan.meta)) {
afterSpans.shift();
beforeSpan.text += afterSpan.text;
}
}
this.lines[startLine] = this.lines[startLine].concat(middleSpans);
}
this.lines[startLine] = this.lines[startLine].concat(afterSpans);
// Delete lines in-between range
this.lines.splice(startLine + 1, endLine - startLine);
// Notify change
if (this.on_change) {
this.on_change(this.lines);
}
// Return new position
return {
line: startLine,
character: startCharacter
};
}
/**
* Deletes a single character in front or behind the specified character position, handling deleting new lines, etc.
* @param {boolean} forward - True if deleting the next character, otherwise deletes the previous character
* @param {number} startLine - The line number to delete from
* @param {number} startCharacter - The character position to delete from
*/
delete_character(forward, startLine, startCharacter) {
let endLine = startLine;
let endCharacter = startCharacter;
// Delete forwards
if (forward) {
// If there are characters after cursor on this line we remove one
if (startCharacter < this.get_line_character_count(startLine)) {
++endCharacter;
}
// if there are Lines after this one we append it
else if (startLine < this.lines.length - 1) {
++endLine;
endCharacter = 0;
}
}
// Delete backwards
else {
// If there are characters before the cursor on this line we remove one
if (startCharacter > 0) {
--startCharacter;
}
// if there are rows before we append current to previous one
else if (startLine > 0) {
--startLine;
startCharacter = this.get_line_character_count(startLine);
}
}
return this.delete_range(startLine, startCharacter, endLine, endCharacter);
}
/**
* Retrieves a metadata summary object for the specified range of text.
* @param {number} startLine - The starting line of the text range
* @param {number} startCharacter - The character position at the starting line of the text range
* @param {number} endLine - The ending line of the text range
* @param {number} endCharacter - The character position at the ending line of the text range
*/
get_meta_range(startLine, startCharacter, endLine, endCharacter) {
// Check bounds
startLine >= 0 || (startLine = 0);
startCharacter >= 0 || (startCharacter = 0);
endLine < this.lines.length || (endLine = this.lines.length - 1);
const endLineCharacterCount = this.get_line_character_count(endLine);
endCharacter <= endLineCharacterCount || (
endCharacter = endLineCharacterCount
);
const isEmpty = startLine === endLine && startCharacter === endCharacter;
// Loop through all spans in range and collect meta values
const metaCollection = {};
for (const metaKey in metaDefaults) {
metaCollection[metaKey] = [];
}
let isInsideRange = false;
for (let lineIndex = startLine; lineIndex <= endLine; lineIndex++) {
const line = this.lines[lineIndex];
let spanStartCharacter = 0;
let startSpan = null;
let endSpan = null;
for (let spanIndex = 0; spanIndex < line.length; spanIndex++) {
const span = line[spanIndex];
if (lineIndex === startLine) {
if (
(!isEmpty && startCharacter >= spanStartCharacter && startCharacter < spanStartCharacter + span.text.length) ||
(isEmpty && startCharacter > spanStartCharacter && startCharacter <= spanStartCharacter + span.text.length) ||
(startCharacter === 0 && spanStartCharacter === 0)
) {
isInsideRange = true;
startSpan = span;
}
}
if (lineIndex === endLine && isInsideRange) {
if (
(!isEmpty && endCharacter <= spanStartCharacter + span.text.length) ||
(isEmpty && endCharacter < spanStartCharacter + span.text.length)
) {
endSpan = span;
isInsideRange = false;
}
}
if (isInsideRange || startSpan === span || (!isEmpty && endSpan === span)) {
for (const metaKey in metaCollection) {
let metaValue = span.meta[metaKey];
if (metaValue == null) {
metaValue = metaDefaults[metaKey];
}
if (!metaCollection[metaKey].includes(metaValue)) {
metaCollection[metaKey].push(metaValue);
}
}
}
spanStartCharacter += span.text.length;
}
}
// Fill in default values for undefined meta keys
for (const metaKey in metaDefaults) {
if (metaCollection[metaKey].length === 0) {
metaCollection[metaKey] = [metaDefaults[metaKey]];
}
}
return metaCollection;
}
/**
* Sets styling metadata for the specified range of text.
* @param {number} startLine - The starting line of the text range
* @param {number} startCharacter - The character position at the starting line of the text range
* @param {number} endLine - The ending line of the text range
* @param {number} endCharacter - The character position at the ending line of the text range
* @param {object} meta - The meta to set
*/
set_meta_range(startLine, startCharacter, endLine, endCharacter, meta) {
// Check bounds
startLine >= 0 || (startLine = 0);
startCharacter >= 0 || (startCharacter = 0);
endLine < this.lines.length || (endLine = this.lines.length - 1);
const endLineCharacterCount = this.get_line_character_count(endLine);
endCharacter <= endLineCharacterCount || (
endCharacter = endLineCharacterCount
);
// Set meta of spans in selection
let isInsideRange = false;
for (let lineIndex = startLine; lineIndex <= endLine; lineIndex++) {
const line = this.lines[lineIndex];
let newLine = [];
let spanStartCharacter = 0;
for (let span of line) {
const spanText = span.text;
const spanLength = spanText.length;
if (lineIndex === startLine) {
if (startCharacter <= spanStartCharacter) {
isInsideRange = true;
}
}
if (lineIndex === endLine) {
if (endCharacter < spanStartCharacter + spanLength) {
isInsideRange = false;
}
}
// Selection start splits the span it's inside of
let choppedStartCharacters = 0;
if (startCharacter > spanStartCharacter && startCharacter < spanStartCharacter + spanLength && lineIndex === startLine) {
choppedStartCharacters = startCharacter - spanStartCharacter;
newLine.push({
text: span.text.slice(0, startCharacter - spanStartCharacter),
meta: JSON.parse(JSON.stringify(span.meta))
});
span.text = span.text.slice(startCharacter - spanStartCharacter);
isInsideRange = true;
}
newLine.push(span);
// Selection end splits the span it's inside of
if (endCharacter > spanStartCharacter && endCharacter < spanStartCharacter + spanLength && lineIndex === endLine) {
newLine.push({
text: span.text.slice(endCharacter - spanStartCharacter - choppedStartCharacters),
meta: JSON.parse(JSON.stringify(span.meta))
});
span.text = span.text.slice(0, endCharacter - spanStartCharacter - choppedStartCharacters);
isInsideRange = true;
}
// Add meta to span
if (isInsideRange) {
for (const metaKey in meta) {
span.meta[metaKey] = meta[metaKey];
}
}
spanStartCharacter += spanLength;
}
this.lines[lineIndex] = newLine;
}
this.normalize(startLine, endLine);
// Notify change
if (this.on_change) {
this.on_change(this.lines);
}
}
/**
* Merges sibling spans that have the same metadata, and removes empty spans.
* @param {number} startLine - The starting line of the text range
* @param {number} endLine - The ending line of the text range
*/
normalize(startLine, endLine) {
for (let lineIndex = startLine; lineIndex <= endLine; lineIndex++) {
const line = this.lines[lineIndex];
let spanIndex = 0;
for (spanIndex = 0; spanIndex < line.length; spanIndex++) {
const span1 = line[spanIndex];
const span2 = line[spanIndex + 1];
if (span1 && span2 && this.is_same_span_meta(span1.meta, span2.meta)) {
line[spanIndex] = {
text: span1.text + span2.text,
meta: span1.meta
};
line.splice(spanIndex + 1, 1);
spanIndex--;
continue;
}
if (span1.text === '' && line.length > 1) {
line.splice(spanIndex, 1);
spanIndex--;
continue;
}
}
}
}
}
/**
* This class represents a single selection range in a text editor's document.
*/
class Text_selection_class {
constructor(/* Text_editor_class */ editor) {
this.editor = editor;
this.isVisible = false;
this.isCursorVisible = false;
this.isActiveSideEnd = true;
this.isBlinkVisible = true;
this.blinkInterval = 500;
this.start = {
line: 0,
character: 0
};
this.end = {
line: 0,
character: 0
};
this.set_position(0, 0);
}
/**
* Returns if the current text selection contains no characters
* @returns {boolean}
*/
is_empty() {
return this.compare_position(this.start.line, this.start.character, this.end.line, this.end.character) === 0;
}
/**
* Determines the relative position of two line/character sets.
* @param {number} line1
* @param {number} character1
* @param {number} line2
* @param {number} character2
* @returns {number} -1 if line1/character1 is less than line2/character2, 1 if greater, and 0 if equal
*/
compare_position(line1, character1, line2, character2) {
if (line1 < line2) {
return -1;
} else if (line1 > line2) {
return 1;
} else {
if (character1 < character2) {
return -1;
} else if (character1 > character2) {
return 1;
} else {
return 0;
}
}
}
/**
* Sets the head position of the selection to the specified line/character, optionally extends to selection to that position.
* @param {number} line - The line number to set the selection to
* @param {number} character - The character index to set the selection to
* @param {boolean} [keepSelection] - If true, extends the current selection to the specified position. If false or undefined, sets an empty selection at that position.
*/
set_position(line, character, keepSelection) {
if (line == null) {
line = this.end.line;
}
if (character == null) {
character = this.end.character;
}
// Check lower bounds
line >= 0 || (line = 0);
character >= 0 || (character = 0);
// Check upper bounds
const lineCount = this.editor.document.get_line_count();
line < lineCount || (line = lineCount - 1);
const lineCharacterCount = this.editor.document.get_line_character_count(line);
character <= lineCharacterCount || (character = lineCharacterCount);
// Add to selection
if (keepSelection) {
const positionCompare = this.compare_position(
line,
character,
this.start.line,
this.start.character
);
// Determine whether we should make the start side of the range active, selection moving left or up.
if (positionCompare === -1 && (this.is_empty() || line < this.start.line)) {
this.isActiveSideEnd = false;
}
// Assign new value to the side that is active
if (this.isActiveSideEnd) {
this.end.line = line;
this.end.character = character;
} else {
this.start.line = line;
this.start.character = character;
}
// Making sure that end is greater than start and swap if necessary
if (this.compare_position(this.start.line, this.start.character, this.end.line, this.end.character) > 0) {
this.isActiveSideEnd = !this.isActiveSideEnd;
const temp = {
line: this.start.line,
character: this.start.character
}
this.start.line = this.end.line;
this.start.character = this.end.character;
this.end.line = temp.line;
this.end.character = temp.character;
}
}
// Empty cursor move
else {
this.isActiveSideEnd = true;
this.start.line = this.end.line = line;
this.start.character = this.end.character = character;
}
// Reset cursor blink
this.isBlinkVisible = true;
if (this.isVisible) {
this.start_blinking();
}
}
/**
* Retrieves the position of the head of the selection (could be the start or end of the selection based on previous operations)
* @returns {object} - { line, character }
*/
get_position() {
if (this.isActiveSideEnd) {
return {
character: this.end.character,
line: this.end.line
};
} else {
return {
character: this.start.character,
line: this.start.line
};
}
}
/**
* Gets the plain text value in the current selection range.
* @returns {string}
*/
get_text() {
const positionCompare = this.compare_position(this.start.line, this.start.character, this.end.line, this.end.character);
const firstLine = positionCompare === 1 ? this.end.line : this.start.line;
const lastLine = positionCompare === 1 ? this.start.line : this.end.line;
const firstCharacter = positionCompare === 1 ? this.end.character : this.start.character;
const lastCharacter = positionCompare === 1 ? this.start.character : this.end.character;
let textLines = [];
for (let i = firstLine; i <= lastLine; i++) {
if (i === firstLine && i === lastLine) {
textLines.push(this.editor.document.get_line_text(i).slice(firstCharacter, lastCharacter));
} else if (i === firstLine) {
textLines.push(this.editor.document.get_line_text(i).slice(firstCharacter));
} else if (i === lastLine) {
textLines.push(this.editor.document.get_line_text(i).slice(0, lastCharacter));
} else {
textLines.push(this.editor.document.get_line_text(i));
}
}
return textLines.join('\n');
}
/**
* Sets the visibility of the selection in the editor.
* @param {boolean} isVisible
*/
set_visible(isVisible) {
if (this.isVisible != isVisible) {
this.isVisible = isVisible;
}
}