WbwDetailParent.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. import { AutoComplete, Input } from "antd";
  2. import { useEffect, useState } from "react";
  3. import { useAppSelector } from "../../../hooks";
  4. import { inlineDict as _inlineDict } from "../../../reducers/inline-dict";
  5. import type { IWbw } from "./WbwWord";
  6. import type { IApiResponseDictData } from "../../../api/Dict";
  7. export const getParentInDict = (
  8. wordIn: string,
  9. wordIndex: string[],
  10. wordList: IApiResponseDictData[]
  11. ): string[] => {
  12. if (wordIndex.includes(wordIn)) {
  13. const result = wordList.filter((word) => word.word === wordIn);
  14. //查重
  15. //TODO 加入信心指数并排序
  16. const myMap = new Map<string, number>();
  17. const parent: string[] = [];
  18. for (const iterator of result) {
  19. if (iterator.parent) {
  20. myMap.set(iterator.parent, 1);
  21. }
  22. }
  23. myMap.forEach((_value, key, _map) => {
  24. parent.push(key);
  25. });
  26. return parent;
  27. } else {
  28. return [];
  29. }
  30. };
  31. interface ValueType {
  32. key?: string;
  33. label: React.ReactNode;
  34. value: string | number;
  35. }
  36. interface IWidget {
  37. data: IWbw;
  38. readonly?: boolean;
  39. onChange?: Function;
  40. }
  41. const WbwDetailParentWidget = ({
  42. data,
  43. readonly = false,
  44. onChange,
  45. }: IWidget) => {
  46. const [parentOptions, setParentOptions] = useState<ValueType[]>([]);
  47. const inlineDict = useAppSelector(_inlineDict);
  48. useEffect(() => {
  49. if (!data.real.value) {
  50. return;
  51. }
  52. const parent = getParentInDict(
  53. data.word.value,
  54. inlineDict.wordIndex,
  55. inlineDict.wordList
  56. );
  57. const parentOptions = parent.map((item) => {
  58. return {
  59. label: item,
  60. value: item,
  61. };
  62. });
  63. const findParent = parentOptions.find(
  64. (value) => value.value === data.real.value
  65. );
  66. if (findParent) {
  67. setParentOptions(parentOptions);
  68. } else {
  69. setParentOptions([
  70. ...parentOptions,
  71. { label: data.real.value, value: data.real.value },
  72. ]);
  73. }
  74. }, [inlineDict, data]);
  75. return (
  76. <AutoComplete
  77. disabled={readonly}
  78. options={parentOptions}
  79. value={data.parent?.value}
  80. onChange={(value: any, _option: ValueType | ValueType[]) => {
  81. console.debug("wbw parent onChange", value);
  82. if (typeof onChange !== "undefined") {
  83. onChange(value);
  84. }
  85. }}
  86. >
  87. <Input disabled={readonly} allowClear placeholder="请输入" />
  88. </AutoComplete>
  89. );
  90. };
  91. export default WbwDetailParentWidget;