Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 27x 27x | import { useCallback, useEffect, useMemo, useState } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import get from 'lodash/get';
import { EndOfList, IconButton, Popper } from '@folio/stripes/components';
import SearchField from '../SearchField';
import css from '../../../styles/TypeDown.css';
import { useTypedown } from '../hooks/typedownHooks';
import selectorSafe from '../utils/selectorSafe';
const Typedown = ({
// This offers the ability to pass additional information into the header, footer and listItem renders.
additionalInfo = {},
className,
dataOptions,
displayClearItem = true,
displayValueWhileOpen = true,
dropdownPlacement = 'bottom-start',
endOfList,
getDisplayValue, // Can overrule displayValue entirely
id,
initialOpenDelay = 800, // Initial opening delay of 800ms (handles any stripes animations)
input,
isSelected,
filterPath,
label,
meta,
onChange,
onType,
// DEPRECATED. This prop exists to force the renderHeader, renderFooter and renderListItem
// to render with option props instead of array params. In a future breaking change that
// should be made the NORM and this prop removed.
renderWithOptions = false,
renderFooter = null,
renderHeader = null,
renderListItem = null,
renderTrigger = null,
required,
selectedStyles, // A way to pass any styles that need to be applied globally on selection
uniqueIdentificationPath = 'id'
}) => {
const selectedUniqueId = get(input.value, uniqueIdentificationPath);
const [selectedValue, setSelectedValue] = useState(input.value); // Track what's been selected in state as well
// Display data needs to be in line with data options but also able to react to default handleType
const [displayData, setDisplayData] = useState(dataOptions);
// keep track of what we've typed and whether we've typed an exact match or not
const [currentlyTyped, setCurrentlyTyped] = useState('');
const [exactMatch, setExactMatch] = useState(false);
useEffect(() => {
setDisplayData(dataOptions);
}, [dataOptions]);
// Setup default handleType
const handleType = useCallback((e) => {
const regex = new RegExp(`${e.target.value.toLowerCase()}`);
if (onType) {
onType(e);
} else if (filterPath && e?.target?.value) {
setDisplayData(dataOptions.filter(item => get(item, filterPath)?.toLowerCase()?.match(regex)));
} else if (e?.target?.value) {
setDisplayData(dataOptions.filter(item => get(item, uniqueIdentificationPath)?.toLowerCase()?.match(regex)));
} else {
setDisplayData(dataOptions);
}
setCurrentlyTyped(e.target.value);
if (displayData.length === 1 && get(displayData[0], filterPath) === e.target.value) {
setExactMatch(true);
} else {
setExactMatch(false);
}
}, [dataOptions, displayData, filterPath, onType, uniqueIdentificationPath]);
// Hook to set up all the essentials
const {
refs: {
listRef,
triggerRef,
triggerComponentRef,
overlayRef,
footerRef,
headerRef
},
handlers: {
handleNextFocus,
},
variables: {
open,
portal,
resizeRef,
searchWidth
}
} = useTypedown(
input.name,
{
dataOptions,
timeout: initialOpenDelay
}
);
const renderItem = useCallback((option, optionIsSelected = false) => (
<div
className={css.listItem}
>
{renderListItem ?
(
renderWithOptions ?
renderListItem({
additionalInfo,
option,
currentlyTyped,
exactMatch,
optionIsSelected,
selectedValue
}) :
// DEPRECATED see above
renderListItem(option, currentlyTyped, exactMatch, optionIsSelected, selectedValue, additionalInfo)
) :
get(option, uniqueIdentificationPath)
}
</div>
), [
additionalInfo,
currentlyTyped,
exactMatch,
renderListItem,
renderWithOptions,
selectedValue,
uniqueIdentificationPath
]);
const handleChange = useCallback(value => {
input.onChange(value);
setSelectedValue(value);
if (typeof onChange === 'function') {
onChange(value);
}
}, [input, onChange]);
const renderTypedownTrigger = () => {
const triggerComponentId = `typedown-trigger-${selectorSafe(input.name)}`;
return (
<div
ref={triggerRef}
id={`typedown-parent-${selectorSafe(input.name)}-trigger`}
>
{renderTrigger ?
renderTrigger({ // Pass all props in that searchfield uses.
handleType,
input, // Pass input? Useful when not controlled I guess
meta,
open,
selectedValue,
triggerComponentId,
triggerComponentRef,
})
:
<SearchField
ref={triggerComponentRef}
// Pass meta through so correct styling gets applied to the TextField
id={triggerComponentId}
label={label}
marginBottom0
meta={meta}
onChange={handleType}
required={required}
/>
}
</div>
);
};
const dropDown = useCallback(() => {
return (
<div
className={css.dropdownMenu}
id={`typedown-parent-${selectorSafe(input.name)}-menu`}
style={{ '--searchWidth': `${searchWidth}px` }}
>
{renderHeader &&
<div
ref={headerRef}
className={css.header}
id={`typedown-header-${selectorSafe(input.name)}`}
>
{/* Adopt a more extensible pattern for renderHeader, renderFooter will eventually follow */}
{renderHeader({
additionalInfo,
currentlyTyped,
displayData,
handleType,
exactMatch
})}
</div>
}
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
<div
ref={listRef}
className={css.listContainer}
id="typedown-list"
/* This is an acceptable exception to the no-static-element-interactions
* as we are only PREVENTING interactions, namely focus change on scrollbar click
* Without this, the typedown closes instantly when the scrollbar is clicked or dragged.
* This does NOT prevent item click, as e.propagation is not prevented.
*/
onMouseDown={(e) => e.preventDefault()}
>
{displayData?.length ? displayData?.map((d, _index) => {
const isSelectedEval = isSelected ? isSelected(input.value, d) : get(input.value, uniqueIdentificationPath) === get(d, uniqueIdentificationPath);
const selectedCSS = selectedStyles ?? css.selectedMenuButton;
const uniqueButtonKey = `typedown-button-[${get(d, uniqueIdentificationPath)}]`;
return (
<button
key={uniqueButtonKey}
className={classnames(
css.fullWidth,
css.menuButton,
{ [`${selectedCSS}`]: isSelectedEval },
)}
data-selected={isSelectedEval}
id={uniqueButtonKey}
onClick={() => {
handleChange(d);
handleNextFocus();
}}
type="button"
>
{renderItem(d, isSelectedEval)}
</button>
);
}) :
endOfList || <EndOfList />
}
</div>
{renderFooter &&
<div
ref={footerRef}
className={css.footer}
id={`typedown-footer-${selectorSafe(input.name)}`}
>
{
renderWithOptions ?
renderFooter({
additionalInfo,
displayData,
currentlyTyped,
exactMatch
}) :
// DEPRECATED, see above
renderFooter(displayData, currentlyTyped, exactMatch, additionalInfo)
}
</div>
}
</div>
);
}, [
additionalInfo,
currentlyTyped,
displayData,
endOfList,
exactMatch,
footerRef,
handleChange,
handleNextFocus,
handleType,
headerRef,
input.name,
input.value,
isSelected,
listRef,
renderFooter,
renderHeader,
renderItem,
renderWithOptions,
searchWidth,
selectedStyles,
uniqueIdentificationPath
]);
const renderSelectedItem = useCallback(() => (
<div
className={classnames(
css.selectedDisplay
)}
>
<div
className={css.selectedItem}
>
{renderItem(input.value)}
</div>
{displayClearItem &&
<IconButton
className={css.clearItem}
icon="times-circle-solid"
onClick={() => handleChange()}
/>
}
</div>
), [displayClearItem, handleChange, input.value, renderItem]);
const displayValue = useMemo(() => {
// Allow full control over whether to display the value
if (getDisplayValue) {
return getDisplayValue({
selectedUniqueId,
open
});
}
return !!selectedUniqueId && (!open || displayValueWhileOpen);
}, [displayValueWhileOpen, getDisplayValue, open, selectedUniqueId]);
return (
<div
ref={resizeRef}
className={classnames(
css.typedown,
className
)}
id={`typedown-id-${id}`}
>
{renderTypedownTrigger()}
<Popper
key="typedown-menu-toggle"
anchorRef={triggerRef}
className={classnames(
css.dropdown,
css.fullWidth
)}
isOpen={open}
modifiers={{
flip: { boundariesElement: 'viewport', padding: 10 },
preventOverflow: { boundariesElement: 'viewport', padding: 10 }
}}
overlayProps={{
'ref': overlayRef,
'tabIndex': '-1',
'onClick': (e) => { e.stopPropagation(); } // prevent propagation of click events
}}
overlayRef={overlayRef}
placement={dropdownPlacement}
portal={portal}
>
{dropDown()}
</Popper>
{displayValue && renderSelectedItem()}
</div>
);
};
Typedown.propTypes = {
additionalInfo: PropTypes.object, // In TS this will need to be a generic passed in on the type I guess :/
className: PropTypes.string,
dataOptions: PropTypes.arrayOf(PropTypes.object), // In TS this again will need to be a generic type on the Typedown
displayClearItem: PropTypes.bool,
displayValueWhileOpen: PropTypes.bool,
dropdownPlacement: PropTypes.string,
endOfList: PropTypes.oneOfType([
PropTypes.func,
PropTypes.node,
PropTypes.element
]),
filterPath: PropTypes.string,
getDisplayValue: PropTypes.func,
id: PropTypes.string,
initialOpenDelay: PropTypes.number,
input: PropTypes.object,
isSelected: PropTypes.func,
label: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element
]),
meta: PropTypes.object,
onChange: PropTypes.func,
onType: PropTypes.func,
renderHeader: PropTypes.func,
renderFooter: PropTypes.func,
renderListItem: PropTypes.func,
renderTrigger: PropTypes.func,
renderWithOptions: PropTypes.bool,
required: PropTypes.bool,
selectedStyles: PropTypes.string,
uniqueIdentificationPath: PropTypes.string
};
export default Typedown;
|