-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.tsx
353 lines (306 loc) · 9.54 KB
/
index.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
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
import './styles.less';
import {
EditorState,
Extension,
Compartment,
EditorSelection,
} from '@codemirror/state';
import {
drawSelection,
EditorView,
highlightActiveLine,
keymap,
} from '@codemirror/view';
import { standardKeymap, historyKeymap, history } from '@codemirror/commands';
import { insertNewlineContinueList, spaceTabBinding } from './commands';
import { markdown } from '@codemirror/lang-markdown';
import { javascriptLanguage } from '@codemirror/lang-javascript';
import { classHighlighter } from '@lezer/highlight';
import { phraseEmphasis } from './phraseEmphasis';
import { heading, headingRE } from './heading';
import { wordmarkTheme } from './wordmarkTheme';
import { link } from './link';
import { listTask } from './listTask';
import { image } from './image';
import { blockquote } from './blockquote';
import { codeblock } from './codeblock';
import { webkitPlugins } from './webkit';
import { lightColor, darkColor } from './colorTheme';
import { hideActiveLine, showActiveLine } from './activeLine';
import { fontSize, fontFamily, letterSpacing } from './layoutTheme';
import { frontMatter } from './frontMatter';
import {
syntaxHighlighting,
defaultHighlightStyle,
} from '@codemirror/language';
const extensions = [
wordmarkTheme(),
history(),
keymap.of(standardKeymap),
keymap.of(historyKeymap),
keymap.of([spaceTabBinding, insertNewlineContinueList]),
EditorView.lineWrapping,
markdown({
defaultCodeLanguage: javascriptLanguage,
// Disable markdown keymaps.
addKeymap: false,
}),
syntaxHighlighting(defaultHighlightStyle),
syntaxHighlighting(classHighlighter),
EditorView.contentAttributes.of({ spellcheck: 'true' }),
drawSelection(),
listTask(),
phraseEmphasis(),
heading(),
link(),
image(),
blockquote(),
codeblock(),
frontMatter(),
// This must be after hr as otherwise it will alter the class names.
highlightActiveLine(),
webkitPlugins(),
];
// If empty string then it's just follow system.
type ThemeColor = '' | 'Light' | 'Dark';
//https://discuss.codemirror.net/t/codemirror-next-0-18-0/2983
let colorThemeComp = new Compartment();
const colorThemeExtension = colorThemeComp.of(getColor());
let activeLineComp = new Compartment();
const activeLineExtension = activeLineComp.of(hideActiveLine());
let fontSizeComp = new Compartment();
const fontSizeExtension = fontSizeComp.of(fontSize(16));
let letterSpacingComp = new Compartment();
const letterSpacingExtension = letterSpacingComp.of(letterSpacing(0));
let fontFamilyComp = new Compartment();
const fontFamilyExtension = fontFamilyComp.of(fontFamily());
// State for debugging.
let debugState = EditorState.create({
doc: `---
layout: post
categories: [intro, admin]
---
# Welcome to [Markword](https://github.com/fuermosi777/markword)
## Introduction
Markword is a **WYSIWYG** *and* _lightweight_ [markdown](https://daringfireball.net/projects/markdown/) editor based on [Codemirror 6](https://codemirror.net/6/). It ~~doesn't~~ supports direct <http://google.com> links, and \`inline codes\`.
## Features
- Real time markdown render
- Publish to Github pages (Jekyll) and Medium
- Apple Silicon native support
1. Support ordered list
2. When Enter
---
- [ ] Panaba
- [x] Floor makeover
![photos](https://picsum.photos/200 =100x)
\`\`\`js
// This function is for demo purpose.
function fibonacci(n) {
for (let i = 0; i < n.length; i++) {
console.log("Fi: ", fibonacci(4));
}
return n < 1 ? 0 : n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2);
}
\`\`\`
> Quotes
> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
### Heading 3 is possible
#### Heading 4
###### Heading 6 Is also possible
`,
extensions: makeExtensions(),
});
// Get color theme based on current environment.
// If name is given, use it. Otherwise respect the name from URL params.
// Otherwise respect system appearance.
function getColor(name?: ThemeColor): Extension {
if (name) {
return name === 'Dark' ? darkColor() : lightColor();
}
// Override if forced set in the url params.
// This is for testing purpose, shouldn't be used by the client.
const urlParams = new URLSearchParams(window.location.search);
const themeFromUrl = urlParams.get('theme') as ThemeColor;
if (themeFromUrl) {
return themeFromUrl === 'Dark' ? darkColor() : lightColor();
}
// If color is not given, and doesn't in url, just respect system.
let color = lightColor();
if (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
) {
color = darkColor();
}
return color;
}
function makeExtensions() {
return [
...extensions,
colorThemeExtension,
activeLineExtension,
fontSizeExtension,
fontFamilyExtension,
letterSpacingExtension,
];
}
// https://stackoverflow.com/a/64752311
function decodeBase64(base64: string) {
const text = window.atob(base64);
const length = text.length;
const bytes = new Uint8Array(length);
for (let i = 0; i < length; i++) {
bytes[i] = text.charCodeAt(i);
}
const decoder = new TextDecoder(); // default is utf-8
return decoder.decode(bytes);
}
let view: EditorView;
window
.matchMedia('(prefers-color-scheme: dark)')
.addEventListener('change', (event) => {
if (event.matches) {
ClientUpdateTheme('Dark');
} else {
ClientUpdateTheme('Light');
}
});
if (location.hostname === 'localhost' || location.hostname === '127.0.0.1') {
view = new EditorView({
state: debugState,
parent: document.getElementById('container')!,
});
}
// Start a new editor with base64 encoded content.
function ClientInitEditor(doc: string) {
if (view) {
view.destroy();
}
view = new EditorView({
state: EditorState.create({
doc: decodeBase64(doc),
extensions: makeExtensions(),
}),
parent: document.getElementById('container')!,
});
}
// Update the content with new base64 encoded content.
function ClientUpdateContent(doc: string) {
if (view) {
view.dispatch({
changes: {
from: 0,
to: view.state.doc.length,
insert: decodeBase64(doc),
},
});
}
}
// Updates the theme for the editor.
function ClientUpdateTheme(name: ThemeColor) {
if (view) {
view.dispatch({
effects: colorThemeComp.reconfigure(getColor(name)),
});
}
}
function ClientUpdateFontSize(value: number) {
if (view) {
view.dispatch({
effects: fontSizeComp.reconfigure(fontSize(value)),
});
}
}
// Value starts from 0, in double.
function ClientUpdateLetterSpacing(value: number) {
if (view) {
view.dispatch({
effects: letterSpacingComp.reconfigure(letterSpacing(value)),
});
}
}
function ClientUpdateFont(name: string) {
if (view) {
view.dispatch({
effects: fontFamilyComp.reconfigure(fontFamily(name)),
});
}
}
function ClientToggleActiveLine(on: boolean) {
if (view) {
view.dispatch({
effects: activeLineComp.reconfigure(
on ? showActiveLine() : hideActiveLine(),
),
});
}
}
function ClientToggleHeading(heading: number) {
if (view) {
view.dispatch(
view.state.changeByRange((range) => {
let line = view.state.doc.lineAt(range.from);
let changes = [];
// First remove #s is there are.
let removed = line.text.replace(headingRE, '');
changes.push({ from: line.from, to: line.to, insert: removed });
let added = Array(heading + 1).join('#') + ' ';
changes.push({ from: line.from, insert: added });
return {
changes,
range: EditorSelection.range(range.from, range.to),
};
}),
);
}
}
// TODO: add remove inline format.
function ClientToggleInlineFormat(indicators: string) {
if (view) {
view.dispatch(
view.state.changeByRange((range) => {
return {
changes: [
{ from: range.from, insert: indicators },
{ from: range.to, insert: indicators },
],
range: EditorSelection.range(
range.from,
range.to + indicators.length * 2,
),
};
}),
);
}
}
// For example, insert "**" and move cursor inbetween two *.
function ClientInsert(text: string, offset = 0) {
if (view) {
view.dispatch(
view.state.changeByRange((range) => {
return {
changes: [{ from: range.from, insert: text }],
range: EditorSelection.range(
range.from + text.length - offset,
range.from + text.length - offset,
),
};
}),
);
}
}
const _global = (window /* browser */ || global) /* node */ as any;
_global.ClientInitEditor = ClientInitEditor;
_global.ClientUpdateContent = ClientUpdateContent;
_global.ClientToggleActiveLine = ClientToggleActiveLine;
_global.ClientUpdateFontSize = ClientUpdateFontSize;
_global.ClientUpdateLetterSpacing = ClientUpdateLetterSpacing;
_global.ClientUpdateFont = ClientUpdateFont;
_global.ClientToggleHeading = ClientToggleHeading;
_global.ClientToggleInlineFormat = ClientToggleInlineFormat;
_global.ClientInsert = ClientInsert;
// @ts-ignore
const webkit = window.webkit;
if (webkit) {
webkit.messageHandlers.Loaded.postMessage('');
}