foundation.ts 15 KB

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