@webcoder49/code-input 2.1.0 → 2.5.0

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.
Files changed (44) hide show
  1. package/CONTRIBUTING.md +11 -1
  2. package/README.md +26 -11
  3. package/code-input.css +126 -29
  4. package/code-input.d.ts +153 -11
  5. package/code-input.js +218 -193
  6. package/code-input.min.css +1 -1
  7. package/code-input.min.js +1 -1
  8. package/package.json +1 -1
  9. package/plugins/README.md +28 -6
  10. package/plugins/auto-close-brackets.js +61 -0
  11. package/plugins/auto-close-brackets.min.js +1 -0
  12. package/plugins/autocomplete.js +21 -12
  13. package/plugins/autocomplete.min.js +1 -1
  14. package/plugins/autodetect.js +4 -4
  15. package/plugins/autodetect.min.js +1 -1
  16. package/plugins/find-and-replace.css +145 -0
  17. package/plugins/find-and-replace.js +746 -0
  18. package/plugins/find-and-replace.min.css +1 -0
  19. package/plugins/find-and-replace.min.js +1 -0
  20. package/plugins/go-to-line.css +77 -0
  21. package/plugins/go-to-line.js +175 -0
  22. package/plugins/go-to-line.min.css +1 -0
  23. package/plugins/go-to-line.min.js +1 -0
  24. package/plugins/indent.js +166 -15
  25. package/plugins/indent.min.js +1 -1
  26. package/plugins/prism-line-numbers.css +10 -9
  27. package/plugins/prism-line-numbers.min.css +1 -1
  28. package/plugins/select-token-callbacks.js +289 -0
  29. package/plugins/select-token-callbacks.min.js +1 -0
  30. package/plugins/special-chars.css +1 -5
  31. package/plugins/special-chars.js +65 -61
  32. package/plugins/special-chars.min.css +2 -2
  33. package/plugins/special-chars.min.js +1 -1
  34. package/plugins/test.js +1 -2
  35. package/plugins/test.min.js +1 -1
  36. package/tests/hljs.html +55 -0
  37. package/tests/i18n.html +197 -0
  38. package/tests/prism-match-braces-compatibility.js +215 -0
  39. package/tests/prism-match-braces-compatibility.min.js +1 -0
  40. package/tests/prism.html +54 -0
  41. package/tests/tester.js +593 -0
  42. package/tests/tester.min.js +21 -0
  43. package/plugins/debounce-update.js +0 -40
  44. package/plugins/debounce-update.min.js +0 -1
@@ -0,0 +1,746 @@
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
+ findMatchesOnValueChange = true; // Needed so the program can insert text to the find value and thus add it to Ctrl+Z without highlighting matches.
10
+
11
+ instructions = {
12
+ start: "Search for matches in your code.",
13
+ none: "No matches",
14
+ oneFound: "1 match found.",
15
+ matchIndex: (index, count) => `${index} of ${count} matches.`,
16
+ error: (message) => `Error: ${message}`,
17
+ infiniteLoopError: "Causes an infinite loop",
18
+ closeDialog: "Close Dialog and Return to Editor",
19
+ findPlaceholder: "Find",
20
+ findCaseSensitive: "Match Case Sensitive",
21
+ findRegExp: "Use JavaScript Regular Expression",
22
+ replaceTitle: "Replace",
23
+ replacePlaceholder: "Replace with",
24
+ findNext: "Find Next Occurrence",
25
+ findPrevious: "Find Previous Occurrence",
26
+ replaceActionShort: "Replace",
27
+ replaceAction: "Replace This Occurrence",
28
+ replaceAllActionShort: "Replace All",
29
+ replaceAllAction: "Replace All Occurrences"
30
+ };
31
+
32
+ /**
33
+ * Create a find-and-replace command plugin to pass into a template
34
+ * @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)`.
35
+ * @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)`.
36
+ * @param {Object} instructionTranslations: user interface string keys mapped to translated versions for localisation. Look at the find-and-replace.js source code for the English text and available keys.
37
+ */
38
+ constructor(useCtrlF = true, useCtrlH = true, instructionTranslations = {}) {
39
+ super([]); // No observed attributes
40
+ this.useCtrlF = useCtrlF;
41
+ this.useCtrlH = useCtrlH;
42
+ this.addTranslations(this.instructions, instructionTranslations);
43
+ }
44
+
45
+ /* Add keystroke events */
46
+ afterElementsAdded(codeInput) {
47
+ const textarea = codeInput.textareaElement;
48
+ if(this.useCtrlF) {
49
+ textarea.addEventListener('keydown', (event) => { this.checkCtrlF(codeInput, event); });
50
+ }
51
+ if(this.useCtrlH) {
52
+ textarea.addEventListener('keydown', (event) => { this.checkCtrlH(codeInput, event); });
53
+ }
54
+ }
55
+
56
+ /* After highlight, retry match highlighting */
57
+ afterHighlight(codeInput) {
58
+ if(codeInput.pluginData.findAndReplace != undefined && codeInput.pluginData.findAndReplace.dialog != undefined) {
59
+ if(!codeInput.pluginData.findAndReplace.dialog.classList.contains("code-input_find-and-replace_hidden-dialog")) {
60
+ // Code updated and dialog open - re-highlight find matches
61
+ codeInput.pluginData.findAndReplace.dialog.findMatchState.rehighlightMatches();
62
+ this.updateMatchDescription(codeInput.pluginData.findAndReplace.dialog);
63
+
64
+ if(codeInput.pluginData.findAndReplace.dialog.findMatchState.numMatches == 0) {
65
+ // No more matches after editing
66
+ codeInput.pluginData.findAndReplace.dialog.findInput.classList.add('code-input_find-and-replace_error');
67
+ }
68
+ }
69
+ }
70
+ }
71
+
72
+ /* 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 */
73
+ text2RegExp(string, caseSensitive, stringIsRegexp) {
74
+ // "i" flag means case-"i"nsensitive
75
+ return new RegExp(stringIsRegexp ? string : string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), caseSensitive ? "g" : "gi"); // $& means the whole matched string
76
+ }
77
+
78
+ /* Update the dialog description to show the find matches */
79
+ updateMatchDescription(dialog) {
80
+ // 1-indexed
81
+ if(dialog.findInput.value.length == 0) {
82
+ dialog.matchDescription.textContent = this.instructions.start;
83
+ } else if(dialog.findMatchState.numMatches <= 0) {
84
+ dialog.matchDescription.textContent = this.instructions.none;
85
+ } else if(dialog.findMatchState.numMatches == 1) {
86
+ dialog.matchDescription.textContent = this.instructions.oneFound;
87
+ } else {
88
+ dialog.matchDescription.textContent = this.instructions.matchIndex(dialog.findMatchState.focusedMatchID+1, dialog.findMatchState.numMatches);
89
+ }
90
+ }
91
+
92
+ /* Called with a find input keyup event to find all matches in the code and focus the next match if Enter is pressed */
93
+ updateFindMatches(dialog) {
94
+ // Update matches for find functionality; debounce it to prevent delay with single-character search
95
+ let oldValue = dialog.findInput.value;
96
+ setTimeout(() => {
97
+ if(oldValue == dialog.findInput.value) {
98
+ // Stopped typing
99
+ dialog.findMatchState.clearMatches();
100
+ if(oldValue.length > 0) {
101
+ try {
102
+ dialog.findMatchState.updateMatches(this.text2RegExp(dialog.findInput.value, dialog.findCaseSensitiveCheckbox.checked, dialog.findRegExpCheckbox.checked));
103
+ } catch (err) {
104
+ if(err instanceof SyntaxError) {
105
+ // Syntax error due to malformed RegExp
106
+ dialog.findInput.classList.add('code-input_find-and-replace_error');
107
+ // Only show last part of error message
108
+ let messageParts = err.message.split(": ");
109
+ dialog.matchDescription.textContent = this.instructions.error(messageParts[messageParts.length-1]); // Show only last part of error.
110
+ return;
111
+ } else {
112
+ throw err;
113
+ }
114
+ }
115
+
116
+ if(dialog.findMatchState.numMatches > 0) {
117
+ dialog.findInput.classList.remove('code-input_find-and-replace_error');
118
+ } else {
119
+ // No matches - error
120
+ dialog.findInput.classList.add('code-input_find-and-replace_error');
121
+ }
122
+ }
123
+ this.updateMatchDescription(dialog);
124
+ }
125
+ }, 100);
126
+ }
127
+
128
+ /* Deal with Enter being pressed in the find field */
129
+ checkFindPrompt(dialog, codeInput, event) {
130
+ if (event.key == 'Enter') {
131
+ // Find next match
132
+ dialog.findMatchState.nextMatch();
133
+ this.updateMatchDescription(dialog);
134
+ }
135
+ }
136
+
137
+ /* Deal with Enter being pressed in the replace field */
138
+ checkReplacePrompt(dialog, codeInput, event) {
139
+ if (event.key == 'Enter') {
140
+ // Replace focused match
141
+ dialog.findMatchState.replaceOnce(dialog.replaceInput.value);
142
+ dialog.replaceInput.focus();
143
+ this.updateMatchDescription(dialog);
144
+ }
145
+ }
146
+
147
+ /* Called with a dialog box keyup event to close and clear the dialog box */
148
+ cancelPrompt(dialog, codeInput, event) {
149
+ event.preventDefault();
150
+
151
+ // Add current value of find/replace to Ctrl+Z stack.
152
+ this.findMatchesOnValueChange = false;
153
+ dialog.findInput.focus();
154
+ dialog.findInput.selectionStart = 0;
155
+ dialog.findInput.selectionEnd = dialog.findInput.value.length;
156
+ document.execCommand("insertText", false, dialog.findInput.value);
157
+ this.findMatchesOnValueChange = true;
158
+
159
+ // Reset original selection in code-input
160
+ dialog.textarea.focus();
161
+ dialog.setAttribute("inert", true); // Hide from keyboard navigation when closed.
162
+ dialog.setAttribute("tabindex", -1); // Hide from keyboard navigation when closed.
163
+ dialog.setAttribute("aria-hidden", true); // Hide from screen reader when closed.
164
+
165
+ if(dialog.findMatchState.numMatches > 0) {
166
+ // Select focused match
167
+ codeInput.textareaElement.selectionStart = dialog.findMatchState.matchStartIndexes[dialog.findMatchState.focusedMatchID];
168
+ codeInput.textareaElement.selectionEnd = dialog.findMatchState.matchEndIndexes[dialog.findMatchState.focusedMatchID];
169
+ } else {
170
+ // Select text selected before
171
+ codeInput.textareaElement.selectionStart = dialog.selectionStart;
172
+ codeInput.textareaElement.selectionEnd = dialog.selectionEnd;
173
+ }
174
+
175
+ dialog.findMatchState.clearMatches();
176
+
177
+ // Remove dialog after animation
178
+ dialog.classList.add('code-input_find-and-replace_hidden-dialog');
179
+ }
180
+
181
+ /**
182
+ * Show a find-and-replace dialog.
183
+ * @param {codeInput.CodeInput} codeInputElement the `<code-input>` element.
184
+ * @param {boolean} replacePartExpanded whether the replace part of the find-and-replace dialog should be expanded
185
+ */
186
+ showPrompt(codeInputElement, replacePartExpanded) {
187
+ let dialog;
188
+ if(codeInputElement.pluginData.findAndReplace == undefined || codeInputElement.pluginData.findAndReplace.dialog == undefined) {
189
+ const textarea = codeInputElement.textareaElement;
190
+
191
+ dialog = document.createElement('div');
192
+ const findInput = document.createElement('input');
193
+ const findCaseSensitiveCheckbox = document.createElement('input');
194
+ const findRegExpCheckbox = document.createElement('input');
195
+ const matchDescription = document.createElement('code');
196
+ matchDescription.setAttribute("aria-live", "assertive"); // Screen reader must read the number of matches found.
197
+
198
+ const replaceInput = document.createElement('input');
199
+ const replaceDropdown = document.createElement('details');
200
+ const replaceSummary = document.createElement('summary');
201
+
202
+ const buttonContainer = document.createElement('div');
203
+ const findNextButton = document.createElement('button');
204
+ const findPreviousButton = document.createElement('button');
205
+ const replaceButton = document.createElement('button');
206
+ const replaceAllButton = document.createElement('button');
207
+ const cancel = document.createElement('span');
208
+ cancel.setAttribute("tabindex", 0); // Visible to keyboard navigation
209
+ cancel.setAttribute("title", this.instructions.closeDialog);
210
+
211
+ buttonContainer.appendChild(findNextButton);
212
+ buttonContainer.appendChild(findPreviousButton);
213
+ buttonContainer.appendChild(replaceButton);
214
+ buttonContainer.appendChild(replaceAllButton);
215
+ buttonContainer.appendChild(cancel);
216
+ dialog.appendChild(buttonContainer);
217
+
218
+ dialog.appendChild(findInput);
219
+ dialog.appendChild(findRegExpCheckbox);
220
+ dialog.appendChild(findCaseSensitiveCheckbox);
221
+ dialog.appendChild(matchDescription);
222
+ replaceDropdown.appendChild(replaceSummary);
223
+ replaceDropdown.appendChild(replaceInput);
224
+
225
+ dialog.appendChild(replaceDropdown);
226
+
227
+ dialog.className = 'code-input_find-and-replace_dialog';
228
+ findInput.spellcheck = false;
229
+ findInput.placeholder = this.instructions.findPlaceholder;
230
+ findCaseSensitiveCheckbox.setAttribute("type", "checkbox");
231
+ findCaseSensitiveCheckbox.title = this.instructions.findCaseSensitive;
232
+ findCaseSensitiveCheckbox.classList.add("code-input_find-and-replace_case-sensitive-checkbox");
233
+ findRegExpCheckbox.setAttribute("type", "checkbox");
234
+ findRegExpCheckbox.title = this.instructions.findRegExp;
235
+ findRegExpCheckbox.classList.add("code-input_find-and-replace_reg-exp-checkbox");
236
+
237
+ matchDescription.textContent = "Search for matches in your code.";
238
+ matchDescription.classList.add("code-input_find-and-replace_match-description");
239
+
240
+
241
+ replaceSummary.innerText = this.instructions.replaceTitle;
242
+ replaceInput.spellcheck = false;
243
+ replaceInput.placeholder = this.instructions.replacePlaceholder;
244
+ findNextButton.innerText = "↓";
245
+ findNextButton.title = this.instructions.findNext;
246
+ findPreviousButton.innerText = "↑";
247
+ findPreviousButton.title = this.instructions.findPrevious;
248
+ replaceButton.className = 'code-input_find-and-replace_button-hidden';
249
+ replaceButton.innerText = this.instructions.replaceActionShort;
250
+ replaceButton.title = this.instructions.replaceAction;
251
+ replaceButton.addEventListener("focus", () => {
252
+ // Show replace section
253
+ replaceDropdown.setAttribute("open", true);
254
+ });
255
+ replaceAllButton.className = 'code-input_find-and-replace_button-hidden';
256
+ replaceAllButton.innerText = this.instructions.replaceAllActionShort;
257
+ replaceAllButton.title = this.instructions.replaceAllAction;
258
+ replaceAllButton.addEventListener("focus", () => {
259
+ // Show replace section
260
+ replaceDropdown.setAttribute("open", true);
261
+ });
262
+
263
+ findNextButton.addEventListener("click", (event) => {
264
+ // Stop form submit
265
+ event.preventDefault();
266
+
267
+ dialog.findMatchState.nextMatch();
268
+ this.updateMatchDescription(dialog);
269
+ });
270
+ findPreviousButton.addEventListener("click", () => {
271
+ // Stop form submit
272
+ event.preventDefault();
273
+
274
+ dialog.findMatchState.previousMatch();
275
+ this.updateMatchDescription(dialog);
276
+ });
277
+ replaceButton.addEventListener("click", (event) => {
278
+ // Stop form submit
279
+ event.preventDefault();
280
+
281
+ dialog.findMatchState.replaceOnce(replaceInput.value);
282
+ dialog.focus();
283
+ });
284
+ replaceAllButton.addEventListener("click", (event) => {
285
+ // Stop form submit
286
+ event.preventDefault();
287
+
288
+ dialog.findMatchState.replaceAll(replaceInput.value);
289
+ replaceAllButton.focus();
290
+ });
291
+
292
+ replaceDropdown.addEventListener("toggle", () => {
293
+ // When replace dropdown opened show replace buttons
294
+ replaceButton.classList.toggle("code-input_find-and-replace_button-hidden");
295
+ replaceAllButton.classList.toggle("code-input_find-and-replace_button-hidden");
296
+ });
297
+
298
+ // To store the state of find-and-replace functionality
299
+ dialog.findMatchState = new codeInput.plugins.FindAndReplace.FindMatchState(codeInputElement);
300
+
301
+ dialog.codeInput = codeInputElement;
302
+ dialog.textarea = textarea;
303
+ dialog.findInput = findInput;
304
+ dialog.findCaseSensitiveCheckbox = findCaseSensitiveCheckbox;
305
+ dialog.findRegExpCheckbox = findRegExpCheckbox;
306
+ dialog.matchDescription = matchDescription;
307
+ dialog.replaceInput = replaceInput;
308
+ dialog.replaceDropdown = replaceDropdown;
309
+
310
+ if(this.checkCtrlH) {
311
+ findInput.addEventListener('keydown', (event) => {
312
+ /* Open replace part on Ctrl+H */
313
+ if (event.ctrlKey && event.key == 'h') {
314
+ event.preventDefault();
315
+ replaceDropdown.setAttribute("open", true);
316
+ }
317
+ });
318
+ }
319
+
320
+ findInput.addEventListener('keypress', (event) => {
321
+ /* Stop enter from submitting form */
322
+ if (event.key == 'Enter') event.preventDefault();
323
+ });
324
+ replaceInput.addEventListener('keypress', (event) => {
325
+ /* Stop enter from submitting form */
326
+ if (event.key == 'Enter') event.preventDefault();
327
+ });
328
+ replaceInput.addEventListener('input', (event) => {
329
+ // Ctrl+Z can trigger this. If the dialog/replace dropdown aren't open, open them!
330
+ if(dialog.classList.contains("code-input_find-and-replace_hidden-dialog")) {
331
+ // Show prompt
332
+ this.showPrompt(dialog.codeInput, true);
333
+ } else if(!dialog.replaceDropdown.hasAttribute("open")) {
334
+ // Open dropdown
335
+ dialog.replaceDropdown.setAttribute("open", true);
336
+ }
337
+ });
338
+
339
+ dialog.addEventListener('keyup', (event) => {
340
+ /* Close prompt on Enter pressed */
341
+ if (event.key == 'Escape') this.cancelPrompt(dialog, codeInputElement, event);
342
+ });
343
+
344
+ findInput.addEventListener('keyup', (event) => { this.checkFindPrompt(dialog, codeInputElement, event); });
345
+ findInput.addEventListener('input', (event) => {
346
+ if(this.findMatchesOnValueChange) this.updateFindMatches(dialog);
347
+ // Ctrl+Z can trigger this. If the dialog isn't open, open it!
348
+ if(dialog.classList.contains("code-input_find-and-replace_hidden-dialog")) {
349
+ this.showPrompt(dialog.codeInput, false);
350
+ }
351
+ });
352
+ findCaseSensitiveCheckbox.addEventListener('click', (event) => { this.updateFindMatches(dialog); });
353
+ findRegExpCheckbox.addEventListener('click', (event) => { this.updateFindMatches(dialog); });
354
+
355
+ replaceInput.addEventListener('keyup', (event) => {
356
+ this.checkReplacePrompt(dialog, codeInputElement, event);
357
+ replaceInput.focus();
358
+ });
359
+ cancel.addEventListener('click', (event) => { this.cancelPrompt(dialog, codeInputElement, event); });
360
+ cancel.addEventListener('keypress', (event) => { if (event.key == "Space" || event.key == "Enter") this.cancelPrompt(dialog, codeInputElement, event); });
361
+
362
+ codeInputElement.dialogContainerElement.appendChild(dialog);
363
+ codeInputElement.pluginData.findAndReplace = {dialog: dialog};
364
+ findInput.focus();
365
+
366
+ if(replacePartExpanded) {
367
+ replaceDropdown.setAttribute("open", true);
368
+ }
369
+
370
+ // Save selection position
371
+ dialog.selectionStart = codeInputElement.textareaElement.selectionStart;
372
+ dialog.selectionEnd = codeInputElement.textareaElement.selectionEnd;
373
+
374
+ if(dialog.selectionStart < dialog.selectionEnd) {
375
+ // Copy selected text to Find input
376
+ let textToFind = codeInputElement.textareaElement.value.substring(dialog.selectionStart, dialog.selectionEnd);
377
+ dialog.findInput.focus();
378
+ dialog.findInput.selectionStart = 0;
379
+ dialog.findInput.selectionEnd = dialog.findInput.value.length;
380
+ document.execCommand("insertText", false, textToFind);
381
+ }
382
+ } else {
383
+ dialog = codeInputElement.pluginData.findAndReplace.dialog;
384
+ // Re-open dialog
385
+ dialog.classList.remove("code-input_find-and-replace_hidden-dialog");
386
+ dialog.removeAttribute("inert"); // Show to keyboard navigation when open.
387
+ dialog.setAttribute("tabindex", 0); // Show to keyboard navigation when open.
388
+ dialog.removeAttribute("aria-hidden"); // Show to screen reader when open.
389
+ dialog.findInput.focus();
390
+ if(replacePartExpanded) {
391
+ dialog.replaceDropdown.setAttribute("open", true);
392
+ } else {
393
+ dialog.replaceDropdown.removeAttribute("open");
394
+ }
395
+ }
396
+
397
+ // Save selection position
398
+ dialog.selectionStart = codeInputElement.textareaElement.selectionStart;
399
+ dialog.selectionEnd = codeInputElement.textareaElement.selectionEnd;
400
+
401
+ if(dialog.selectionStart < dialog.selectionEnd) {
402
+ // Copy selected text to Find input
403
+ let textToFind = codeInputElement.textareaElement.value.substring(dialog.selectionStart, dialog.selectionEnd);
404
+ dialog.findInput.focus();
405
+ dialog.findInput.selectionStart = 0;
406
+ dialog.findInput.selectionEnd = dialog.findInput.value.length;
407
+ document.execCommand("insertText", false, textToFind);
408
+ }
409
+
410
+ // Highlight matches
411
+ this.updateFindMatches(dialog);
412
+ }
413
+
414
+ /* Event handler for keydown event that makes Ctrl+F open find dialog */
415
+ checkCtrlF(codeInput, event) {
416
+ if (event.ctrlKey && event.key == 'f') {
417
+ event.preventDefault();
418
+ this.showPrompt(codeInput, false);
419
+ }
420
+ }
421
+
422
+ /* Event handler for keydown event that makes Ctrl+H open find+replace dialog */
423
+ checkCtrlH(codeInput, event) {
424
+ if (event.ctrlKey && event.key == 'h') {
425
+ event.preventDefault();
426
+ this.showPrompt(codeInput, true);
427
+ }
428
+ }
429
+ }
430
+
431
+ // Number of matches to highlight at once, for efficiency reasons
432
+ const CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE = 500;
433
+
434
+ /* This class stores the state of find and replace in a specific code-input element */
435
+ codeInput.plugins.FindAndReplace.FindMatchState = class {
436
+ codeInput = null;
437
+ lastValue = null; // of codeInput, so know when to update matches
438
+ lastSearchRegexp = null; // to be able to update matches
439
+ numMatches = 0;
440
+ focusedMatchID = 0;
441
+ matchStartIndexes = []; // For each match in order
442
+ matchEndIndexes = []; // For each match in order
443
+ focusedMatchStartIndex = 0;
444
+
445
+ 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.
446
+
447
+ constructor(codeInputElement) {
448
+ this.focusedMatchStartIndex = codeInputElement.textareaElement.selectionStart;
449
+ this.codeInput = codeInputElement;
450
+ }
451
+
452
+ /* Clear the find matches, often to prepare for new matches to be added. */
453
+ clearMatches() {
454
+ // Delete match information saved here
455
+ this.numMatches = 0;
456
+ this.matchStartIndexes = [];
457
+ this.matchEndIndexes = [];
458
+
459
+ // Remove generated spans to hold matches
460
+ let tempSpans = this.codeInput.codeElement.querySelectorAll(".code-input_find-and-replace_temporary-span");
461
+ for(let i = 0; i < tempSpans.length; i++) {
462
+ // Replace with textContent as Text node
463
+ tempSpans[i].parentElement.replaceChild(new Text(tempSpans[i].textContent), tempSpans[i]);
464
+ }
465
+
466
+ // Remove old matches
467
+ let oldMatches = this.codeInput.codeElement.querySelectorAll(".code-input_find-and-replace_find-match");
468
+ for(let i = 0; i < oldMatches.length; i++) {
469
+ oldMatches[i].removeAttribute("data-code-input_find-and-replace_match-id"); // No match ID
470
+ oldMatches[i].classList.remove("code-input_find-and-replace_find-match"); // No highlighting
471
+ oldMatches[i].classList.remove("code-input_find-and-replace_find-match-focused"); // No focused highlighting
472
+ }
473
+ }
474
+
475
+ /* Refresh the matches of find functionality with a new search term Regular Expression. */
476
+ updateMatches(searchRegexp) {
477
+ this.lastSearchRegexp = searchRegexp;
478
+ this.lastValue = this.codeInput.value;
479
+ // Add matches
480
+ let matchID = 0;
481
+ let match; // Search result
482
+ this.matchStartIndexes = [];
483
+ this.matchEndIndexes = [];
484
+ this.matchBlocksHighlighted = [];
485
+
486
+ // Make all match blocks be not highlighted except for currently focused
487
+ let focusedMatchBlock = Math.floor(this.focusedMatchID / CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE);
488
+ for(let i = 0; i < focusedMatchBlock; i++) {
489
+ this.matchBlocksHighlighted.push(false);
490
+ }
491
+ this.matchBlocksHighlighted.push(true);
492
+
493
+ while ((match = searchRegexp.exec(this.codeInput.value)) !== null) {
494
+ let matchText = match[0];
495
+ if(matchText.length == 0) {
496
+ throw SyntaxError(this.instructions.infiniteLoopError);
497
+ }
498
+
499
+ // Add next match block if needed
500
+ let currentMatchBlock = Math.floor(matchID / CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE);
501
+ if(this.matchBlocksHighlighted.length < currentMatchBlock) {
502
+ this.matchBlocksHighlighted.push(false);
503
+ }
504
+
505
+ if(this.matchBlocksHighlighted[currentMatchBlock]) {
506
+ this.highlightMatch(matchID, this.codeInput.codeElement, match.index, match.index + matchText.length);
507
+ }
508
+ this.matchStartIndexes.push(match.index);
509
+ this.matchEndIndexes.push(match.index + matchText.length);
510
+ matchID++;
511
+ }
512
+ this.numMatches = matchID;
513
+
514
+ if(this.numMatches > 0) {
515
+ this.focusMatch();
516
+ }
517
+ }
518
+
519
+ /* Highlight all currently found matches again if there are any matches */
520
+ rehighlightMatches() {
521
+ this.updateMatches(this.lastSearchRegexp);
522
+ this.focusMatch();
523
+ }
524
+
525
+ /* Replace one match with the replacementText given */
526
+ replaceOnce(replacementText) {
527
+ if(this.numMatches > 0 && replacementText != this.codeInput.value.substring(0, this.matchStartIndexes[this.focusedMatchID], this.matchEndIndexes[this.focusedMatchID])) {
528
+ // Go to next match
529
+ this.focusedMatchStartIndex += replacementText.length;
530
+
531
+ // Select the match
532
+ this.codeInput.handleEventsFromTextarea = false;
533
+ this.codeInput.textareaElement.focus();
534
+ this.codeInput.textareaElement.selectionStart = this.matchStartIndexes[this.focusedMatchID];
535
+ this.codeInput.textareaElement.selectionEnd = this.matchEndIndexes[this.focusedMatchID];
536
+
537
+ // Replace it with the replacement text
538
+ document.execCommand("insertText", false, replacementText);
539
+ this.codeInput.handleEventsFromTextarea = true;
540
+ }
541
+ }
542
+
543
+ /* Replace all matches with the replacementText given */
544
+ replaceAll(replacementText) {
545
+ const replacementNumChars = replacementText.length;
546
+ let numCharsAdded = 0; // So can adjust match positions
547
+
548
+ for(let i = 0; i < this.numMatches; i++) {
549
+ // Replace each match
550
+
551
+ // Select the match, taking into account characters added before
552
+ this.codeInput.handleEventsFromTextarea = false;
553
+ this.codeInput.textareaElement.focus();
554
+ this.codeInput.textareaElement.selectionStart = this.matchStartIndexes[i] + numCharsAdded;
555
+ this.codeInput.textareaElement.selectionEnd = this.matchEndIndexes[i] + numCharsAdded;
556
+
557
+ numCharsAdded += replacementNumChars - (this.matchEndIndexes[i] - this.matchStartIndexes[i]);
558
+
559
+ // Replace it with the replacement text
560
+ document.execCommand("insertText", false, replacementText);
561
+ this.codeInput.handleEventsFromTextarea = true;
562
+ }
563
+ }
564
+
565
+ /* Focus on the next match found in the find results */
566
+ nextMatch() {
567
+ this.focusMatch((this.focusedMatchID + 1) % this.numMatches);
568
+ }
569
+
570
+ /* Focus on the previous match found in the find results */
571
+ previousMatch() {
572
+ this.focusMatch((this.focusedMatchID + this.numMatches - 1) % this.numMatches);
573
+ }
574
+
575
+ /* Change the focused match to the match with ID matchID. */
576
+ focusMatch(matchID = undefined) {
577
+ if(matchID === undefined) {
578
+ // Focus on first match after focusedMatchStartIndex
579
+ matchID = 0;
580
+ while(matchID < this.matchStartIndexes.length && this.matchStartIndexes[matchID] < this.focusedMatchStartIndex) {
581
+ matchID++;
582
+ }
583
+ if(matchID >= this.matchStartIndexes.length) {
584
+ // After last match, move back to first match
585
+ matchID = 0;
586
+ }
587
+ }
588
+
589
+ // Save focusedMatchStartIndex so if code changed match stays at same place
590
+ this.focusedMatchStartIndex = this.matchStartIndexes[matchID];
591
+ this.focusedMatchID = matchID;
592
+
593
+ // Delete old focus
594
+ let oldFocused = this.codeInput.codeElement.querySelectorAll(".code-input_find-and-replace_find-match-focused");
595
+ for(let i = 0; i < oldFocused.length; i++) {
596
+ oldFocused[i].classList.remove("code-input_find-and-replace_find-match-focused");
597
+ }
598
+
599
+ // Highlight match block if needed
600
+ let highlightedMatchBlock = Math.floor(matchID / CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE);
601
+ if(!this.matchBlocksHighlighted[highlightedMatchBlock]) {
602
+ this.matchBlocksHighlighted[highlightedMatchBlock] = true;
603
+ for(let i = CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE*highlightedMatchBlock; i < CODE_INPUT_FIND_AND_REPLACE_MATCH_BLOCK_SIZE*(highlightedMatchBlock+1); i++) {
604
+ // Highlight match
605
+ this.highlightMatch(i, this.codeInput.codeElement, this.matchStartIndexes[i], this.matchEndIndexes[i])
606
+ }
607
+ }
608
+
609
+ // Add new focus
610
+ let newFocused = this.codeInput.codeElement.querySelectorAll(`.code-input_find-and-replace_find-match[data-code-input_find-and-replace_match-id="${matchID}"]`);
611
+ for(let i = 0; i < newFocused.length; i++) {
612
+ newFocused[i].classList.add("code-input_find-and-replace_find-match-focused");
613
+ }
614
+
615
+ if(newFocused.length > 0) {
616
+ this.codeInput.scrollTo(newFocused[0].offsetLeft - this.codeInput.offsetWidth / 2, newFocused[0].offsetTop - this.codeInput.offsetHeight / 2); // So focused match in centre of screen
617
+ }
618
+ }
619
+
620
+ /* Highlight a match from the find functionality given its start and end indexes in the text.
621
+ Start from the currentElement as this function is recursive. Use the matchID in the class name
622
+ of the match so different matches can be identified.
623
+ This code is similar to codeInput.plugins.SelectTokenCallbacks.SelectedTokenState.updateSelectedTokens*/
624
+ highlightMatch(matchID, currentElement, startIndex, endIndex) {
625
+ for(let i = 0; i < currentElement.childNodes.length; i++) {
626
+ let childElement = currentElement.childNodes[i];
627
+ let childText = childElement.textContent;
628
+
629
+ let noInnerElements = false;
630
+ if(childElement.nodeType == 3) {
631
+ // Text node
632
+ if(i + 1 < currentElement.childNodes.length && currentElement.childNodes[i+1].nodeType == 3) {
633
+ // Can merge with next text node
634
+ currentElement.childNodes[i+1].textContent = childElement.textContent + currentElement.childNodes[i+1].textContent; // Merge textContent with next node
635
+ currentElement.removeChild(childElement); // Delete this node
636
+ i--; // As an element removed
637
+ continue; // Move to next node
638
+ }
639
+ // Text node - replace with span
640
+ noInnerElements = true;
641
+
642
+ let replacementElement = document.createElement("span");
643
+ replacementElement.textContent = childText;
644
+ replacementElement.classList.add("code-input_find-and-replace_temporary-span"); // Can remove span later
645
+
646
+ currentElement.replaceChild(replacementElement, childElement);
647
+ childElement = replacementElement;
648
+ }
649
+
650
+ if(startIndex <= 0) {
651
+ // Started highlight
652
+ if(childText.length >= endIndex) {
653
+ // Match ends in childElement
654
+ if(noInnerElements) {
655
+ // Text node - highlight first part
656
+ let startSpan = document.createElement("span");
657
+ startSpan.classList.add("code-input_find-and-replace_find-match"); // Highlighted
658
+ startSpan.setAttribute("data-code-input_find-and-replace_match-id", matchID);
659
+ startSpan.classList.add("code-input_find-and-replace_temporary-span"); // Can remove span later
660
+ startSpan.textContent = childText.substring(0, endIndex);
661
+ if(startSpan.textContent[0] == "\n") {
662
+ // Newline at start - make clear
663
+ startSpan.classList.add("code-input_find-and-replace_start-newline");
664
+ }
665
+
666
+ let endText = childText.substring(endIndex);
667
+ childElement.textContent = endText;
668
+
669
+ childElement.insertAdjacentElement('beforebegin', startSpan);
670
+ i++; // An extra element has been added
671
+ return;
672
+ } else {
673
+ this.highlightMatch(matchID, childElement, 0, endIndex);
674
+ }
675
+
676
+ // Match ended - nothing to do after backtracking
677
+ return;
678
+ } else {
679
+ // Match goes through child element
680
+ childElement.classList.add("code-input_find-and-replace_find-match"); // Highlighted
681
+ childElement.setAttribute("data-code-input_find-and-replace_match-id", matchID);
682
+ if(childElement.textContent[0] == "\n") {
683
+ // Newline at start - make clear
684
+ childElement.classList.add("code-input_find-and-replace_start-newline");
685
+ }
686
+ }
687
+ } else if(childText.length > startIndex) {
688
+ // Match starts in childElement
689
+ if(noInnerElements) {
690
+ if(childText.length > endIndex) {
691
+ // Match starts and ends in childElement - highlight middle part
692
+ // Text node - highlight last part
693
+ let startSpan = document.createElement("span");
694
+ startSpan.classList.add("code-input_find-and-replace_temporary-span"); // Can remove span later
695
+ startSpan.textContent = childText.substring(0, startIndex);
696
+
697
+ let middleText = childText.substring(startIndex, endIndex);
698
+ childElement.textContent = middleText;
699
+ childElement.classList.add("code-input_find-and-replace_find-match"); // Highlighted
700
+ childElement.setAttribute("data-code-input_find-and-replace_match-id", matchID);
701
+ if(childElement.textContent[0] == "\n") {
702
+ // Newline at start - make clear
703
+ childElement.classList.add("code-input_find-and-replace_start-newline");
704
+ }
705
+
706
+ let endSpan = document.createElement("span");
707
+ endSpan.classList.add("code-input_find-and-replace_temporary-span"); // Can remove span later
708
+ endSpan.textContent = childText.substring(endIndex);
709
+
710
+ childElement.insertAdjacentElement('beforebegin', startSpan);
711
+ childElement.insertAdjacentElement('afterend', endSpan);
712
+ i++; // 2 extra elements have been added
713
+ } else {
714
+ // Text node - highlight last part
715
+ let startText = childText.substring(0, startIndex);
716
+ childElement.textContent = startText;
717
+
718
+ let endSpan = document.createElement("span");
719
+ endSpan.classList.add("code-input_find-and-replace_find-match"); // Highlighted
720
+ endSpan.setAttribute("data-code-input_find-and-replace_match-id", matchID);
721
+ endSpan.classList.add("code-input_find-and-replace_temporary-span"); // Can remove span later
722
+ endSpan.textContent = childText.substring(startIndex);
723
+ if(endSpan.textContent[0] == "\n") {
724
+ // Newline at start - make clear
725
+ endSpan.classList.add("code-input_find-and-replace_start-newline");
726
+ }
727
+
728
+ childElement.insertAdjacentElement('afterend', endSpan);
729
+ i++; // An extra element has been added
730
+ }
731
+ } else {
732
+ this.highlightMatch(matchID, childElement, startIndex, endIndex);
733
+ }
734
+
735
+ if(childText.length > endIndex) {
736
+ // Match completely in childElement - nothing to do after backtracking
737
+ return;
738
+ }
739
+ }
740
+
741
+ // Make indexes skip the element
742
+ startIndex -= childText.length;
743
+ endIndex -= childText.length;
744
+ }
745
+ }
746
+ }