foundation.ts 15 KB

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