File: omnibox_input.ts

package info (click to toggle)
chromium 138.0.7204.157-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,864 kB
  • sloc: cpp: 34,936,859; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,967; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (451 lines) | stat: -rw-r--r-- 16,553 bytes parent folder | download | duplicates (4)
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
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {PageClassification} from './omnibox.mojom-webui.js';
import {OmniboxElement} from './omnibox_element.js';
import sheet from './omnibox_input.css' with {type : 'css'};

export interface QueryInputs {
  inputText: string;
  resetAutocompleteController: boolean;
  cursorLock: boolean;
  cursorPosition: number;
  zeroSuggest: boolean;
  preventInlineAutocomplete: boolean;
  preferKeyword: boolean;
  currentUrl: string;
  pageClassification: number;
}

export interface DisplayInputs {
  showIncompleteResults: boolean;
  showDetails: boolean;
  showAllProviders: boolean;
  elideCells: boolean;
  thinRows: boolean;
}

export class OmniboxInput extends OmniboxElement {
  private elements: {
    top: HTMLElement,
    arrowPadding: HTMLElement,
    connectWindowOmnibox: HTMLInputElement,
    currentUrl: HTMLInputElement,
    elideCells: HTMLInputElement,
    exportClipboard: HTMLElement,
    exportFile: HTMLElement,
    filterText: HTMLInputElement,
    historyWarning: HTMLElement,
    importClipboard: HTMLElement,
    importedWarning: HTMLElement,
    importFile: HTMLElement,
    importFileInput: HTMLInputElement,
    inputText: HTMLInputElement,
    lockCursorPosition: HTMLInputElement,
    pageClassification: HTMLSelectElement,
    preferKeyword: HTMLInputElement,
    preventInlineAutocomplete: HTMLInputElement,
    processBatch: HTMLElement,
    processBatchInput: HTMLInputElement,
    resetAutocompleteController: HTMLInputElement,
    responsesCount: HTMLElement,
    responseSelection: HTMLInputElement,
    showAllProviders: HTMLInputElement,
    showDetails: HTMLInputElement,
    showIncompleteResults: HTMLInputElement,
    thinRows: HTMLInputElement,
    zeroSuggest: HTMLInputElement,
  };

  constructor() {
    super('omnibox-input-template');
    this.shadowRoot!.adoptedStyleSheets = [sheet];
  }

  connectedCallback() {
    this.elements = {
      top: this.$<HTMLElement>('#top')!,
      arrowPadding: this.$<HTMLElement>('#arrow-padding')!,
      connectWindowOmnibox: this.$<HTMLInputElement>('#connect-window-omnibox')!
      ,
      currentUrl: this.$<HTMLInputElement>('#current-url')!,
      elideCells: this.$<HTMLInputElement>('#elide-cells')!,
      exportClipboard: this.$<HTMLElement>('#export-clipboard')!,
      exportFile: this.$<HTMLElement>('#export-file')!,
      filterText: this.$<HTMLInputElement>('#filter-text')!,
      historyWarning: this.$<HTMLElement>('#history-warning')!,
      importClipboard: this.$<HTMLElement>('#import-clipboard')!,
      importedWarning: this.$<HTMLElement>('#imported-warning')!,
      importFile: this.$<HTMLElement>('#import-file')!,
      importFileInput: this.$<HTMLInputElement>('#import-file-input')!,
      inputText: this.$<HTMLInputElement>('#input-text')!,
      lockCursorPosition: this.$<HTMLInputElement>('#lock-cursor-position')!,
      pageClassification: this.$<HTMLSelectElement>('#page-classification')!,
      preferKeyword: this.$<HTMLInputElement>('#prefer-keyword')!,
      preventInlineAutocomplete:
          this.$<HTMLInputElement>('#prevent-inline-autocomplete')!,
      processBatch: this.$<HTMLElement>('#process-batch')!,
      processBatchInput: this.$<HTMLInputElement>('#process-batch-input')!,
      resetAutocompleteController:
          this.$<HTMLInputElement>('#reset-autocomplete-controller')!,
      responsesCount: this.$<HTMLElement>('#responses-count')!,
      responseSelection: this.$<HTMLInputElement>('#response-selection')!,
      showAllProviders: this.$<HTMLInputElement>('#show-all-providers')!,
      showDetails: this.$<HTMLInputElement>('#show-details')!,
      showIncompleteResults:
          this.$<HTMLInputElement>('#show-incomplete-results')!,
      thinRows: this.$<HTMLInputElement>('#thin-rows')!,
      zeroSuggest: this.$<HTMLInputElement>('#zero-suggest')!,
    };
    this.restoreInputs();
    this.setupElementListeners();
    this.addPageClassification();
  }

  // Add Page Classification labels as options to dropdown.
  private addPageClassification() {
    const dropdown = this.$<HTMLSelectElement>('#page-classification')!;
    for (const page in Object.keys(PageClassification)) {
      const label = PageClassification[page];
      // Filter out built-in reverse mappings for this numeric enum.
      if (label === undefined) {
        continue;
      }
      const option = document.createElement('option');
      option.value = page;
      option.text = label;
      // Pre-select the OTHER option.
      page === '4' ? option.selected = true : null;
      dropdown.appendChild(option);
    }
  }

  private storeInputs() {
    const inputs = {
      connectWindowOmnibox: this.connectWindowOmnibox,
      displayInputs: this.displayInputs,
    };
    window.localStorage.setItem('preserved-inputs', JSON.stringify(inputs));
  }

  private restoreInputs() {
    const inputsString = window.localStorage.getItem('preserved-inputs');
    const inputs = inputsString && JSON.parse(inputsString) || {};
    this.elements.connectWindowOmnibox.checked = inputs.connectWindowOmnibox;
    this.displayInputs =
        inputs.displayInputs || OmniboxInput.defaultDisplayInputs;
  }

  private setupElementListeners() {
    [this.elements.inputText,
     this.elements.resetAutocompleteController,
     this.elements.lockCursorPosition,
     this.elements.zeroSuggest,
     this.elements.preventInlineAutocomplete,
     this.elements.preferKeyword,
     this.elements.currentUrl,
     this.elements.pageClassification,
    ].forEach(element => {
      element.addEventListener('input', this.onQueryInputsChanged.bind(this));
    });

    // Set text of #arrow-padding to substring of #input-text text, from
    // beginning until cursor position, in order to correctly align .arrow-up.
    this.elements.inputText.addEventListener(
        'input', this.positionCursorPositionIndicators.bind(this));

    this.elements.connectWindowOmnibox.addEventListener(
        'input', this.storeInputs.bind(this));

    this.elements.responseSelection.addEventListener(
        'input', this.onResponseSelectionChanged.bind(this));
    this.elements.responseSelection.addEventListener(
        'blur', this.onResponseSelectionBlur.bind(this));

    [this.elements.showIncompleteResults,
     this.elements.showDetails,
     this.elements.showAllProviders,
     this.elements.elideCells,
     this.elements.thinRows,
    ].forEach(element => {
      element.addEventListener('input', this.onDisplayInputsChanged.bind(this));
    });

    this.elements.filterText.addEventListener(
        'input', this.onFilterInputsChanged.bind(this));

    this.elements.exportClipboard.addEventListener(
        'click', this.onExportClipboard.bind(this));
    this.elements.exportFile.addEventListener(
        'click', this.onExportFile.bind(this));
    this.elements.importClipboard.addEventListener(
        'click', this.onImportClipboard.bind(this));
    this.elements.importFileInput.addEventListener(
        'input', this.onImportFile.bind(this));
    this.elements.processBatchInput.addEventListener(
        'input', this.onProcessBatchFile.bind(this));

    this.setupDragListeners(this.elements.top);
    this.elements.top.addEventListener('drop', this.onImportDropped.bind(this));

    this.setupDragListeners(this.elements.processBatch);
    this.elements.processBatch.addEventListener(
        'drop', this.onProcessBatchDropped.bind(this));

    this.$all<HTMLElement>('.button').forEach(
        el => el.addEventListener('keypress', (e: KeyboardEvent) => {
          if (e.key === ' ' || e.key === 'Enter') {
            el.click();
          }
        }));
  }

  /**
   * Sets up boilerplate event listeners for an element that is able to receive
   * drag events.
   */
  private setupDragListeners(element: Element) {
    // There are 2 classes toggled during drags:
    // - `drag-background` alters the `element`'s background when the mouse is
    //   over it to indicate it's a drag target.
    // - `drag-silence` silences mouse events from the children of `element`
    //   while the drag is active. This is necessary to avoid receiving
    //   `dragenter` & `dragleave` events when children of `element` are entered
    //   or left.
    // Ideally, there'd be just 1 class controlling both behaviors and active
    // when dragging over `element`. However, `dragenter` and `dragleave` events
    // are racy (see https://stackoverflow.com/questions/7110353). So instead,
    // toggle `drag-background` when the dragging-mouse enters/leaves `element`.
    // And toggle `drag-silence` when the mouse begins/stops dragging. This
    // workaround isn't 100% accurate, but all the other workarounds (e.g. those
    // listed in the stackoverflow answers), were significantly worse.
    element.addEventListener('dragenter', () => {
      element.classList.add('drag-background');
      element.classList.add('drag-silence');
    });
    element.addEventListener(
        'dragleave', () => element.classList.remove('drag-background'));
    element.addEventListener('dragover', e => e.preventDefault());
    element.addEventListener('drop', e => {
      e.preventDefault();
      element.classList.remove('drag-background');
      element.classList.remove('drag-silence');
    });
    element.addEventListener(
        'mouseenter', () => element.classList.remove('drag-silence'));
  }

  private onQueryInputsChanged() {
    this.elements.importedWarning.hidden = true;
    this.dispatchEvent(
        new CustomEvent('query-inputs-changed', {detail: this.queryInputs}));
  }

  get queryInputs(): QueryInputs {
    return {
      inputText: this.elements.inputText.value,
      resetAutocompleteController:
          this.elements.resetAutocompleteController.checked,
      cursorLock: this.elements.lockCursorPosition.checked,
      cursorPosition: this.cursorPosition,
      zeroSuggest: this.elements.zeroSuggest.checked,
      preventInlineAutocomplete:
          this.elements.preventInlineAutocomplete.checked,
      preferKeyword: this.elements.preferKeyword.checked,
      currentUrl: this.elements.currentUrl.value,
      pageClassification: Number(this.elements.pageClassification.value),
    };
  }

  set queryInputs(queryInputs: QueryInputs) {
    this.elements.inputText.value = queryInputs.inputText;
    this.elements.resetAutocompleteController.checked =
        queryInputs.resetAutocompleteController;
    this.elements.lockCursorPosition.checked = queryInputs.cursorLock;
    this.cursorPosition = queryInputs.cursorPosition;
    this.elements.zeroSuggest.checked = queryInputs.zeroSuggest;
    this.elements.preventInlineAutocomplete.checked =
        queryInputs.preventInlineAutocomplete;
    this.elements.preferKeyword.checked = queryInputs.preferKeyword;
    this.elements.currentUrl.value = queryInputs.currentUrl;
    this.elements.pageClassification.value =
        String(queryInputs.pageClassification);
  }

  private get cursorPosition(): number {
    return this.elements.lockCursorPosition.checked ?
        this.elements.inputText.value.length :
        Number(this.elements.inputText.selectionEnd);
  }

  private set cursorPosition(value: number) {
    this.elements.inputText.setSelectionRange(value, value);
    this.positionCursorPositionIndicators();
  }

  private positionCursorPositionIndicators() {
    this.elements.arrowPadding.textContent =
        this.elements.inputText.value.substring(0, this.cursorPosition);
  }

  get connectWindowOmnibox(): boolean {
    return this.elements.connectWindowOmnibox.checked;
  }

  private onResponseSelectionChanged() {
    const {value, max} = this.elements.responseSelection;
    this.elements.historyWarning.hidden = value === '0' || value === max;
    this.dispatchEvent(
        new CustomEvent('response-select', {detail: Number(value) - 1}));
  }

  private onResponseSelectionBlur() {
    const {value, min, max} = this.elements.responseSelection;
    this.elements.responseSelection.value =
        String(Math.max(Math.min(Number(value), Number(max)), Number(min)));
    this.onResponseSelectionChanged();
  }

  set responsesCount(value: number) {
    if (this.elements.responseSelection.value ===
        this.elements.responseSelection.max) {
      this.elements.responseSelection.value = String(value);
    }
    this.elements.responseSelection.max = String(value);
    this.elements.responseSelection.min = String(value ? 1 : 0);
    this.elements.responsesCount.textContent = String(value);
    this.onResponseSelectionBlur();
  }

  private onDisplayInputsChanged() {
    this.storeInputs();
    this.dispatchEvent(new CustomEvent(
        'display-inputs-changed', {detail: this.displayInputs}));
  }

  get displayInputs(): DisplayInputs {
    return {
      showIncompleteResults: this.elements.showIncompleteResults.checked,
      showDetails: this.elements.showDetails.checked,
      showAllProviders: this.elements.showAllProviders.checked,
      elideCells: this.elements.elideCells.checked,
      thinRows: this.elements.thinRows.checked,
    };
  }

  set displayInputs(displayInputs: DisplayInputs) {
    this.elements.showIncompleteResults.checked =
        displayInputs.showIncompleteResults;
    this.elements.showDetails.checked = displayInputs.showDetails;
    this.elements.showAllProviders.checked = displayInputs.showAllProviders;
    this.elements.elideCells.checked = displayInputs.elideCells;
    this.elements.thinRows.checked = displayInputs.thinRows;
  }

  private onFilterInputsChanged() {
    this.dispatchEvent(new CustomEvent(
        'filter-input-changed', {detail: this.elements.filterText.value}));
  }

  private onExportClipboard() {
    this.dispatchEvent(new CustomEvent('export-clipboard'));
  }

  private onExportFile() {
    this.dispatchEvent(new CustomEvent('export-file'));
  }

  private async onImportClipboard() {
    this.import(await navigator.clipboard.readText());
  }

  private onImportFile(event: Event) {
    const file = (event.target as HTMLInputElement).files?.[0];
    if (file) {
      this.importFile(file);
    }
  }

  private onProcessBatchFile(event: Event) {
    const file = (event.target as HTMLInputElement).files?.[0];
    if (file) {
      this.processBatchFile(file);
    }
  }

  private onImportDropped(event: DragEvent) {
    const data = event.dataTransfer!;
    const dragText = data.getData('Text');
    if (dragText) {
      this.import(dragText);
    } else if (data.files[0]) {
      this.importFile(data.files[0]);
    }
  }

  private onProcessBatchDropped(event: DragEvent) {
    const data = event.dataTransfer!;
    const dragText = data.getData('Text');
    if (dragText) {
      this.processBatch(dragText);
    } else if (data.files[0]) {
      this.processBatchFile(data.files[0]);
    }
  }

  private importFile(file: File) {
    OmniboxInput.readFile(file).then(this.import.bind(this));
  }

  private processBatchFile(file: File) {
    OmniboxInput.readFile(file).then(this.processBatch.bind(this));
  }

  private import(importString: string) {
    try {
      const importData = JSON.parse(importString);
      // TODO(manukh): If import fails, this UI state change shouldn't happen.
      this.elements.importedWarning.hidden = false;
      this.dispatchEvent(new CustomEvent('import', {detail: importData}));
    } catch (error) {
      console.error('error during import, invalid json:', error);
    }
  }

  private processBatch(processBatchString: string) {
    try {
      const processBatchData = JSON.parse(processBatchString);
      this.dispatchEvent(
          new CustomEvent('process-batch', {detail: processBatchData}));
    } catch (error) {
      console.error('error during process batch, invalid json:', error);
    }
  }

  private static readFile(file: File): Promise<string> {
    return new Promise(resolve => {
      const reader = new FileReader();
      reader.onloadend = () => {
        if (reader.readyState === FileReader.DONE) {
          resolve(reader.result as string);
        } else {
          console.error('error importing, unable to read file:', reader.error);
        }
      };
      reader.readAsText(file);
    });
  }

  static get defaultDisplayInputs(): DisplayInputs {
    return {
      showIncompleteResults: false,
      showDetails: false,
      showAllProviders: true,
      elideCells: true,
      thinRows: false,
    };
  }
}

customElements.define('omnibox-input', OmniboxInput);