mdStore.ts 5.15 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
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
52
53
54
55
56
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
// mdStore.ts
import { create } from "zustand";
import axios from "axios";

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;
}

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
  },
}));

export default useMdStore;