foundation.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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.bindKeyBoardEvent();
  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. 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. }
  137. handleSelect(option: StateOptionItem, optionIndex?: number): void {
  138. const { renderSelectedItem } = this.getProps();
  139. let newInputValue: string | number = '';
  140. if (renderSelectedItem && typeof renderSelectedItem === 'function') {
  141. newInputValue = renderSelectedItem(option);
  142. warning(
  143. typeof newInputValue !== 'string',
  144. 'Warning: [Semi AutoComplete] renderSelectedItem must return string, please check your function return'
  145. );
  146. } else {
  147. newInputValue = option.value;
  148. }
  149. // 1. trigger onSelect
  150. // 2. close Dropdown
  151. if (this._isControlledComponent()) {
  152. this.closeDropdown();
  153. this.notifySelect(option);
  154. } else {
  155. // 1. update Input
  156. // 2. update Selection
  157. // 3. trigger onSelect
  158. // 4. close Dropdown
  159. this._adapter.updateInputValue(newInputValue);
  160. this.updateSelection(option);
  161. this.notifySelect(option);
  162. this.closeDropdown();
  163. }
  164. this._adapter.notifyChange(newInputValue);
  165. this._adapter.updateFocusIndex(optionIndex);
  166. }
  167. updateSelection(option: StateOptionItem) {
  168. const selection = new Map();
  169. if (option) {
  170. selection.set(option.label, option);
  171. }
  172. this._adapter.updateSelection(selection);
  173. }
  174. notifySelect(option: StateOptionItem) {
  175. if (this._backwardLabelInValue()) {
  176. this._adapter.notifySelect(option);
  177. } else {
  178. this._adapter.notifySelect(option.value);
  179. }
  180. }
  181. _backwardLabelInValue() {
  182. const props = this.getProps();
  183. let { onSelectWithObject } = props;
  184. return onSelectWithObject;
  185. }
  186. handleDataChange(newData: any[]) {
  187. const options = this._generateList(newData);
  188. this._adapter.updateOptionList(options);
  189. this._adapter.rePositionDropdown();
  190. }
  191. handleValueChange(propValue: any) {
  192. let { data, defaultActiveFirstOption } = this.getProps();
  193. let selectedValue = '';
  194. if (this._backwardLabelInValue() && Object.prototype.toString.call(propValue) === '[object Object]') {
  195. selectedValue = propValue.value;
  196. } else {
  197. selectedValue = propValue;
  198. }
  199. let renderSelectedItem = this._getRenderSelectedItem();
  200. const options = this._generateList(data);
  201. // Get the option whose value match from options
  202. let selectedOption: StateOptionItem | Array<StateOptionItem> = options.filter(option => renderSelectedItem(option) === selectedValue);
  203. const canMatchInData = selectedOption.length;
  204. const selectedOptionIndex = options.findIndex(option => renderSelectedItem(option) === selectedValue);
  205. let inputValue = '';
  206. if (canMatchInData) {
  207. selectedOption = selectedOption[0];
  208. inputValue = renderSelectedItem(selectedOption);
  209. } else {
  210. const cbItem = this._backwardLabelInValue() ? propValue : { label: selectedValue, value: selectedValue };
  211. inputValue = renderSelectedItem(cbItem);
  212. }
  213. this._adapter.updateInputValue(inputValue);
  214. this.updateSelection(canMatchInData ? selectedOption : null);
  215. if (selectedOptionIndex === -1 && defaultActiveFirstOption) {
  216. this._adapter.updateFocusIndex(0);
  217. } else {
  218. this._adapter.updateFocusIndex(selectedOptionIndex);
  219. }
  220. }
  221. _modifyFocusIndex(searchValue) {
  222. let { focusIndex } = this.getStates();
  223. let { data, defaultActiveFirstOption } = this.getProps();
  224. let renderSelectedItem = this._getRenderSelectedItem();
  225. const options = this._generateList(data);
  226. const selectedOptionIndex = options.findIndex(option => renderSelectedItem(option) === searchValue);
  227. if (selectedOptionIndex === -1 && defaultActiveFirstOption) {
  228. if (focusIndex !== 0) {
  229. this._adapter.updateFocusIndex(0);
  230. }
  231. } else {
  232. if (selectedOptionIndex !== focusIndex) {
  233. this._adapter.updateFocusIndex(selectedOptionIndex);
  234. }
  235. }
  236. }
  237. _modifyFocusIndexOnPanelOpen() {
  238. let { inputValue } = this.getStates();
  239. this._modifyFocusIndex(inputValue);
  240. }
  241. _getRenderSelectedItem() {
  242. let { renderSelectedItem } = this.getProps();
  243. if (typeof renderSelectedItem === 'undefined') {
  244. renderSelectedItem = (option: any) => option.value;
  245. } else if (renderSelectedItem && typeof renderSelectedItem === 'function') {
  246. // do nothing
  247. }
  248. return renderSelectedItem;
  249. }
  250. handleClear() {
  251. this._adapter.notifyClear();
  252. }
  253. bindKeyBoardEvent() {
  254. this._keydownHandler = (event: KeyboardEvent): void => {
  255. this._handleKeyDown(event);
  256. };
  257. this._adapter.registerKeyDown(this._keydownHandler);
  258. }
  259. unBindKeyBoardEvent() {
  260. if (this._keydownHandler) {
  261. this._adapter.unregisterKeyDown(this._keydownHandler);
  262. }
  263. }
  264. _handleKeyDown(event: KeyboardEvent) {
  265. const key = event.keyCode;
  266. const { visible } = this.getStates();
  267. if (!visible) {
  268. return;
  269. }
  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. this._handleEnterKeyDown();
  283. break;
  284. case KeyCode.ESC:
  285. this.closeDropdown();
  286. break;
  287. default:
  288. break;
  289. }
  290. }
  291. _getEnableFocusIndex(offset: number) {
  292. const { focusIndex, options } = this.getStates();
  293. const visibleOptions = options.filter((item: StateOptionItem) => item.show);
  294. const optionsLength = visibleOptions.length;
  295. let index = focusIndex + offset;
  296. if (index < 0) {
  297. index = optionsLength - 1;
  298. }
  299. if (index >= optionsLength) {
  300. index = 0;
  301. }
  302. // avoid newIndex option is disabled
  303. if (offset > 0) {
  304. let nearestActiveOption = -1;
  305. for (let i = 0; i < visibleOptions.length; i++) {
  306. const optionIsActive = !visibleOptions[i].disabled;
  307. if (optionIsActive) {
  308. nearestActiveOption = i;
  309. }
  310. if (nearestActiveOption >= index) {
  311. break;
  312. }
  313. }
  314. index = nearestActiveOption;
  315. } else {
  316. let nearestActiveOption = visibleOptions.length;
  317. for (let i = optionsLength - 1; i >= 0; i--) {
  318. const optionIsActive = !visibleOptions[i].disabled;
  319. if (optionIsActive) {
  320. nearestActiveOption = i;
  321. }
  322. if (nearestActiveOption <= index) {
  323. break;
  324. }
  325. }
  326. index = nearestActiveOption;
  327. }
  328. this._adapter.updateFocusIndex(index);
  329. }
  330. _handleArrowKeyDown(offset: number): void {
  331. this._getEnableFocusIndex(offset);
  332. }
  333. _handleEnterKeyDown() {
  334. const { visible, options, focusIndex } = this.getStates();
  335. if (focusIndex !== -1 && options.length !== 0) {
  336. const visibleOptions = options.filter((item: StateOptionItem) => item.show);
  337. const selectedOption = visibleOptions[focusIndex];
  338. this.handleSelect(selectedOption, focusIndex);
  339. } else if (visible) {
  340. // this.close();
  341. }
  342. }
  343. handleOptionMouseEnter(optionIndex: number): void {
  344. this._adapter.updateFocusIndex(optionIndex);
  345. }
  346. handleFocus(e: FocusEvent) {
  347. this._adapter.notifyFocus(e);
  348. }
  349. handleBlur(e: FocusEvent) {
  350. // 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
  351. // internal-issues:1231
  352. setTimeout(() => {
  353. this._adapter.notifyBlur(e);
  354. this.closeDropdown();
  355. }, 100);
  356. }
  357. }
  358. export default AutoCompleteFoundation;