foundation.ts 15 KB

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