foundation.ts 37 KB

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