TermSearch.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { useState, useEffect } from "react";
  2. import { Col, _List, Row, Skeleton, Typography } from "antd";
  3. import { get } from "../../request";
  4. import type {
  5. ITermDataResponse,
  6. ITermListResponse,
  7. ITermResponse,
  8. } from "../../api/Term";
  9. import TermItem from "./TermItem";
  10. import type { ITerm } from "./TermEdit";
  11. const { Title } = Typography;
  12. interface IWidget {
  13. word?: string;
  14. wordId?: string;
  15. compact?: boolean;
  16. onIdChange?: Function;
  17. }
  18. const TermSearchWidget = ({
  19. word,
  20. wordId,
  21. compact = false,
  22. onIdChange,
  23. }: IWidget) => {
  24. const [tableData, setTableData] = useState<ITermDataResponse[]>();
  25. const [loading, setLoading] = useState(false);
  26. const loadById = (id: string) => {
  27. const url = `/v2/terms/${id}`;
  28. console.info("term url", url);
  29. setLoading(true);
  30. get<ITermResponse>(url)
  31. .then((json) => {
  32. setTableData([json.data]);
  33. })
  34. .finally(() => setLoading(false))
  35. .catch((error) => {
  36. console.error(error);
  37. });
  38. };
  39. useEffect(() => {
  40. if (typeof word === "undefined" && typeof wordId === "undefined") {
  41. return;
  42. }
  43. if (word && word.length > 0) {
  44. const url = `/v2/terms?view=word&word=${word}`;
  45. console.info("term url", url);
  46. setLoading(true);
  47. get<ITermListResponse>(url)
  48. .then((json) => {
  49. setTableData(json.data.rows);
  50. })
  51. .finally(() => setLoading(false))
  52. .catch((error) => {
  53. console.error(error);
  54. });
  55. } else if (wordId && wordId.length > 0) {
  56. loadById(wordId);
  57. }
  58. }, [word, wordId]);
  59. return (
  60. <>
  61. <Row>
  62. <Col flex="200px">{compact ? <></> : <></>}</Col>
  63. <Col flex="760px">
  64. <Title level={4}>{word}</Title>
  65. {loading ? (
  66. <Skeleton active />
  67. ) : (
  68. <div>
  69. {tableData?.map((item, _id) => {
  70. return (
  71. <TermItem
  72. data={item}
  73. onTermClick={(value: ITerm) => {
  74. console.debug("on term click", value);
  75. if (typeof onIdChange === "undefined") {
  76. if (value.id) {
  77. loadById(value.id);
  78. }
  79. } else {
  80. onIdChange(value.id);
  81. }
  82. }}
  83. />
  84. );
  85. })}
  86. </div>
  87. )}
  88. </Col>
  89. <Col flex="200px"></Col>
  90. </Row>
  91. </>
  92. );
  93. };
  94. export default TermSearchWidget;