@cloud-ru/ds-code-editor 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/LICENSE +201 -0
- package/README.md +365 -0
- package/dist/cjs/components/AsyncCodeEditor/AsyncCodeEditor.d.ts +22 -0
- package/dist/cjs/components/AsyncCodeEditor/AsyncCodeEditor.js +33 -0
- package/dist/cjs/components/AsyncCodeEditor/index.d.ts +1 -0
- package/dist/cjs/components/AsyncCodeEditor/index.js +17 -0
- package/dist/cjs/components/CodeEditor/CodeEditor.d.ts +23 -0
- package/dist/cjs/components/CodeEditor/CodeEditor.js +183 -0
- package/dist/cjs/components/CodeEditor/hooks.d.ts +43 -0
- package/dist/cjs/components/CodeEditor/hooks.js +103 -0
- package/dist/cjs/components/CodeEditor/index.d.ts +1 -0
- package/dist/cjs/components/CodeEditor/index.js +17 -0
- package/dist/cjs/components/CodeEditor/styles.module.css +49 -0
- package/dist/cjs/components/LazyCodeEditor/LazyCodeEditor.d.ts +13 -0
- package/dist/cjs/components/LazyCodeEditor/LazyCodeEditor.js +31 -0
- package/dist/cjs/components/LazyCodeEditor/index.d.ts +1 -0
- package/dist/cjs/components/LazyCodeEditor/index.js +17 -0
- package/dist/cjs/components/LazyCodeEditor/styles.module.css +7 -0
- package/dist/cjs/components/index.d.ts +3 -0
- package/dist/cjs/components/index.js +19 -0
- package/dist/cjs/constants.d.ts +113 -0
- package/dist/cjs/constants.js +132 -0
- package/dist/cjs/index.d.ts +5 -0
- package/dist/cjs/index.js +21 -0
- package/dist/cjs/loader.d.ts +10 -0
- package/dist/cjs/loader.js +17 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/style.css +56 -0
- package/dist/cjs/types.d.ts +67 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/utils.d.ts +11 -0
- package/dist/cjs/utils.js +94 -0
- package/dist/cjs/withMonaco.d.ts +6 -0
- package/dist/cjs/withMonaco.js +14 -0
- package/dist/esm/components/AsyncCodeEditor/AsyncCodeEditor.d.ts +22 -0
- package/dist/esm/components/AsyncCodeEditor/AsyncCodeEditor.js +29 -0
- package/dist/esm/components/AsyncCodeEditor/index.d.ts +1 -0
- package/dist/esm/components/AsyncCodeEditor/index.js +1 -0
- package/dist/esm/components/CodeEditor/CodeEditor.d.ts +23 -0
- package/dist/esm/components/CodeEditor/CodeEditor.js +177 -0
- package/dist/esm/components/CodeEditor/hooks.d.ts +43 -0
- package/dist/esm/components/CodeEditor/hooks.js +99 -0
- package/dist/esm/components/CodeEditor/index.d.ts +1 -0
- package/dist/esm/components/CodeEditor/index.js +1 -0
- package/dist/esm/components/CodeEditor/styles.module.css +49 -0
- package/dist/esm/components/LazyCodeEditor/LazyCodeEditor.d.ts +13 -0
- package/dist/esm/components/LazyCodeEditor/LazyCodeEditor.js +25 -0
- package/dist/esm/components/LazyCodeEditor/index.d.ts +1 -0
- package/dist/esm/components/LazyCodeEditor/index.js +1 -0
- package/dist/esm/components/LazyCodeEditor/styles.module.css +7 -0
- package/dist/esm/components/index.d.ts +3 -0
- package/dist/esm/components/index.js +3 -0
- package/dist/esm/constants.d.ts +113 -0
- package/dist/esm/constants.js +129 -0
- package/dist/esm/index.d.ts +5 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/loader.d.ts +10 -0
- package/dist/esm/loader.js +12 -0
- package/dist/esm/style.css +56 -0
- package/dist/esm/types.d.ts +67 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/utils.d.ts +11 -0
- package/dist/esm/utils.js +86 -0
- package/dist/esm/withMonaco.d.ts +6 -0
- package/dist/esm/withMonaco.js +10 -0
- package/dist/tsconfig.cjs.tsbuildinfo +1 -0
- package/dist/tsconfig.esm.tsbuildinfo +1 -0
- package/package.json +56 -0
- package/src/components/AsyncCodeEditor/AsyncCodeEditor.tsx +33 -0
- package/src/components/AsyncCodeEditor/index.ts +1 -0
- package/src/components/CodeEditor/CodeEditor.tsx +297 -0
- package/src/components/CodeEditor/hooks.ts +138 -0
- package/src/components/CodeEditor/index.ts +1 -0
- package/src/components/CodeEditor/styles.module.scss +66 -0
- package/src/components/LazyCodeEditor/LazyCodeEditor.tsx +39 -0
- package/src/components/LazyCodeEditor/index.ts +1 -0
- package/src/components/LazyCodeEditor/styles.module.scss +10 -0
- package/src/components/index.ts +3 -0
- package/src/constants.ts +135 -0
- package/src/index.ts +5 -0
- package/src/loader.ts +20 -0
- package/src/types.ts +73 -0
- package/src/utils.ts +94 -0
- package/src/withMonaco.ts +14 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { Spinner } from '@cloud-ru/ds-loader';
|
|
3
|
+
import { useThemeContext } from '@cloud-ru/ds-theme';
|
|
4
|
+
import { Typography } from '@cloud-ru/ds-typography';
|
|
5
|
+
import { CopyButton } from '@cloud-ru/ds-uikit-product-copy';
|
|
6
|
+
import { extractSupportProps, isBrowser, useLayoutEffect } from '@cloud-ru/ds-utils';
|
|
7
|
+
import { Editor, useMonaco } from '@monaco-editor/react';
|
|
8
|
+
import cn from 'classnames';
|
|
9
|
+
import { useCallback, useId, useMemo, useRef, useState } from 'react';
|
|
10
|
+
import { CODE_EDITOR_OPTIONS, DEFAULT_THEME_OPTIONS, DEFAULT_THEME_VALUES, TEST_IDS } from '../../constants.js';
|
|
11
|
+
import { hexWithAlpha, isDark, uppercaseFirstLetter } from '../../utils.js';
|
|
12
|
+
import { useApplyJsonSchema, useCalculatedThemeValues } from './hooks.js';
|
|
13
|
+
import styles from './styles.module.css';
|
|
14
|
+
// monaco theme parser принимает только hex (#RRGGBB / #RRGGBBAA);
|
|
15
|
+
// rgba(...) он не понимает и подставляет fail-safe red. См. utils.hexWithAlpha.
|
|
16
|
+
const withAlpha = hexWithAlpha;
|
|
17
|
+
function CodeEditorClient({ themeName, className, theme, options, loading, background = true, onMount, language, onCopyClick, hasHeader, showRowNumber = true, value, defaultValue, ...props }) {
|
|
18
|
+
const monaco = useMonaco();
|
|
19
|
+
// TODO(FF-8312): live theme switch без перезагрузки страницы. useThemeContext
|
|
20
|
+
// отдаёт класс из стора провайдера, который в микрофронт-режиме обновляется
|
|
21
|
+
// через явный re-publish от хост-приложения; в standalone (Storybook, docs) при
|
|
22
|
+
// toggle темы CSS-классы DS-провайдера меняются на корне, но themeClassName
|
|
23
|
+
// отсюда не пересчитывается — нужен либо MutationObserver на родительские
|
|
24
|
+
// theme-классы, либо подписка на сам тогглер. Сейчас обходится reload'ом.
|
|
25
|
+
const { themeClassName } = useThemeContext();
|
|
26
|
+
const [wrapperElement, setWrapperElement] = useState(null);
|
|
27
|
+
const setWrapperRef = useCallback((el) => setWrapperElement(el), []);
|
|
28
|
+
const instanceId = useId();
|
|
29
|
+
const unmountedRef = useRef(false);
|
|
30
|
+
const { jsonSchemaProps, jsonSchemaOptions } = useApplyJsonSchema(language, 'jsonSchema' in props ? props.jsonSchema : undefined);
|
|
31
|
+
useLayoutEffect(() => () => {
|
|
32
|
+
unmountedRef.current = true;
|
|
33
|
+
}, []);
|
|
34
|
+
const onEditorMount = useCallback((editor, monacoInstance) => {
|
|
35
|
+
if (monacoInstance && isBrowser()) {
|
|
36
|
+
// document.fonts.ready resolves в произвольный момент; не вызываем
|
|
37
|
+
// remeasureFonts, если редактор уже размонтирован — иначе монако
|
|
38
|
+
// обращается к disposed editor instance.
|
|
39
|
+
document?.fonts?.ready.then(() => {
|
|
40
|
+
if (!unmountedRef.current)
|
|
41
|
+
monacoInstance.editor.remeasureFonts();
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
onMount?.(editor, monacoInstance);
|
|
45
|
+
}, [onMount]);
|
|
46
|
+
const themeValues = useCalculatedThemeValues({
|
|
47
|
+
themeName: themeName ?? themeClassName,
|
|
48
|
+
stylesOriginNode: wrapperElement,
|
|
49
|
+
});
|
|
50
|
+
const themeDataWithoutBase = useMemo(() => ({
|
|
51
|
+
// inherit=true — наследуем дефолты monaco (vs/vs-dark) под слоты,
|
|
52
|
+
// которые не задаются явно (например, hint colors, error squiggles).
|
|
53
|
+
// Иначе monaco подставляет жёсткие фолбэки, не вяжущиеся с темой DS.
|
|
54
|
+
inherit: true,
|
|
55
|
+
...(themeValues?.palette
|
|
56
|
+
? {
|
|
57
|
+
semanticTokenColors: {
|
|
58
|
+
parameter: { foreground: themeValues.palette.violet },
|
|
59
|
+
property: { foreground: themeValues.palette.blue },
|
|
60
|
+
enumMember: { foreground: themeValues.palette.blue },
|
|
61
|
+
variable: { foreground: themeValues.palette.red },
|
|
62
|
+
'variable.constant': { foreground: themeValues.palette.orange },
|
|
63
|
+
function: { foreground: themeValues.palette.blue },
|
|
64
|
+
method: { foreground: themeValues.palette.blue },
|
|
65
|
+
type: { foreground: themeValues.palette.yellow },
|
|
66
|
+
class: { foreground: themeValues.palette.yellow },
|
|
67
|
+
},
|
|
68
|
+
rules: [
|
|
69
|
+
{ foreground: themeValues.palette.green, token: 'comment' },
|
|
70
|
+
{ foreground: themeValues.palette.green, token: 'string' },
|
|
71
|
+
// JSON: keys — blue, values — green
|
|
72
|
+
{ foreground: themeValues.palette.blue, token: 'string.key.json' },
|
|
73
|
+
{ foreground: themeValues.palette.green, token: 'string.value.json' },
|
|
74
|
+
{ foreground: themeValues.palette.orange, token: 'number' },
|
|
75
|
+
{ foreground: themeValues.palette.violet, token: 'keyword' },
|
|
76
|
+
{ foreground: themeValues.palette.violet, token: 'keyword.json' },
|
|
77
|
+
{ foreground: themeValues.palette.blue, token: 'operator' },
|
|
78
|
+
{ foreground: themeValues.palette.red, token: 'variable' },
|
|
79
|
+
{ foreground: themeValues.palette.yellow, token: 'type' },
|
|
80
|
+
{ foreground: themeValues.palette.red, token: 'regexp' },
|
|
81
|
+
{ foreground: themeValues.palette.red, token: 'invalid' },
|
|
82
|
+
{ foreground: themeValues.text.main, token: 'delimiter' },
|
|
83
|
+
{ foreground: themeValues.text.main, token: 'delimiter.bracket' },
|
|
84
|
+
{ foreground: themeValues.text.main, token: 'identifier' },
|
|
85
|
+
{ foreground: themeValues.text.main, token: '' },
|
|
86
|
+
],
|
|
87
|
+
colors: {
|
|
88
|
+
focusBorder: '#00000000',
|
|
89
|
+
'editor.background': '#00000000',
|
|
90
|
+
'editor.foreground': themeValues.text.main,
|
|
91
|
+
'editor.selectionBackground': themeValues.stateLayer.border,
|
|
92
|
+
// inactive (на blur) — наследует тёмный дефолт vs; задаём явно
|
|
93
|
+
// тот же stateLayer.border, чтобы blur не «темнил» выделение.
|
|
94
|
+
'editor.inactiveSelectionBackground': themeValues.stateLayer.border,
|
|
95
|
+
'editor.lineHighlightBackground': themeValues.stateLayer.filled,
|
|
96
|
+
'editor.lineHighlightBorder': '#00000000',
|
|
97
|
+
'editorCursor.foreground': themeValues.brand.accent,
|
|
98
|
+
'editorWhitespace.foreground': themeValues.text.secondary,
|
|
99
|
+
'scrollbarSlider.background': withAlpha(themeValues.text.main, 0.16),
|
|
100
|
+
'scrollbarSlider.hoverBackground': withAlpha(themeValues.text.main, 0.28),
|
|
101
|
+
'scrollbarSlider.activeBackground': withAlpha(themeValues.text.main, 0.4),
|
|
102
|
+
'editorLineNumber.foreground': themeValues.text.secondary,
|
|
103
|
+
'editorLineNumber.activeForeground': themeValues.text.main,
|
|
104
|
+
// monaco red-rainbow bracket pair colorization → нейтрализуем
|
|
105
|
+
// на theme-уровне (опция bracketPairColorization не всегда
|
|
106
|
+
// отключает встроенные CSS-классы).
|
|
107
|
+
'editorBracketHighlight.foreground1': themeValues.text.main,
|
|
108
|
+
'editorBracketHighlight.foreground2': themeValues.text.main,
|
|
109
|
+
'editorBracketHighlight.foreground3': themeValues.text.main,
|
|
110
|
+
'editorBracketHighlight.foreground4': themeValues.text.main,
|
|
111
|
+
'editorBracketHighlight.foreground5': themeValues.text.main,
|
|
112
|
+
'editorBracketHighlight.foreground6': themeValues.text.main,
|
|
113
|
+
'editorBracketHighlight.unexpectedBracket.foreground': themeValues.palette.red,
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
: DEFAULT_THEME_VALUES),
|
|
117
|
+
}), [themeValues]);
|
|
118
|
+
const dark = useMemo(() => {
|
|
119
|
+
const bg = themeValues?.bg;
|
|
120
|
+
return bg ? isDark(bg) : false;
|
|
121
|
+
}, [themeValues?.bg]);
|
|
122
|
+
// defineTheme writes to monaco's global theme registry. Run via layoutEffect
|
|
123
|
+
// so the theme is registered before <Editor theme=... /> mounts (avoid FOUC),
|
|
124
|
+
// then re-register whenever the computed token values change.
|
|
125
|
+
useLayoutEffect(() => {
|
|
126
|
+
if (!monaco)
|
|
127
|
+
return;
|
|
128
|
+
monaco.editor.defineTheme('snackDark', { ...themeDataWithoutBase, base: 'vs-dark' });
|
|
129
|
+
monaco.editor.defineTheme('snack', { ...themeDataWithoutBase, base: 'vs' });
|
|
130
|
+
}, [monaco, themeDataWithoutBase]);
|
|
131
|
+
const mergedOptions = useMemo(() => ({
|
|
132
|
+
...CODE_EDITOR_OPTIONS,
|
|
133
|
+
...jsonSchemaOptions,
|
|
134
|
+
...(themeValues?.mono
|
|
135
|
+
? {
|
|
136
|
+
fontSize: Number.parseFloat(themeValues.mono.body.s['font-size']),
|
|
137
|
+
fontWeight: themeValues.mono.body.s['font-weight'],
|
|
138
|
+
fontFamily: themeValues.mono.body.s['font-family'],
|
|
139
|
+
}
|
|
140
|
+
: DEFAULT_THEME_OPTIONS.mono.s),
|
|
141
|
+
...options,
|
|
142
|
+
lineNumbers: showRowNumber ? 'on' : 'off',
|
|
143
|
+
lineDecorationsWidth: showRowNumber ? CODE_EDITOR_OPTIONS.lineDecorationsWidth : 0,
|
|
144
|
+
lineNumbersMinChars: showRowNumber ? CODE_EDITOR_OPTIONS.lineNumbersMinChars : 0,
|
|
145
|
+
}), [options, themeValues?.mono, jsonSchemaOptions, showRowNumber]);
|
|
146
|
+
const isLoading = loading === true;
|
|
147
|
+
return (_jsxs("div", { className: cn(styles.root, className), "data-background": background ? 'true' : undefined, "data-has-header": hasHeader ? 'true' : undefined, "data-loading": isLoading ? 'true' : undefined, "data-language": language || undefined, "data-test-id": TEST_IDS.root, ...extractSupportProps(props), ref: setWrapperRef, children: [hasHeader && (_jsxs("div", { className: styles.header, "data-test-id": TEST_IDS.header, children: [language && (_jsx(Typography, { variant: 'label', size: 's', className: styles.language, "data-test-id": TEST_IDS.language, children: uppercaseFirstLetter(language) })), _jsx(CopyButton, { valueToCopy: value ?? defaultValue ?? '', size: 's', onClick: onCopyClick, "data-test-id": TEST_IDS.copyButton })] })), isLoading ? (_jsx("div", { className: styles.loadingOverlay, "data-test-id": TEST_IDS.loading, children: _jsx(Spinner, {}) })) : (
|
|
148
|
+
// Собственный flex-обёрточный div: @monaco-editor/react рендерит вокруг
|
|
149
|
+
// редактора <section style="height: 100%">, и эта `height: 100%`
|
|
150
|
+
// считается от ближайшего элемента с определённой высотой. Если бы
|
|
151
|
+
// section жил прямо в .root, его «100%» равнялось бы полной высоте
|
|
152
|
+
// root'а — и при toggle `hasHeader` редактор бы оверфлоил вниз
|
|
153
|
+
// (header добавляется сверху, section не сжимается). Прокладка с
|
|
154
|
+
// `flex: 1; min-height: 0` корректно отдаёт section ровно оставшееся
|
|
155
|
+
// место в flex-колонке и позволяет automaticLayout пересчитать монако.
|
|
156
|
+
_jsx("div", { className: styles.editorWrap, children: _jsx(Editor, { ...jsonSchemaProps, ...props,
|
|
157
|
+
// Без явного path Monaco генерит инкрементный inmemory:/model/N
|
|
158
|
+
// на каждое создание модели — при повторных mount/unmount компонента
|
|
159
|
+
// (например, при toggle hasHeader через decorator) копии моделей
|
|
160
|
+
// остаются в глобальном реестре monaco. Стабильный path по language
|
|
161
|
+
// гарантирует одну модель на язык в рамках инстанса страницы.
|
|
162
|
+
path: jsonSchemaProps.path ?? (language ? `inmemory://ds-code-editor/${instanceId}/${language}` : undefined), value: value, defaultValue: defaultValue, theme: theme ?? (dark ? 'snackDark' : 'snack'), className: styles.editor,
|
|
163
|
+
// Boolean `loading` управляется нашим overlay'ем — Monaco-prop принимает только ReactNode/undefined.
|
|
164
|
+
loading: typeof loading === 'boolean' ? _jsx(Spinner, {}) : (loading ?? _jsx(Spinner, {})), options: mergedOptions, onMount: onEditorMount, language: language }) }))] }));
|
|
165
|
+
}
|
|
166
|
+
export function CodeEditor(props) {
|
|
167
|
+
// monaco-editor обращается к `window` / `document.fonts` на module-init и
|
|
168
|
+
// спавнит web-workers, поэтому на SSR падает. Внешний компонент — без хуков:
|
|
169
|
+
// на сервере рендерим placeholder-шейп (root-div с теми же data-*-атрибутами,
|
|
170
|
+
// чтобы layout не прыгал при гидрации); на клиенте делегируем в подкомпонент,
|
|
171
|
+
// где живут все хуки monaco.
|
|
172
|
+
if (!isBrowser()) {
|
|
173
|
+
const { className, background = true, hasHeader, language } = props;
|
|
174
|
+
return (_jsx("div", { className: cn(styles.root, className), "data-background": background ? 'true' : undefined, "data-has-header": hasHeader ? 'true' : undefined, "data-language": language || undefined, "data-test-id": TEST_IDS.root, ...extractSupportProps(props) }));
|
|
175
|
+
}
|
|
176
|
+
return _jsx(CodeEditorClient, { ...props });
|
|
177
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { JsonSchema } from '../../types.js';
|
|
2
|
+
type UseCalculatedThemeValuesProps = {
|
|
3
|
+
stylesOriginNode: HTMLDivElement | null;
|
|
4
|
+
themeName?: string;
|
|
5
|
+
};
|
|
6
|
+
export declare function useCalculatedThemeValues({ stylesOriginNode, themeName }: UseCalculatedThemeValuesProps): {
|
|
7
|
+
bg: string;
|
|
8
|
+
text: {
|
|
9
|
+
main: string;
|
|
10
|
+
secondary: string;
|
|
11
|
+
};
|
|
12
|
+
stateLayer: {
|
|
13
|
+
filled: string;
|
|
14
|
+
border: string;
|
|
15
|
+
};
|
|
16
|
+
palette: {
|
|
17
|
+
red: string;
|
|
18
|
+
orange: string;
|
|
19
|
+
yellow: string;
|
|
20
|
+
green: string;
|
|
21
|
+
blue: string;
|
|
22
|
+
violet: string;
|
|
23
|
+
};
|
|
24
|
+
brand: {
|
|
25
|
+
accent: string;
|
|
26
|
+
};
|
|
27
|
+
mono: {
|
|
28
|
+
body: {
|
|
29
|
+
s: {
|
|
30
|
+
'font-weight': string;
|
|
31
|
+
'font-size': string;
|
|
32
|
+
'font-family': string;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
} | undefined;
|
|
37
|
+
export declare function useApplyJsonSchema(language?: string, jsonSchema?: JsonSchema): {
|
|
38
|
+
jsonSchemaProps: {
|
|
39
|
+
path: string | undefined;
|
|
40
|
+
};
|
|
41
|
+
jsonSchemaOptions: import("monaco-editor").editor.IStandaloneEditorConstructionOptions | undefined;
|
|
42
|
+
};
|
|
43
|
+
export {};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { useThemeContext } from '@cloud-ru/ds-theme';
|
|
2
|
+
import { useLayoutEffect } from '@cloud-ru/ds-utils';
|
|
3
|
+
import { useMonaco } from '@monaco-editor/react';
|
|
4
|
+
import { configureMonacoYaml } from 'monaco-yaml';
|
|
5
|
+
import { useCallback, useEffect, useMemo, useState } from 'react';
|
|
6
|
+
import { CODE_EDITOR_OPTIONS, THEME_VARS, YAML_CODE_EDITOR_OPTIONS } from '../../constants.js';
|
|
7
|
+
import { getJsonSchema } from '../../utils.js';
|
|
8
|
+
function getJsonDefaults(monaco) {
|
|
9
|
+
const json = monaco.languages.json;
|
|
10
|
+
return json?.jsonDefaults;
|
|
11
|
+
}
|
|
12
|
+
function mapThemeTree(styles, tree) {
|
|
13
|
+
if (typeof tree === 'string') {
|
|
14
|
+
return styles.getPropertyValue(tree);
|
|
15
|
+
}
|
|
16
|
+
const res = {};
|
|
17
|
+
for (const [key, value] of Object.entries(tree)) {
|
|
18
|
+
res[key] = mapThemeTree(styles, value);
|
|
19
|
+
}
|
|
20
|
+
return res;
|
|
21
|
+
}
|
|
22
|
+
export function useCalculatedThemeValues({ stylesOriginNode, themeName }) {
|
|
23
|
+
const [values, setValues] = useState(undefined);
|
|
24
|
+
const { themeClassName } = useThemeContext();
|
|
25
|
+
const trigger = themeName ?? themeClassName;
|
|
26
|
+
// useLayoutEffect — getComputedStyle should run before paint to avoid theme-switch flicker.
|
|
27
|
+
useLayoutEffect(() => {
|
|
28
|
+
if (stylesOriginNode) {
|
|
29
|
+
const styles = getComputedStyle(stylesOriginNode);
|
|
30
|
+
setValues(mapThemeTree(styles, THEME_VARS));
|
|
31
|
+
}
|
|
32
|
+
}, [stylesOriginNode, trigger]);
|
|
33
|
+
return values;
|
|
34
|
+
}
|
|
35
|
+
export function useApplyJsonSchema(language, jsonSchema) {
|
|
36
|
+
const monaco = useMonaco();
|
|
37
|
+
const [jsonSchemaOptions, setJsonSchemaOptions] = useState({});
|
|
38
|
+
const modelPath = jsonSchema?.fileMatch;
|
|
39
|
+
const preparedJsonSchema = useMemo(() => getJsonSchema(jsonSchema), [jsonSchema]);
|
|
40
|
+
const configureYamlLanguage = useCallback(() => {
|
|
41
|
+
if (!monaco || !preparedJsonSchema) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const model = configureMonacoYaml(monaco, {
|
|
45
|
+
enableSchemaRequest: true,
|
|
46
|
+
schemas: [preparedJsonSchema],
|
|
47
|
+
});
|
|
48
|
+
return {
|
|
49
|
+
options: YAML_CODE_EDITOR_OPTIONS,
|
|
50
|
+
dispose: model.dispose,
|
|
51
|
+
};
|
|
52
|
+
}, [monaco, preparedJsonSchema]);
|
|
53
|
+
/**
|
|
54
|
+
* Global monaco state — last mount wins if two CodeEditor instances target the same language with different schemas.
|
|
55
|
+
*/
|
|
56
|
+
const configureJsonLanguage = useCallback(() => {
|
|
57
|
+
if (!monaco || !preparedJsonSchema) {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
const jsonDefaults = getJsonDefaults(monaco);
|
|
61
|
+
if (!jsonDefaults)
|
|
62
|
+
return;
|
|
63
|
+
jsonDefaults.setDiagnosticsOptions({
|
|
64
|
+
validate: true,
|
|
65
|
+
schemas: [preparedJsonSchema],
|
|
66
|
+
});
|
|
67
|
+
return {
|
|
68
|
+
options: CODE_EDITOR_OPTIONS,
|
|
69
|
+
dispose: () => {
|
|
70
|
+
// Reset diagnostics so the previously-registered schema doesn't linger.
|
|
71
|
+
// NB: global monaco state — если рядом смонтированы 2+ CodeEditor с разными
|
|
72
|
+
// JSON-схемами, dispose одного гасит схему другого. Multi-instance
|
|
73
|
+
// ref-counting сюда не зашит сознательно (см. комментарий выше).
|
|
74
|
+
jsonDefaults.setDiagnosticsOptions({ validate: true, schemas: [] });
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}, [monaco, preparedJsonSchema]);
|
|
78
|
+
const configureJsonSchema = useCallback(() => {
|
|
79
|
+
switch (language) {
|
|
80
|
+
case 'yaml':
|
|
81
|
+
return configureYamlLanguage();
|
|
82
|
+
case 'json':
|
|
83
|
+
return configureJsonLanguage();
|
|
84
|
+
default:
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
}, [language, configureYamlLanguage, configureJsonLanguage]);
|
|
88
|
+
useEffect(() => {
|
|
89
|
+
const jsonSchemaSettings = configureJsonSchema();
|
|
90
|
+
setJsonSchemaOptions(jsonSchemaSettings?.options ?? {});
|
|
91
|
+
return () => {
|
|
92
|
+
jsonSchemaSettings?.dispose?.();
|
|
93
|
+
};
|
|
94
|
+
}, [configureJsonSchema]);
|
|
95
|
+
return useMemo(() => ({
|
|
96
|
+
jsonSchemaProps: { path: modelPath },
|
|
97
|
+
jsonSchemaOptions,
|
|
98
|
+
}), [jsonSchemaOptions, modelPath]);
|
|
99
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './CodeEditor.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './CodeEditor.js';
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
.root{
|
|
2
|
+
position:relative;
|
|
3
|
+
display:flex;
|
|
4
|
+
flex-direction:column;
|
|
5
|
+
width:100%;
|
|
6
|
+
min-width:0;
|
|
7
|
+
height:100%;
|
|
8
|
+
}
|
|
9
|
+
.root[data-background]{
|
|
10
|
+
background-color:var(--sn-theme-color-neutral-background, var(--sn-brand-color-neutral-90, var(--sn-primitive-color-gray-90, #eeeff3)));
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
.loadingOverlay{
|
|
14
|
+
display:flex;
|
|
15
|
+
flex:1;
|
|
16
|
+
align-items:center;
|
|
17
|
+
justify-content:center;
|
|
18
|
+
min-height:var(--sn-primitive-dimension-48, 48px);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
.header{
|
|
22
|
+
position:relative;
|
|
23
|
+
z-index:0;
|
|
24
|
+
display:flex;
|
|
25
|
+
gap:var(--sn-codeEditor-anatomy-size-header-gap, var(--sn-primitive-dimension-8, 8px));
|
|
26
|
+
align-items:center;
|
|
27
|
+
justify-content:space-between;
|
|
28
|
+
padding:var(--sn-codeEditor-anatomy-size-header-paddingVertical, var(--sn-primitive-dimension-2, 2px)) var(--sn-codeEditor-anatomy-size-header-paddingRight, var(--sn-primitive-dimension-2, 2px)) var(--sn-codeEditor-anatomy-size-header-paddingVertical, var(--sn-primitive-dimension-2, 2px)) var(--sn-codeEditor-anatomy-size-header-paddingLeft, var(--sn-primitive-dimension-12, 12px));
|
|
29
|
+
border-bottom:var(--sn-primitive-strokeWeight-strokeRegular, 1px) solid var(--sn-theme-color-available-borderColor, var(--sn-brand-color-state-neutralBorder-forLightMode-default-borderColor, rgba(159, 166, 198, 0.3019607843)));
|
|
30
|
+
background-color:var(--sn-theme-color-neutral-background, var(--sn-brand-color-neutral-90, var(--sn-primitive-color-gray-90, #eeeff3)));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
.language{
|
|
34
|
+
color:var(--sn-theme-color-available-version-textSecondary, var(--sn-brand-color-text-version-secondary, rgba(65, 66, 78, 0.8)));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
.editorWrap{
|
|
38
|
+
position:relative;
|
|
39
|
+
overflow:hidden;
|
|
40
|
+
flex:1;
|
|
41
|
+
min-height:0;
|
|
42
|
+
padding-top:var(--sn-codeEditor-anatomy-size-content-paddingVertical, var(--sn-primitive-dimension-4, 4px));
|
|
43
|
+
padding-bottom:var(--sn-codeEditor-anatomy-size-content-paddingVertical, var(--sn-primitive-dimension-4, 4px));
|
|
44
|
+
background-color:inherit;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
.editor{
|
|
48
|
+
background-color:inherit;
|
|
49
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { CodeEditorProps } from '../CodeEditor/index.js';
|
|
2
|
+
export type LazyCodeEditorProps = CodeEditorProps;
|
|
3
|
+
/**
|
|
4
|
+
* Готовый preset на базе `AsyncCodeEditor` + `Suspense`.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```tsx
|
|
8
|
+
* import { LazyCodeEditor } from '@cloud-ru/ds-code-editor'
|
|
9
|
+
*
|
|
10
|
+
* const MyComponent = () => <LazyCodeEditor language='json' value='' />
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
export declare function LazyCodeEditor(props: LazyCodeEditorProps): import("react/jsx-runtime").JSX.Element;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { Spinner } from '@cloud-ru/ds-loader';
|
|
3
|
+
import { lazy, Suspense } from 'react';
|
|
4
|
+
import { AsyncCodeEditor } from '../AsyncCodeEditor/index.js';
|
|
5
|
+
import styles from './styles.module.css';
|
|
6
|
+
const CodeEditor = lazy(() => AsyncCodeEditor());
|
|
7
|
+
function Loader({ width, height }) {
|
|
8
|
+
// Прокидываем width/height из пропсов потребителя в fallback, чтобы при
|
|
9
|
+
// <LazyCodeEditor height='100%' /> внутри fixed-height контейнера спиннер
|
|
10
|
+
// не «схлопывался» в min-height и не было layout-прыжка при появлении monaco.
|
|
11
|
+
return (_jsx("div", { className: styles.fallback, style: { width, height }, children: _jsx(Spinner, {}) }));
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Готовый preset на базе `AsyncCodeEditor` + `Suspense`.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```tsx
|
|
18
|
+
* import { LazyCodeEditor } from '@cloud-ru/ds-code-editor'
|
|
19
|
+
*
|
|
20
|
+
* const MyComponent = () => <LazyCodeEditor language='json' value='' />
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export function LazyCodeEditor(props) {
|
|
24
|
+
return (_jsx(Suspense, { fallback: _jsx(Loader, { width: props.width, height: props.height }), children: _jsx(CodeEditor, { ...props }) }));
|
|
25
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './LazyCodeEditor.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './LazyCodeEditor.js';
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
export declare const TEST_IDS: {
|
|
2
|
+
readonly root: "code-editor";
|
|
3
|
+
readonly header: "code-editor__header";
|
|
4
|
+
readonly language: "code-editor__language";
|
|
5
|
+
readonly copyButton: "code-editor__copy-button";
|
|
6
|
+
readonly loading: "code-editor__loading";
|
|
7
|
+
};
|
|
8
|
+
export declare const DEFAULT_SCHEMA_URI = "schema://editor-schema";
|
|
9
|
+
export declare const DEFAULT_THEME_VALUES: {
|
|
10
|
+
semanticTokenColors: {
|
|
11
|
+
enumMember: {
|
|
12
|
+
foreground: string;
|
|
13
|
+
};
|
|
14
|
+
'variable.constant': {
|
|
15
|
+
foreground: string;
|
|
16
|
+
};
|
|
17
|
+
'variable.defaultLibrary': {
|
|
18
|
+
foreground: string;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
rules: {
|
|
22
|
+
foreground: string;
|
|
23
|
+
token: string;
|
|
24
|
+
}[];
|
|
25
|
+
colors: {
|
|
26
|
+
'editor.background': string;
|
|
27
|
+
'editor.foreground': string;
|
|
28
|
+
'editor.selectionBackground': string;
|
|
29
|
+
'editor.lineHighlightBackground': string;
|
|
30
|
+
'editorCursor.foreground': string;
|
|
31
|
+
'editorWhitespace.foreground': string;
|
|
32
|
+
'scrollbarSlider.background': string;
|
|
33
|
+
'scrollbarSlider.hoverBackground': string;
|
|
34
|
+
'scrollbarSlider.activeBackground': string;
|
|
35
|
+
'editorLineNumber.foreground': string;
|
|
36
|
+
'editorLineNumber.activeForeground': string;
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
export declare const DEFAULT_THEME_OPTIONS: {
|
|
40
|
+
mono: {
|
|
41
|
+
s: {
|
|
42
|
+
fontWeight: string;
|
|
43
|
+
fontSize: number;
|
|
44
|
+
fontFamily: string;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
export declare const THEME_VARS: {
|
|
49
|
+
bg: string;
|
|
50
|
+
text: {
|
|
51
|
+
main: string;
|
|
52
|
+
secondary: string;
|
|
53
|
+
};
|
|
54
|
+
stateLayer: {
|
|
55
|
+
filled: string;
|
|
56
|
+
border: string;
|
|
57
|
+
};
|
|
58
|
+
palette: {
|
|
59
|
+
red: string;
|
|
60
|
+
orange: string;
|
|
61
|
+
yellow: string;
|
|
62
|
+
green: string;
|
|
63
|
+
blue: string;
|
|
64
|
+
violet: string;
|
|
65
|
+
};
|
|
66
|
+
brand: {
|
|
67
|
+
accent: string;
|
|
68
|
+
};
|
|
69
|
+
mono: {
|
|
70
|
+
body: {
|
|
71
|
+
s: {
|
|
72
|
+
'font-weight': string;
|
|
73
|
+
'font-size': string;
|
|
74
|
+
'font-family': string;
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
export declare const CODE_EDITOR_OPTIONS: {
|
|
80
|
+
automaticLayout: boolean;
|
|
81
|
+
minimap: {
|
|
82
|
+
enabled: boolean;
|
|
83
|
+
};
|
|
84
|
+
padding: {
|
|
85
|
+
top: number;
|
|
86
|
+
bottom: number;
|
|
87
|
+
};
|
|
88
|
+
tabSize: number;
|
|
89
|
+
scrollBeyondLastLine: boolean;
|
|
90
|
+
fixedOverflowWidgets: boolean;
|
|
91
|
+
lineDecorationsWidth: number;
|
|
92
|
+
lineNumbersMinChars: number;
|
|
93
|
+
scrollbar: {
|
|
94
|
+
verticalScrollbarSize: number;
|
|
95
|
+
horizontalScrollbarSize: number;
|
|
96
|
+
useShadows: boolean;
|
|
97
|
+
};
|
|
98
|
+
contextmenu: boolean;
|
|
99
|
+
guides: {
|
|
100
|
+
indentation: boolean;
|
|
101
|
+
};
|
|
102
|
+
bracketPairColorization: {
|
|
103
|
+
enabled: boolean;
|
|
104
|
+
};
|
|
105
|
+
stickyScroll: {
|
|
106
|
+
enabled: boolean;
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
export declare const YAML_CODE_EDITOR_OPTIONS: {
|
|
110
|
+
quickSuggestions: {
|
|
111
|
+
strings: boolean;
|
|
112
|
+
};
|
|
113
|
+
};
|