-
-
Notifications
You must be signed in to change notification settings - Fork 377
/
Demo.tsx
78 lines (67 loc) 路 2.43 KB
/
Demo.tsx
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
/* Copyright 2021, Milkdown by Mirone. */
import React from 'react';
import { useSearchParams } from 'react-router-dom';
import { i18nConfig, Local } from '../../route';
import { decode } from '../../utils/share';
import { Mode } from '../constant';
import { localCtx } from '../Context';
import { MilkdownRef, OnlineEditor } from '../MilkdownEditor/OnlineEditor';
import { CodeMirror, CodeMirrorRef } from './CodeMirror';
import className from './style.module.css';
type DemoProps = {
mode: Mode;
isDarkMode: boolean;
};
const importDemo = (local: Local) => {
const route = i18nConfig[local].route;
const path = ['index', route].filter((x) => x).join('.');
return import(`./content/${path}.md`);
};
export const Demo = ({ mode }: DemoProps) => {
const ref = React.useRef<HTMLDivElement>(null);
const lockCode = React.useRef(false);
const milkdownRef = React.useRef<MilkdownRef>(null);
const codeMirrorRef = React.useRef<CodeMirrorRef>(null);
const local = React.useContext(localCtx);
const [md, setMd] = React.useState('');
const [searchParams] = useSearchParams();
React.useEffect(() => {
const text = searchParams.get('text');
if (text) {
setMd(decode(text));
return;
}
importDemo(local)
.then((x) => {
setMd(x.default);
return;
})
.catch(console.error);
}, [local, searchParams]);
const milkdownListener = React.useCallback((markdown: string) => {
const lock = lockCode.current;
if (lock) return;
const { current } = codeMirrorRef;
if (!current) return;
current.update(markdown);
}, []);
const onCodeChange = React.useCallback((getCode: () => string) => {
const { current } = milkdownRef;
if (!current) return;
const value = getCode();
current.update(value);
}, []);
const classes = [
className['container'],
mode === Mode.TwoSide ? className['twoSide'] : '',
mode === Mode.TwoSide ? 'two-side' : '',
].join(' ');
return !md.length ? null : (
<div ref={ref} className={classes}>
<div className={className['milk']}>
<OnlineEditor ref={milkdownRef} content={md} onChange={milkdownListener} />
</div>
<CodeMirror ref={codeMirrorRef} value={md} onChange={onCodeChange} lock={lockCode} />
</div>
);
};