foundation.ts 44 KB

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