index.tsx 8.48 KB
Newer Older
dechen lin's avatar
dechen lin committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { useEffect, useRef, useState } from "react";
import { Tooltip } from "antd";

import cls from "classnames";
import styles from "./index.module.scss";
import { useDeepCompareEffect, useHover } from "ahooks";
import IconFont from "@/components/icon-font";
import { downloadFileUseAScript } from "@/utils/download";
import { MD_DRIVE_PDF } from "@/constant/event";
import { useIntl } from "react-intl";
import LazyUrlMarkdown from "../url-markdown";
import exitFullScreenSvg from "@/assets/pdf/exitFullScreen.svg";
import fullScreenSvg from "@/assets/pdf/fullScreen.svg";
import { MD_PREVIEW_TYPE } from "@/types/extract-task-type";
import _ from "lodash";
import { TaskIdResItem } from "@/api/extract";
import useMdStore from "@/store/mdStore";
import CodeMirror from "@/components/code-mirror";
import { useParams } from "react-router-dom";
dechen lin's avatar
dechen lin committed
20
import SaveStatus, { SaveStatusRef } from "@/components/SaveStatus";
dechen lin's avatar
dechen lin committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51

interface IMdViewerProps {
  md?: string;
  className?: string;
  filename?: string;
  url?: string;
  taskInfo: TaskIdResItem;
  curPage: number;
  fullScreen?: boolean;
  setFullScreen?: (value?: boolean) => void;
}

const MdViewer: React.FC<IMdViewerProps> = ({
  fullScreen,
  setFullScreen,
  taskInfo,
  className = "",
  curPage,
}) => {
  const mdViewerPef = useRef<HTMLDivElement>(null);
  const url = taskInfo?.fullMdLink || "";
  const containerRef = useRef<HTMLDivElement>(null);
  const isHovering = useHover(containerRef);
  const { formatMessage } = useIntl();
  const [displayType, setDisplayType] = useState(MD_PREVIEW_TYPE.preview);
  const params = useParams();
  const {
    setAllMdContentWithAnchor,
    allMdContentWithAnchor,
    setMdUrlArr,
    mdContents,
dechen lin's avatar
dechen lin committed
52
    updateMdContent,
dechen lin's avatar
dechen lin committed
53
54
55
56
  } = useMdStore();
  const [lineWrap, setLineWrap] = useState(false);

  const threshold = 562 - 427;
dechen lin's avatar
dechen lin committed
57
  const statusRef = useRef<SaveStatusRef>(null);
dechen lin's avatar
dechen lin committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

  const menuList = [
    {
      name: formatMessage({ id: "extractor.markdown.preview" }),
      code: MD_PREVIEW_TYPE.preview,
    },
    {
      name: formatMessage({ id: "extractor.markdown.code" }),
      code: MD_PREVIEW_TYPE.code,
    },
  ];

  const getVisibleFromType = (str: string, type: string) => {
    return str === type
      ? "relative w-full h-full"
      : "w-0 h-0 overflow-hidden hidden";
  };

  const pushMdViewerScroll = (scrollType?: "instant" | "smooth") => {
    const container = document.getElementById(`md-container`);
    // md渲染的时候用一个元素包括anchor
    const element =
      displayType === MD_PREVIEW_TYPE.preview
        ? document.getElementById(`md-anchor-${curPage - 1}`)?.parentElement
        : document.getElementById(`code-${curPage - 1}`);
    if (element && container) {
      container.scrollTo({
        top: element.offsetTop - 124,
        behavior: scrollType || "smooth",
      });
    }
  };

  useEffect(() => {
    if (isHovering) return;
    pushMdViewerScroll();
  }, [curPage, isHovering]);

  useEffect(() => {
    pushMdViewerScroll("instant");
  }, [displayType]);

  useEffect(() => {
    if (!isHovering) return;
    const handleScroll = () => {
      if (!containerRef.current) return;

      taskInfo?.markdownUrl?.forEach((page, index) => {
        const element =
          displayType === MD_PREVIEW_TYPE.preview
            ? document.getElementById(`md-anchor-${index}`)?.parentElement
            : document.getElementById(`code-${index}`);

        if (element) {
          const rect = element.getBoundingClientRect();

          if (rect.top <= threshold) {
            document.dispatchEvent(
              new CustomEvent(MD_DRIVE_PDF, {
                detail: index,
              })
            );
          }
        }
      });
    };

    const container = containerRef.current;
    if (container) {
      container.addEventListener("scroll", handleScroll);
    }

    return () => {
      if (container) {
        container?.removeEventListener("scroll", handleScroll);
      }
    };
  }, [taskInfo, isHovering, displayType]);

  useDeepCompareEffect(() => {
    if (taskInfo?.markdownUrl) {
      setMdUrlArr(taskInfo?.markdownUrl);
    }
  }, [taskInfo?.markdownUrl, params?.jobID]);

dechen lin's avatar
dechen lin committed
143
  const handleContentChange = (val: string, index: number) => {
dechen lin's avatar
dechen lin committed
144
    setAllMdContentWithAnchor(val);
dechen lin's avatar
dechen lin committed
145
146
147
148
    statusRef?.current?.triggerSave();
    if (taskInfo?.file_key) {
      updateMdContent(taskInfo.file_key!, index, val);
    }
dechen lin's avatar
dechen lin committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
  };

  return (
    <div className={cls(className)} ref={mdViewerPef}>
      <div
        className={cls(
          "h-[49px] px-6  border-0 border-solid border-b-[1px] border-[#EBECF0] w-full pl-[24px] flex justify-between   items-center"
        )}
      >
        <ul className="p-1 list-none mb-0 inline-block rounded-sm mr-auto  bg-[#F4F5F9] select-none">
          {menuList.map((item) => (
            <li
              key={item.code}
              className={`mx-[0.125rem] px-2 leading-[25px] inline-block rounded-sm text-[14px] cursor-pointer  text-color ${
                displayType === item.code && "bg-white text-primary"
              }`}
              onClick={() => setDisplayType(item.code)}
            >
              {item.name}
            </li>
          ))}
        </ul>
dechen lin's avatar
dechen lin committed
171
        <SaveStatus ref={statusRef} />
dechen lin's avatar
dechen lin committed
172
173
174
175
176
        {displayType === "code" && (
          <>
            <Tooltip
              title={
                fullScreen
dechen lin's avatar
dechen lin committed
177
                  ? formatMessage({ id: "extractor.button.lineWrap" })
dechen lin's avatar
dechen lin committed
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
                  : formatMessage({
                      id: "extractor.button.lineWrap",
                    })
              }
            >
              <IconFont
                type="icon-line-wrap"
                className={cls(
                  "text-lg text-[#464a53] leading-0  ml-[1rem] cursor-pointer hover:bg-[#F4F5F9] p-1 rounded",
                  lineWrap && "!text-[#0D53DE]"
                )}
                onClick={() => setLineWrap?.(!lineWrap)}
              />
            </Tooltip>
            <span className="w-[1px] h-[0.75rem] bg-[#D7D8DD] mx-[1rem]"></span>
          </>
        )}
        <Tooltip
          title={
            fullScreen
              ? formatMessage({ id: "extractor.button.exitFullScreen" })
              : formatMessage({
                  id: "extractor.button.fullScreen",
                })
          }
        >
          <span
            className="cursor-pointer w-[1.5rem] user-select-none flex items-center justify-center h-[1.5rem] hover:bg-[#F4F5F9] rounded "
            onClick={() => setFullScreen?.(!fullScreen)}
          >
            {!fullScreen ? (
              <img
                className=" w-[1.125rem] h-[1.125rem] "
                src={fullScreenSvg}
              />
            ) : (
              <img
                className=" w-[1.125rem] h-[1.125rem] "
                src={exitFullScreenSvg}
              />
            )}
          </span>
        </Tooltip>
        <span className="w-[1px] h-[0.75rem] bg-[#D7D8DD] ml-[1rem]"></span>
        <Tooltip title={formatMessage({ id: "extractor.button.download" })}>
          <IconFont
            type="icon-xiazai"
            className="text-lg text-[#464a53] leading-0  ml-[1rem] cursor-pointer hover:bg-[#F4F5F9] p-1 rounded"
            onClick={() =>
              downloadFileUseAScript(
                url,
                `${_(taskInfo?.fileName).split(".").slice(0, -1).join(".")}.md`
              )
            }
          />
        </Tooltip>
      </div>
      <div
        className={cls(
          "bg-white !h-[calc(100%-60px)] px-6 py-8 overflow-auto w-full max-w-[100%]",
          styles.scrollBar
        )}
        id="md-container"
        ref={containerRef}
      >
        <div
          className={cls(
            getVisibleFromType(displayType, MD_PREVIEW_TYPE.preview)
          )}
        >
          <LazyUrlMarkdown
            markdownClass={"relative"}
            content={allMdContentWithAnchor}
          />
        </div>
        <div
          className={cls(getVisibleFromType(displayType, MD_PREVIEW_TYPE.code))}
        >
          {taskInfo?.markdownUrl?.map((url: string, index: number) => {
            const md = mdContents[url]?.content || "";
            if (!md) return null;
            return (
              <div key={url} id={`code-${index}`} className="opacity-1 z-[-1]">
                <CodeMirror
                  value={md}
                  lineWrapping={lineWrap}
dechen lin's avatar
dechen lin committed
264
                  onChange={(val) => handleContentChange(val, index)}
dechen lin's avatar
dechen lin committed
265
266
267
268
269
270
271
272
273
274
275
276
                  editable
                  className="w-full h-full"
                />
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};
export default MdViewer;