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