File size: 9,769 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import React, { cloneElement, isValidElement } from 'react';
import { BugOutlined } from '@ant-design/icons';
import { Button, Drawer, Flex, Grid, Popover, Tag, Timeline, Typography } from 'antd';
import type { TimelineItemProps } from 'antd';
import { createStyles } from 'antd-style';

import useFetch from '../../../hooks/useFetch';
import useLocale from '../../../hooks/useLocale';
import useLocation from '../../../hooks/useLocation';
import { matchDeprecated } from '../../utils';
import Link from '../Link';

interface ChangelogInfo {
  version: string;
  changelog: string;
  refs: string[];
  contributors: string[];
  releaseDate: string;
}

const useStyle = createStyles(({ token, css }) => ({
  listWrap: css`
    > li {
      line-height: 2;
    }
  `,
  linkRef: css`
    margin-inline-start: ${token.marginXS}px;
  `,
  bug: css`
    font-size: ${token.fontSize}px;
    color: #aaa;
    margin-inline-start: ${token.marginXS}px;
    display: inline-block;
    vertical-align: inherit;
    cursor: pointer;
    &:hover {
      color: #333;
    }
  `,
  bugReasonTitle: css`
    padding: ${token.paddingXXS}px ${token.paddingXS}px;
  `,
  bugReasonList: css`
    width: 100%;
    max-width: 100%;
    li {
      padding: ${token.paddingXXS}px ${token.paddingXS}px;
      a {
        display: flex;
        align-items: center;
        gap: ${token.marginXXS}px;
      }
    }
  `,
  extraLink: css`
    font-size: ${token.fontSize}px;
  `,
  drawerContent: {
    position: 'relative',
    [`> ${token.antCls}-drawer-body`]: {
      scrollbarWidth: 'thin',
      scrollbarGutter: 'stable',
    },
  },
  versionWrap: css`
    margin-bottom: 1em;
  `,
  versionTitle: css`
    height: 28px;
    line-height: 28px;
    font-weight: 600;
    font-size: 20px;
    margin: 0 !important;
  `,
  versionTag: css`
    user-select: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    &:last-child {
      margin-inline-end: 0;
    }
  `,
}));

const locales = {
  cn: {
    full: '查看完整日志',
    changelog: '更新日志',
    loading: '加载中...',
    empty: '暂无更新',
    bugList: 'Bug 版本',
  },
  en: {
    full: 'Full Changelog',
    changelog: 'Changelog',
    loading: 'loading...',
    empty: 'Nothing update',
    bugList: 'Bug Versions',
  },
};

const ParseChangelog: React.FC<{ changelog: string }> = (props) => {
  const { changelog = '' } = props;

  const parsedChangelog = React.useMemo(() => {
    const nodes: React.ReactNode[] = [];

    let isQuota = false;
    let isBold = false;
    let lastStr = '';

    for (let i = 0; i < changelog.length; i += 1) {
      const char = changelog[i];
      const isDoubleAsterisk = char === '*' && changelog[i + 1] === '*';

      if (char !== '`' && !isDoubleAsterisk) {
        lastStr += char;
      } else {
        let node: React.ReactNode = lastStr;
        if (isQuota) {
          node = <code key={`code-${i}`}>{node}</code>;
        } else if (isBold) {
          node = <strong key={`strong-${i}`}>{node}</strong>;
        }

        nodes.push(node);
        lastStr = '';
        if (char === '`') {
          isQuota = !isQuota;
        } else if (isDoubleAsterisk) {
          isBold = !isBold;
          i += 1; // Skip the next '*'
        }
      }
    }

    nodes.push(lastStr);

    return nodes;
  }, [changelog]);

  return <span>{parsedChangelog}</span>;
};

const RefLinks: React.FC<{ refs: string[]; contributors: string[] }> = ({ refs, contributors }) => {
  const { styles } = useStyle();

  return (
    <>
      {refs?.map((ref) => (
        <React.Fragment key={ref}>
          <a className={styles.linkRef} key={ref} href={ref} target="_blank" rel="noreferrer">
            #{ref.match(/[^/]+$/)?.[0]}
          </a>
        </React.Fragment>
      ))}
      {contributors?.map((contributor) => (
        <React.Fragment key={contributor}>
          <a
            className={styles.linkRef}
            key={contributor}
            href={`https://github.com/${contributor}`}
            target="_blank"
            rel="noreferrer"
          >
            @{contributor}
          </a>
        </React.Fragment>
      ))}
    </>
  );
};

const RenderChangelogList: React.FC<{ changelogList: ChangelogInfo[] }> = ({ changelogList }) => {
  const elements: React.ReactNode[] = [];
  const { styles } = useStyle();
  const len = changelogList.length;
  for (let i = 0; i < len; i += 1) {
    const { refs, changelog, contributors } = changelogList[i];
    // Check if the next line is an image link and append it to the current line
    if (i + 1 < len && changelogList[i + 1].changelog.trim().startsWith('<img')) {
      const imgDom = new DOMParser().parseFromString(changelogList[i + 1].changelog, 'text/html');
      const imgElement = imgDom.querySelector<HTMLImageElement>('img');
      elements.push(
        <li key={i}>
          <ParseChangelog changelog={changelog} />
          <RefLinks refs={refs} contributors={contributors} />
          <br />
          <img
            src={imgElement?.getAttribute('src') || ''}
            alt={imgElement?.getAttribute('alt') || ''}
            width={imgElement?.getAttribute('width') || ''}
          />
        </li>,
      );
      i += 1; // Skip the next line
    } else {
      elements.push(
        <li key={i}>
          <ParseChangelog changelog={changelog} />
          <RefLinks refs={refs} contributors={contributors} />
        </li>,
      );
    }
  }
  return <ul className={styles.listWrap}>{elements}</ul>;
};

const useChangelog = (componentPath: string, lang: 'cn' | 'en'): ChangelogInfo[] => {
  const logFileName = `components-changelog-${lang}.json`;

  const data = useFetch({
    key: `component-changelog-${lang}`,
    request: () => import(`../../../preset/${logFileName}`),
  });
  return React.useMemo(() => {
    const component = componentPath.replace(/-/g, '');
    const componentName = Object.keys(data).find(
      (name) => name.toLowerCase() === component.toLowerCase(),
    );
    return data[componentName as keyof typeof data] as ChangelogInfo[];
  }, [data, componentPath]);
};

const ComponentChangelog: React.FC<Readonly<React.PropsWithChildren>> = (props) => {
  const { children } = props;
  const [locale, lang] = useLocale(locales);
  const [show, setShow] = React.useState(false);
  const { pathname } = useLocation();

  const { styles } = useStyle();

  const componentPath = pathname.match(/\/components\/([^/]+)/)?.[1] || '';

  const list = useChangelog(componentPath, lang);

  const timelineItems = React.useMemo<TimelineItemProps[]>(() => {
    const changelogMap: Record<string, ChangelogInfo[]> = {};

    list?.forEach((info) => {
      changelogMap[info.version] = changelogMap[info.version] || [];
      changelogMap[info.version].push(info);
    });

    return Object.keys(changelogMap).map((version) => {
      const changelogList = changelogMap[version];
      const bugVersionInfo = matchDeprecated(version);
      return {
        children: (
          <Typography>
            <Flex className={styles.versionWrap} justify="flex-start" align="center" gap="middle">
              <Button
                color="default"
                className={styles.versionTitle}
                variant="link"
                href={`/changelog${lang === 'cn' ? '-cn' : ''}/#${version.replace(/\./g, '').replace(/\s.*/g, '-')}`}
              >
                {version}
                {bugVersionInfo.match && (
                  <Popover
                    destroyOnHidden
                    placement="right"
                    title={<span className={styles.bugReasonTitle}>{locale.bugList}</span>}
                    content={
                      <ul className={styles.bugReasonList}>
                        {bugVersionInfo.reason.map<React.ReactNode>((reason, index) => (
                          <li key={`reason-${index}`}>
                            <a type="link" target="_blank" rel="noreferrer" href={reason}>
                              <BugOutlined />
                              {reason
                                ?.replace(/#.*$/, '')
                                ?.replace(
                                  /^https:\/\/github\.com\/ant-design\/ant-design\/(issues|pull)\//,
                                  '#',
                                )}
                            </a>
                          </li>
                        ))}
                      </ul>
                    }
                  >
                    <BugOutlined className={styles.bug} />
                  </Popover>
                )}
              </Button>
              <Tag className={styles.versionTag} bordered={false} color="blue">
                {changelogList[0]?.releaseDate}
              </Tag>
            </Flex>
            <RenderChangelogList changelogList={changelogList} />
          </Typography>
        ),
      };
    });
  }, [list]);

  const screens = Grid.useBreakpoint();
  const width = screens.md ? '48vw' : '90vw';

  if (!pathname.startsWith('/components/') || !list || !list.length) {
    return null;
  }

  return (
    <>
      {isValidElement(children) &&
        cloneElement(children as React.ReactElement<any>, {
          onClick: () => setShow(true),
        })}
      <Drawer
        destroyOnHidden
        className={styles.drawerContent}
        title={locale.changelog}
        extra={
          <Link className={styles.extraLink} to={`/changelog${lang === 'cn' ? '-cn' : ''}`}>
            {locale.full}
          </Link>
        }
        open={show}
        width={width}
        onClose={() => setShow(false)}
      >
        <Timeline items={timelineItems} />
      </Drawer>
    </>
  );
};

export default ComponentChangelog;