foundation.ts 44 KB

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