SearchVocabulary.tsx 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import { get } from "../../request";
  2. import type { IVocabularyListResponse } from "../../api/Dict";
  3. import { useEffect, useRef, useState } from "react";
  4. import { AutoComplete, Input, Space, Typography } from "antd";
  5. import { DictIcon } from "../../assets/icon";
  6. const { Text, Link } = Typography;
  7. interface ValueType {
  8. key?: string;
  9. label: React.ReactNode;
  10. value: string | number;
  11. }
  12. interface IWidget {
  13. value?: string;
  14. api?: string;
  15. compact?: boolean;
  16. onSearch?: Function;
  17. onSplit?: Function;
  18. }
  19. const SearchVocabularyWidget = ({
  20. value,
  21. api = "vocabulary",
  22. compact = false,
  23. onSplit,
  24. onSearch,
  25. }: IWidget) => {
  26. const [options, setOptions] = useState<ValueType[]>([]);
  27. const [_fetching, setFetching] = useState(false);
  28. const [input, setInput] = useState<string>();
  29. const [factors, setFactors] = useState<string[]>([]);
  30. const intervalRef = useRef<number | null>(null); //防抖计时器句柄
  31. console.debug("value", value);
  32. useEffect(() => {
  33. console.debug("dict input", value);
  34. setInput(value);
  35. factorChange(value);
  36. }, [value]);
  37. const renderItem = (title: string, count: number, meaning?: string) => ({
  38. value: title,
  39. label: (
  40. <div>
  41. <div
  42. style={{
  43. display: "flex",
  44. justifyContent: "space-between",
  45. }}
  46. >
  47. {title}
  48. <span>
  49. <DictIcon /> {count}
  50. </span>
  51. </div>
  52. <div>
  53. <Text type="secondary">{meaning}</Text>
  54. </div>
  55. </div>
  56. ),
  57. });
  58. /**
  59. * 停止查字典计时
  60. * 在两种情况下停止计时
  61. * 1. 开始查字典
  62. * 2. 防抖时间内鼠标移出单词区
  63. */
  64. const stopLookup = () => {
  65. if (intervalRef.current) {
  66. window.clearInterval(intervalRef.current);
  67. intervalRef.current = null;
  68. }
  69. };
  70. const factorChange = (word?: string) => {
  71. if (typeof word === "undefined" || word.includes(":")) {
  72. setFactors([]);
  73. return;
  74. }
  75. const strFactors = word.replaceAll("+", "-");
  76. if (strFactors.indexOf("-") >= 0) {
  77. setFactors(strFactors.split("-"));
  78. if (typeof onSplit !== "undefined") {
  79. onSplit(strFactors.replaceAll("-", "+"));
  80. }
  81. } else {
  82. setFactors([]);
  83. if (typeof onSplit !== "undefined") {
  84. onSplit();
  85. }
  86. }
  87. };
  88. const search = (value: string) => {
  89. console.log("search", value);
  90. stopLookup();
  91. if (value === "") {
  92. return;
  93. }
  94. get<IVocabularyListResponse>(`/v2/${api}?view=key&key=${value}`)
  95. .then((json) => {
  96. const words: ValueType[] = json.data.rows
  97. .map((item) => {
  98. let weight = item.count / (item.strlen - value.length + 0.1);
  99. if (item.word.length === value.length) {
  100. weight = 100;
  101. }
  102. return {
  103. word: item.word,
  104. count: item.count,
  105. meaning: item.meaning,
  106. weight: weight,
  107. };
  108. })
  109. .sort((a, b) => b.weight - a.weight)
  110. .slice(0, 7)
  111. .map((item) => {
  112. return renderItem(item.word, item.count, item.meaning);
  113. });
  114. setOptions(words);
  115. })
  116. .finally(() => {
  117. console.log("finally");
  118. setFetching(false);
  119. });
  120. };
  121. const _____startLookup = (value: string) => {
  122. //开始计时,计时结束查字典
  123. console.log("开始计时");
  124. intervalRef.current = window.setInterval(search, 500, value);
  125. };
  126. return (
  127. <div style={{ width: "100%" }}>
  128. <AutoComplete
  129. getPopupContainer={(_node: HTMLElement) =>
  130. document.getElementsByClassName("dict_search_div")[0] as HTMLElement
  131. }
  132. value={input}
  133. style={{ width: "100%" }}
  134. popupClassName="certain-category-search-dropdown"
  135. dropdownMatchSelectWidth={400}
  136. options={options}
  137. onChange={(value: string) => {
  138. console.log("input", value);
  139. setInput(value);
  140. factorChange(value);
  141. }}
  142. onSearch={(value: string) => {
  143. console.log("auto complete on search", value);
  144. setFetching(true);
  145. search(value);
  146. }}
  147. onSelect={(value: string, _option: ValueType) => {
  148. if (typeof onSearch !== "undefined") {
  149. onSearch(value);
  150. }
  151. }}
  152. >
  153. <Input.Search
  154. style={{ width: "100%" }}
  155. size={compact ? undefined : "large"}
  156. placeholder="search here"
  157. onSearch={(value: string) => {
  158. console.log("on search", value);
  159. if (typeof onSearch !== "undefined") {
  160. onSearch(value);
  161. }
  162. }}
  163. />
  164. </AutoComplete>
  165. <Space style={{ display: "none" }}>
  166. {factors.map((item, id) => {
  167. return (
  168. <Link
  169. key={id}
  170. onClick={() => {
  171. if (typeof onSearch !== "undefined") {
  172. onSearch(item, true);
  173. }
  174. }}
  175. >
  176. {item}
  177. </Link>
  178. );
  179. })}
  180. </Space>
  181. </div>
  182. );
  183. };
  184. export default SearchVocabularyWidget;