-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript-code.tsx
More file actions
464 lines (429 loc) · 15.4 KB
/
Copy pathscript-code.tsx
File metadata and controls
464 lines (429 loc) · 15.4 KB
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import React, { useEffect, useRef, useState } from 'react';
import { Compartment, EditorState, type Extension } from '@codemirror/state';
import {
crosshairCursor,
drawSelection,
dropCursor,
EditorView,
highlightActiveLine,
highlightActiveLineGutter,
highlightSpecialChars,
keymap,
lineNumbers,
placeholder as cmPlaceholder,
rectangularSelection,
} from '@codemirror/view';
import {
defaultKeymap,
history,
historyKeymap,
indentWithTab,
} from '@codemirror/commands';
import {
bracketMatching,
defaultHighlightStyle,
foldGutter,
foldKeymap,
HighlightStyle,
indentOnInput,
syntaxHighlighting,
} from '@codemirror/language';
import { oneDark } from '@codemirror/theme-one-dark';
import { tags } from '@lezer/highlight';
import {
autocompletion,
completionKeymap,
} from '@codemirror/autocomplete';
import type { ScriptCodeEditorProps, LanguageConfig } from './types';
import { createCompletionSource } from './autocomplete';
import { resolveLanguageConfig } from './languages';
import { TypePanel } from './type-panel';
import { Toolbar } from './components/toolbar';
import { ExpandSidebarButton } from './components/expand-sidebar-button';
const darkHighlightStyle = HighlightStyle.define([
{ tag: tags.keyword, color: '#c678dd' },
{ tag: tags.operator, color: '#56b6c2' },
{ tag: tags.variableName, color: '#e5c07b' },
{ tag: tags.string, color: '#98c379' },
{ tag: tags.comment, color: '#5c6370', fontStyle: 'italic' },
{ tag: tags.number, color: '#d19a66' },
{ tag: tags.bool, color: '#d19a66' },
{ tag: tags.null, color: '#d19a66' },
{ tag: tags.propertyName, color: '#e06c75' },
{ tag: tags.function(tags.variableName), color: '#61afef' },
{ tag: tags.definition(tags.variableName), color: '#e5c07b' },
{ tag: tags.typeName, color: '#e5c07b' },
{ tag: tags.className, color: '#e5c07b' },
{ tag: tags.annotation, color: '#d19a66' },
]);
function buildThemeExtensions(theme: 'dark' | 'light'): Extension[] {
const isDark = theme === 'dark';
const exts: Extension[] = [];
if (isDark) {
exts.push(oneDark);
exts.push(syntaxHighlighting(darkHighlightStyle));
} else {
exts.push(syntaxHighlighting(defaultHighlightStyle));
}
exts.push(
EditorView.theme({
'.cm-tooltip.cm-tooltip-autocomplete': {
backgroundColor: isDark ? '#21252b' : '#ffffff',
borderColor: isDark ? '#434343' : '#d9d9d9',
borderRadius: '4px',
boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
overflow: 'hidden',
},
'.cm-tooltip-autocomplete > ul > li': {
padding: '4px 8px',
color: isDark ? '#abb2bf' : '#333',
},
'.cm-tooltip-autocomplete > ul > li[aria-selected]': {
backgroundColor: isDark ? '#2c313a' : '#e6f4ff',
color: isDark ? '#fff' : '#000',
},
'.cm-completionLabel': { fontFamily: 'monospace' },
'.cm-completionDetail': {
color: isDark ? '#7f848e' : '#888',
fontStyle: 'normal',
marginLeft: '8px',
},
'.cm-completionInfo': {
backgroundColor: isDark ? '#282c34' : '#fafafa',
borderColor: isDark ? '#434343' : '#d9d9d9',
color: isDark ? '#abb2bf' : '#333',
padding: '6px 8px',
},
'.cm-completionIcon': { width: '1.2em', fontSize: '0.9em', paddingRight: '4px' },
'.cm-completionIcon-property::after': { content: '"F"', color: '#61afef' },
'.cm-completionIcon-function::after': { content: '"M"', color: '#c678dd' },
'.cm-completionIcon-variable::after': { content: '"V"', color: '#e5c07b' },
'.cm-completionIcon-keyword::after': { content: '"K"', color: '#56b6c2' },
})
);
return exts;
}
function buildAutocompleteExt(
languageConfig: LanguageConfig,
metadata: ScriptCodeEditorProps['metadata']
): Extension {
return autocompletion({
override: [createCompletionSource(languageConfig, metadata)],
activateOnTyping: true,
icons: true,
});
}
/** 构建布局扩展 — 全屏时取消高度限制 */
function buildLayoutExtensions(
fontSize: number,
minHeight: number,
maxHeight: number,
isFullscreen: boolean
): Extension {
if (isFullscreen) {
return EditorView.theme({
'&': { fontSize: `${fontSize}px`, height: '100%' },
'.cm-scroller': {
overflow: 'auto',
flex: '1',
minHeight: '0',
},
'.cm-content': { fontFamily: 'monospace' },
});
}
return EditorView.theme({
'&': { fontSize: `${fontSize}px` },
'.cm-scroller': {
overflow: 'auto',
minHeight: `${minHeight}px`,
maxHeight: `${maxHeight}px`,
},
'.cm-content': { fontFamily: 'monospace', minHeight: `${minHeight}px` },
'.cm-gutters': { minHeight: `${minHeight}px` },
});
}
export const ScriptCodeEditor: React.FC<ScriptCodeEditorProps> = (props) => {
const {
value,
readonly = false,
onChange,
onCompile,
onFormat,
onThemeChange,
language = 'groovy',
placeholder,
defaultTheme,
title,
metadata,
defaultSidebarOpen,
enableThemeToggle,
enableFormat,
enableCompile,
enableFullscreen,
toolbar,
toolbarExtra,
options = {},
} = props;
const { fontSize = 14, minHeight = 300, maxHeight = 300 } = options;
// 解析语言配置(字符串名或自定义 LanguageConfig)
const languageConfig = resolveLanguageConfig(language);
const effectivePlaceholder = placeholder ?? languageConfig.placeholder ?? '';
// 合并格式化器:onFormat prop 优先,fallback 到 languageConfig.formatter
const effectiveFormatter = onFormat ?? (
languageConfig.formatter
? (code: string) => languageConfig.formatter!(code)
: undefined
);
// 内部主题状态(prop 仅作初始值)
const [internalTheme, setInternalTheme] = useState<'dark' | 'light'>(defaultTheme ?? 'dark');
// 外部 defaultTheme prop 变化时同步内部状态
useEffect(() => {
if (defaultTheme !== undefined) {
setInternalTheme(defaultTheme);
}
}, [defaultTheme]);
const editorContainerRef = useRef<HTMLDivElement>(null);
const viewRef = useRef<EditorView | null>(null);
const themeCompartmentRef = useRef(new Compartment());
const autocompleteCompartmentRef = useRef(new Compartment());
const layoutCompartmentRef = useRef(new Compartment());
const languageCompartmentRef = useRef(new Compartment());
// 用 ref 持有回调,避免闭包过期
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const metadataRef = useRef(metadata);
metadataRef.current = metadata;
// 侧边栏状态
const [sidebarOpen, setSidebarOpen] = useState(
defaultSidebarOpen ?? (metadata != null)
);
const [panelWidth, setPanelWidth] = useState(300);
// 全屏状态
const [isFullscreen, setIsFullscreen] = useState(false);
// ── 全屏时锁定 body 滚动 ──────────────────────────────
useEffect(() => {
if (isFullscreen) {
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
return () => { document.body.style.overflow = prev; };
}
}, [isFullscreen]);
// ── ESC 键退出全屏 ──────────────────────────────────────
useEffect(() => {
if (!isFullscreen) return;
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') setIsFullscreen(false);
};
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}, [isFullscreen]);
// ── 创建编辑器(仅在首次挂载和布局属性变化时) ──────────
useEffect(() => {
if (!editorContainerRef.current) return;
const themeCompartment = themeCompartmentRef.current;
const acCompartment = autocompleteCompartmentRef.current;
const layoutCompartment = layoutCompartmentRef.current;
const langCompartment = languageCompartmentRef.current;
const extensions: Extension[] = [
lineNumbers(),
highlightActiveLineGutter(),
highlightSpecialChars(),
history(),
foldGutter(),
drawSelection(),
dropCursor(),
EditorState.allowMultipleSelections.of(true),
indentOnInput(),
bracketMatching(),
rectangularSelection(),
crosshairCursor(),
highlightActiveLine(),
keymap.of([
...defaultKeymap,
...historyKeymap,
...foldKeymap,
...completionKeymap,
indentWithTab,
]),
// 语言扩展放入 compartment,切换语言时热更新不重建编辑器
langCompartment.of(languageConfig.extension()),
cmPlaceholder(effectivePlaceholder),
EditorView.updateListener.of((update) => {
if (update.docChanged && onChangeRef.current) {
onChangeRef.current(update.state.doc.toString());
}
}),
// 布局扩展放入 compartment,全屏时热更新高度约束
layoutCompartment.of(buildLayoutExtensions(fontSize, minHeight, maxHeight, false)),
// 主题相关扩展放入 compartment,热更新不重建编辑器
themeCompartment.of(buildThemeExtensions(internalTheme)),
// 自动补全放入 compartment
acCompartment.of(buildAutocompleteExt(languageConfig, metadataRef.current)),
];
if (readonly) {
extensions.push(EditorState.readOnly.of(true));
}
const state = EditorState.create({ doc: value, extensions });
const view = new EditorView({ state, parent: editorContainerRef.current });
viewRef.current = view;
return () => { view.destroy(); };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fontSize, minHeight, maxHeight, effectivePlaceholder, readonly]);
// ── 同步外部 value 变化 ──────────────────────────────────
useEffect(() => {
if (viewRef.current && value !== viewRef.current.state.doc.toString()) {
viewRef.current.dispatch({
changes: {
from: 0,
to: viewRef.current.state.doc.length,
insert: value,
},
});
}
}, [value]);
// ── theme 变化时热更新(不重建编辑器) ──────────────────
useEffect(() => {
if (!viewRef.current) return;
viewRef.current.dispatch({
effects: themeCompartmentRef.current.reconfigure(
buildThemeExtensions(internalTheme)
),
});
}, [internalTheme]);
// ── metadata 变化时热更新补全源 ──────────────────────────
useEffect(() => {
if (!viewRef.current) return;
viewRef.current.dispatch({
effects: autocompleteCompartmentRef.current.reconfigure(
buildAutocompleteExt(languageConfig, metadata)
),
});
}, [metadata, languageConfig]);
// ── language 变化时热更新语言扩展和补全源(不重建编辑器) ──
useEffect(() => {
if (!viewRef.current) return;
viewRef.current.dispatch({
effects: [
languageCompartmentRef.current.reconfigure(languageConfig.extension()),
autocompleteCompartmentRef.current.reconfigure(
buildAutocompleteExt(languageConfig, metadata)
),
],
});
}, [languageConfig]);
// ── 全屏/尺寸变化时热更新布局约束(不重建编辑器) ────────
useEffect(() => {
if (!viewRef.current) return;
viewRef.current.dispatch({
effects: layoutCompartmentRef.current.reconfigure(
buildLayoutExtensions(fontSize, minHeight, maxHeight, isFullscreen)
),
});
requestAnimationFrame(() => {
viewRef.current?.requestMeasure();
});
}, [isFullscreen, fontSize, minHeight, maxHeight]);
// ── 渲染 ──────────────────────────────────────────────────
const isDark = internalTheme === 'dark';
const borderColor = isDark ? '#434343' : '#d9d9d9';
const expandBtnBg = isDark ? '#2c313a' : '#f0f0f0';
const expandBtnColor = isDark ? '#abb2bf' : '#666';
const handleCompile = () => {
if (onCompile && viewRef.current) {
onCompile(viewRef.current.state.doc.toString());
}
};
const handleFormat = () => {
if (!viewRef.current) return;
const code = viewRef.current.state.doc.toString();
const formatter = effectiveFormatter;
if (!formatter) return;
const formatted = formatter(code);
if (typeof formatted === 'string' && formatted !== code) {
viewRef.current.dispatch({
changes: { from: 0, to: viewRef.current.state.doc.length, insert: formatted },
});
}
};
return (
<div
className="script-editor"
style={
isFullscreen
? {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 9999,
backgroundColor: isDark ? '#21252b' : '#ffffff',
display: 'flex',
flexDirection: 'column',
}
: { display: 'flex', flexDirection: 'column' }
}
>
{/* ── 工具栏 ─────────────────────────────────────── */}
<Toolbar
title={title}
theme={internalTheme}
onThemeChange={(next) => {
setInternalTheme(next);
onThemeChange?.(next);
}}
enableThemeToggle={enableThemeToggle}
enableFormat={enableFormat}
onFormat={readonly || !effectiveFormatter ? undefined : (onFormat ?? handleFormat)}
enableCompile={enableCompile}
onCompile={onCompile ? handleCompile : undefined}
enableFullscreen={enableFullscreen}
isFullscreen={isFullscreen}
onToggleFullscreen={() => setIsFullscreen((prev) => !prev)}
toolbar={toolbar}
toolbarExtra={toolbarExtra}
description={metadata?.description}
/>
{/* ── 编辑器 + 侧边栏 ───────────────────────────── */}
<div
className="script-editor-body"
style={{
display: 'flex',
border: `1px solid ${borderColor}`,
borderTop: 'none',
borderRadius: isFullscreen ? 0 : '0 0 6px 6px',
overflow: 'hidden',
flex: isFullscreen ? 1 : undefined,
minHeight: isFullscreen ? 0 : undefined,
}}
>
<div className="script-editor-code" style={{ flex: 1, minWidth: 0, position: 'relative' }}>
{metadata && !sidebarOpen && (
<ExpandSidebarButton
borderColor={borderColor}
expandBtnColor={expandBtnColor}
expandBtnBg={expandBtnBg}
onClick={() => setSidebarOpen(true)}
/>
)}
<div
ref={editorContainerRef}
className="script-editor-codemirror"
style={isFullscreen ? { height: '100%' } : undefined}
/>
</div>
{metadata && sidebarOpen && (
<TypePanel
metadata={metadata}
theme={internalTheme}
minHeight={isFullscreen ? undefined : minHeight}
maxHeight={isFullscreen ? undefined : maxHeight}
width={panelWidth}
onWidthChange={setPanelWidth}
onCollapse={() => setSidebarOpen(false)}
/>
)}
</div>
</div>
);
};