foundation.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. /* argus-disable unPkgSensitiveInfo */
  2. /* eslint-disable max-len */
  3. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  4. import KeyCode from '../utils/keyCode';
  5. import { isNumber, isString, isEqual } from 'lodash-es';
  6. import warning from '../utils/warning';
  7. import isNullOrUndefined from '../utils/isNullOrUndefined';
  8. import { BasicOptionProps } from './optionFoundation';
  9. export interface SelectAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> {
  10. getTriggerWidth(): number;
  11. setOptionsWidth?(): any;
  12. updateFocusState(focus: boolean): void;
  13. focusTrigger(): void;
  14. unregisterClickOutsideHandler(): void;
  15. setOptionWrapperWidth(width: string | number): void;
  16. getOptionsFromChildren(): BasicOptionProps[];
  17. updateOptions(options: BasicOptionProps[]): void;
  18. rePositionDropdown(): void;
  19. updateFocusIndex(index: number): void;
  20. updateSelection(selection: Map<any, any>): void;
  21. openMenu(): void;
  22. notifyDropdownVisibleChange(visible: boolean): void;
  23. registerClickOutsideHandler(event: any): void;
  24. toggleInputShow(show: boolean, cb: () => void): void;
  25. closeMenu(): void;
  26. notifyCreate(option: BasicOptionProps): void;
  27. getMaxLimit(): number;
  28. getSelections(): Map<any, any>;
  29. notifyMaxLimit(arg: BasicOptionProps): void;
  30. notifyClear(): void;
  31. updateInputValue(inputValue: string): void;
  32. focusInput(): void;
  33. notifySearch(inputValue: string): void;
  34. registerKeyDown(handler: () => void): void;
  35. unregisterKeyDown(): void;
  36. notifyChange(value: string | BasicOptionProps | (string | BasicOptionProps)[]): void;
  37. notifySelect(value: BasicOptionProps['value'], option: BasicOptionProps): void;
  38. notifyDeselect(value: BasicOptionProps['value'], option: BasicOptionProps): void;
  39. notifyBlur(event: any): void;
  40. notifyFocus(event: any): void;
  41. notifyListScroll(event: any): void;
  42. notifyMouseLeave(event: any): void;
  43. notifyMouseEnter(event: any): void;
  44. updateHovering(isHover: boolean): void;
  45. }
  46. type PropValue = string | number | Record<string, any>;
  47. export default class SelectFoundation extends BaseFoundation<SelectAdapter> {
  48. constructor(adapter: SelectAdapter) {
  49. super({ ...adapter });
  50. }
  51. // keyboard event listner
  52. // eslint-disable-next-line @typescript-eslint/member-ordering
  53. _keydownHandler: (...arg: any[]) => void | null = null;
  54. init() {
  55. this._setDropdownWidth();
  56. const isDefaultOpen = this.getProp('defaultOpen');
  57. const isOpen = this.getProp('open');
  58. const originalOptions = this._collectOptions();
  59. this._setDefaultSelection(originalOptions);
  60. if (isDefaultOpen || isOpen) {
  61. this.open(undefined, originalOptions);
  62. }
  63. const autoFocus = this.getProp('autoFocus');
  64. if (autoFocus) {
  65. this.focus();
  66. }
  67. }
  68. focus() {
  69. this._focusTrigger();
  70. const isFilterable = this._isFilterable();
  71. this._adapter.updateFocusState(true);
  72. if (isFilterable) {
  73. this.toggle2SearchInput(true);
  74. }
  75. }
  76. _focusTrigger() {
  77. this._adapter.focusTrigger();
  78. // this.bindKeyBoardEvent();
  79. }
  80. destroy() {
  81. this._adapter.unregisterClickOutsideHandler();
  82. this.unBindKeyBoardEvent();
  83. }
  84. _setDropdownWidth() {
  85. const { style, dropdownMatchSelectWidth } = this.getProps();
  86. let width;
  87. if (dropdownMatchSelectWidth) {
  88. if (style && isNumber(style.width)) {
  89. width = style.width;
  90. } else if (style && isString(style.width) && !style.width.includes('%')) {
  91. width = style.width;
  92. } else {
  93. width = this._adapter.getTriggerWidth();
  94. }
  95. this._adapter.setOptionWrapperWidth(width);
  96. }
  97. }
  98. _collectOptions() {
  99. const originalOptions = this._adapter.getOptionsFromChildren();
  100. this._adapter.updateOptions(originalOptions);
  101. // Reposition the drop-down layer
  102. this._adapter.rePositionDropdown();
  103. return originalOptions;
  104. }
  105. _setDefaultSelection(originalOptions: BasicOptionProps[]) {
  106. let { value } = this.getProps();
  107. const { defaultValue } = this.getProps();
  108. if (this._isControlledComponent()) {
  109. // do nothing
  110. } else {
  111. value = defaultValue;
  112. }
  113. this._update(value, originalOptions);
  114. }
  115. // call when props.optionList change
  116. handleOptionListChange() {
  117. const newOptionList = this._collectOptions();
  118. const { selections } = this.getStates();
  119. this.updateOptionsActiveStatus(selections, newOptionList);
  120. // reset focusIndex
  121. const { defaultActiveFirstOption } = this.getProps();
  122. if (defaultActiveFirstOption) {
  123. this._adapter.updateFocusIndex(0);
  124. }
  125. }
  126. // In uncontrolled mode, when props.optionList change,
  127. // but already had defaultValue or choose some option
  128. handleOptionListChangeHadDefaultValue() {
  129. const selections = this.getState('selections');
  130. let value;
  131. const { onChangeWithObject } = this.getProps();
  132. const isMultiple = this._isMultiple();
  133. switch (true) {
  134. case isMultiple && Boolean(selections.size):
  135. try {
  136. value = [...selections].map(item =>
  137. // At this point item1 is directly the object
  138. (onChangeWithObject ? item[1] : item[1].value)
  139. );
  140. } catch (error) {
  141. value = [];
  142. }
  143. break;
  144. case isMultiple && !selections.size:
  145. value = [];
  146. break;
  147. case !isMultiple && Boolean(selections.size):
  148. try {
  149. value = onChangeWithObject ? [...selections][0][1] : [...selections][0][1].value;
  150. } catch (error) {}
  151. break;
  152. case !isMultiple && !selections.size:
  153. break;
  154. default:
  155. break;
  156. }
  157. const originalOptions = this._adapter.getOptionsFromChildren();
  158. this._update(value, originalOptions);
  159. }
  160. // call when props.value change
  161. handleValueChange(value: PropValue) {
  162. const { allowCreate } = this.getProps();
  163. let originalOptions;
  164. // AllowCreate and controlled mode, no need to re-collect optionList
  165. if (allowCreate && this._isControlledComponent()) {
  166. originalOptions = this.getState('options') as BasicOptionProps[];
  167. originalOptions.forEach(item => (item._show = true));
  168. } else {
  169. // originalOptions = this.getState('options');
  170. // The options in state cannot be used directly here, because it is possible to update the optionList and props.value at the same time, and the options in state are still old at this time
  171. originalOptions = this._adapter.getOptionsFromChildren();
  172. }
  173. // Multi-selection, controlled mode, you need to reposition the drop-down menu after updating
  174. this._adapter.rePositionDropdown();
  175. this._update(value, originalOptions);
  176. }
  177. // Update the selected item in the selection box
  178. _update(propValue: PropValue, originalOptions: BasicOptionProps[]) {
  179. let selections;
  180. if (!this._isMultiple()) {
  181. // Radio
  182. selections = this._updateSingle(propValue, originalOptions);
  183. } else {
  184. selections = this._updateMultiple(propValue as (PropValue)[], originalOptions);
  185. }
  186. // Update the text in the selection box
  187. this._adapter.updateSelection(selections);
  188. // Update the selected item in the drop-down box
  189. this.updateOptionsActiveStatus(selections, originalOptions);
  190. }
  191. // Optionally selected updates (when components are mounted, or after value changes)
  192. _updateSingle(propValue: PropValue, originalOptions: BasicOptionProps[]) {
  193. const selections = new Map();
  194. const { onChangeWithObject } = this.getProps();
  195. // When onChangeWithObject is true, the defaultValue or Value passed by the props should be the object, which corresponds to the result returned by onChange, so the value of the object needs to be taken as a judgment comparison
  196. const selectedValue = onChangeWithObject && typeof propValue !== 'undefined' ? (propValue as BasicOptionProps).value : propValue;
  197. const selectedOptions = originalOptions.filter(option => option.value === selectedValue);
  198. const noMatchOptionInList = !selectedOptions.length && typeof selectedValue !== 'undefined';
  199. // If the current value, there is a matching option in the optionList
  200. if (selectedOptions.length) {
  201. const selectedOption = selectedOptions[0];
  202. const optionExist = { ...selectedOption };
  203. // if (onChangeWithObject) {
  204. // OptionExist = {... propValue }; // value is the object with the'value 'Key
  205. // }
  206. selections.set(optionExist.label, optionExist);
  207. } else if (noMatchOptionInList) {
  208. // If the current value does not have a corresponding item in the optionList, construct an option and update it to the selection. However, it does not need to be inserted into the list
  209. let optionNotExist = { value: propValue, label: propValue, _notExist: true };
  210. if (onChangeWithObject) {
  211. optionNotExist = { ...propValue as BasicOptionProps, _notExist: true } as any;
  212. }
  213. selections.set(optionNotExist.label, optionNotExist);
  214. }
  215. return selections;
  216. }
  217. // Multi-selected option update (when the component is mounted, or after the value changes)
  218. _updateMultiple(propValue: PropValue[], originalOptions: BasicOptionProps[]) {
  219. const nowSelections = this.getState('selections');
  220. let selectedOptionList: any[] = [];
  221. // Multiple selection is to determine whether it is an array to avoid the problem of defaultValue/value incoming string error
  222. const propValueIsArray = Array.isArray(propValue);
  223. this.checkMultipleProps();
  224. // If N values are currently selected, the corresponding option data is retrieved from the current selections for retrieval. Because these selected options may not exist in the new optionList
  225. if (nowSelections.size) {
  226. selectedOptionList = [...nowSelections].map(item => item[1]);
  227. }
  228. const selections = new Map();
  229. let selectedValues = propValue;
  230. const { onChangeWithObject } = this.getProps();
  231. // When onChangeWithObject is true
  232. if (onChangeWithObject && propValueIsArray) {
  233. selectedValues = propValue.map((item: BasicOptionProps) => item.value) as any;
  234. }
  235. if (propValueIsArray && selectedValues.length) {
  236. selectedValues.forEach((selectedValue: string, i: number) => {
  237. // The current value exists in the current optionList
  238. const index = originalOptions.findIndex(option => option.value === selectedValue);
  239. if (index !== -1) {
  240. selections.set(originalOptions[index].label, originalOptions[index]);
  241. } else {
  242. // The current value exists in the optionList that has been selected before the change, and does not exist in the current optionList, then directly take the corresponding value from the selections, no need to construct a new option
  243. const indexInSelectedList = selectedOptionList.findIndex(option => option.value === selectedValue);
  244. if (indexInSelectedList !== -1) {
  245. const option = selectedOptionList[indexInSelectedList];
  246. selections.set(option.label, option);
  247. } else {
  248. // The current value does not exist in the current optionList or the list before the change. Construct an option and update it to the selection
  249. let optionNotExist = { value: selectedValue, label: selectedValue, _notExist: true };
  250. onChangeWithObject ? (optionNotExist = { ...propValue[i] as any, _notExist: true }) : null;
  251. selections.set(optionNotExist.label, optionNotExist);
  252. }
  253. }
  254. });
  255. }
  256. return selections;
  257. }
  258. _isMultiple() {
  259. return this.getProp('multiple');
  260. }
  261. _isDisabled() {
  262. return this.getProp('disabled');
  263. }
  264. _isFilterable() {
  265. return Boolean(this.getProp('filter')); // filter can be boolean or function
  266. }
  267. handleClick(e: any) {
  268. const { clickToHide } = this.getProps();
  269. const { isOpen } = this.getStates();
  270. const isDisabled = this._isDisabled();
  271. if (isDisabled) {
  272. return;
  273. } else if (!isOpen) {
  274. this.open();
  275. this._notifyFocus(e);
  276. } else if (isOpen && clickToHide) {
  277. this.close(e);
  278. } else if (isOpen && !clickToHide) {
  279. this.focusInput();
  280. }
  281. }
  282. open(acInput?: string, originalOptions?: BasicOptionProps[]) {
  283. const isFilterable = this._isFilterable();
  284. const options = originalOptions || this.getState('options');
  285. // When searchable, when the drop-down box expands
  286. if (isFilterable) {
  287. // Also clears the options filter to show all candidates
  288. // Options created dynamically but not selected are also filtered out
  289. const sugInput = '';
  290. const newOptions = this._filterOption(options, sugInput).filter(item => !item._inputCreateOnly);
  291. this._adapter.updateOptions(newOptions);
  292. this.toggle2SearchInput(true);
  293. }
  294. this._adapter.openMenu();
  295. this._setDropdownWidth();
  296. this._adapter.notifyDropdownVisibleChange(true);
  297. this.bindKeyBoardEvent();
  298. this._adapter.registerClickOutsideHandler((e: MouseEvent) => {
  299. this.close(e);
  300. });
  301. }
  302. toggle2SearchInput(isShow: boolean) {
  303. if (isShow) {
  304. this._adapter.toggleInputShow(isShow, () => this.focusInput());
  305. } else {
  306. this._adapter.toggleInputShow(isShow, () => undefined);
  307. }
  308. }
  309. close(e?: any) {
  310. const isFilterable = this._isFilterable();
  311. if (isFilterable) {
  312. this.unBindKeyBoardEvent();
  313. this.clearInput();
  314. this.toggle2SearchInput(false);
  315. }
  316. this._adapter.closeMenu();
  317. this._adapter.notifyDropdownVisibleChange(false);
  318. this.unBindKeyBoardEvent();
  319. this._notifyBlur(e);
  320. this._adapter.unregisterClickOutsideHandler();
  321. this._adapter.updateFocusState(false);
  322. }
  323. onSelect(option: BasicOptionProps, optionIndex: number, event: MouseEvent | KeyboardEvent) {
  324. const isDisabled = this._isDisabled();
  325. if (isDisabled) {
  326. return;
  327. }
  328. // If the allowCreate dynamically created option is selected, onCreate needs to be triggered
  329. if (option._inputCreateOnly) {
  330. this._adapter.notifyCreate(option);
  331. }
  332. const isMultiple = this._isMultiple();
  333. if (!isMultiple) {
  334. this._handleSingleSelect(option, event);
  335. } else {
  336. this._handleMultipleSelect(option, event);
  337. }
  338. this._adapter.updateFocusIndex(optionIndex);
  339. }
  340. _handleSingleSelect({ value, label, ...rest }: BasicOptionProps, event: any) {
  341. const selections = new Map().set(label, { value, label, ...rest });
  342. // First trigger onSelect, then trigger onChange
  343. this._notifySelect(value, { value, label, ...rest });
  344. // If it is a controlled component, directly notify
  345. if (this._isControlledComponent()) {
  346. this._notifyChange(selections);
  347. this.close(event);
  348. } else {
  349. this._adapter.updateSelection(selections);
  350. // notify user
  351. this._notifyChange(selections);
  352. // Update the selected item in the drop-down box
  353. this.close(event);
  354. this.updateOptionsActiveStatus(selections);
  355. }
  356. }
  357. _handleMultipleSelect({ value, label, ...rest }: BasicOptionProps, event: MouseEvent | KeyboardEvent) {
  358. const maxLimit = this._adapter.getMaxLimit();
  359. const selections = this._adapter.getSelections();
  360. if (selections.has(label)) {
  361. this._notifyDeselect(value, { value, label, ...rest });
  362. selections.delete(label);
  363. } else if (maxLimit && selections.size === maxLimit) {
  364. this._adapter.notifyMaxLimit({ value, label, ...rest });
  365. return;
  366. } else {
  367. this._notifySelect(value, { value, label, ...rest });
  368. selections.set(label, { value, label, ...rest });
  369. }
  370. if (this._isControlledComponent()) {
  371. // Controlled components, directly notified
  372. this._notifyChange(selections);
  373. if (this._isFilterable()) {
  374. this.clearInput();
  375. this.focusInput();
  376. }
  377. } else {
  378. // Uncontrolled components, update ui
  379. this._adapter.updateSelection(selections);
  380. // In multi-select mode, the drop-down pop-up layer is repositioned every time the value is changed, because the height selection of the selection box may have changed
  381. this._adapter.rePositionDropdown();
  382. let { options } = this.getStates();
  383. // Searchable filtering, when selected, resets Input
  384. if (this._isFilterable()) {
  385. this.clearInput();
  386. this.focusInput();
  387. // At the same time, the filtering of options is also cleared, in order to show all candidates
  388. const sugInput = '';
  389. options = this._filterOption(options, sugInput);
  390. }
  391. this.updateOptionsActiveStatus(selections, options);
  392. this._notifyChange(selections);
  393. }
  394. }
  395. clearSelected() {
  396. const selections = new Map();
  397. if (this._isControlledComponent()) {
  398. this._notifyChange(selections);
  399. this._adapter.notifyClear();
  400. } else {
  401. this._adapter.updateSelection(selections);
  402. this.updateOptionsActiveStatus(selections);
  403. this._notifyChange(selections);
  404. this._adapter.notifyClear();
  405. }
  406. // when call manually by ref method
  407. const { isOpen } = this.getStates();
  408. if (isOpen) {
  409. this._adapter.rePositionDropdown();
  410. }
  411. }
  412. // Update the selected item in the drop-down box
  413. updateOptionsActiveStatus(selections: Map<any, any>, options: BasicOptionProps[] = this.getState('options')) {
  414. const { allowCreate } = this.getProps();
  415. const newOptions = options.map(option => {
  416. if (selections.has(option.label)) {
  417. option._selected = true;
  418. if (allowCreate) {
  419. delete option._inputCreateOnly;
  420. }
  421. } else {
  422. if (option._inputCreateOnly) {
  423. option._show = false;
  424. }
  425. option._selected = false;
  426. }
  427. return option;
  428. });
  429. this._adapter.updateOptions(newOptions);
  430. }
  431. removeTag(item: BasicOptionProps) {
  432. const selections = this._adapter.getSelections();
  433. selections.delete(item.label);
  434. if (this._isControlledComponent()) {
  435. this._notifyDeselect(item.value, item);
  436. this._notifyChange(selections);
  437. } else {
  438. this._notifyDeselect(item.value, item);
  439. this._adapter.updateSelection(selections);
  440. this.updateOptionsActiveStatus(selections);
  441. // Repostion drop-down layer, because the selection may have changed the number of rows, resulting in a height change
  442. this._adapter.rePositionDropdown();
  443. this._notifyChange(selections);
  444. }
  445. }
  446. clearInput() {
  447. this._adapter.updateInputValue('');
  448. }
  449. focusInput() {
  450. this._adapter.focusInput();
  451. this._adapter.updateFocusState(true);
  452. }
  453. handleInputChange(sugInput: string) {
  454. // Input is a controlled component, so the value needs to be updated
  455. this._adapter.updateInputValue(sugInput);
  456. const { options, isOpen } = this.getStates();
  457. const { allowCreate, remote } = this.getProps();
  458. let optionsAfterFilter = options;
  459. if (!remote) {
  460. // Filter options based on input
  461. optionsAfterFilter = this._filterOption(options, sugInput);
  462. }
  463. // When allowClear is true, an entry can be created. You need to include the current input as a new Option input
  464. optionsAfterFilter = this._createOptionByInput(allowCreate, optionsAfterFilter, sugInput);
  465. this._adapter.updateOptions(optionsAfterFilter);
  466. this._adapter.notifySearch(sugInput);
  467. // In multi-select mode, the drop-down box is repositioned each time you enter, because it may cause a line break as the input changes
  468. if (this._isMultiple()) {
  469. this._adapter.rePositionDropdown();
  470. }
  471. }
  472. _filterOption(originalOptions: BasicOptionProps[], sugInput: string) {
  473. const filter = this.getProp('filter');
  474. if (!filter) {
  475. // 1. No filtering
  476. return originalOptions;
  477. } else if (typeof filter === 'boolean' && filter) {
  478. // 2. When true, the default filter is used
  479. const input = sugInput.toLowerCase();
  480. return originalOptions.map(option => {
  481. const label = option.label.toString().toLowerCase();
  482. const groupLabel = option._parentGroup && option._parentGroup.label;
  483. const matchOption = label.includes(input);
  484. const matchGroup = isString(groupLabel) && groupLabel.toLowerCase().includes(input);
  485. if (matchOption || matchGroup) {
  486. option._show = true;
  487. } else {
  488. option._show = false;
  489. }
  490. return option;
  491. });
  492. } else if (typeof filter === 'function') {
  493. // 3. When passing in a custom function, use a custom function for filtering
  494. return originalOptions.map(option => {
  495. filter(sugInput, option) ? (option._show = true) : (option._show = false);
  496. return option;
  497. });
  498. }
  499. return undefined;
  500. }
  501. _createOptionByInput(allowCreate: boolean, optionsAfterFilter: BasicOptionProps[], sugInput: string) {
  502. if (allowCreate) {
  503. if (sugInput) {
  504. // optionsAfterFilter clone ??? needClone ?
  505. const newOptionByInput = {
  506. _show: true,
  507. _selected: false,
  508. value: sugInput,
  509. label: sugInput,
  510. // True indicates that the option was dynamically created during user filtering
  511. _inputCreateOnly: true,
  512. };
  513. let createOptionIndex = -1;
  514. let matchOptionIndex = -1;
  515. optionsAfterFilter.forEach((option, index) => {
  516. if (!option._show && !option._inputCreateOnly) {
  517. return;
  518. }
  519. // The matching algorithm is not necessarily through labels?
  520. if (option.label === sugInput) {
  521. matchOptionIndex = index;
  522. }
  523. if (option._inputCreateOnly) {
  524. createOptionIndex = index;
  525. option.value = sugInput;
  526. option.label = sugInput;
  527. option._show = true;
  528. }
  529. });
  530. if (createOptionIndex === -1 && matchOptionIndex === -1) {
  531. optionsAfterFilter.push(newOptionByInput);
  532. }
  533. if (matchOptionIndex !== -1) {
  534. optionsAfterFilter = optionsAfterFilter.filter(item => !item._inputCreateOnly);
  535. }
  536. } else {
  537. // Delete input unselected items
  538. optionsAfterFilter = optionsAfterFilter.filter(item => !item._inputCreateOnly);
  539. }
  540. }
  541. // TODO Promise supports asynchronous creation
  542. return optionsAfterFilter;
  543. }
  544. bindKeyBoardEvent() {
  545. this._keydownHandler = event => {
  546. this._handleKeyDown(event);
  547. };
  548. this._adapter.registerKeyDown(this._keydownHandler);
  549. }
  550. unBindKeyBoardEvent() {
  551. if (this._keydownHandler) {
  552. this._adapter.unregisterKeyDown();
  553. }
  554. }
  555. _handleKeyDown(event: KeyboardEvent) {
  556. const key = event.keyCode;
  557. const { isOpen } = this.getStates();
  558. const { loading } = this.getProps();
  559. if (!isOpen || loading) {
  560. return;
  561. }
  562. switch (key) {
  563. case KeyCode.UP:
  564. // Prevent Input's cursor from following
  565. // Prevent Input cursor from following
  566. event.preventDefault();
  567. this._handleArrowKeyDown(-1);
  568. break;
  569. case KeyCode.DOWN:
  570. // Prevent Input's cursor from following
  571. // Prevent Input cursor from following
  572. event.preventDefault();
  573. this._handleArrowKeyDown(1);
  574. break;
  575. case KeyCode.BACKSPACE:
  576. this._handleBackspaceKeyDown();
  577. break;
  578. case KeyCode.ENTER:
  579. // internal-issues:302
  580. // prevent trigger form’s submit when use in form
  581. event.preventDefault();
  582. event.stopPropagation();
  583. this._handleEnterKeyDown(event);
  584. break;
  585. case KeyCode.ESC:
  586. this.close(event);
  587. break;
  588. default:
  589. break;
  590. }
  591. }
  592. _getEnableFocusIndex(offset: number) {
  593. const { focusIndex, options } = this.getStates();
  594. const visibleOptions = options.filter((item: BasicOptionProps) => item._show);
  595. // let visibleOptions = options;
  596. const optionsLength = visibleOptions.length;
  597. let index = focusIndex + offset;
  598. if (index < 0) {
  599. index = optionsLength - 1;
  600. }
  601. if (index >= optionsLength) {
  602. index = 0;
  603. }
  604. // avoid newIndex option is disabled
  605. if (offset > 0) {
  606. let nearestActiveOption = -1;
  607. for (let i = 0; i < visibleOptions.length; i++) {
  608. const optionIsActive = !visibleOptions[i].disabled;
  609. if (optionIsActive) {
  610. nearestActiveOption = i;
  611. }
  612. if (nearestActiveOption >= index) {
  613. break;
  614. }
  615. }
  616. index = nearestActiveOption;
  617. } else {
  618. let nearestActiveOption = visibleOptions.length;
  619. for (let i = optionsLength - 1; i >= 0; i--) {
  620. const optionIsActive = !visibleOptions[i].disabled;
  621. if (optionIsActive) {
  622. nearestActiveOption = i;
  623. }
  624. if (nearestActiveOption <= index) {
  625. break;
  626. }
  627. }
  628. index = nearestActiveOption;
  629. }
  630. // console.log('new:' + index);
  631. this._adapter.updateFocusIndex(index);
  632. // TODO requires scrollIntoView
  633. }
  634. _handleArrowKeyDown(offset: number) {
  635. this._getEnableFocusIndex(offset);
  636. }
  637. _handleEnterKeyDown(event: KeyboardEvent) {
  638. const { isOpen, options, focusIndex } = this.getStates();
  639. if (focusIndex !== -1) {
  640. const visibleOptions = options.filter((item: BasicOptionProps) => item._show);
  641. const { length } = visibleOptions;
  642. // fix issue 1201
  643. if (length <= focusIndex) {
  644. return;
  645. }
  646. if (visibleOptions && length) {
  647. const selectedOption = visibleOptions[focusIndex];
  648. if (selectedOption.disabled) {
  649. return;
  650. }
  651. this.onSelect(selectedOption, focusIndex, event);
  652. }
  653. } else if (isOpen) {
  654. }
  655. }
  656. _handleBackspaceKeyDown() {
  657. if (this._isMultiple()) {
  658. const selections = this._adapter.getSelections();
  659. const { inputValue } = this.getStates();
  660. const length = selections.size;
  661. if (length && !inputValue) {
  662. const keys = [...selections.keys()];
  663. let index = length - 1;
  664. let targetLabel = keys[index];
  665. let targetItem = selections.get(targetLabel);
  666. let isAllDisabled = false;
  667. // can skip disabled item when remove trigger by backspace
  668. if (targetItem.disabled && index === 0) {
  669. return;
  670. }
  671. while (targetItem.disabled && index !== 0) {
  672. index = index - 1;
  673. targetLabel = keys[index];
  674. targetItem = selections.get(targetLabel);
  675. // eslint-disable-next-line
  676. if (index == 0 && targetItem.disabled) {
  677. isAllDisabled = true;
  678. }
  679. }
  680. if (!isAllDisabled) {
  681. this.removeTag(targetItem);
  682. }
  683. }
  684. }
  685. }
  686. _notifyChange(selections: Map<any, any>) {
  687. const { onChangeWithObject } = this.getProps();
  688. const stateSelections = this.getState('selections');
  689. let notifyVal;
  690. const selectionsProps = [...selections.values()];
  691. const isMultiple = this._isMultiple();
  692. const hasChange = this._diffSelections(selections, stateSelections, isMultiple);
  693. if (!hasChange) {
  694. return;
  695. }
  696. switch (true) {
  697. case onChangeWithObject:
  698. this._notifyChangeWithObject(selections);
  699. break;
  700. case !onChangeWithObject && !isMultiple:
  701. notifyVal = selectionsProps.length ? selectionsProps[0].value : undefined;
  702. this._adapter.notifyChange(notifyVal);
  703. break;
  704. case !onChangeWithObject && isMultiple:
  705. notifyVal = selectionsProps.length ? selectionsProps.map(props => props.value) : [];
  706. this._adapter.notifyChange(notifyVal);
  707. break;
  708. default:
  709. break;
  710. }
  711. }
  712. _removeInternalKey(option: BasicOptionProps) {
  713. delete option._parentGroup;
  714. delete option._show;
  715. delete option._selected;
  716. if ('_keyInOptionList' in option) {
  717. option.key = option._keyInOptionList;
  718. delete option._keyInOptionList;
  719. }
  720. return option;
  721. }
  722. _notifySelect(value: BasicOptionProps['value'], option: BasicOptionProps) {
  723. const newOption = this._removeInternalKey(option);
  724. this._adapter.notifySelect(value, newOption);
  725. }
  726. _notifyDeselect(value: BasicOptionProps['value'], option: BasicOptionProps) {
  727. const newOption = this._removeInternalKey(option);
  728. this._adapter.notifyDeselect(value, newOption);
  729. }
  730. _diffSelections(selections: Map<any, any>, oldSelections: Map<any, any>, isMultiple: boolean) {
  731. let diff = true;
  732. if (!isMultiple) {
  733. const selectionProps = [...selections.values()];
  734. const oldSelectionProps = [...oldSelections.values()];
  735. const optionLabel = selectionProps[0] ? selectionProps[0].label : selectionProps[0];
  736. const oldOptionLabel = oldSelectionProps[0] ? oldSelectionProps[0].label : oldSelectionProps[0];
  737. diff = !isEqual(optionLabel, oldOptionLabel);
  738. } else {
  739. // When multiple selection, there is no scene where the value is different between the two operations
  740. }
  741. return diff;
  742. }
  743. // When onChangeWithObject is true, the onChange input parameter is not only value, but also label and other parameters
  744. _notifyChangeWithObject(selections: Map<any, any>) {
  745. const stateSelections = this.getState('selections');
  746. const values = [];
  747. for (const item of selections.entries()) {
  748. let val = { label: item[0], ...item[1] };
  749. val = this._removeInternalKey(val);
  750. values.push(val);
  751. }
  752. if (!this._isMultiple()) {
  753. this._adapter.notifyChange(values[0]);
  754. } else {
  755. this._adapter.notifyChange(values);
  756. }
  757. }
  758. // Scenes that may trigger blur:
  759. // 1、clickOutSide
  760. // 2、click option / press enter, and then select complete(when multiple is false
  761. // 3、press esc when dropdown list open
  762. _notifyBlur(e: FocusEvent) {
  763. this._adapter.notifyBlur(e);
  764. }
  765. // Scenes that may trigger focus:
  766. // 1、click selection
  767. _notifyFocus(e: FocusEvent) {
  768. this._adapter.notifyFocus(e);
  769. }
  770. handleMouseEnter(e: MouseEvent) {
  771. this._adapter.updateHovering(true);
  772. this._adapter.notifyMouseEnter(e);
  773. }
  774. handleMouseLeave(e: MouseEvent) {
  775. this._adapter.updateHovering(false);
  776. this._adapter.notifyMouseLeave(e);
  777. }
  778. handleClearClick(e: MouseEvent) {
  779. this.clearInput();
  780. // TODO
  781. this.clearSelected();
  782. // prevent this click open dropdown
  783. e.stopPropagation();
  784. }
  785. handleOptionMouseEnter(optionIndex: number) {
  786. this._adapter.updateFocusIndex(optionIndex);
  787. }
  788. handleListScroll(e: any) {
  789. this._adapter.notifyListScroll(e);
  790. }
  791. // handleTriggerFocus(e) {
  792. // console.log('handleTriggerFocus');
  793. // this._adapter.updateFocusState(true);
  794. // }
  795. handleTriggerBlur(e: FocusEvent) {
  796. this._adapter.updateFocusState(false);
  797. const { filter, autoFocus } = this.getProps();
  798. const { isOpen, isFocus } = this.getStates();
  799. // Under normal circumstances, blur will be accompanied by dropdown close, so the notify of blur can be called uniformly in close
  800. // But when autoFocus, because dropdown is not expanded, you need to listen for the trigger's blur and trigger the notify callback
  801. if (autoFocus && isFocus && !isOpen) {
  802. // blur when autoFocus & not open dropdown yet
  803. this._notifyBlur(e);
  804. }
  805. }
  806. selectAll() {
  807. const { options } = this.getStates();
  808. const { onChangeWithObject } = this.getProps();
  809. let selectedValues = [];
  810. const isMultiple = this._isMultiple();
  811. if (!isMultiple) {
  812. console.warn(`[Semi Select]: It seems that you have called the selectAll method in the single-selection Select.
  813. Please note that this is not a legal way to use it`
  814. );
  815. return;
  816. }
  817. if (onChangeWithObject) {
  818. selectedValues = options;
  819. } else {
  820. selectedValues = options.map((option: BasicOptionProps) => option.value);
  821. }
  822. this.handleValueChange(selectedValues);
  823. this._adapter.notifyChange(selectedValues);
  824. }
  825. /**
  826. * Check whether the props
  827. * -defaultValue/value in multiple selection mode is array
  828. * @param {Object} props
  829. */
  830. checkMultipleProps(props?: Record<string, any>) {
  831. if (this._isMultiple()) {
  832. const currentProps = props ? props : this.getProps();
  833. const { defaultValue, value } = currentProps;
  834. const selectedValues = value || defaultValue;
  835. if (!isNullOrUndefined(selectedValues) && !Array.isArray(selectedValues)) {
  836. warning(true, '[Semi Select] defaultValue/value should be array type in multiple mode');
  837. }
  838. }
  839. }
  840. }