File size: 5,038 Bytes
9d2d895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * HS2 product chapter typeahead picker. Same keyboard model as CountryPicker.
 */

import { filterHs2, getAllHs2, type Hs2Entry } from './RouteExplorer.utils';
import { setTrustedHtml, trustedHtml } from '@/utils/dom-utils';


export interface Hs2PickerOptions {
  placeholder?: string;
  initialHs2?: string | null;
  onCommit: (hs2: string) => void;
  onCancel?: () => void;
}

export class Hs2Picker {
  public readonly element: HTMLDivElement;
  private input: HTMLInputElement;
  private list: HTMLUListElement;
  private results: Hs2Entry[] = [];
  private highlightIndex = 0;
  private opts: Hs2PickerOptions;

  constructor(opts: Hs2PickerOptions) {
    this.opts = opts;
    this.element = document.createElement('div');
    this.element.className = 're-picker re-picker--hs2';

    this.input = document.createElement('input');
    this.input.type = 'text';
    this.input.className = 're-picker__input';
    this.input.placeholder = opts.placeholder ?? 'Search products (HS code)';
    this.input.autocomplete = 'off';
    this.input.spellcheck = false;
    this.input.setAttribute('aria-label', opts.placeholder ?? 'Search products');

    this.list = document.createElement('ul');
    this.list.className = 're-picker__list';
    this.list.setAttribute('role', 'listbox');

    this.list.style.display = 'none';
    this.element.append(this.input, this.list);

    if (opts.initialHs2) {
      const initial = getAllHs2().find((e) => e.hs2 === opts.initialHs2);
      if (initial) this.input.value = `${initial.label} (HS ${initial.hs2})`;
    }

    this.input.addEventListener('input', () => { this.showList(); this.refreshResults(this.input.value); });
    this.input.addEventListener('focus', () => { this.refreshResults(this.input.value); this.showList(); });
    this.input.addEventListener('blur', () => { setTimeout(() => this.hideList(), 150); });
    this.input.addEventListener('keydown', this.handleKeydown);
    this.list.addEventListener('click', this.handleClick);
  }

  private showList(): void { this.list.style.display = 'block'; }
  private hideList(): void { this.list.style.display = 'none'; }

  public focusInput(): void {
    this.input.focus();
    this.input.select();
  }

  public setValue(hs2: string | null): void {
    if (!hs2) {
      this.input.value = '';
      this.refreshResults('');
      return;
    }
    const e = getAllHs2().find((x) => x.hs2 === hs2);
    if (e) {
      this.input.value = `${e.label} (HS ${e.hs2})`;
      this.refreshResults('');
    }
  }

  private refreshResults(query: string): void {
    this.results = filterHs2(query).slice(0, 50);
    this.highlightIndex = 0;
    this.renderList();
  }

  private renderList(): void {
    setTrustedHtml(this.list, trustedHtml('', "legacy direct innerHTML migration"));
    if (this.results.length === 0) {
      const empty = document.createElement('li');
      empty.className = 're-picker__empty';
      empty.textContent = 'No matching products';
      this.list.append(empty);
      return;
    }
    this.results.forEach((entry, idx) => {
      const li = document.createElement('li');
      li.className = 're-picker__item';
      li.setAttribute('role', 'option');
      li.dataset.hs2 = entry.hs2;
      li.dataset.idx = String(idx);
      if (idx === this.highlightIndex) {
        li.classList.add('re-picker__item--active');
        li.setAttribute('aria-selected', 'true');
      }
      setTrustedHtml(li, trustedHtml(`<span class="re-picker__code">HS ${entry.hs2}</span><span class="re-picker__name">${escapeHtml(entry.label)}</span>`, "legacy direct innerHTML migration"));
      this.list.append(li);
    });
  }

  private commit(idx: number): void {
    const entry = this.results[idx];
    if (!entry) return;
    this.input.value = `${entry.label} (HS ${entry.hs2})`;
    this.hideList();
    this.input.blur();
    this.opts.onCommit(entry.hs2);
  }

  private handleKeydown = (e: KeyboardEvent): void => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      this.highlightIndex = Math.min(this.highlightIndex + 1, this.results.length - 1);
      this.renderList();
      return;
    }
    if (e.key === 'ArrowUp') {
      e.preventDefault();
      this.highlightIndex = Math.max(this.highlightIndex - 1, 0);
      this.renderList();
      return;
    }
    if (e.key === 'Enter') {
      e.preventDefault();
      this.commit(this.highlightIndex);
      return;
    }
    if (e.key === 'Escape') {
      e.preventDefault();
      this.opts.onCancel?.();
      return;
    }
  };

  private handleClick = (e: MouseEvent): void => {
    const target = e.target as HTMLElement;
    const item = target.closest('.re-picker__item') as HTMLElement | null;
    if (!item || item.dataset.idx === undefined) return;
    const idx = Number.parseInt(item.dataset.idx, 10);
    this.commit(idx);
  };
}

function escapeHtml(s: string): string {
  return s.replace(/[&<>"']/g, (c) =>
    c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : c === '"' ? '&quot;' : '&#39;',
  );
}