foundation.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. import { isString, isNumber, isUndefined, isObject } from 'lodash';
  3. import warning from '../utils/warning';
  4. import KeyCode from '../utils/keyCode';
  5. interface KeyboardAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> {
  6. registerKeyDown: (callback: (event: any) => void) => void;
  7. unregisterKeyDown: (callback: (event: any) => void) => void;
  8. updateFocusIndex: (focusIndex: number) => void;
  9. notifyKeyDown: (e: any) => void
  10. }
  11. export interface DataItem {
  12. [x: string]: any;
  13. value?: string | number;
  14. label?: any // reactNode
  15. }
  16. export interface StateOptionItem extends DataItem {
  17. show?: boolean;
  18. key?: string | number
  19. }
  20. export type AutoCompleteData = Array<DataItem | string>;
  21. export interface AutoCompleteAdapter<P = Record<string, any>, S = Record<string, any>> extends KeyboardAdapter<P, S> {
  22. getTriggerWidth: () => number | undefined;
  23. setOptionWrapperWidth: (width: number) => void;
  24. updateInputValue: (inputValue: string | number) => void;
  25. toggleListVisible: (isShow: boolean) => void;
  26. updateOptionList: (optionList: Array<StateOptionItem>) => void;
  27. updateScrollTop: (index: number) => void;
  28. updateSelection: (selection: Map<any, any>) => void;
  29. notifySearch: (inputValue: string) => void;
  30. notifyChange: (value: string | number) => void;
  31. notifySelect: (option: StateOptionItem | string | number) => void;
  32. notifyDropdownVisibleChange: (isVisible: boolean) => void;
  33. notifyClear: () => void;
  34. notifyFocus: (event?: any) => void;
  35. notifyBlur: (event?: any) => void;
  36. rePositionDropdown: () => void;
  37. persistEvent: (event: any) => void;
  38. registerClickOutsideHandler: (cb: (e: any) => void) => void;
  39. unregisterClickOutsideHandler: () => void
  40. }
  41. class AutoCompleteFoundation<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<AutoCompleteAdapter<P, S>, P, S> {
  42. private _keydownHandler: (args: any) => void | null;
  43. constructor(adapter: AutoCompleteAdapter<P, S>) {
  44. super({ ...adapter });
  45. }
  46. isPanelOpen = false;
  47. init(): void {
  48. this._setDropdownWidth();
  49. const { defaultOpen, data, defaultValue, value } = this.getProps();
  50. if (data && data.length) {
  51. const initOptions = this._generateList(data);
  52. this._adapter.updateOptionList(initOptions);
  53. }
  54. if (defaultOpen) {
  55. this.openDropdown();
  56. }
  57. // When both defaultValue and value exist, finally the value of value will be taken as initValue
  58. let initValue: string;
  59. if (typeof defaultValue !== 'undefined') {
  60. initValue = defaultValue;
  61. }
  62. if (typeof value !== 'undefined') {
  63. initValue = value;
  64. }
  65. if (typeof initValue !== 'undefined') {
  66. this.handleValueChange(initValue);
  67. }
  68. }
  69. destroy(): void {
  70. this._adapter.unregisterClickOutsideHandler();
  71. // this.unBindKeyBoardEvent();
  72. }
  73. _setDropdownWidth(): void {
  74. const { style, dropdownMatchSelectWidth } = this.getProps();
  75. let width;
  76. if (dropdownMatchSelectWidth) {
  77. if (style && isNumber(style.width)) {
  78. width = style.width;
  79. } else if (style && isString(style.width) && !style.width.includes('%')) {
  80. width = style.width;
  81. } else {
  82. width = this._adapter.getTriggerWidth();
  83. }
  84. this._adapter.setOptionWrapperWidth(width);
  85. }
  86. }
  87. handleInputClick(e?: MouseEvent): void {
  88. const { options } = this.getStates();
  89. const { disabled } = this.getProps();
  90. if (!disabled) {
  91. if (this.isPanelOpen) {
  92. this.closeDropdown();
  93. } else {
  94. this.openDropdown();
  95. }
  96. }
  97. }
  98. openDropdown(): void {
  99. this.isPanelOpen = true;
  100. this._adapter.toggleListVisible(true);
  101. this._setDropdownWidth();
  102. this._adapter.registerClickOutsideHandler(e => this.closeDropdown(e));
  103. this._adapter.notifyDropdownVisibleChange(true);
  104. this._modifyFocusIndexOnPanelOpen();
  105. }
  106. closeDropdown(e?: any): void {
  107. this.isPanelOpen = false;
  108. this._adapter.toggleListVisible(false);
  109. this._adapter.unregisterClickOutsideHandler();
  110. this._adapter.notifyDropdownVisibleChange(false);
  111. // After closing the panel, you can still open the panel by pressing the enter key
  112. // this.unBindKeyBoardEvent();
  113. }
  114. // props.data => optionList
  115. _generateList(data: AutoCompleteData): Array<StateOptionItem> {
  116. const { renderItem } = this.getProps();
  117. const options: Array<StateOptionItem> = [];
  118. if (data && data.length) {
  119. data.forEach((item, i) => {
  120. const key = String(new Date().getTime()) + i;
  121. let option: StateOptionItem = {};
  122. if (isString(item) || isNumber(item)) {
  123. option = { value: item as string, key, label: item, show: true };
  124. } else if (isObject(item) && !isUndefined(item.value)) {
  125. option = { show: true, ...item };
  126. }
  127. if (renderItem && typeof renderItem === 'function') {
  128. option.label = renderItem(item);
  129. }
  130. options.push(option);
  131. });
  132. }
  133. return options;
  134. }
  135. handleSearch(inputValue: string): void {
  136. this._adapter.updateInputValue(inputValue);
  137. this._adapter.notifySearch(inputValue);
  138. this._adapter.notifyChange(inputValue);
  139. this._modifyFocusIndex(inputValue);
  140. if (!this.isPanelOpen) {
  141. this.openDropdown();
  142. }
  143. }
  144. handleSelect(option: StateOptionItem, optionIndex?: number): void {
  145. const { renderSelectedItem } = this.getProps();
  146. let newInputValue: string | number = '';
  147. if (renderSelectedItem && typeof renderSelectedItem === 'function') {
  148. newInputValue = renderSelectedItem(option);
  149. warning(
  150. typeof newInputValue !== 'string',
  151. 'Warning: [Semi AutoComplete] renderSelectedItem must return string, please check your function return'
  152. );
  153. } else {
  154. newInputValue = option.value;
  155. }
  156. // 1. trigger onSelect
  157. // 2. close Dropdown
  158. if (this._isControlledComponent()) {
  159. this.closeDropdown();
  160. this.notifySelect(option);
  161. } else {
  162. // 1. update Input
  163. // 2. update Selection
  164. // 3. trigger onSelect
  165. // 4. close Dropdown
  166. this._adapter.updateInputValue(newInputValue);
  167. this.updateSelection(option);
  168. this.notifySelect(option);
  169. this.closeDropdown();
  170. }
  171. this._adapter.notifyChange(newInputValue);
  172. this._adapter.updateFocusIndex(optionIndex);
  173. }
  174. updateSelection(option: StateOptionItem) {
  175. const selection = new Map();
  176. if (option) {
  177. selection.set(option.label, option);
  178. }
  179. this._adapter.updateSelection(selection);
  180. }
  181. notifySelect(option: StateOptionItem) {
  182. if (this._backwardLabelInValue()) {
  183. this._adapter.notifySelect(option);
  184. } else {
  185. this._adapter.notifySelect(option.value);
  186. }
  187. }
  188. _backwardLabelInValue() {
  189. const props = this.getProps();
  190. let { onSelectWithObject } = props;
  191. return onSelectWithObject;
  192. }
  193. handleDataChange(newData: any[]) {
  194. const options = this._generateList(newData);
  195. this._adapter.updateOptionList(options);
  196. this._adapter.rePositionDropdown();
  197. }
  198. handleValueChange(propValue: any) {
  199. let { data, defaultActiveFirstOption } = this.getProps();
  200. let selectedValue = '';
  201. if (this._backwardLabelInValue() && Object.prototype.toString.call(propValue) === '[object Object]') {
  202. selectedValue = propValue.value;
  203. } else {
  204. selectedValue = propValue;
  205. }
  206. let renderSelectedItem = this._getRenderSelectedItem();
  207. const options = this._generateList(data);
  208. // Get the option whose value match from options
  209. let selectedOption: StateOptionItem | Array<StateOptionItem> = options.length ? options.filter(option => renderSelectedItem(option) === selectedValue) : [];
  210. const canMatchInData = selectedOption.length;
  211. const selectedOptionIndex = options.findIndex(option => renderSelectedItem(option) === selectedValue);
  212. let inputValue = '';
  213. if (canMatchInData) {
  214. selectedOption = selectedOption[0];
  215. inputValue = renderSelectedItem(selectedOption);
  216. } else {
  217. const cbItem = this._backwardLabelInValue() ? propValue : { label: selectedValue, value: selectedValue };
  218. inputValue = renderSelectedItem(cbItem);
  219. }
  220. this._adapter.updateInputValue(inputValue);
  221. this.updateSelection(canMatchInData ? selectedOption : null);
  222. if (selectedOptionIndex === -1 && defaultActiveFirstOption) {
  223. this._adapter.updateFocusIndex(0);
  224. } else {
  225. this._adapter.updateFocusIndex(selectedOptionIndex);
  226. }
  227. }
  228. _modifyFocusIndex(searchValue) {
  229. let { focusIndex } = this.getStates();
  230. let { data, defaultActiveFirstOption } = this.getProps();
  231. let selectedOptionIndex = -1;
  232. if (searchValue) {
  233. let renderSelectedItem = this._getRenderSelectedItem();
  234. const options = this._generateList(data);
  235. selectedOptionIndex = options.findIndex(option => renderSelectedItem(option) === searchValue);
  236. }
  237. if (selectedOptionIndex === -1 && defaultActiveFirstOption) {
  238. if (focusIndex !== 0) {
  239. this._adapter.updateFocusIndex(0);
  240. }
  241. } else {
  242. if (selectedOptionIndex !== focusIndex) {
  243. this._adapter.updateFocusIndex(selectedOptionIndex);
  244. }
  245. }
  246. }
  247. _modifyFocusIndexOnPanelOpen() {
  248. let { inputValue } = this.getStates();
  249. this._modifyFocusIndex(inputValue);
  250. }
  251. _getRenderSelectedItem() {
  252. let { renderSelectedItem } = this.getProps();
  253. if (typeof renderSelectedItem === 'undefined') {
  254. renderSelectedItem = (option: any) => {
  255. return option?.value;
  256. };
  257. } else if (renderSelectedItem && typeof renderSelectedItem === 'function') {
  258. // do nothing
  259. }
  260. return renderSelectedItem;
  261. }
  262. handleClear() {
  263. this._adapter.notifyClear();
  264. }
  265. bindKeyBoardEvent() {
  266. this._keydownHandler = (event: KeyboardEvent): void => {
  267. this._handleKeyDown(event);
  268. };
  269. this._adapter.registerKeyDown(this._keydownHandler);
  270. }
  271. // unBindKeyBoardEvent() {
  272. // if (this._keydownHandler) {
  273. // this._adapter.unregisterKeyDown(this._keydownHandler);
  274. // }
  275. // }
  276. _handleKeyDown(event: KeyboardEvent) {
  277. const key = event.keyCode;
  278. const { visible } = this.getStates();
  279. switch (key) {
  280. case KeyCode.UP:
  281. // Prevent Input's cursor from following the movement
  282. event.preventDefault();
  283. this._handleArrowKeyDown(-1);
  284. break;
  285. case KeyCode.DOWN:
  286. // Prevent Input's cursor from following the movement
  287. event.preventDefault();
  288. this._handleArrowKeyDown(1);
  289. break;
  290. case KeyCode.ENTER:
  291. // when custom trigger, prevent outer open panel again
  292. event.preventDefault();
  293. this._handleEnterKeyDown();
  294. break;
  295. case KeyCode.ESC:
  296. this.closeDropdown();
  297. break;
  298. case KeyCode.TAB:
  299. this.closeDropdown();
  300. break;
  301. default:
  302. break;
  303. }
  304. this._adapter.notifyKeyDown(event);
  305. }
  306. _getEnableFocusIndex(offset: number) {
  307. const { focusIndex, options } = this.getStates();
  308. const visibleOptions = options.filter((item: StateOptionItem) => item.show);
  309. const optionsLength = visibleOptions.length;
  310. let index = focusIndex + offset;
  311. if (index < 0) {
  312. index = optionsLength - 1;
  313. }
  314. if (index >= optionsLength) {
  315. index = 0;
  316. }
  317. // avoid newIndex option is disabled
  318. if (offset > 0) {
  319. let nearestActiveOption = -1;
  320. for (let i = 0; i < visibleOptions.length; i++) {
  321. const optionIsActive = !visibleOptions[i].disabled;
  322. if (optionIsActive) {
  323. nearestActiveOption = i;
  324. }
  325. if (nearestActiveOption >= index) {
  326. break;
  327. }
  328. }
  329. index = nearestActiveOption;
  330. } else {
  331. let nearestActiveOption = visibleOptions.length;
  332. for (let i = optionsLength - 1; i >= 0; i--) {
  333. const optionIsActive = !visibleOptions[i].disabled;
  334. if (optionIsActive) {
  335. nearestActiveOption = i;
  336. }
  337. if (nearestActiveOption <= index) {
  338. break;
  339. }
  340. }
  341. index = nearestActiveOption;
  342. }
  343. this._adapter.updateFocusIndex(index);
  344. this._adapter.updateScrollTop(index);
  345. }
  346. _handleArrowKeyDown(offset: number): void {
  347. const { visible } = this.getStates();
  348. if (!visible) {
  349. this.openDropdown();
  350. } else {
  351. this._getEnableFocusIndex(offset);
  352. }
  353. }
  354. _handleEnterKeyDown() {
  355. const { visible, options, focusIndex } = this.getStates();
  356. if (!visible) {
  357. this.openDropdown();
  358. } else {
  359. if (focusIndex !== undefined && focusIndex !== -1 && options.length !== 0) {
  360. const visibleOptions = options.filter((item: StateOptionItem) => item.show);
  361. const selectedOption = visibleOptions[focusIndex];
  362. this.handleSelect(selectedOption, focusIndex);
  363. } else {
  364. this.closeDropdown();
  365. }
  366. }
  367. }
  368. handleOptionMouseEnter(optionIndex: number): void {
  369. this._adapter.updateFocusIndex(optionIndex);
  370. }
  371. handleFocus(e: FocusEvent) {
  372. // If you get the focus through the tab key, you need to manually bind keyboard events
  373. // Then you can open the panel by pressing the enter key
  374. this.bindKeyBoardEvent();
  375. this._adapter.notifyFocus(e);
  376. }
  377. handleBlur(e: any) {
  378. // only need persist on react adapter
  379. // https://reactjs.org/docs/legacy-event-pooling.html
  380. this._persistEvent(e);
  381. this._adapter.notifyBlur(e);
  382. }
  383. }
  384. export default AutoCompleteFoundation;