@webcoder49/code-input 2.1.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,652 @@
1
+ /**
2
+ * Add Find-and-Replace (Ctrl+F for find, Ctrl+H for replace by default) functionality to the code editor.
3
+ * Files: find-and-replace.js / find-and-replace.css
4
+ */
5
+ codeInput.plugins.FindAndReplace = class extends codeInput.Plugin {
6
+ useCtrlF = false;
7
+ useCtrlH = false;
8
+
9
+ /**
10
+ * Create a find-and-replace command plugin to pass into a template
11
+ * @param {boolean} useCtrlF Should Ctrl+F be overriden for find-and-replace find functionality? If not, you can trigger it yourself using (instance of this plugin)`.showPrompt(code-input element, false)`.
12
+ * @param {boolean} useCtrlH Should Ctrl+H be overriden for find-and-replace replace functionality? If not, you can trigger it yourself using (instance of this plugin)`.showPrompt(code-input element, true)`.
13
+ */
14
+ constructor(useCtrlF = true, useCtrlH = true) {
15
+ super([]); // No observed attributes
16
+ this.useCtrlF = useCtrlF;
17
+ this.useCtrlH = useCtrlH;
18
+ }
19
+
20
+ /* Add keystroke events */
21
+ afterElementsAdded(codeInput) {
22
+ const textarea = codeInput.textareaElement;
23
+ if(this.useCtrlF) {
24
+ textarea.addEventListener('keydown', (event) => { this.checkCtrlF(codeInput, event); });
25
+ }
26
+ if(this.useCtrlH) {
27
+ textarea.addEventListener('keydown', (event) => { this.checkCtrlH(codeInput, event); });
28
+ }
29
+ }
30
+
31
+ /* After highlight, retry match highlighting */
32
+ afterHighlight(codeInput) {
33
+ if(codeInput.pluginData.findAndReplace != undefined && codeInput.pluginData.findAndReplace.dialog != undefined) {
34
+ if(!codeInput.pluginData.findAndReplace.dialog.classList.contains("code-input_find-and-replace_hidden-dialog")) {
35
+ // Code updated and dialog open - re-highlight find matches
36
+ codeInput.pluginData.findAndReplace.dialog.findMatchState.rehighlightMatches();
37
+ this.updateMatchDescription(codeInput.pluginData.findAndReplace.dialog);
38
+
39
+ if(codeInput.pluginData.findAndReplace.dialog.findMatchState.numMatches == 0) {
40
+ // No more matches after editing
41
+ codeInput.pluginData.findAndReplace.dialog.findInput.classList.add('code-input_find-and-replace_error');
42
+ }
43
+ }
44
+ }
45
+ }
46
+
47
+ /* Get a Regular Expression to match a specific piece of text, by escaping the text: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */
48
+ text2RegExp(string, caseSensitive, stringIsRegexp) {
49
+ // "i" flag means case-"i"nsensitive
50
+ return new RegExp(stringIsRegexp ? string : string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), caseSensitive ? "g" : "gi"); // $& means the whole matched string
51
+ }
52
+
53
+ /* Update the dialog description to show the find matches */
54
+ updateMatchDescription(dialog) {
55
+ // 1-indexed
56
+ if(dialog.findInput.value.length == 0) {
57
+ dialog.matchDescription.textContent = "Search for matches in your code.";
58
+ } else if(dialog.findMatchState.numMatches <= 0) {
59
+ dialog.matchDescription.textContent = "No matches.";
60
+ } else if(dialog.findMatchState.numMatches == 1) {
61
+ dialog.matchDescription.textContent = "1 match found.";
62
+ } else {
63
+ dialog.matchDescription.textContent = `${dialog.findMatchState.focusedMatchID+1} of ${dialog.findMatchState.numMatches} matches.`;
64
+ }
65
+ }
66
+
67
+ /* Called with a find input keyup event to find all matches in the code and focus the next match if Enter is pressed */
68
+ updateFindMatches(dialog) {
69
+ // Update matches for find functionality; debounce it to prevent delay with single-character search
70
+ let oldValue = dialog.findInput.value;
71
+ setTimeout(() => {
72
+ if(oldValue == dialog.findInput.value) {
73
+ // Stopped typing
74
+ dialog.findMatchState.clearMatches();
75
+ if(oldValue.length > 0) {
76
+ try {
77
+ dialog.findMatchState.updateMatches(this.text2RegExp(dialog.findInput.value, dialog.findCaseSensitiveCheckbox.checked, dialog.findRegExpCheckbox.checked));
78
+ } catch (err) {
79
+ if(err instanceof SyntaxError) {
80
+ // Syntax error due to malformed RegExp
81
+ dialog.findInput.classList.add('code-input_find-and-replace_error');
82
+ // Only show last part of error message
83
+ let messageParts = err.message.split(": ");
84
+ dialog.matchDescription.textContent = "Error: " + messageParts[messageParts.length-1]; // Show only last part of error.
85
+ return;
86
+ } else {
87
+ throw err;
88
+ }
89
+ }
90
+
91
+ if(dialog.findMatchState.numMatches > 0) {
92
+ dialog.findInput.classList.remove('code-input_find-and-replace_error');
93
+ } else {
94
+ // No matches - error
95
+ dialog.findInput.classList.add('code-input_find-and-replace_error');
96
+ }
97
+ }
98
+ this.updateMatchDescription(dialog);
99
+ }
100
+ }, 100);
101
+ }
102
+
103
+ /* Deal with Enter and Escape being pressed in the find field */
104
+ checkFindPrompt(dialog, codeInput, event) {
105
+ if (event.key == 'Enter') {
106
+ // Find next match
107
+ dialog.findMatchState.nextMatch();
108
+ this.updateMatchDescription(dialog);
109
+ }
110
+ }
111
+
112
+ /* Deal with Enter and Escape being pressed in the replace field */
113
+ checkReplacePrompt(dialog, codeInput, event) {
114
+ if (event.key == 'Enter') {
115
+ // Replace focused match
116
+ dialog.findMatchState.replaceOnce(dialog.replaceInput.value);
117
+ this.updateMatchDescription(dialog);
118
+ }
119
+ }
120
+
121
+ /* Called with a dialog box keyup event to close and clear the dialog box */
122
+ cancelPrompt(dialog, codeInput, event) {
123
+ event.preventDefault();
124
+
125
+ // Reset original selection in code-input
126
+ dialog.textarea.focus();
127
+ if(dialog.findMatchState.numMatches > 0) {
128
+ // Select focused match
129
+ codeInput.textareaElement.selectionStart = dialog.findMatchState.matchStartIndexes[dialog.findMatchState.focusedMatchID];
130
+ codeInput.textareaElement.selectionEnd = dialog.findMatchState.matchEndIndexes[dialog.findMatchState.focusedMatchID];
131
+ } else {
132
+ // Select text selected before
133
+ codeInput.textareaElement.selectionStart = dialog.selectionStart;
134
+ codeInput.textareaElement.selectionEnd = dialog.selectionEnd;
135
+ }
136
+
137
+ dialog.findMatchState.clearMatches();
138
+
139
+ // Remove dialog after animation
140
+ dialog.classList.add('code-input_find-and-replace_hidden-dialog');
141
+ }
142
+
143
+ /**
144
+ * Show a find-and-replace dialog.
145
+ * @param {codeInput.CodeInput} codeInputElement the `<code-input>` element.
146
+ * @param {boolean} replacePartExpanded whether the replace part of the find-and-replace dialog should be expanded
147
+ */
148
+ showPrompt(codeInputElement, replacePartExpanded) {
149
+ if(codeInputElement.pluginData.findAndReplace == undefined || codeInputElement.pluginData.findAndReplace.dialog == undefined) {
150
+ const textarea = codeInputElement.textareaElement;
151
+
152
+ const dialog = document.createElement('div');
153
+ const findInput = document.createElement('input');
154
+ const findCaseSensitiveCheckbox = document.createElement('input');
155
+ const findRegExpCheckbox = document.createElement('input');
156
+ const matchDescription = document.createElement('code');
157
+
158
+ const replaceInput = document.createElement('input');
159
+ const replaceDropdown = document.createElement('details');
160
+ const replaceSummary = document.createElement('summary');
161
+
162
+ const buttonContainer = document.createElement('div');
163
+ const findNextButton = document.createElement('button');
164
+ const findPreviousButton = document.createElement('button');
165
+ const replaceButton = document.createElement('button');
166
+ const replaceAllButton = document.createElement('button');
167
+ const cancel = document.createElement('span');
168
+
169
+ buttonContainer.appendChild(findNextButton);
170
+ buttonContainer.appendChild(findPreviousButton);
171
+ buttonContainer.appendChild(replaceButton);
172
+ buttonContainer.appendChild(replaceAllButton);
173
+ buttonContainer.appendChild(cancel);
174
+ dialog.appendChild(buttonContainer);
175
+
176
+ dialog.appendChild(findInput);
177
+ dialog.appendChild(findRegExpCheckbox);
178
+ dialog.appendChild(findCaseSensitiveCheckbox);
179
+ dialog.appendChild(matchDescription);
180
+ replaceDropdown.appendChild(replaceSummary);
181
+ replaceDropdown.appendChild(replaceInput);
182
+
183
+ dialog.appendChild(replaceDropdown);
184
+
185
+ dialog.className = 'code-input_find-and-replace_dialog';
186
+ findInput.spellcheck = false;
187
+ findInput.placeholder = "Find";
188
+ findCaseSensitiveCheckbox.setAttribute("type", "checkbox");
189
+ findCaseSensitiveCheckbox.title = "Match Case Sensitive";
190
+ findCaseSensitiveCheckbox.classList.add("code-input_find-and-replace_case-sensitive-checkbox");
191
+ findRegExpCheckbox.setAttribute("type", "checkbox");
192
+ findRegExpCheckbox.title = "Use JavaScript Regular Expression";
193
+ findRegExpCheckbox.classList.add("code-input_find-and-replace_reg-exp-checkbox");
194
+
195
+ matchDescription.textContent = "Search for matches in your code.";
196
+ matchDescription.classList.add("code-input_find-and-replace_match-description");
197
+
198
+
199
+ replaceSummary.innerText = "Replace";
200
+ replaceInput.spellcheck = false;
201
+ replaceInput.placeholder = "Replace with";
202
+ findNextButton.innerText = "↓";
203
+ findNextButton.title = "Find Next Occurence";
204
+ findPreviousButton.innerText = "↑";
205
+ findPreviousButton.title = "Find Previous Occurence";
206
+ replaceButton.className = 'code-input_find-and-replace_button-hidden';
207
+ replaceButton.innerText = "Replace";
208
+ replaceButton.title = "Replace This Occurence";
209
+ replaceAllButton.className = 'code-input_find-and-replace_button-hidden';
210
+ replaceAllButton.innerText = "Replace All";
211
+ replaceAllButton.title = "Replace All Occurences";
212
+
213
+ findNextButton.addEventListener("click", (event) => {
214
+ // Stop form submit
215
+ event.preventDefault();
216
+
217
+ dialog.findMatchState.nextMatch();
218
+ this.updateMatchDescription(dialog);
219
+ });
220
+ findPreviousButton.addEventListener("click", () => {
221
+ // Stop form submit
222
+ event.preventDefault();
223
+
224
+ dialog.findMatchState.previousMatch();
225
+ this.updateMatchDescription(dialog);
226
+ });
227
+ replaceButton.addEventListener("click", (event) => {
228
+ // Stop form submit
229
+ event.preventDefault();
230
+
231
+ dialog.findMatchState.replaceOnce(replaceInput.value);
232
+ replaceButton.focus();
233
+ });
234
+ replaceAllButton.addEventListener("click", (event) => {
235
+ // Stop form submit
236
+ event.preventDefault();
237
+
238
+ dialog.findMatchState.replaceAll(replaceInput.value);
239
+ replaceAllButton.focus();
240
+ });
241
+
242
+ replaceDropdown.addEventListener("toggle", () => {
243
+ // When replace dropdown opened show replace buttons
244
+ replaceButton.classList.toggle("code-input_find-and-replace_button-hidden");
245
+ replaceAllButton.classList.toggle("code-input_find-and-replace_button-hidden");
246
+ });
247
+
248
+ // To store the state of find-and-replace functionality
249
+ dialog.findMatchState = new codeInput.plugins.FindAndReplace.FindMatchState(codeInputElement);
250
+
251
+ dialog.codeInput = codeInputElement;
252
+ dialog.textarea = textarea;
253
+ dialog.findInput = findInput;
254
+ dialog.findCaseSensitiveCheckbox = findCaseSensitiveCheckbox;
255
+ dialog.findRegExpCheckbox = findRegExpCheckbox;
256
+ dialog.matchDescription = matchDescription;
257
+ dialog.replaceInput = replaceInput;
258
+ dialog.replaceDropdown = replaceDropdown;
259
+
260
+ if(this.checkCtrlH) {
261
+ findInput.addEventListener('keydown', (event) => {
262
+ /* Open replace part on Ctrl+H */
263
+ if (event.ctrlKey && event.key == 'h') {
264
+ event.preventDefault();
265
+ replaceDropdown.setAttribute("open", true);
266
+ }
267
+ });
268
+ }
269
+
270
+ findInput.addEventListener('keypress', (event) => {
271
+ /* Stop enter from submitting form */
272
+ if (event.key == 'Enter') event.preventDefault();
273
+ });
274
+ replaceInput.addEventListener('keypress', (event) => {
275
+ /* Stop enter from submitting form */
276
+ if (event.key == 'Enter') event.preventDefault();
277
+ });
278
+
279
+ dialog.addEventListener('keyup', (event) => {
280
+ /* Close prompt on Enter pressed */
281
+ if (event.key == 'Escape') this.cancelPrompt(dialog, codeInputElement, event);
282
+ });
283
+
284
+ findInput.addEventListener('keyup', (event) => { this.checkFindPrompt(dialog, codeInputElement, event); });
285
+ findInput.addEventListener('input', (event) => { this.updateFindMatches(dialog); });
286
+ findCaseSensitiveCheckbox.addEventListener('click', (event) => { this.updateFindMatches(dialog); });
287
+ findRegExpCheckbox.addEventListener('click', (event) => { this.updateFindMatches(dialog); });
288
+
289
+ replaceInput.addEventListener('keyup', (event) => {
290
+ this.checkReplacePrompt(dialog, codeInputElement, event);
291
+ replaceInput.focus();
292
+ });
293
+ cancel.addEventListener('click', (event) => { this.cancelPrompt(dialog, codeInputElement, event); });
294
+
295
+ codeInputElement.dialogContainerElement.appendChild(dialog);
296
+ codeInputElement.pluginData.findAndReplace = {dialog: dialog};
297
+ findInput.focus();
298
+
299
+ if(replacePartExpanded) {
300
+ replaceDropdown.setAttribute("open", true);
301
+ }
302
+
303
+ // Save selection position
304
+ dialog.selectionStart = codeInputElement.textareaElement.selectionStart;
305
+ dialog.selectionEnd = codeInputElement.textareaElement.selectionEnd;
306
+ } else {
307
+ // Re-open dialog
308
+ codeInputElement.pluginData.findAndReplace.dialog.classList.remove("code-input_find-and-replace_hidden-dialog");
309
+ codeInputElement.pluginData.findAndReplace.dialog.findInput.focus();
310
+ if(replacePartExpanded) {
311
+ codeInputElement.pluginData.findAndReplace.dialog.replaceDropdown.setAttribute("open", true);
312
+ } else {
313
+ codeInputElement.pluginData.findAndReplace.dialog.replaceDropdown.removeAttribute("open");
314
+ }
315
+
316
+
317
+ // Highlight matches
318
+ this.updateFindMatches(codeInputElement.pluginData.findAndReplace.dialog);
319
+
320
+ // Save selection position
321
+ codeInputElement.pluginData.findAndReplace.dialog.selectionStart = codeInputElement.textareaElement.selectionStart;
322
+ codeInputElement.pluginData.findAndReplace.dialog.selectionEnd = codeInputElement.textareaElement.selectionEnd;
323
+ }
324
+ }
325
+
326
+ /* Event handler for keydown event that makes Ctrl+F open find dialog */
327
+ checkCtrlF(codeInput, event) {
328
+ if (event.ctrlKey && event.key == 'f') {
329
+ event.preventDefault();
330
+ this.showPrompt(codeInput, false);
331
+ }
332
+ }
333
+
334
+ /* Event handler for keydown event that makes Ctrl+H open find+replace dialog */
335
+ checkCtrlH(codeInput, event) {
336
+ if (event.ctrlKey && event.key == 'h') {
337
+ event.preventDefault();
338
+ this.showPrompt(codeInput, true);
339
+ }
340
+ }
341
+ }
342
+
343
+ // Number of matches to highlight at once, for efficiency reasons
344
+ const CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE = 500;
345
+
346
+ /* This class stores the state of find and replace in a specific code-input element */
347
+ codeInput.plugins.FindAndReplace.FindMatchState = class {
348
+ codeInput = null;
349
+ lastValue = null; // of codeInput, so know when to update matches
350
+ lastSearchRegexp = null; // to be able to update matches
351
+ numMatches = 0;
352
+ focusedMatchID = 0;
353
+ matchStartIndexes = []; // For each match in order
354
+ matchEndIndexes = []; // For each match in order
355
+ focusedMatchStartIndex = 0;
356
+
357
+ matchBlocksHighlighted = []; // Each block represents a CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE number of matches (up to it for the last), and is highlighted separately to prevent excessive delay.
358
+
359
+ constructor(codeInputElement) {
360
+ this.focusedMatchStartIndex = codeInputElement.textareaElement.selectionStart;
361
+ this.codeInput = codeInputElement;
362
+ }
363
+
364
+ /* Clear the find matches, often to prepare for new matches to be added. */
365
+ clearMatches() {
366
+ // Delete match information saved here
367
+ this.numMatches = 0;
368
+ this.matchStartIndexes = [];
369
+ this.matchEndIndexes = [];
370
+
371
+ // Remove generated spans to hold matches
372
+ let tempSpans = this.codeInput.codeElement.querySelectorAll(".code-input_find-and-replace_temporary-span");
373
+ for(let i = 0; i < tempSpans.length; i++) {
374
+ // Replace with textContent as Text node
375
+ tempSpans[i].parentElement.replaceChild(new Text(tempSpans[i].textContent), tempSpans[i]);
376
+ }
377
+
378
+ // Remove old matches
379
+ let oldMatches = this.codeInput.codeElement.querySelectorAll(".code-input_find-and-replace_find-match");
380
+ for(let i = 0; i < oldMatches.length; i++) {
381
+ oldMatches[i].removeAttribute("data-code-input_find-and-replace_match-id"); // No match ID
382
+ oldMatches[i].classList.remove("code-input_find-and-replace_find-match"); // No highlighting
383
+ oldMatches[i].classList.remove("code-input_find-and-replace_find-match-focused"); // No focused highlighting
384
+ }
385
+ }
386
+
387
+ /* Refresh the matches of find functionality with a new search term Regular Expression. */
388
+ updateMatches(searchRegexp) {
389
+ this.lastSearchRegexp = searchRegexp;
390
+ this.lastValue = this.codeInput.value;
391
+ // Add matches
392
+ let matchID = 0;
393
+ let match; // Search result
394
+ this.matchStartIndexes = [];
395
+ this.matchEndIndexes = [];
396
+ this.matchBlocksHighlighted = [];
397
+
398
+ // Make all match blocks be not highlighted except for currently focused
399
+ let focusedMatchBlock = Math.floor(this.focusedMatchID / CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE);
400
+ for(let i = 0; i < focusedMatchBlock; i++) {
401
+ this.matchBlocksHighlighted.push(false);
402
+ }
403
+ this.matchBlocksHighlighted.push(true);
404
+
405
+ while ((match = searchRegexp.exec(this.codeInput.value)) !== null) {
406
+ let matchText = match[0];
407
+ if(matchText.length == 0) {
408
+ throw SyntaxError("Causes an infinite loop");
409
+ }
410
+
411
+ // Add next match block if needed
412
+ let currentMatchBlock = Math.floor(matchID / CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE);
413
+ if(this.matchBlocksHighlighted.length < currentMatchBlock) {
414
+ this.matchBlocksHighlighted.push(false);
415
+ }
416
+
417
+ if(this.matchBlocksHighlighted[currentMatchBlock]) {
418
+ this.highlightMatch(matchID, this.codeInput.codeElement, match.index, match.index + matchText.length);
419
+ }
420
+ this.matchStartIndexes.push(match.index);
421
+ this.matchEndIndexes.push(match.index + matchText.length);
422
+ matchID++;
423
+ }
424
+ this.numMatches = matchID;
425
+
426
+ if(this.numMatches > 0) {
427
+ this.focusMatch();
428
+ }
429
+ }
430
+
431
+ /* Highlight all currently found matches again if there are any matches */
432
+ rehighlightMatches() {
433
+ this.updateMatches(this.lastSearchRegexp);
434
+ this.focusMatch();
435
+ }
436
+
437
+ /* Replace one match with the replacementText given */
438
+ replaceOnce(replacementText) {
439
+ if(this.numMatches > 0 && replacementText != this.codeInput.value.substring(0, this.matchStartIndexes[this.focusedMatchID], this.matchEndIndexes[this.focusedMatchID])) {
440
+ // Go to next match
441
+ this.focusedMatchStartIndex += replacementText.length;
442
+
443
+ // Select the match
444
+ this.codeInput.textareaElement.focus();
445
+ this.codeInput.textareaElement.selectionStart = this.matchStartIndexes[this.focusedMatchID];
446
+ this.codeInput.textareaElement.selectionEnd = this.matchEndIndexes[this.focusedMatchID];
447
+
448
+ // Replace it with the replacement text
449
+ document.execCommand("insertText", false, replacementText);
450
+ }
451
+ }
452
+
453
+ /* Replace all matches with the replacementText given */
454
+ replaceAll(replacementText) {
455
+ const replacementNumChars = replacementText.length;
456
+ let numCharsAdded = 0; // So can adjust match positions
457
+
458
+ for(let i = 0; i < this.numMatches; i++) {
459
+ // Replace each match
460
+
461
+ // Select the match, taking into account characters added before
462
+ this.codeInput.textareaElement.focus();
463
+ this.codeInput.textareaElement.selectionStart = this.matchStartIndexes[i] + numCharsAdded;
464
+ this.codeInput.textareaElement.selectionEnd = this.matchEndIndexes[i] + numCharsAdded;
465
+
466
+ numCharsAdded += replacementNumChars - (this.matchEndIndexes[i] - this.matchStartIndexes[i]);
467
+
468
+ // Replace it with the replacement text
469
+ document.execCommand("insertText", false, replacementText);
470
+ }
471
+ }
472
+
473
+ /* Focus on the next match found in the find results */
474
+ nextMatch() {
475
+ this.focusMatch((this.focusedMatchID + 1) % this.numMatches);
476
+ }
477
+
478
+ /* Focus on the previous match found in the find results */
479
+ previousMatch() {
480
+ this.focusMatch((this.focusedMatchID + this.numMatches - 1) % this.numMatches);
481
+ }
482
+
483
+ /* Change the focused match to the match with ID matchID. */
484
+ focusMatch(matchID = undefined) {
485
+ if(matchID === undefined) {
486
+ // Focus on first match after focusedMatchStartIndex
487
+ matchID = 0;
488
+ while(matchID < this.matchStartIndexes.length && this.matchStartIndexes[matchID] < this.focusedMatchStartIndex) {
489
+ matchID++;
490
+ }
491
+ if(matchID >= this.matchStartIndexes.length) {
492
+ // After last match, move back to first match
493
+ matchID = 0;
494
+ }
495
+ }
496
+
497
+ // Save focusedMatchStartIndex so if code changed match stays at same place
498
+ this.focusedMatchStartIndex = this.matchStartIndexes[matchID];
499
+ this.focusedMatchID = matchID;
500
+
501
+ // Delete old focus
502
+ let oldFocused = this.codeInput.codeElement.querySelectorAll(".code-input_find-and-replace_find-match-focused");
503
+ for(let i = 0; i < oldFocused.length; i++) {
504
+ oldFocused[i].classList.remove("code-input_find-and-replace_find-match-focused");
505
+ }
506
+
507
+ // Highlight match block if needed
508
+ let highlightedMatchBlock = Math.floor(matchID / CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE);
509
+ if(!this.matchBlocksHighlighted[highlightedMatchBlock]) {
510
+ this.matchBlocksHighlighted[highlightedMatchBlock] = true;
511
+ for(let i = CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE*highlightedMatchBlock; i < CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE*(highlightedMatchBlock+1); i++) {
512
+ // Highlight match
513
+ this.highlightMatch(i, this.codeInput.codeElement, this.matchStartIndexes[i], this.matchEndIndexes[i])
514
+ }
515
+ }
516
+
517
+ // Add new focus
518
+ let newFocused = this.codeInput.codeElement.querySelectorAll(`.code-input_find-and-replace_find-match[data-code-input_find-and-replace_match-id="${matchID}"]`);
519
+ for(let i = 0; i < newFocused.length; i++) {
520
+ newFocused[i].classList.add("code-input_find-and-replace_find-match-focused");
521
+ }
522
+
523
+ if(newFocused.length > 0) {
524
+ this.codeInput.scrollTo(newFocused[0].offsetLeft - this.codeInput.offsetWidth / 2, newFocused[0].offsetTop - this.codeInput.offsetHeight / 2); // So focused match in centre of screen
525
+ }
526
+ }
527
+
528
+ /* Highlight a match from the find functionality given its start and end indexes in the text.
529
+ Start from the currentElement as this function is recursive. Use the matchID in the class name
530
+ of the match so different matches can be identified. */
531
+ highlightMatch(matchID, currentElement, startIndex, endIndex) {
532
+ for(let i = 0; i < currentElement.childNodes.length; i++) {
533
+ let childElement = currentElement.childNodes[i];
534
+ let childText = childElement.textContent;
535
+
536
+ let noInnerElements = false;
537
+ if(childElement.nodeType == 3) {
538
+ if(i + 1 < currentElement.childNodes.length && currentElement.childNodes[i+1].nodeType == 3) {
539
+ // Can merge with next text node
540
+ currentElement.childNodes[i+1].textContent = childElement.textContent + currentElement.childNodes[i+1].textContent; // Merge textContent with next node
541
+ currentElement.removeChild(childElement); // Delete this node
542
+ i--; // As an element removed
543
+ continue; // Move to next node
544
+ }
545
+ // Text node - replace with span
546
+ noInnerElements = true;
547
+
548
+ let replacementElement = document.createElement("span");
549
+ replacementElement.textContent = childText;
550
+ replacementElement.classList.add("code-input_find-and-replace_temporary-span"); // Can remove
551
+
552
+ currentElement.replaceChild(replacementElement, childElement);
553
+ childElement = replacementElement;
554
+ }
555
+
556
+ if(startIndex <= 0) {
557
+ // Started highlight
558
+ if(childText.length >= endIndex) {
559
+ // Match ends in childElement
560
+ if(noInnerElements) {
561
+ // Text node - highlight first part
562
+ let startSpan = document.createElement("span");
563
+ startSpan.classList.add("code-input_find-and-replace_find-match"); // Highlighted
564
+ startSpan.setAttribute("data-code-input_find-and-replace_match-id", matchID);
565
+ startSpan.classList.add("code-input_find-and-replace_temporary-span"); // Can remove
566
+ startSpan.textContent = childText.substring(0, endIndex);
567
+ if(startSpan.textContent[0] == "\n") {
568
+ // Newline at start - make clear
569
+ startSpan.classList.add("code-input_find-and-replace_start-newline");
570
+ }
571
+
572
+ let endText = childText.substring(endIndex);
573
+ childElement.textContent = endText;
574
+
575
+ childElement.insertAdjacentElement('beforebegin', startSpan);
576
+ i++; // An extra element has been added
577
+ return;
578
+ } else {
579
+ this.highlightMatch(matchID, childElement, 0, endIndex);
580
+ }
581
+
582
+ // Match ended - nothing to do after backtracking
583
+ return;
584
+ } else {
585
+ // Match goes through child element
586
+ childElement.classList.add("code-input_find-and-replace_find-match"); // Highlighted
587
+ childElement.setAttribute("data-code-input_find-and-replace_match-id", matchID);
588
+ if(childElement.textContent[0] == "\n") {
589
+ // Newline at start - make clear
590
+ childElement.classList.add("code-input_find-and-replace_start-newline");
591
+ }
592
+ }
593
+ } else if(childText.length > startIndex) {
594
+ // Match starts in childElement
595
+ if(noInnerElements) {
596
+ if(childText.length > endIndex) {
597
+ // Match starts and ends in childElement - highlight middle part
598
+ // Text node - highlight last part
599
+ let startSpan = document.createElement("span");
600
+ startSpan.classList.add("code-input_find-and-replace_temporary-span"); // Can remove
601
+ startSpan.textContent = childText.substring(0, startIndex);
602
+
603
+ let middleText = childText.substring(startIndex, endIndex);
604
+ childElement.textContent = middleText;
605
+ childElement.classList.add("code-input_find-and-replace_find-match"); // Highlighted
606
+ childElement.setAttribute("data-code-input_find-and-replace_match-id", matchID);
607
+ if(childElement.textContent[0] == "\n") {
608
+ // Newline at start - make clear
609
+ childElement.classList.add("code-input_find-and-replace_start-newline");
610
+ }
611
+
612
+ let endSpan = document.createElement("span");
613
+ endSpan.classList.add("code-input_find-and-replace_temporary-span"); // Can remove
614
+ endSpan.textContent = childText.substring(endIndex);
615
+
616
+ childElement.insertAdjacentElement('beforebegin', startSpan);
617
+ childElement.insertAdjacentElement('afterend', endSpan);
618
+ i++; // 2 extra elements have been added
619
+ } else {
620
+ // Text node - highlight last part
621
+ let startText = childText.substring(0, startIndex);
622
+ childElement.textContent = startText;
623
+
624
+ let endSpan = document.createElement("span");
625
+ endSpan.classList.add("code-input_find-and-replace_find-match"); // Highlighted
626
+ endSpan.setAttribute("data-code-input_find-and-replace_match-id", matchID);
627
+ endSpan.classList.add("code-input_find-and-replace_temporary-span"); // Can remove
628
+ endSpan.textContent = childText.substring(startIndex);
629
+ if(endSpan.textContent[0] == "\n") {
630
+ // Newline at start - make clear
631
+ endSpan.classList.add("code-input_find-and-replace_start-newline");
632
+ }
633
+
634
+ childElement.insertAdjacentElement('afterend', endSpan);
635
+ i++; // An extra element has been added
636
+ }
637
+ } else {
638
+ this.highlightMatch(matchID, childElement, startIndex, endIndex);
639
+ }
640
+
641
+ if(childText.length > endIndex) {
642
+ // Match completely in childElement - nothing to do after backtracking
643
+ return;
644
+ }
645
+ }
646
+
647
+ // Make indexes skip the element
648
+ startIndex -= childText.length;
649
+ endIndex -= childText.length;
650
+ }
651
+ }
652
+ }
@@ -0,0 +1 @@
1
+ .code-input_find-and-replace_find-match{color:inherit;text-shadow:none!important;background-color:#ff0!important}.code-input_find-and-replace_find-match-focused,.code-input_find-and-replace_find-match-focused *{background-color:#f80!important;color:#000!important}.code-input_find-and-replace_start-newline::before{content:"⤶"}@keyframes code-input_find-and-replace_roll-in{0%{opacity:0;transform:translateY(-34px)}100%{opacity:1;transform:translateY(0)}}@keyframes code-input_find-and-replace_roll-out{0%{opacity:1;top:0}100%{opacity:0;top:-34px}}.code-input_find-and-replace_dialog{position:absolute;top:0;right:14px;padding:6px;padding-top:8px;border:solid 1px #00000044;background-color:#fff;border-radius:6px;box-shadow:0 .2em 1em .2em rgba(0,0,0,.16)}.code-input_find-and-replace_dialog:not(.code-input_find-and-replace_hidden-dialog){animation:code-input_find-and-replace_roll-in .2s;opacity:1;pointer-events:all}.code-input_find-and-replace_dialog.code-input_find-and-replace_hidden-dialog{animation:code-input_find-and-replace_roll-out .2s;opacity:0;pointer-events:none}.code-input_find-and-replace_dialog input::placeholder{font-size:80%}.code-input_find-and-replace_dialog input{position:relative;width:240px;height:32px;top:-3px;font-size:large;color:#000000aa;border:0}.code-input_find-and-replace_dialog input:hover{outline:0}.code-input_find-and-replace_dialog input.code-input_find-and-replace_error{color:#ff0000aa}.code-input_find-and-replace_dialog button,.code-input_find-and-replace_dialog input[type=checkbox]{display:inline-block;line-height:24px;font-size:22px;cursor:pointer;appearance:none;width:min-content;margin:5px;padding:5px;border:0;background-color:#ddd;text-align:center;color:#000;vertical-align:top}.code-input_find-and-replace_dialog input[type=checkbox].code-input_find-and-replace_case-sensitive-checkbox::before{content:"Aa"}.code-input_find-and-replace_dialog input[type=checkbox].code-input_find-and-replace_reg-exp-checkbox::before{content:".*"}.code-input_find-and-replace_dialog button:hover,.code-input_find-and-replace_dialog input[type=checkbox]:hover{background-color:#bbb}.code-input_find-and-replace_dialog input[type=checkbox]:checked{background-color:#222;color:#fff}.code-input_find-and-replace_match-description{display:block;color:#444}.code-input_find-and-replace_dialog button,.code-input_find-and-replace_dialog details summary{cursor:pointer}.code-input_find-and-replace_dialog button.code-input_find-and-replace_button-hidden{opacity:0;pointer-events:none}.code-input_find-and-replace_dialog span{display:block;float:right;margin:5px;padding:5px;width:24px;line-height:24px;font-family:system-ui;font-size:22px;font-weight:500;text-align:center;border-radius:50%;color:#000;opacity:.6}.code-input_find-and-replace_dialog span:before{content:"\00d7"}.code-input_find-and-replace_dialog span:hover{opacity:.8;background-color:#00000018}