@acusti/dropdown 0.14.0 → 0.15.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.
package/dist/Dropdown.js CHANGED
@@ -3,41 +3,12 @@ import { Style } from '@acusti/styling';
3
3
  import useIsOutOfBounds from '@acusti/use-is-out-of-bounds';
4
4
  import classnames from 'classnames';
5
5
  import * as React from 'react';
6
- import {
7
- BODY_CLASS_NAME,
8
- BODY_SELECTOR,
9
- LABEL_CLASS_NAME,
10
- LABEL_TEXT_CLASS_NAME,
11
- ROOT_CLASS_NAME,
12
- STYLES,
13
- TRIGGER_CLASS_NAME,
14
- } from './styles.js';
15
- import {
16
- getActiveItemElement,
17
- getItemElements,
18
- ITEM_SELECTOR,
19
- KEY_EVENT_ELEMENTS,
20
- setActiveItem,
21
- } from './helpers.js';
6
+ import { BODY_CLASS_NAME, BODY_SELECTOR, LABEL_CLASS_NAME, LABEL_TEXT_CLASS_NAME, ROOT_CLASS_NAME, STYLES, TRIGGER_CLASS_NAME, } from './styles.js';
7
+ import { getActiveItemElement, getItemElements, ITEM_SELECTOR, KEY_EVENT_ELEMENTS, setActiveItem, } from './helpers.js';
22
8
  const { Children, Fragment, useCallback, useLayoutEffect, useRef, useState } = React;
23
- const noop = () => {};
24
- const CHILDREN_ERROR =
25
- '@acusti/dropdown requires either 1 child (the dropdown body) or 2 children: the dropdown trigger and the dropdown body.';
26
- const Dropdown = ({
27
- allowEmpty = true,
28
- children,
29
- className,
30
- disabled,
31
- hasItems = true,
32
- isOpenOnMount,
33
- isSearchable,
34
- label,
35
- name,
36
- onSubmitItem,
37
- placeholder,
38
- tabIndex,
39
- value,
40
- }) => {
9
+ const noop = () => { };
10
+ const CHILDREN_ERROR = '@acusti/dropdown requires either 1 child (the dropdown body) or 2 children: the dropdown trigger and the dropdown body.';
11
+ const Dropdown = ({ allowEmpty = true, children, className, disabled, hasItems = true, isOpenOnMount, isSearchable, label, name, onSubmitItem, placeholder, tabIndex, value, }) => {
41
12
  const childrenCount = Children.count(children);
42
13
  if (childrenCount !== 1 && childrenCount !== 2) {
43
14
  if (childrenCount === 0) {
@@ -99,39 +70,30 @@ const Dropdown = ({
99
70
  // doesn’t close before expected. It also enables using <Link />s in the dropdown body.
100
71
  closingTimerRef.current = setTimeout(closeDropdown, 90);
101
72
  }
102
- if (!hasItemsRef.current) return;
73
+ if (!hasItemsRef.current)
74
+ return;
103
75
  const nextElement = getActiveItemElement(dropdownElementRef.current);
104
76
  if (!nextElement) {
105
77
  // If not allowEmpty, don’t allow submitting an empty item
106
- if (!allowEmptyRef.current) return;
78
+ if (!allowEmptyRef.current)
79
+ return;
107
80
  // If we have an input element as trigger & the user didn’t clear the text, do nothing
108
- if (
109
- (_a = inputElementRef.current) === null || _a === void 0
110
- ? void 0
111
- : _a.value
112
- )
81
+ if ((_a = inputElementRef.current) === null || _a === void 0 ? void 0 : _a.value)
113
82
  return;
114
83
  }
115
- const label =
116
- (nextElement === null || nextElement === void 0
117
- ? void 0
118
- : nextElement.innerText) || '';
119
- const nextValue =
120
- (nextElement === null || nextElement === void 0
121
- ? void 0
122
- : nextElement.dataset.uktValue) || label;
84
+ const label = (nextElement === null || nextElement === void 0 ? void 0 : nextElement.innerText) || '';
85
+ const nextValue = (nextElement === null || nextElement === void 0 ? void 0 : nextElement.dataset.uktValue) || label;
123
86
  const nextItem = { element: nextElement, value: nextValue };
124
87
  if (inputElementRef.current) {
125
88
  inputElementRef.current.value = label;
126
- if (
127
- inputElementRef.current ===
128
- inputElementRef.current.ownerDocument.activeElement
129
- ) {
89
+ if (inputElementRef.current ===
90
+ inputElementRef.current.ownerDocument.activeElement) {
130
91
  inputElementRef.current.blur();
131
92
  }
132
93
  }
133
94
  // If parent is controlling Dropdown via props.value and nextValue is the same, do nothing
134
- if (valueRef.current && valueRef.current === nextValue) return;
95
+ if (valueRef.current && valueRef.current === nextValue)
96
+ return;
135
97
  if (onSubmitItemRef.current) {
136
98
  onSubmitItemRef.current(nextItem);
137
99
  }
@@ -139,24 +101,27 @@ const Dropdown = ({
139
101
  const handleMouseMove = useCallback(({ clientX, clientY }) => {
140
102
  currentInputMethodRef.current = 'mouse';
141
103
  const initialPosition = mouseDownPositionRef.current;
142
- if (!initialPosition) return;
143
- if (
144
- Math.abs(initialPosition.clientX - clientX) < 12 &&
145
- Math.abs(initialPosition.clientY - clientY) < 12
146
- ) {
104
+ if (!initialPosition)
105
+ return;
106
+ if (Math.abs(initialPosition.clientX - clientX) < 12 &&
107
+ Math.abs(initialPosition.clientY - clientY) < 12) {
147
108
  return;
148
109
  }
149
110
  setIsOpening(false);
150
111
  }, []);
151
112
  const handleMouseOver = useCallback((event) => {
152
- if (!hasItemsRef.current) return;
113
+ if (!hasItemsRef.current)
114
+ return;
153
115
  // If user isn’t currently using the mouse to navigate the dropdown, do nothing
154
- if (currentInputMethodRef.current !== 'mouse') return;
116
+ if (currentInputMethodRef.current !== 'mouse')
117
+ return;
155
118
  // Ensure we have the dropdown root HTMLElement
156
119
  const dropdownElement = dropdownElementRef.current;
157
- if (!dropdownElement) return;
120
+ if (!dropdownElement)
121
+ return;
158
122
  const itemElements = getItemElements(dropdownElement);
159
- if (!itemElements) return;
123
+ if (!itemElements)
124
+ return;
160
125
  const eventTarget = event.target;
161
126
  const item = eventTarget.closest(ITEM_SELECTOR);
162
127
  const element = item || eventTarget;
@@ -171,327 +136,282 @@ const Dropdown = ({
171
136
  }
172
137
  }, []);
173
138
  const cleanupEventListenersRef = useRef(noop);
174
- const handleRef = useCallback(
175
- (ref) => {
176
- dropdownElementRef.current = ref;
177
- if (!ref) {
178
- // If component was unmounted, cleanup handlers
179
- cleanupEventListenersRef.current();
180
- cleanupEventListenersRef.current = noop;
139
+ const handleRef = useCallback((ref) => {
140
+ dropdownElementRef.current = ref;
141
+ if (!ref) {
142
+ // If component was unmounted, cleanup handlers
143
+ cleanupEventListenersRef.current();
144
+ cleanupEventListenersRef.current = noop;
145
+ return;
146
+ }
147
+ const { ownerDocument } = ref;
148
+ let inputElement = inputElementRef.current;
149
+ // Check if trigger from props is an input or textarea element
150
+ if (isTriggerFromProps && !inputElement && ref.firstElementChild) {
151
+ inputElement = ref.firstElementChild.querySelector('input:not([type=radio]):not([type=checkbox]):not([type=range]),textarea');
152
+ inputElementRef.current = inputElement;
153
+ }
154
+ const handleMouseDown = ({ clientX, clientY, target }) => {
155
+ const eventTarget = target;
156
+ if (dropdownElementRef.current &&
157
+ !dropdownElementRef.current.contains(eventTarget)) {
158
+ // Close dropdown on an outside click
159
+ closeDropdown();
181
160
  return;
182
161
  }
183
- const { ownerDocument } = ref;
184
- let inputElement = inputElementRef.current;
185
- // Check if trigger from props is an input or textarea element
186
- if (isTriggerFromProps && !inputElement && ref.firstElementChild) {
187
- inputElement = ref.firstElementChild.querySelector(
188
- 'input:not([type=radio]):not([type=checkbox]):not([type=range]),textarea',
189
- );
190
- inputElementRef.current = inputElement;
191
- }
192
- const handleMouseDown = ({ clientX, clientY, target }) => {
193
- const eventTarget = target;
194
- if (
195
- dropdownElementRef.current &&
196
- !dropdownElementRef.current.contains(eventTarget)
197
- ) {
198
- // Close dropdown on an outside click
199
- closeDropdown();
200
- return;
201
- }
202
- if (isOpenRef.current) return;
203
- setIsOpen(true);
204
- setIsOpening(true);
205
- mouseDownPositionRef.current = { clientX, clientY };
206
- isOpeningTimerRef.current = setTimeout(() => {
207
- setIsOpening(false);
162
+ if (isOpenRef.current)
163
+ return;
164
+ setIsOpen(true);
165
+ setIsOpening(true);
166
+ mouseDownPositionRef.current = { clientX, clientY };
167
+ isOpeningTimerRef.current = setTimeout(() => {
168
+ setIsOpening(false);
169
+ isOpeningTimerRef.current = null;
170
+ }, 1000);
171
+ };
172
+ const handleMouseUp = ({ target }) => {
173
+ if (!isOpenRef.current || closingTimerRef.current)
174
+ return;
175
+ // If still isOpening (gets set false 1s after open triggers), set it to false onMouseUp
176
+ if (isOpeningRef.current) {
177
+ setIsOpening(false);
178
+ if (isOpeningTimerRef.current) {
179
+ clearTimeout(isOpeningTimerRef.current);
208
180
  isOpeningTimerRef.current = null;
209
- }, 1000);
181
+ }
182
+ return;
183
+ }
184
+ const isTargetInBody = target.closest(BODY_SELECTOR);
185
+ // If mouseup is on dropdown body and there are no items, don’t close the dropdown
186
+ if (!hasItemsRef.current && isTargetInBody)
187
+ return;
188
+ // If mouseup is on an item, trigger submit item, else close the dropdown
189
+ if (isTargetInBody) {
190
+ handleSubmitItem();
191
+ }
192
+ else if (!inputElementRef.current ||
193
+ (dropdownElementRef.current &&
194
+ dropdownElementRef.current.contains(ownerDocument.activeElement))) {
195
+ // If dropdown is searchable and ref is still focused, this won’t be invoked
196
+ closeDropdown();
197
+ }
198
+ };
199
+ const handleKeyDown = (event) => {
200
+ const { altKey, ctrlKey, key, metaKey } = event;
201
+ const eventTarget = event.target;
202
+ const dropdownElement = dropdownElementRef.current;
203
+ if (!dropdownElement)
204
+ return;
205
+ const onEventHandled = () => {
206
+ event.stopPropagation();
207
+ event.preventDefault();
208
+ currentInputMethodRef.current = 'keyboard';
210
209
  };
211
- const handleMouseUp = ({ target }) => {
212
- if (!isOpenRef.current || closingTimerRef.current) return;
213
- // If still isOpening (gets set false 1s after open triggers), set it to false onMouseUp
214
- if (isOpeningRef.current) {
215
- setIsOpening(false);
216
- if (isOpeningTimerRef.current) {
217
- clearTimeout(isOpeningTimerRef.current);
218
- isOpeningTimerRef.current = null;
219
- }
210
+ const isEventTargetingDropdown = dropdownElement.contains(eventTarget);
211
+ if (!isOpenRef.current) {
212
+ // If dropdown is closed, don’t handle key events if event target isn’t within dropdown
213
+ if (!isEventTargetingDropdown)
214
+ return;
215
+ // Open the dropdown on spacebar, enter, or if isSearchable and user hits the up/down arrows
216
+ if (key === ' ' ||
217
+ key === 'Enter' ||
218
+ (hasItemsRef.current &&
219
+ (key === 'ArrowUp' || key === 'ArrowDown'))) {
220
+ onEventHandled();
221
+ setIsOpen(true);
220
222
  return;
221
223
  }
222
- const isTargetInBody = target.closest(BODY_SELECTOR);
223
- // If mouseup is on dropdown body and there are no items, don’t close the dropdown
224
- if (!hasItemsRef.current && isTargetInBody) return;
225
- // If mouseup is on an item, trigger submit item, else close the dropdown
226
- if (isTargetInBody) {
227
- handleSubmitItem();
228
- } else if (
229
- !inputElementRef.current ||
230
- (dropdownElementRef.current &&
231
- dropdownElementRef.current.contains(ownerDocument.activeElement))
232
- ) {
233
- // If dropdown is searchable and ref is still focused, this won’t be invoked
234
- closeDropdown();
224
+ return;
225
+ }
226
+ // If dropdown isOpen, hasItems, and not isSearchable, handle entering characters
227
+ if (hasItemsRef.current && !inputElementRef.current) {
228
+ let isEditingCharacters = !ctrlKey && !metaKey && /^[A-Za-z0-9]$/.test(key);
229
+ // User could also be editing characters if there are already characters entered
230
+ // and they are hitting delete or spacebar
231
+ if (!isEditingCharacters && enteredCharactersRef.current) {
232
+ isEditingCharacters = key === ' ' || key === 'Backspace';
235
233
  }
236
- };
237
- const handleKeyDown = (event) => {
238
- const { altKey, ctrlKey, key, metaKey } = event;
239
- const eventTarget = event.target;
240
- const dropdownElement = dropdownElementRef.current;
241
- if (!dropdownElement) return;
242
- const onEventHandled = () => {
243
- event.stopPropagation();
244
- event.preventDefault();
245
- currentInputMethodRef.current = 'keyboard';
246
- };
247
- const isEventTargetingDropdown = dropdownElement.contains(eventTarget);
248
- if (!isOpenRef.current) {
249
- // If dropdown is closed, don’t handle key events if event target isn’t within dropdown
250
- if (!isEventTargetingDropdown) return;
251
- // Open the dropdown on spacebar, enter, or if isSearchable and user hits the up/down arrows
252
- if (
253
- key === ' ' ||
254
- key === 'Enter' ||
255
- (hasItemsRef.current &&
256
- (key === 'ArrowUp' || key === 'ArrowDown'))
257
- ) {
258
- onEventHandled();
259
- setIsOpen(true);
260
- return;
234
+ if (isEditingCharacters) {
235
+ onEventHandled();
236
+ if (key === 'Backspace') {
237
+ enteredCharactersRef.current =
238
+ enteredCharactersRef.current.slice(0, -1);
261
239
  }
240
+ else {
241
+ enteredCharactersRef.current += key;
242
+ }
243
+ setActiveItem({
244
+ dropdownElement,
245
+ // If input element came from props, only override the input’s value
246
+ // with an exact text match so user can enter a value not in items
247
+ isExactMatch: isTriggerFromPropsRef.current,
248
+ text: enteredCharactersRef.current,
249
+ });
250
+ if (clearEnteredCharactersTimerRef.current) {
251
+ clearTimeout(clearEnteredCharactersTimerRef.current);
252
+ }
253
+ clearEnteredCharactersTimerRef.current = setTimeout(() => {
254
+ enteredCharactersRef.current = '';
255
+ clearEnteredCharactersTimerRef.current = null;
256
+ }, 1500);
262
257
  return;
263
258
  }
264
- // If dropdown isOpen, hasItems, and not isSearchable, handle entering characters
265
- if (hasItemsRef.current && !inputElementRef.current) {
266
- let isEditingCharacters =
267
- !ctrlKey && !metaKey && /^[A-Za-z0-9]$/.test(key);
268
- // User could also be editing characters if there are already characters entered
269
- // and they are hitting delete or spacebar
270
- if (!isEditingCharacters && enteredCharactersRef.current) {
271
- isEditingCharacters = key === ' ' || key === 'Backspace';
272
- }
273
- if (isEditingCharacters) {
274
- onEventHandled();
275
- if (key === 'Backspace') {
276
- enteredCharactersRef.current =
277
- enteredCharactersRef.current.slice(0, -1);
278
- } else {
279
- enteredCharactersRef.current += key;
280
- }
259
+ }
260
+ // If dropdown isOpen, handle submitting the value
261
+ if (key === 'Enter' || (key === ' ' && !inputElementRef.current)) {
262
+ onEventHandled();
263
+ handleSubmitItem();
264
+ return;
265
+ }
266
+ // If dropdown isOpen, handle closing it on escape or spacebar if !hasItems
267
+ if (key === 'Escape' ||
268
+ (isEventTargetingDropdown && key === ' ' && !hasItemsRef.current)) {
269
+ // If there are no items & event target element uses key events, don’t close it
270
+ if (!hasItemsRef.current &&
271
+ (eventTarget.isContentEditable ||
272
+ KEY_EVENT_ELEMENTS.has(eventTarget.tagName))) {
273
+ return;
274
+ }
275
+ closeDropdown();
276
+ return;
277
+ }
278
+ // Handle ↑/↓ arrows
279
+ if (hasItemsRef.current) {
280
+ if (key === 'ArrowUp') {
281
+ onEventHandled();
282
+ if (altKey || metaKey) {
281
283
  setActiveItem({
282
284
  dropdownElement,
283
- // If input element came from props, only override the input’s value
284
- // with an exact text match so user can enter a value not in items
285
- isExactMatch: isTriggerFromPropsRef.current,
286
- text: enteredCharactersRef.current,
285
+ index: 0,
287
286
  });
288
- if (clearEnteredCharactersTimerRef.current) {
289
- clearTimeout(clearEnteredCharactersTimerRef.current);
290
- }
291
- clearEnteredCharactersTimerRef.current = setTimeout(() => {
292
- enteredCharactersRef.current = '';
293
- clearEnteredCharactersTimerRef.current = null;
294
- }, 1500);
295
- return;
296
287
  }
297
- }
298
- // If dropdown isOpen, handle submitting the value
299
- if (key === 'Enter' || (key === ' ' && !inputElementRef.current)) {
300
- onEventHandled();
301
- handleSubmitItem();
302
- return;
303
- }
304
- // If dropdown isOpen, handle closing it on escape or spacebar if !hasItems
305
- if (
306
- key === 'Escape' ||
307
- (isEventTargetingDropdown && key === ' ' && !hasItemsRef.current)
308
- ) {
309
- // If there are no items & event target element uses key events, don’t close it
310
- if (
311
- !hasItemsRef.current &&
312
- (eventTarget.isContentEditable ||
313
- KEY_EVENT_ELEMENTS.has(eventTarget.tagName))
314
- ) {
315
- return;
288
+ else {
289
+ setActiveItem({
290
+ dropdownElement,
291
+ indexAddend: -1,
292
+ });
316
293
  }
317
- closeDropdown();
318
294
  return;
319
295
  }
320
- // Handle ↑/↓ arrows
321
- if (hasItemsRef.current) {
322
- if (key === 'ArrowUp') {
323
- onEventHandled();
324
- if (altKey || metaKey) {
325
- setActiveItem({
326
- dropdownElement,
327
- index: 0,
328
- });
329
- } else {
330
- setActiveItem({
331
- dropdownElement,
332
- indexAddend: -1,
333
- });
334
- }
335
- return;
296
+ if (key === 'ArrowDown') {
297
+ onEventHandled();
298
+ if (altKey || metaKey) {
299
+ // Using a negative index counts back from the end
300
+ setActiveItem({
301
+ dropdownElement,
302
+ index: -1,
303
+ });
336
304
  }
337
- if (key === 'ArrowDown') {
338
- onEventHandled();
339
- if (altKey || metaKey) {
340
- // Using a negative index counts back from the end
341
- setActiveItem({
342
- dropdownElement,
343
- index: -1,
344
- });
345
- } else {
346
- setActiveItem({
347
- dropdownElement,
348
- indexAddend: 1,
349
- });
350
- }
351
- return;
305
+ else {
306
+ setActiveItem({
307
+ dropdownElement,
308
+ indexAddend: 1,
309
+ });
352
310
  }
353
- }
354
- };
355
- // Close dropdown if any element is focused outside of this dropdown
356
- const handleFocusIn = (event) => {
357
- if (!isOpenRef.current) return;
358
- const eventTarget = event.target;
359
- // If focused element is a descendant or a parent of the dropdown, do nothing
360
- if (
361
- !dropdownElementRef.current ||
362
- dropdownElementRef.current.contains(eventTarget) ||
363
- eventTarget.contains(dropdownElementRef.current)
364
- ) {
365
311
  return;
366
312
  }
367
- closeDropdown();
368
- };
369
- document.addEventListener('focusin', handleFocusIn);
370
- document.addEventListener('keydown', handleKeyDown);
371
- document.addEventListener('mousedown', handleMouseDown);
372
- document.addEventListener('mouseup', handleMouseUp);
373
- if (ownerDocument !== document) {
374
- ownerDocument.addEventListener('focusin', handleFocusIn);
375
- ownerDocument.addEventListener('keydown', handleKeyDown);
376
- ownerDocument.addEventListener('mousedown', handleMouseDown);
377
- ownerDocument.addEventListener('mouseup', handleMouseUp);
378
313
  }
379
- // If dropdown should be open on mount, focus it
380
- if (isOpenOnMount) {
381
- ref.focus();
314
+ };
315
+ // Close dropdown if any element is focused outside of this dropdown
316
+ const handleFocusIn = (event) => {
317
+ if (!isOpenRef.current)
318
+ return;
319
+ const eventTarget = event.target;
320
+ // If focused element is a descendant or a parent of the dropdown, do nothing
321
+ if (!dropdownElementRef.current ||
322
+ dropdownElementRef.current.contains(eventTarget) ||
323
+ eventTarget.contains(dropdownElementRef.current)) {
324
+ return;
325
+ }
326
+ closeDropdown();
327
+ };
328
+ document.addEventListener('focusin', handleFocusIn);
329
+ document.addEventListener('keydown', handleKeyDown);
330
+ document.addEventListener('mousedown', handleMouseDown);
331
+ document.addEventListener('mouseup', handleMouseUp);
332
+ if (ownerDocument !== document) {
333
+ ownerDocument.addEventListener('focusin', handleFocusIn);
334
+ ownerDocument.addEventListener('keydown', handleKeyDown);
335
+ ownerDocument.addEventListener('mousedown', handleMouseDown);
336
+ ownerDocument.addEventListener('mouseup', handleMouseUp);
337
+ }
338
+ // If dropdown should be open on mount, focus it
339
+ if (isOpenOnMount) {
340
+ ref.focus();
341
+ }
342
+ const handleInput = (event) => {
343
+ const dropdownElement = dropdownElementRef.current;
344
+ if (!dropdownElement)
345
+ return;
346
+ if (!isOpenRef.current)
347
+ setIsOpen(true);
348
+ const input = event.target;
349
+ const isDeleting = enteredCharactersRef.current.length > input.value.length;
350
+ enteredCharactersRef.current = input.value;
351
+ // Don’t set a new active item if user is deleting text unless text is now empty
352
+ if (isDeleting && input.value.length)
353
+ return;
354
+ setActiveItem({
355
+ dropdownElement,
356
+ // If input element came from props, only override the input’s value
357
+ // with an exact text match so user can enter a value not in items
358
+ isExactMatch: isTriggerFromPropsRef.current,
359
+ text: enteredCharactersRef.current,
360
+ });
361
+ };
362
+ if (inputElement) {
363
+ inputElement.addEventListener('input', handleInput);
364
+ }
365
+ cleanupEventListenersRef.current = () => {
366
+ document.removeEventListener('focusin', handleFocusIn);
367
+ document.removeEventListener('keydown', handleKeyDown);
368
+ document.removeEventListener('mousedown', handleMouseDown);
369
+ document.removeEventListener('mouseup', handleMouseUp);
370
+ if (ownerDocument !== document) {
371
+ ownerDocument.removeEventListener('focusin', handleFocusIn);
372
+ ownerDocument.removeEventListener('keydown', handleKeyDown);
373
+ ownerDocument.removeEventListener('mousedown', handleMouseDown);
374
+ ownerDocument.removeEventListener('mouseup', handleMouseUp);
382
375
  }
383
- const handleInput = (event) => {
384
- const dropdownElement = dropdownElementRef.current;
385
- if (!dropdownElement) return;
386
- if (!isOpenRef.current) setIsOpen(true);
387
- const input = event.target;
388
- const isDeleting =
389
- enteredCharactersRef.current.length > input.value.length;
390
- enteredCharactersRef.current = input.value;
391
- // Don’t set a new active item if user is deleting text unless text is now empty
392
- if (isDeleting && input.value.length) return;
393
- setActiveItem({
394
- dropdownElement,
395
- // If input element came from props, only override the input’s value
396
- // with an exact text match so user can enter a value not in items
397
- isExactMatch: isTriggerFromPropsRef.current,
398
- text: enteredCharactersRef.current,
399
- });
400
- };
401
376
  if (inputElement) {
402
- inputElement.addEventListener('input', handleInput);
377
+ inputElement.removeEventListener('input', handleInput);
403
378
  }
404
- cleanupEventListenersRef.current = () => {
405
- document.removeEventListener('focusin', handleFocusIn);
406
- document.removeEventListener('keydown', handleKeyDown);
407
- document.removeEventListener('mousedown', handleMouseDown);
408
- document.removeEventListener('mouseup', handleMouseUp);
409
- if (ownerDocument !== document) {
410
- ownerDocument.removeEventListener('focusin', handleFocusIn);
411
- ownerDocument.removeEventListener('keydown', handleKeyDown);
412
- ownerDocument.removeEventListener('mousedown', handleMouseDown);
413
- ownerDocument.removeEventListener('mouseup', handleMouseUp);
414
- }
415
- if (inputElement) {
416
- inputElement.removeEventListener('input', handleInput);
417
- }
418
- };
419
- },
420
- [closeDropdown, handleSubmitItem, isOpenOnMount, isTriggerFromProps],
421
- );
379
+ };
380
+ }, [closeDropdown, handleSubmitItem, isOpenOnMount, isTriggerFromProps]);
422
381
  const handleTriggerFocus = useCallback(() => {
423
382
  setIsOpen(true);
424
383
  }, []);
425
384
  if (!isTriggerFromProps) {
426
385
  if (isSearchable) {
427
- trigger = React.createElement(InputText, {
428
- className: TRIGGER_CLASS_NAME,
429
- disabled: disabled,
430
- initialValue: value || '',
431
- name: name,
432
- onFocus: handleTriggerFocus,
433
- placeholder: placeholder,
434
- ref: inputElementRef,
435
- selectTextOnFocus: true,
436
- tabIndex: tabIndex,
437
- type: 'text',
438
- });
439
- } else {
440
- trigger = React.createElement(
441
- 'button',
442
- { className: TRIGGER_CLASS_NAME, tabIndex: 0 },
443
- trigger,
444
- );
386
+ trigger = (React.createElement(InputText, { className: TRIGGER_CLASS_NAME, disabled: disabled, initialValue: value || '', name: name, onFocus: handleTriggerFocus, placeholder: placeholder, ref: inputElementRef, selectTextOnFocus: true, tabIndex: tabIndex, type: "text" }));
387
+ }
388
+ else {
389
+ trigger = (React.createElement("button", { className: TRIGGER_CLASS_NAME, tabIndex: 0 }, trigger));
445
390
  }
446
391
  }
447
392
  if (label) {
448
- trigger = React.createElement(
449
- 'label',
450
- { className: LABEL_CLASS_NAME },
451
- React.createElement('div', { className: LABEL_TEXT_CLASS_NAME }, label),
452
- trigger,
453
- );
393
+ trigger = (React.createElement("label", { className: LABEL_CLASS_NAME },
394
+ React.createElement("div", { className: LABEL_TEXT_CLASS_NAME }, label),
395
+ trigger));
454
396
  }
455
- return React.createElement(
456
- Fragment,
457
- null,
397
+ return (React.createElement(Fragment, null,
458
398
  React.createElement(Style, null, STYLES),
459
- React.createElement(
460
- 'div',
461
- {
462
- className: classnames(ROOT_CLASS_NAME, className, {
463
- disabled,
464
- 'is-open': isOpen,
465
- 'is-searchable': isSearchable,
466
- }),
467
- onMouseMove: handleMouseMove,
468
- onMouseOver: handleMouseOver,
469
- ref: handleRef,
470
- tabIndex:
471
- isSearchable || inputElementRef.current || !isTriggerFromProps
472
- ? undefined
473
- : 0,
474
- },
399
+ React.createElement("div", { className: classnames(ROOT_CLASS_NAME, className, {
400
+ disabled,
401
+ 'is-open': isOpen,
402
+ 'is-searchable': isSearchable,
403
+ }), onMouseMove: handleMouseMove, onMouseOver: handleMouseOver, ref: handleRef, tabIndex: isSearchable || inputElementRef.current || !isTriggerFromProps
404
+ ? undefined
405
+ : 0 },
475
406
  trigger,
476
- isOpen
477
- ? React.createElement(
478
- 'div',
479
- {
480
- className: classnames(BODY_CLASS_NAME, {
481
- 'calculating-position': !outOfBounds.hasLayout,
482
- 'has-items': hasItems,
483
- 'out-of-bounds-bottom': outOfBounds.bottom,
484
- 'out-of-bounds-left': outOfBounds.left,
485
- 'out-of-bounds-right': outOfBounds.right,
486
- 'out-of-bounds-top': outOfBounds.top,
487
- }),
488
- ref: setDropdownBodyElement,
489
- },
490
- children[1] || children[0] || children,
491
- )
492
- : null,
493
- ),
494
- );
407
+ isOpen ? (React.createElement("div", { className: classnames(BODY_CLASS_NAME, {
408
+ 'calculating-position': !outOfBounds.hasLayout,
409
+ 'has-items': hasItems,
410
+ 'out-of-bounds-bottom': outOfBounds.bottom,
411
+ 'out-of-bounds-left': outOfBounds.left,
412
+ 'out-of-bounds-right': outOfBounds.right,
413
+ 'out-of-bounds-top': outOfBounds.top,
414
+ }), ref: setDropdownBodyElement }, children[1] || children[0] || children)) : null)));
495
415
  };
496
416
  export default Dropdown;
497
- //# sourceMappingURL=Dropdown.js.map
417
+ //# sourceMappingURL=Dropdown.js.map
@@ -5,54 +5,54 @@
5
5
  * @flow
6
6
  */
7
7
 
8
- import * as React from 'react';
8
+ import * as React from "react";
9
9
  export type Item = {|
10
- element: HTMLElement | null,
11
- value: string,
10
+ element: HTMLElement | null,
11
+ value: string,
12
12
  |};
13
13
  export type Props = {|
14
- /**
15
- * Boolean indicating if the user can submit an empty value (i.e. clear the value); defaults to true
16
- */
17
- allowEmpty?: boolean,
14
+ /**
15
+ * Boolean indicating if the user can submit an empty value (i.e. clear the value); defaults to true
16
+ */
17
+ allowEmpty?: boolean,
18
18
 
19
- /**
20
- * Can take a single React element (e.g. ReactChild) or exactly two renderable children
21
- */
22
- children: React.Element<any> | [React.Node, React.Node],
23
- className?: string,
24
- disabled?: boolean,
19
+ /**
20
+ * Can take a single React element (e.g. ReactChild) or exactly two renderable children
21
+ */
22
+ children: React.Element<any> | [React.Node, React.Node],
23
+ className?: string,
24
+ disabled?: boolean,
25
25
 
26
- /**
27
- * Group identifier string links dropdowns together into a menu (like macOS top menubar)
28
- */
29
- group?: string,
30
- hasItems?: boolean,
31
- isOpenOnMount?: boolean,
32
- isSearchable?: boolean,
33
- label?: string,
26
+ /**
27
+ * Group identifier string links dropdowns together into a menu (like macOS top menubar)
28
+ */
29
+ group?: string,
30
+ hasItems?: boolean,
31
+ isOpenOnMount?: boolean,
32
+ isSearchable?: boolean,
33
+ label?: string,
34
34
 
35
- /**
36
- * Only usable in conjunction with {isSearchable: true}; used as search input’s name
37
- */
38
- name?: string,
39
- onSubmitItem?: (payload: Item) => void,
35
+ /**
36
+ * Only usable in conjunction with {isSearchable: true}; used as search input’s name
37
+ */
38
+ name?: string,
39
+ onSubmitItem?: (payload: Item) => void,
40
40
 
41
- /**
42
- * Only usable in conjunction with {isSearchable: true}; used as search input’s placeholder
43
- */
44
- placeholder?: string,
41
+ /**
42
+ * Only usable in conjunction with {isSearchable: true}; used as search input’s placeholder
43
+ */
44
+ placeholder?: string,
45
45
 
46
- /**
47
- * Only usable in conjunction with {isSearchable: true}; used as search input’s tabIndex
48
- */
49
- tabIndex?: number,
46
+ /**
47
+ * Only usable in conjunction with {isSearchable: true}; used as search input’s tabIndex
48
+ */
49
+ tabIndex?: number,
50
50
 
51
- /**
52
- * Used as search input’s value if props.isSearchable === true
53
- * Used to determine if value has changed to avoid triggering onSubmitItem if not
54
- */
55
- value?: string,
51
+ /**
52
+ * Used as search input’s value if props.isSearchable === true
53
+ * Used to determine if value has changed to avoid triggering onSubmitItem if not
54
+ */
55
+ value?: string,
56
56
  |};
57
57
  declare var Dropdown: React.StatelessFunctionalComponent<Props>;
58
58
  declare export default typeof Dropdown;
package/dist/helpers.d.ts CHANGED
@@ -1,48 +1,33 @@
1
- export declare const ITEM_SELECTOR = '[data-ukt-item], [data-ukt-value]';
1
+ export declare const ITEM_SELECTOR = "[data-ukt-item], [data-ukt-value]";
2
2
  export declare const KEY_EVENT_ELEMENTS: Set<string>;
3
- export declare const getItemElements: (
4
- dropdownElement: HTMLElement | null,
5
- ) => NodeListOf<Element> | HTMLCollection | null;
6
- export declare const getActiveItemElement: (
7
- dropdownElement: HTMLElement | null,
8
- ) => HTMLElement | null;
9
- export declare const setActiveItem: ({
10
- dropdownElement,
11
- element,
12
- index,
13
- indexAddend,
14
- isExactMatch,
15
- text,
16
- }:
17
- | {
18
- dropdownElement: HTMLElement;
19
- element: HTMLElement;
20
- index?: null | undefined;
21
- indexAddend?: null | undefined;
22
- isExactMatch?: null | undefined;
23
- text?: null | undefined;
24
- }
25
- | {
26
- dropdownElement: HTMLElement;
27
- element?: null | undefined;
28
- index: number;
29
- indexAddend?: null | undefined;
30
- isExactMatch?: null | undefined;
31
- text?: null | undefined;
32
- }
33
- | {
34
- dropdownElement: HTMLElement;
35
- element?: null | undefined;
36
- index?: null | undefined;
37
- indexAddend: number;
38
- isExactMatch?: null | undefined;
39
- text?: null | undefined;
40
- }
41
- | {
42
- dropdownElement: HTMLElement;
43
- element?: null | undefined;
44
- index?: null | undefined;
45
- indexAddend?: null | undefined;
46
- isExactMatch?: boolean | undefined;
47
- text: string;
48
- }) => void;
3
+ export declare const getItemElements: (dropdownElement: HTMLElement | null) => NodeListOf<Element> | HTMLCollection | null;
4
+ export declare const getActiveItemElement: (dropdownElement: HTMLElement | null) => HTMLElement | null;
5
+ export declare const setActiveItem: ({ dropdownElement, element, index, indexAddend, isExactMatch, text, }: {
6
+ dropdownElement: HTMLElement;
7
+ element: HTMLElement;
8
+ index?: null | undefined;
9
+ indexAddend?: null | undefined;
10
+ isExactMatch?: null | undefined;
11
+ text?: null | undefined;
12
+ } | {
13
+ dropdownElement: HTMLElement;
14
+ element?: null | undefined;
15
+ index: number;
16
+ indexAddend?: null | undefined;
17
+ isExactMatch?: null | undefined;
18
+ text?: null | undefined;
19
+ } | {
20
+ dropdownElement: HTMLElement;
21
+ element?: null | undefined;
22
+ index?: null | undefined;
23
+ indexAddend: number;
24
+ isExactMatch?: null | undefined;
25
+ text?: null | undefined;
26
+ } | {
27
+ dropdownElement: HTMLElement;
28
+ element?: null | undefined;
29
+ index?: null | undefined;
30
+ indexAddend?: null | undefined;
31
+ isExactMatch?: boolean | undefined;
32
+ text: string;
33
+ }) => void;
package/dist/helpers.js CHANGED
@@ -3,16 +3,20 @@ import { BODY_SELECTOR } from './styles.js';
3
3
  export const ITEM_SELECTOR = `[data-ukt-item], [data-ukt-value]`;
4
4
  export const KEY_EVENT_ELEMENTS = new Set(['INPUT', 'TEXTAREA']);
5
5
  export const getItemElements = (dropdownElement) => {
6
- if (!dropdownElement) return null;
6
+ if (!dropdownElement)
7
+ return null;
7
8
  const bodyElement = dropdownElement.querySelector(BODY_SELECTOR);
8
- if (!bodyElement) return null;
9
+ if (!bodyElement)
10
+ return null;
9
11
  let items = bodyElement.querySelectorAll(ITEM_SELECTOR);
10
- if (items.length) return items;
12
+ if (items.length)
13
+ return items;
11
14
  // If no items found via [data-ukt-item] or [data-ukt-value] selector,
12
15
  // use first instance of multiple children found
13
16
  items = bodyElement.children;
14
17
  while (items.length === 1) {
15
- if (!items[0].children) break;
18
+ if (!items[0].children)
19
+ break;
16
20
  items = items[0].children;
17
21
  }
18
22
  // If unable to find an element with more than one child, treat direct child as items
@@ -22,7 +26,8 @@ export const getItemElements = (dropdownElement) => {
22
26
  return items;
23
27
  };
24
28
  export const getActiveItemElement = (dropdownElement) => {
25
- if (!dropdownElement) return null;
29
+ if (!dropdownElement)
30
+ return null;
26
31
  return dropdownElement.querySelector('[data-ukt-active]');
27
32
  };
28
33
  const clearItemElementsState = (itemElements) => {
@@ -32,45 +37,40 @@ const clearItemElementsState = (itemElements) => {
32
37
  }
33
38
  });
34
39
  };
35
- export const setActiveItem = ({
36
- dropdownElement,
37
- element,
38
- index,
39
- indexAddend,
40
- isExactMatch,
41
- text,
42
- }) => {
40
+ export const setActiveItem = ({ dropdownElement, element, index, indexAddend, isExactMatch, text, }) => {
43
41
  const items = getItemElements(dropdownElement);
44
- if (!items) return;
42
+ if (!items)
43
+ return;
45
44
  const itemElements = Array.from(items);
46
- if (!itemElements.length) return;
45
+ if (!itemElements.length)
46
+ return;
47
47
  const lastIndex = itemElements.length - 1;
48
- const currentActiveIndex = itemElements.findIndex((itemElement) =>
49
- itemElement.hasAttribute('data-ukt-active'),
50
- );
48
+ const currentActiveIndex = itemElements.findIndex((itemElement) => itemElement.hasAttribute('data-ukt-active'));
51
49
  let nextActiveIndex = currentActiveIndex;
52
50
  if (typeof index === 'number') {
53
51
  // Negative index means count back from the end
54
52
  nextActiveIndex = index < 0 ? itemElements.length + index : index;
55
53
  }
56
54
  if (element) {
57
- nextActiveIndex = itemElements.findIndex(
58
- (itemElement) => itemElement === element,
59
- );
60
- } else if (typeof indexAddend === 'number') {
55
+ nextActiveIndex = itemElements.findIndex((itemElement) => itemElement === element);
56
+ }
57
+ else if (typeof indexAddend === 'number') {
61
58
  // If there’s no currentActiveIndex and we are handling -1, start at lastIndex
62
59
  if (currentActiveIndex === -1 && indexAddend === -1) {
63
60
  nextActiveIndex = lastIndex;
64
- } else {
61
+ }
62
+ else {
65
63
  nextActiveIndex += indexAddend;
66
64
  }
67
65
  // Keep it within the bounds of the items list
68
66
  if (nextActiveIndex < 0) {
69
67
  nextActiveIndex = 0;
70
- } else if (nextActiveIndex > lastIndex) {
68
+ }
69
+ else if (nextActiveIndex > lastIndex) {
71
70
  nextActiveIndex = lastIndex;
72
71
  }
73
- } else if (typeof text === 'string') {
72
+ }
73
+ else if (typeof text === 'string') {
74
74
  // If text is empty, clear existing active items and early return
75
75
  if (!text) {
76
76
  clearItemElementsState(itemElements);
@@ -79,19 +79,19 @@ export const setActiveItem = ({
79
79
  const itemTexts = itemElements.map((itemElement) => itemElement.innerText);
80
80
  if (isExactMatch) {
81
81
  const textToCompare = text.toLowerCase();
82
- nextActiveIndex = itemTexts.findIndex((itemText) =>
83
- itemText.toLowerCase().startsWith(textToCompare),
84
- );
82
+ nextActiveIndex = itemTexts.findIndex((itemText) => itemText.toLowerCase().startsWith(textToCompare));
85
83
  // If isExactMatch is required and no exact match was found, clear active items
86
84
  if (nextActiveIndex === -1) {
87
85
  clearItemElementsState(itemElements);
88
86
  }
89
- } else {
87
+ }
88
+ else {
90
89
  const bestMatch = getBestMatch({ items: itemTexts, text });
91
90
  nextActiveIndex = itemTexts.findIndex((text) => text === bestMatch);
92
91
  }
93
92
  }
94
- if (nextActiveIndex === -1 || nextActiveIndex === currentActiveIndex) return;
93
+ if (nextActiveIndex === -1 || nextActiveIndex === currentActiveIndex)
94
+ return;
95
95
  // Clear any existing active dropdown body item state
96
96
  clearItemElementsState(itemElements);
97
97
  const nextActiveItem = items[nextActiveIndex];
@@ -101,11 +101,11 @@ export const setActiveItem = ({
101
101
  let { parentElement } = nextActiveItem;
102
102
  let scrollableParent = null;
103
103
  while (!scrollableParent && parentElement && parentElement !== dropdownElement) {
104
- const isScrollable =
105
- parentElement.scrollHeight > parentElement.clientHeight + 15;
104
+ const isScrollable = parentElement.scrollHeight > parentElement.clientHeight + 15;
106
105
  if (isScrollable) {
107
106
  scrollableParent = parentElement;
108
- } else {
107
+ }
108
+ else {
109
109
  parentElement = parentElement.parentElement;
110
110
  }
111
111
  }
@@ -119,7 +119,8 @@ export const setActiveItem = ({
119
119
  // Item isn’t fully visible; adjust scrollTop to put item within closest edge
120
120
  if (isAboveTop) {
121
121
  scrollTop -= parentRect.top - itemRect.top;
122
- } else {
122
+ }
123
+ else {
123
124
  scrollTop += itemRect.bottom - parentRect.bottom;
124
125
  }
125
126
  scrollableParent.scrollTop = scrollTop;
@@ -127,4 +128,4 @@ export const setActiveItem = ({
127
128
  }
128
129
  }
129
130
  };
130
- //# sourceMappingURL=helpers.js.map
131
+ //# sourceMappingURL=helpers.js.map
@@ -5,46 +5,46 @@
5
5
  * @flow
6
6
  */
7
7
 
8
- declare export var ITEM_SELECTOR: '[data-ukt-item], [data-ukt-value]';
8
+ declare export var ITEM_SELECTOR: "[data-ukt-item], [data-ukt-value]";
9
9
  declare export var KEY_EVENT_ELEMENTS: Set<string>;
10
10
  declare export var getItemElements: (
11
- dropdownElement: HTMLElement | null,
11
+ dropdownElement: HTMLElement | null
12
12
  ) => NodeListOf<Element> | HTMLCollection | null;
13
13
  declare export var getActiveItemElement: (
14
- dropdownElement: HTMLElement | null,
14
+ dropdownElement: HTMLElement | null
15
15
  ) => HTMLElement | null;
16
16
  declare export var setActiveItem: (
17
- x:
18
- | {|
19
- dropdownElement: HTMLElement,
20
- element: HTMLElement,
21
- index?: null | void,
22
- indexAddend?: null | void,
23
- isExactMatch?: null | void,
24
- text?: null | void,
25
- |}
26
- | {|
27
- dropdownElement: HTMLElement,
28
- element?: null | void,
29
- index: number,
30
- indexAddend?: null | void,
31
- isExactMatch?: null | void,
32
- text?: null | void,
33
- |}
34
- | {|
35
- dropdownElement: HTMLElement,
36
- element?: null | void,
37
- index?: null | void,
38
- indexAddend: number,
39
- isExactMatch?: null | void,
40
- text?: null | void,
41
- |}
42
- | {|
43
- dropdownElement: HTMLElement,
44
- element?: null | void,
45
- index?: null | void,
46
- indexAddend?: null | void,
47
- isExactMatch?: boolean | void,
48
- text: string,
49
- |},
17
+ x:
18
+ | {|
19
+ dropdownElement: HTMLElement,
20
+ element: HTMLElement,
21
+ index?: null | void,
22
+ indexAddend?: null | void,
23
+ isExactMatch?: null | void,
24
+ text?: null | void,
25
+ |}
26
+ | {|
27
+ dropdownElement: HTMLElement,
28
+ element?: null | void,
29
+ index: number,
30
+ indexAddend?: null | void,
31
+ isExactMatch?: null | void,
32
+ text?: null | void,
33
+ |}
34
+ | {|
35
+ dropdownElement: HTMLElement,
36
+ element?: null | void,
37
+ index?: null | void,
38
+ indexAddend: number,
39
+ isExactMatch?: null | void,
40
+ text?: null | void,
41
+ |}
42
+ | {|
43
+ dropdownElement: HTMLElement,
44
+ element?: null | void,
45
+ index?: null | void,
46
+ indexAddend?: null | void,
47
+ isExactMatch?: boolean | void,
48
+ text: string,
49
+ |}
50
50
  ) => void;
package/dist/styles.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const ROOT_CLASS_NAME = 'uktdropdown';
1
+ export declare const ROOT_CLASS_NAME = "uktdropdown";
2
2
  export declare const ROOT_SELECTOR: string;
3
3
  export declare const BODY_CLASS_NAME: string;
4
4
  export declare const LABEL_CLASS_NAME: string;
package/dist/styles.js CHANGED
@@ -77,4 +77,4 @@ ${BODY_SELECTOR} [data-ukt-active] {
77
77
  color: var(--uktdd-body-color-hover);
78
78
  }
79
79
  `;
80
- //# sourceMappingURL=styles.js.map
80
+ //# sourceMappingURL=styles.js.map
@@ -5,7 +5,7 @@
5
5
  * @flow
6
6
  */
7
7
 
8
- declare export var ROOT_CLASS_NAME: 'uktdropdown';
8
+ declare export var ROOT_CLASS_NAME: "uktdropdown";
9
9
  declare export var ROOT_SELECTOR: string;
10
10
  declare export var BODY_CLASS_NAME: string;
11
11
  declare export var LABEL_CLASS_NAME: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@acusti/dropdown",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "exports": "./dist/Dropdown.js",
@@ -26,7 +26,7 @@
26
26
  "typescript": "^4.4.3"
27
27
  },
28
28
  "dependencies": {
29
- "@acusti/input-text": "^0.7.0",
29
+ "@acusti/input-text": "^0.8.0",
30
30
  "@acusti/matchmaking": "^0.3.0",
31
31
  "@acusti/styling": "^0.4.0",
32
32
  "@acusti/use-is-out-of-bounds": "^0.4.0"