AnthologyTocTree.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { useEffect, useState } from "react";
  2. import { get } from "../../request";
  3. import type { IArticleMapListResponse } from "../../api/Article";
  4. import type { ListNodeData } from "../article/EditableTree";
  5. import TocTree from "../article/TocTree";
  6. interface IWidget {
  7. anthologyId?: string;
  8. channels?: string[];
  9. onClick?: (
  10. anthologyId: string,
  11. id: string,
  12. target: "_blank" | "self"
  13. ) => void;
  14. onArticleSelect?: (anthologyId: string, keys: string[]) => void;
  15. }
  16. const AnthologyTocTreeWidget = ({
  17. anthologyId,
  18. channels,
  19. onClick,
  20. onArticleSelect,
  21. }: IWidget) => {
  22. const [tocData, setTocData] = useState<ListNodeData[]>([]);
  23. const [expandedKeys, setExpandedKeys] = useState<string[]>();
  24. useEffect(() => {
  25. if (typeof anthologyId === "undefined") {
  26. return;
  27. }
  28. let url = `/v2/article-map?view=anthology&id=${anthologyId}&lazy=1`;
  29. url += channels && channels.length > 0 ? "&channel=" + channels[0] : "";
  30. console.log("url", url);
  31. get<IArticleMapListResponse>(url).then((json) => {
  32. if (json.ok) {
  33. const toc: ListNodeData[] = json.data.rows.map((item) => {
  34. return {
  35. key: item.article_id ? item.article_id : item.title,
  36. title: item.title_text ? item.title_text : item.title,
  37. level: item.level,
  38. children: item.children,
  39. status: item.status,
  40. deletedAt: item.deleted_at,
  41. };
  42. });
  43. setTocData(toc);
  44. if (json.data.rows.length === json.data.count) {
  45. setExpandedKeys(
  46. json.data.rows
  47. .filter((value) => value.level === 1)
  48. .map((item) => (item.article_id ? item.article_id : item.title))
  49. );
  50. } else {
  51. setExpandedKeys(undefined);
  52. }
  53. }
  54. });
  55. }, [anthologyId, channels]);
  56. return (
  57. <TocTree
  58. treeData={tocData}
  59. expandedKeys={expandedKeys}
  60. onSelect={(keys: string[]) => {
  61. if (
  62. typeof onArticleSelect !== "undefined" &&
  63. typeof anthologyId !== "undefined"
  64. ) {
  65. onArticleSelect(anthologyId, keys);
  66. }
  67. }}
  68. onClick={(
  69. id: string,
  70. e: React.MouseEvent<HTMLSpanElement, MouseEvent>
  71. ) => {
  72. const target = e.ctrlKey || e.metaKey ? "_blank" : "self";
  73. if (
  74. typeof onClick !== "undefined" &&
  75. typeof anthologyId !== "undefined"
  76. ) {
  77. onClick(anthologyId, id, target);
  78. }
  79. }}
  80. />
  81. );
  82. };
  83. export default AnthologyTocTreeWidget;