".github/vscode:/vscode.git/clone" did not exist on "989fb1496529e562acab3fd47a850fcea9c4f0bd"
mdStore.ts 6.67 KB
Newer Older
dechen lin's avatar
dechen lin committed
1
2
3
// mdStore.ts
import { create } from "zustand";
import axios from "axios";
dechen lin's avatar
dechen lin committed
4
import { updateMarkdownContent, UpdateMarkdownRequest } from "@/api/extract"; // 确保路径正确
dechen lin's avatar
dechen lin committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 MdContent {
  content: string;
  isLoading: boolean;
}

type AnchorType =
  | "span"
  | "div"
  | "comment"
  | "data-attribute"
  | "hr"
  | "mark"
  | "p";

interface AnchorOptions {
  type: AnchorType;
  prefix?: string;
  style?: string;
  className?: string;
  customAttributes?: Record<string, string>;
}

const defaultAnchorOptions: AnchorOptions = {
  type: "span",
  prefix: "md-anchor-",
  style: "display:none;",
  className: "",
  customAttributes: {},
};

interface MdState {
  mdContents: Record<string, MdContent>;
  allMdContent: string;
  allMdContentWithAnchor: string;
  error: Error | null;
  currentRequestId: number;
  setMdUrlArr: (urls: string[]) => Promise<void>;
  getAllMdContent: (data: string[]) => string;
  setAllMdContent: (val?: string) => void;
  setAllMdContentWithAnchor: (val?: string) => void;
  getContentWithAnchors: (
    data: string[],
    options?: Partial<AnchorOptions>
  ) => string;
  jumpToAnchor: (anchorId: string) => number;
  reset: () => void;
dechen lin's avatar
dechen lin committed
52
53
54
55
56
  updateMdContent: (
    fileKey: string,
    pageNumber: string | number,
    newContent: string
  ) => Promise<void>;
dechen lin's avatar
dechen lin committed
57
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
}

const MAX_CONCURRENT_REQUESTS = 2;

const initialState = {
  mdContents: {},
  allMdContent: "",
  allMdContentWithAnchor: "",
  error: null,
  currentRequestId: 0,
};

const useMdStore = create<MdState>((set, get) => ({
  ...initialState,

  reset: () => {
    set(initialState);
  },

  setAllMdContent: (value?: string) => {
    set(() => ({
      allMdContent: value,
    }));
  },

  setAllMdContentWithAnchor: (value?: string) => {
    set(() => ({
      allMdContentWithAnchor: value,
    }));
  },

  setMdUrlArr: async (urls: string[]) => {
    const requestId = get().currentRequestId + 1;
    set((state) => ({ currentRequestId: requestId, error: null }));

    const fetchContent = async (url: string): Promise<[string, string]> => {
      try {
        const response = await axios.get<string>(url);
        return [url, response.data];
      } catch (error) {
        if (get().currentRequestId === requestId) {
          set((state) => ({ error: error as Error }));
        }
        return [url, ""];
      }
    };

    const fetchWithConcurrency = async (
      urls: string[]
    ): Promise<[string, string][]> => {
      const queue = [...urls];
      const results: [string, string][] = [];
      const inProgress = new Set<Promise<[string, string]>>();

      while (queue.length > 0 || inProgress.size > 0) {
        while (inProgress.size < MAX_CONCURRENT_REQUESTS && queue.length > 0) {
          const url = queue.shift()!;
          const promise = fetchContent(url);
          inProgress.add(promise);
          promise.then((result) => {
            results.push(result);
            inProgress.delete(promise);
          });
        }
        if (inProgress.size > 0) {
          await Promise.race(inProgress);
        }
      }

      return results;
    };

    const results = await fetchWithConcurrency(urls);

    if (get().currentRequestId === requestId) {
      const newMdContents: Record<string, MdContent> = {};
      results.forEach(([url, content]) => {
        newMdContents[url] = { content, isLoading: false };
      });

      set((state) => ({
        mdContents: newMdContents,
        allMdContent: state.getAllMdContent(results.map((i) => i[1])),
        allMdContentWithAnchor: state.getContentWithAnchors(
          results.map((i) => i[1])
        ),
      }));
    }
  },

  getAllMdContent: (data) => {
    return data?.join("\n\n");
  },

  getContentWithAnchors: (data: string[], options?: Partial<AnchorOptions>) => {
    const opts = { ...defaultAnchorOptions, ...options };

    const generateAnchorTag = (index: number) => {
      const id = `${opts.prefix}${index}`;
      const attributes = Object.entries(opts.customAttributes || {})
        .map(([key, value]) => `${key}="${value}"`)
        .join(" ");

      switch (opts.type) {
        case "span":
        case "div":
        case "mark":
        case "p":
          return `<${opts.type} id="${id}" style="${opts.style}" class="${opts.className}" ${attributes}></${opts.type}>`;
        case "comment":
          return `<!-- anchor: ${id} -->`;
        case "data-attribute":
          return `<span data-anchor="${id}" style="${opts.style}" class="${opts.className}" ${attributes}></span>`;
        case "hr":
          return `<hr id="${id}" style="${opts.style}" class="${opts.className}" ${attributes}>`;
        default:
          return `<span id="${id}" style="${opts.style}" class="${opts.className}" ${attributes}></span>`;
      }
    };

    return data
      ?.map((content, index) => {
        const anchorTag = generateAnchorTag(index);
        return `${anchorTag}\n\n${content}`;
      })
      .join("\n\n");
  },

  jumpToAnchor: (anchorId: string) => {
    const { mdContents } = get();
    const contentArray = Object.values(mdContents).map(
      (content) => content.content
    );
    let totalLength = 0;
    for (let i = 0; i < contentArray.length; i++) {
      if (anchorId === `md-anchor-${i}`) {
        return totalLength;
      }
      totalLength += contentArray[i].length + 2; // +2 for "\n\n"
    }
    return -1; // Anchor not found
  },
dechen lin's avatar
dechen lin committed
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

  updateMdContent: async (
    fileKey: string,
    pageNumber: string,
    newContent: string
  ) => {
    try {
      const params: UpdateMarkdownRequest = {
        file_key: fileKey,
        data: {
          [pageNumber]: newContent,
        },
      };

      const result = await updateMarkdownContent(params);

      if (result && result.success) {
        // 更新本地状态
        set((state) => {
          const updatedMdContents = { ...state.mdContents };
          if (updatedMdContents[fileKey]) {
            updatedMdContents[fileKey] = {
              ...updatedMdContents[fileKey],
              content: newContent,
            };
          }

          // 重新计算 allMdContent 和 allMdContentWithAnchor
          const contentArray = Object.values(updatedMdContents).map(
            (content) => content.content
          );
          const newAllMdContent = state.getAllMdContent(contentArray);
          const newAllMdContentWithAnchor =
            state.getContentWithAnchors(contentArray);

          return {
            mdContents: updatedMdContents,
            allMdContent: newAllMdContent,
            allMdContentWithAnchor: newAllMdContentWithAnchor,
          };
        });
      } else {
        throw new Error("Failed to update Markdown content");
      }
    } catch (error) {
      set({ error: error as Error });
      throw error;
    }
  },
dechen lin's avatar
dechen lin committed
248
249
250
}));

export default useMdStore;