foundation.ts 13 KB

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