liuyn
2024-03-11 a87f1c3df03078814ee97ad0c8ac200a232419e9
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
import { LightningElement, api } from "lwc";
 
const MINIMAL_SEARCH_TERM_LENGTH = 2; // Min number of chars required to search
const SEARCH_DELAY = 300; // Wait 300 ms after user stops typing then, peform search
 
export default class Lookup extends LightningElement {
  @api label;
  @api required;
  @api placeholder = "";
  @api isMultiEntry = false;
  @api errors = [];
  @api scrollAfterNItems;
 
  searchTerm = "";
  searchResults = [];
  hasFocus = false;
  loading = false;
  isDirty = false;
 
  cleanSearchTerm;
  blurTimeout;
  searchThrottlingTimeout;
  curSelection = [];
 
  // EXPOSED FUNCTIONS
  @api
  set selection(initialSelection) {
    this.curSelection = Array.isArray(initialSelection)
      ? initialSelection
      : [initialSelection];
  }
  get selection() {
    return this.curSelection;
  }
 
  @api
  setSearchResults(results) {
    // Reset the spinner
    this.loading = false;
    // Clone results before modifying them to avoid Locker restriction
    const resultsLocal = JSON.parse(JSON.stringify(results));
    // Format results
    this.searchResults = resultsLocal.map(result => {
      // Clone and complete search result if icon is missing
      if (this.searchTerm.length > 0) {
        const regex = new RegExp(`(${this.searchTerm})`, "gi");
        result.titleFormatted = result.title
          ? result.title.replace(regex, "<strong>$1</strong>")
          : result.title;
        result.subtitleFormatted = result.subtitle
          ? result.subtitle.replace(regex, "<strong>$1</strong>")
          : result.subtitle;
      }
      if (typeof result.icon === "undefined") {
        const { id, sObjectType, title, subtitle } = result;
        return {
          id,
          sObjectType,
          icon: "standard:default",
          title,
          subtitle
        };
      }
      return result;
    });
  }
 
  @api
  getSelection() {
    return this.curSelection;
  }
 
  // INTERNAL FUNCTIONS
 
  updateSearchTerm(newSearchTerm) {
    this.searchTerm = newSearchTerm;
 
    // Compare clean new search term with current one and abort if identical
    const newCleanSearchTerm = newSearchTerm
      .trim()
      .replace(/\*/g, "")
      .toLowerCase();
    if (this.cleanSearchTerm === newCleanSearchTerm) {
      return;
    }
 
    // Save clean search term
    this.cleanSearchTerm = newCleanSearchTerm;
 
    // Ignore search terms that are too small
    if (newCleanSearchTerm.length < MINIMAL_SEARCH_TERM_LENGTH) {
      this.searchResults = [];
      return;
    }
 
    // Apply search throttling (prevents search if user is still typing)
    if (this.searchThrottlingTimeout) {
      clearTimeout(this.searchThrottlingTimeout);
    }
    // eslint-disable-next-line @lwc/lwc/no-async-operation
    this.searchThrottlingTimeout = setTimeout(() => {
      // Send search event if search term is long enough
      if (this.cleanSearchTerm.length >= MINIMAL_SEARCH_TERM_LENGTH) {
        // Display spinner until results are returned
        this.loading = true;
 
        const searchEvent = new CustomEvent("search", {
          detail: {
            searchTerm: this.cleanSearchTerm,
            selectedIds: this.curSelection.map(element => element.id)
          }
        });
        this.dispatchEvent(searchEvent);
      }
      this.searchThrottlingTimeout = null;
    }, SEARCH_DELAY);
  }
 
  isSelectionAllowed() {
    if (this.isMultiEntry) {
      return true;
    }
    return !this.hasSelection();
  }
 
  hasResults() {
    return this.searchResults.length > 0;
  }
 
  hasSelection() {
    return this.curSelection.length > 0;
  }
 
  // EVENT HANDLING
 
  handleInput(event) {
    // Prevent action if selection is not allowed
    if (!this.isSelectionAllowed()) {
      return;
    }
    this.updateSearchTerm(event.target.value);
  }
 
  handleResultClick(event) {
    const recordId = event.currentTarget.dataset.recordid;
 
    // Save selection
    let selectedItem = this.searchResults.filter(
      result => result.id === recordId
    );
    if (selectedItem.length === 0) {
      return;
    }
    selectedItem = selectedItem[0];
    const newSelection = [...this.curSelection];
    newSelection.push(selectedItem);
    this.curSelection = newSelection;
    this.isDirty = true;
 
    // Reset search
    this.searchTerm = "";
    this.searchResults = [];
 
    // Notify parent components that selection has changed
    this.dispatchEvent(new CustomEvent("selectionchange"));
  }
 
  handleComboboxClick() {
    // Hide combobox immediatly
    if (this.blurTimeout) {
      window.clearTimeout(this.blurTimeout);
    }
    this.hasFocus = false;
  }
 
  handleFocus() {
    // Prevent action if selection is not allowed
    if (!this.isSelectionAllowed()) {
      return;
    }
    this.hasFocus = true;
  }
 
  handleBlur() {
    // Prevent action if selection is not allowed
    if (!this.isSelectionAllowed()) {
      return;
    }
    // Delay hiding combobox so that we can capture selected result
    // eslint-disable-next-line @lwc/lwc/no-async-operation
    this.blurTimeout = window.setTimeout(() => {
      this.hasFocus = false;
      this.blurTimeout = null;
    }, 300);
  }
 
  handleRemoveSelectedItem(event) {
    const recordId = event.currentTarget.name;
    this.curSelection = this.curSelection.filter(item => item.id !== recordId);
    this.isDirty = true;
    // Notify parent components that selection has changed
    this.dispatchEvent(new CustomEvent("selectionchange"));
  }
 
  handleClearSelection() {
    this.curSelection = [];
    this.isDirty = true;
    // Notify parent components that selection has changed
    this.dispatchEvent(new CustomEvent("selectionchange"));
  }
 
  // STYLE EXPRESSIONS
 
  get getContainerClass() {
    let css = "slds-combobox_container slds-has-inline-listbox ";
    if (this.hasFocus && this.hasResults()) {
      css += "slds-has-input-focus ";
    }
    if (this.errors.length > 0) {
      css += "has-custom-error";
    }
    return css;
  }
 
  get getDropdownClass() {
    let css =
      "slds-combobox slds-dropdown-trigger slds-dropdown-trigger_click ";
    if (
      this.hasFocus &&
      this.cleanSearchTerm &&
      this.cleanSearchTerm.length >= MINIMAL_SEARCH_TERM_LENGTH
    ) {
      css += "slds-is-open";
    }
    return css;
  }
 
  get getInputClass() {
    let css = "slds-input slds-combobox__input has-custom-height ";
    if (
      this.errors.length > 0 ||
      (this.isDirty && this.required && !this.hasSelection())
    ) {
      css += "has-custom-error ";
    }
    if (!this.isMultiEntry) {
      css +=
        "slds-combobox__input-value " +
        (this.hasSelection() ? "has-custom-border" : "");
    }
    return css;
  }
 
  get getComboboxClass() {
    let css = "slds-combobox__form-element slds-input-has-icon ";
    if (this.isMultiEntry) {
      css += "slds-input-has-icon_right";
    } else {
      css += this.hasSelection()
        ? "slds-input-has-icon_left-right"
        : "slds-input-has-icon_right";
    }
    return css;
  }
 
  get getSearchIconClass() {
    let css = "slds-input__icon slds-input__icon_right ";
    if (!this.isMultiEntry) {
      css += this.hasSelection() ? "slds-hide" : "";
    }
    return css;
  }
 
  get getClearSelectionButtonClass() {
    return (
      "slds-button slds-button_icon slds-input__icon slds-input__icon_right " +
      (this.hasSelection() ? "" : "slds-hide")
    );
  }
 
  get getSelectIconName() {
    return this.hasSelection() ? this.curSelection[0].icon : "standard:default";
  }
 
  get getSelectIconClass() {
    return (
      "slds-combobox__input-entity-icon " +
      (this.hasSelection() ? "" : "slds-hide")
    );
  }
 
  get getInputValue() {
    if (this.isMultiEntry) {
      return this.searchTerm;
    }
    return this.hasSelection() ? this.curSelection[0].title : this.searchTerm;
  }
 
  get getInputTitle() {
    if (this.isMultiEntry) {
      return "";
    }
 
    return this.hasSelection() ? this.curSelection[0].title : "";
  }
 
  get getListboxClass() {
    return (
      "slds-listbox slds-listbox_vertical slds-dropdown slds-dropdown_fluid " +
      (this.scrollAfterNItems
        ? "slds-dropdown_length-with-icon-" + this.scrollAfterNItems
        : "")
    );
  }
 
  get isInputReadonly() {
    if (this.isMultiEntry) {
      return false;
    }
    return this.hasSelection();
  }
 
  get isExpanded() {
    return this.hasResults();
  }
}