@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,33 @@
1
+ import { ComponentType } from 'react';
2
+
3
+ import { loadMonacoEditor } from '../../loader';
4
+ import { withMonaco } from '../../withMonaco';
5
+ import { CodeEditorProps } from '../CodeEditor';
6
+
7
+ /**
8
+ * `CodeEditor` с предзагруженным `monaco-editor`.
9
+ *
10
+ * @example
11
+ * ```tsx
12
+ * import { Suspense, lazy } from 'react'
13
+ * import { AsyncCodeEditor } from '@cloud-ru/ds-code-editor'
14
+ *
15
+ * const Editor = lazy(() => AsyncCodeEditor())
16
+ *
17
+ * const MyComponent = () => (
18
+ * <Suspense fallback='loading...'>
19
+ * <Editor language='json' value='' />
20
+ * </Suspense>
21
+ * )
22
+ * ```
23
+ */
24
+ export const AsyncCodeEditor: () => Promise<{ default: ComponentType<CodeEditorProps> }> = async () => {
25
+ const monaco = await loadMonacoEditor();
26
+ // loadMonacoEditor возвращает `unknown` от внешнего loader'а; минимально
27
+ // проверяем, что это объект с editor namespace'ом, иначе откатываемся
28
+ // на дефолтный CDN-loader (@monaco-editor/react).
29
+ if (monaco && typeof monaco === 'object' && 'editor' in monaco) {
30
+ return { default: withMonaco(monaco as typeof import('monaco-editor')).CodeEditor };
31
+ }
32
+ return { default: withMonaco().CodeEditor };
33
+ };
@@ -0,0 +1 @@
1
+ export * from './AsyncCodeEditor';
@@ -0,0 +1,297 @@
1
+ import { Spinner } from '@cloud-ru/ds-loader';
2
+ import { useThemeContext } from '@cloud-ru/ds-theme';
3
+ import { Typography } from '@cloud-ru/ds-typography';
4
+ import { CopyButton } from '@cloud-ru/ds-uikit-product-copy';
5
+ import { extractSupportProps, isBrowser, useLayoutEffect, WithSupportProps } from '@cloud-ru/ds-utils';
6
+ import { Editor, OnMount, useMonaco } from '@monaco-editor/react';
7
+ import cn from 'classnames';
8
+ import { useCallback, useId, useMemo, useRef, useState } from 'react';
9
+
10
+ import { CODE_EDITOR_OPTIONS, DEFAULT_THEME_OPTIONS, DEFAULT_THEME_VALUES, TEST_IDS } from '../../constants';
11
+ import { EditorBaseProps, EditorWithJsonSchemaProps } from '../../types';
12
+ import { hexWithAlpha, isDark, uppercaseFirstLetter } from '../../utils';
13
+ import { useApplyJsonSchema, useCalculatedThemeValues } from './hooks';
14
+ import styles from './styles.module.scss';
15
+
16
+ export type CodeEditorProps = WithSupportProps<{
17
+ /** Используется как trigger в effect deps для перепересчёта theme tokens при смене темы. Уникальное значение на каждую тему. */
18
+ themeName?: string;
19
+ /** Включение/отключение псевдобекграунда. */
20
+ background?: boolean;
21
+ /** Включение/отключение шапки. */
22
+ hasHeader?: boolean;
23
+ /** Включение/отключение колонки с номерами строк. */
24
+ showRowNumber?: boolean;
25
+ /** Клик по кнопке копирования. */
26
+ onCopyClick?(): void;
27
+ /**
28
+ * Имя зарегистрированной monaco-темы из глобального реестра
29
+ * (`monaco.editor.defineTheme(name, …)`). По умолчанию подбирается
30
+ * автоматически по DS-теме провайдера: `'snack'` для светлой, `'snackDark'`
31
+ * для тёмной. Передавай вручную только если регистрируешь свою кастомную
32
+ * тему — иначе оставляй `undefined`.
33
+ */
34
+ theme?: string;
35
+ }> &
36
+ (EditorBaseProps | EditorWithJsonSchemaProps);
37
+
38
+ // monaco theme parser принимает только hex (#RRGGBB / #RRGGBBAA);
39
+ // rgba(...) он не понимает и подставляет fail-safe red. См. utils.hexWithAlpha.
40
+ const withAlpha = hexWithAlpha;
41
+
42
+ function CodeEditorClient({
43
+ themeName,
44
+ className,
45
+ theme,
46
+ options,
47
+ loading,
48
+ background = true,
49
+ onMount,
50
+ language,
51
+ onCopyClick,
52
+ hasHeader,
53
+ showRowNumber = true,
54
+ value,
55
+ defaultValue,
56
+ ...props
57
+ }: CodeEditorProps) {
58
+ const monaco = useMonaco();
59
+ // TODO(FF-8312): live theme switch без перезагрузки страницы. useThemeContext
60
+ // отдаёт класс из стора провайдера, который в микрофронт-режиме обновляется
61
+ // через явный re-publish от хост-приложения; в standalone (Storybook, docs) при
62
+ // toggle темы CSS-классы DS-провайдера меняются на корне, но themeClassName
63
+ // отсюда не пересчитывается — нужен либо MutationObserver на родительские
64
+ // theme-классы, либо подписка на сам тогглер. Сейчас обходится reload'ом.
65
+ const { themeClassName } = useThemeContext();
66
+ const [wrapperElement, setWrapperElement] = useState<HTMLDivElement | null>(null);
67
+ const setWrapperRef = useCallback((el: HTMLDivElement | null) => setWrapperElement(el), []);
68
+ const instanceId = useId();
69
+ const unmountedRef = useRef(false);
70
+
71
+ const { jsonSchemaProps, jsonSchemaOptions } = useApplyJsonSchema(
72
+ language,
73
+ 'jsonSchema' in props ? props.jsonSchema : undefined,
74
+ );
75
+
76
+ useLayoutEffect(
77
+ () => () => {
78
+ unmountedRef.current = true;
79
+ },
80
+ [],
81
+ );
82
+
83
+ const onEditorMount = useCallback<OnMount>(
84
+ (editor, monacoInstance) => {
85
+ if (monacoInstance && isBrowser()) {
86
+ // document.fonts.ready resolves в произвольный момент; не вызываем
87
+ // remeasureFonts, если редактор уже размонтирован — иначе монако
88
+ // обращается к disposed editor instance.
89
+ document?.fonts?.ready.then(() => {
90
+ if (!unmountedRef.current) monacoInstance.editor.remeasureFonts();
91
+ });
92
+ }
93
+ onMount?.(editor, monacoInstance);
94
+ },
95
+ [onMount],
96
+ );
97
+
98
+ const themeValues = useCalculatedThemeValues({
99
+ themeName: themeName ?? themeClassName,
100
+ stylesOriginNode: wrapperElement,
101
+ });
102
+
103
+ const themeDataWithoutBase = useMemo(
104
+ () => ({
105
+ // inherit=true — наследуем дефолты monaco (vs/vs-dark) под слоты,
106
+ // которые не задаются явно (например, hint colors, error squiggles).
107
+ // Иначе monaco подставляет жёсткие фолбэки, не вяжущиеся с темой DS.
108
+ inherit: true,
109
+ ...(themeValues?.palette
110
+ ? {
111
+ semanticTokenColors: {
112
+ parameter: { foreground: themeValues.palette.violet },
113
+ property: { foreground: themeValues.palette.blue },
114
+ enumMember: { foreground: themeValues.palette.blue },
115
+ variable: { foreground: themeValues.palette.red },
116
+ 'variable.constant': { foreground: themeValues.palette.orange },
117
+ function: { foreground: themeValues.palette.blue },
118
+ method: { foreground: themeValues.palette.blue },
119
+ type: { foreground: themeValues.palette.yellow },
120
+ class: { foreground: themeValues.palette.yellow },
121
+ },
122
+ rules: [
123
+ { foreground: themeValues.palette.green, token: 'comment' },
124
+ { foreground: themeValues.palette.green, token: 'string' },
125
+ // JSON: keys — blue, values — green
126
+ { foreground: themeValues.palette.blue, token: 'string.key.json' },
127
+ { foreground: themeValues.palette.green, token: 'string.value.json' },
128
+ { foreground: themeValues.palette.orange, token: 'number' },
129
+ { foreground: themeValues.palette.violet, token: 'keyword' },
130
+ { foreground: themeValues.palette.violet, token: 'keyword.json' },
131
+ { foreground: themeValues.palette.blue, token: 'operator' },
132
+ { foreground: themeValues.palette.red, token: 'variable' },
133
+ { foreground: themeValues.palette.yellow, token: 'type' },
134
+ { foreground: themeValues.palette.red, token: 'regexp' },
135
+ { foreground: themeValues.palette.red, token: 'invalid' },
136
+ { foreground: themeValues.text.main, token: 'delimiter' },
137
+ { foreground: themeValues.text.main, token: 'delimiter.bracket' },
138
+ { foreground: themeValues.text.main, token: 'identifier' },
139
+ { foreground: themeValues.text.main, token: '' },
140
+ ],
141
+ colors: {
142
+ focusBorder: '#00000000',
143
+ 'editor.background': '#00000000',
144
+ 'editor.foreground': themeValues.text.main,
145
+ 'editor.selectionBackground': themeValues.stateLayer.border,
146
+ // inactive (на blur) — наследует тёмный дефолт vs; задаём явно
147
+ // тот же stateLayer.border, чтобы blur не «темнил» выделение.
148
+ 'editor.inactiveSelectionBackground': themeValues.stateLayer.border,
149
+ 'editor.lineHighlightBackground': themeValues.stateLayer.filled,
150
+ 'editor.lineHighlightBorder': '#00000000',
151
+ 'editorCursor.foreground': themeValues.brand.accent,
152
+ 'editorWhitespace.foreground': themeValues.text.secondary,
153
+ 'scrollbarSlider.background': withAlpha(themeValues.text.main, 0.16),
154
+ 'scrollbarSlider.hoverBackground': withAlpha(themeValues.text.main, 0.28),
155
+ 'scrollbarSlider.activeBackground': withAlpha(themeValues.text.main, 0.4),
156
+ 'editorLineNumber.foreground': themeValues.text.secondary,
157
+ 'editorLineNumber.activeForeground': themeValues.text.main,
158
+ // monaco red-rainbow bracket pair colorization → нейтрализуем
159
+ // на theme-уровне (опция bracketPairColorization не всегда
160
+ // отключает встроенные CSS-классы).
161
+ 'editorBracketHighlight.foreground1': themeValues.text.main,
162
+ 'editorBracketHighlight.foreground2': themeValues.text.main,
163
+ 'editorBracketHighlight.foreground3': themeValues.text.main,
164
+ 'editorBracketHighlight.foreground4': themeValues.text.main,
165
+ 'editorBracketHighlight.foreground5': themeValues.text.main,
166
+ 'editorBracketHighlight.foreground6': themeValues.text.main,
167
+ 'editorBracketHighlight.unexpectedBracket.foreground': themeValues.palette.red,
168
+ },
169
+ }
170
+ : DEFAULT_THEME_VALUES),
171
+ }),
172
+ [themeValues],
173
+ );
174
+
175
+ const dark = useMemo(() => {
176
+ const bg = themeValues?.bg;
177
+ return bg ? isDark(bg) : false;
178
+ }, [themeValues?.bg]);
179
+
180
+ // defineTheme writes to monaco's global theme registry. Run via layoutEffect
181
+ // so the theme is registered before <Editor theme=... /> mounts (avoid FOUC),
182
+ // then re-register whenever the computed token values change.
183
+ useLayoutEffect(() => {
184
+ if (!monaco) return;
185
+ monaco.editor.defineTheme('snackDark', { ...themeDataWithoutBase, base: 'vs-dark' });
186
+ monaco.editor.defineTheme('snack', { ...themeDataWithoutBase, base: 'vs' });
187
+ }, [monaco, themeDataWithoutBase]);
188
+
189
+ const mergedOptions = useMemo(
190
+ () => ({
191
+ ...CODE_EDITOR_OPTIONS,
192
+ ...jsonSchemaOptions,
193
+ ...(themeValues?.mono
194
+ ? {
195
+ fontSize: Number.parseFloat(themeValues.mono.body.s['font-size']),
196
+ fontWeight: themeValues.mono.body.s['font-weight'],
197
+ fontFamily: themeValues.mono.body.s['font-family'],
198
+ }
199
+ : DEFAULT_THEME_OPTIONS.mono.s),
200
+ ...options,
201
+ lineNumbers: showRowNumber ? ('on' as const) : ('off' as const),
202
+ lineDecorationsWidth: showRowNumber ? CODE_EDITOR_OPTIONS.lineDecorationsWidth : 0,
203
+ lineNumbersMinChars: showRowNumber ? CODE_EDITOR_OPTIONS.lineNumbersMinChars : 0,
204
+ }),
205
+ [options, themeValues?.mono, jsonSchemaOptions, showRowNumber],
206
+ );
207
+
208
+ const isLoading = loading === true;
209
+
210
+ return (
211
+ <div
212
+ className={cn(styles.root, className)}
213
+ data-background={background ? 'true' : undefined}
214
+ data-has-header={hasHeader ? 'true' : undefined}
215
+ data-loading={isLoading ? 'true' : undefined}
216
+ data-language={language || undefined}
217
+ data-test-id={TEST_IDS.root}
218
+ {...extractSupportProps(props)}
219
+ ref={setWrapperRef}
220
+ >
221
+ {hasHeader && (
222
+ <div className={styles.header} data-test-id={TEST_IDS.header}>
223
+ {language && (
224
+ <Typography variant='label' size='s' className={styles.language} data-test-id={TEST_IDS.language}>
225
+ {uppercaseFirstLetter(language)}
226
+ </Typography>
227
+ )}
228
+ <CopyButton
229
+ valueToCopy={value ?? defaultValue ?? ''}
230
+ size='s'
231
+ onClick={onCopyClick}
232
+ data-test-id={TEST_IDS.copyButton}
233
+ />
234
+ </div>
235
+ )}
236
+ {isLoading ? (
237
+ <div className={styles.loadingOverlay} data-test-id={TEST_IDS.loading}>
238
+ <Spinner />
239
+ </div>
240
+ ) : (
241
+ // Собственный flex-обёрточный div: @monaco-editor/react рендерит вокруг
242
+ // редактора <section style="height: 100%">, и эта `height: 100%`
243
+ // считается от ближайшего элемента с определённой высотой. Если бы
244
+ // section жил прямо в .root, его «100%» равнялось бы полной высоте
245
+ // root'а — и при toggle `hasHeader` редактор бы оверфлоил вниз
246
+ // (header добавляется сверху, section не сжимается). Прокладка с
247
+ // `flex: 1; min-height: 0` корректно отдаёт section ровно оставшееся
248
+ // место в flex-колонке и позволяет automaticLayout пересчитать монако.
249
+ <div className={styles.editorWrap}>
250
+ <Editor
251
+ {...jsonSchemaProps}
252
+ {...props}
253
+ // Без явного path Monaco генерит инкрементный inmemory:/model/N
254
+ // на каждое создание модели — при повторных mount/unmount компонента
255
+ // (например, при toggle hasHeader через decorator) копии моделей
256
+ // остаются в глобальном реестре monaco. Стабильный path по language
257
+ // гарантирует одну модель на язык в рамках инстанса страницы.
258
+ path={
259
+ jsonSchemaProps.path ?? (language ? `inmemory://ds-code-editor/${instanceId}/${language}` : undefined)
260
+ }
261
+ value={value}
262
+ defaultValue={defaultValue}
263
+ theme={theme ?? (dark ? 'snackDark' : 'snack')}
264
+ className={styles.editor}
265
+ // Boolean `loading` управляется нашим overlay'ем — Monaco-prop принимает только ReactNode/undefined.
266
+ loading={typeof loading === 'boolean' ? <Spinner /> : (loading ?? <Spinner />)}
267
+ options={mergedOptions}
268
+ onMount={onEditorMount}
269
+ language={language}
270
+ />
271
+ </div>
272
+ )}
273
+ </div>
274
+ );
275
+ }
276
+
277
+ export function CodeEditor(props: CodeEditorProps) {
278
+ // monaco-editor обращается к `window` / `document.fonts` на module-init и
279
+ // спавнит web-workers, поэтому на SSR падает. Внешний компонент — без хуков:
280
+ // на сервере рендерим placeholder-шейп (root-div с теми же data-*-атрибутами,
281
+ // чтобы layout не прыгал при гидрации); на клиенте делегируем в подкомпонент,
282
+ // где живут все хуки monaco.
283
+ if (!isBrowser()) {
284
+ const { className, background = true, hasHeader, language } = props;
285
+ return (
286
+ <div
287
+ className={cn(styles.root, className)}
288
+ data-background={background ? 'true' : undefined}
289
+ data-has-header={hasHeader ? 'true' : undefined}
290
+ data-language={language || undefined}
291
+ data-test-id={TEST_IDS.root}
292
+ {...extractSupportProps(props as unknown as Record<string, unknown>)}
293
+ />
294
+ );
295
+ }
296
+ return <CodeEditorClient {...props} />;
297
+ }
@@ -0,0 +1,138 @@
1
+ import { useThemeContext } from '@cloud-ru/ds-theme';
2
+ import { useLayoutEffect } from '@cloud-ru/ds-utils';
3
+ import { EditorProps as MonacoEditorProps, Monaco, useMonaco } from '@monaco-editor/react';
4
+ import { configureMonacoYaml, SchemasSettings } from 'monaco-yaml';
5
+ import { useCallback, useEffect, useMemo, useState } from 'react';
6
+
7
+ import { CODE_EDITOR_OPTIONS, THEME_VARS, YAML_CODE_EDITOR_OPTIONS } from '../../constants';
8
+ import { ConfigureJsonSchemaReturn, JsonSchema } from '../../types';
9
+ import { getJsonSchema } from '../../utils';
10
+
11
+ // monaco-editor типизирует languages.json как deprecated, а ESM-сборка не
12
+ // экспортирует namespace в `.d.ts` целиком — runtime API остаётся живым
13
+ // (см. legacy snack-code-editor@0.7.15).
14
+ type JsonLanguageServiceDefaults = {
15
+ setDiagnosticsOptions: (options: { validate?: boolean; schemas?: SchemasSettings[] }) => void;
16
+ };
17
+
18
+ function getJsonDefaults(monaco: Monaco): JsonLanguageServiceDefaults | undefined {
19
+ const json = (monaco.languages as { json?: { jsonDefaults?: JsonLanguageServiceDefaults } }).json;
20
+ return json?.jsonDefaults;
21
+ }
22
+
23
+ function mapThemeTree(
24
+ styles: CSSStyleDeclaration,
25
+ tree: string | Record<string, unknown>,
26
+ ): Record<string, unknown> | string {
27
+ if (typeof tree === 'string') {
28
+ return styles.getPropertyValue(tree);
29
+ }
30
+ const res: Record<string, unknown> = {};
31
+ for (const [key, value] of Object.entries(tree)) {
32
+ res[key] = mapThemeTree(styles, value as string | Record<string, unknown>);
33
+ }
34
+ return res;
35
+ }
36
+
37
+ type UseCalculatedThemeValuesProps = {
38
+ stylesOriginNode: HTMLDivElement | null;
39
+ themeName?: string;
40
+ };
41
+
42
+ export function useCalculatedThemeValues({ stylesOriginNode, themeName }: UseCalculatedThemeValuesProps) {
43
+ const [values, setValues] = useState<typeof THEME_VARS | undefined>(undefined);
44
+
45
+ const { themeClassName } = useThemeContext();
46
+
47
+ const trigger = themeName ?? themeClassName;
48
+
49
+ // useLayoutEffect — getComputedStyle should run before paint to avoid theme-switch flicker.
50
+ useLayoutEffect(() => {
51
+ if (stylesOriginNode) {
52
+ const styles = getComputedStyle(stylesOriginNode);
53
+ setValues(mapThemeTree(styles, THEME_VARS) as typeof THEME_VARS);
54
+ }
55
+ }, [stylesOriginNode, trigger]);
56
+
57
+ return values;
58
+ }
59
+
60
+ export function useApplyJsonSchema(language?: string, jsonSchema?: JsonSchema) {
61
+ const monaco = useMonaco();
62
+
63
+ const [jsonSchemaOptions, setJsonSchemaOptions] = useState<MonacoEditorProps['options']>({});
64
+ const modelPath = jsonSchema?.fileMatch;
65
+
66
+ const preparedJsonSchema: SchemasSettings | undefined = useMemo(() => getJsonSchema(jsonSchema), [jsonSchema]);
67
+
68
+ const configureYamlLanguage = useCallback((): ConfigureJsonSchemaReturn => {
69
+ if (!monaco || !preparedJsonSchema) {
70
+ return;
71
+ }
72
+
73
+ const model = configureMonacoYaml(monaco, {
74
+ enableSchemaRequest: true,
75
+ schemas: [preparedJsonSchema],
76
+ });
77
+
78
+ return {
79
+ options: YAML_CODE_EDITOR_OPTIONS,
80
+ dispose: model.dispose,
81
+ };
82
+ }, [monaco, preparedJsonSchema]);
83
+
84
+ /**
85
+ * Global monaco state — last mount wins if two CodeEditor instances target the same language with different schemas.
86
+ */
87
+ const configureJsonLanguage = useCallback((): ConfigureJsonSchemaReturn => {
88
+ if (!monaco || !preparedJsonSchema) {
89
+ return;
90
+ }
91
+
92
+ const jsonDefaults = getJsonDefaults(monaco);
93
+ if (!jsonDefaults) return;
94
+ jsonDefaults.setDiagnosticsOptions({
95
+ validate: true,
96
+ schemas: [preparedJsonSchema],
97
+ });
98
+
99
+ return {
100
+ options: CODE_EDITOR_OPTIONS,
101
+ dispose: () => {
102
+ // Reset diagnostics so the previously-registered schema doesn't linger.
103
+ // NB: global monaco state — если рядом смонтированы 2+ CodeEditor с разными
104
+ // JSON-схемами, dispose одного гасит схему другого. Multi-instance
105
+ // ref-counting сюда не зашит сознательно (см. комментарий выше).
106
+ jsonDefaults.setDiagnosticsOptions({ validate: true, schemas: [] });
107
+ },
108
+ };
109
+ }, [monaco, preparedJsonSchema]);
110
+
111
+ const configureJsonSchema = useCallback(() => {
112
+ switch (language) {
113
+ case 'yaml':
114
+ return configureYamlLanguage();
115
+ case 'json':
116
+ return configureJsonLanguage();
117
+ default:
118
+ break;
119
+ }
120
+ }, [language, configureYamlLanguage, configureJsonLanguage]);
121
+
122
+ useEffect(() => {
123
+ const jsonSchemaSettings = configureJsonSchema();
124
+ setJsonSchemaOptions(jsonSchemaSettings?.options ?? {});
125
+
126
+ return () => {
127
+ jsonSchemaSettings?.dispose?.();
128
+ };
129
+ }, [configureJsonSchema]);
130
+
131
+ return useMemo(
132
+ () => ({
133
+ jsonSchemaProps: { path: modelPath } satisfies MonacoEditorProps,
134
+ jsonSchemaOptions,
135
+ }),
136
+ [jsonSchemaOptions, modelPath],
137
+ );
138
+ }
@@ -0,0 +1 @@
1
+ export * from './CodeEditor';
@@ -0,0 +1,66 @@
1
+ @use '@cloud-ru/ds-figma-variables/build/scss/styles/styles.module.scss' as base;
2
+ @use '@cloud-ru/ds-figma-variables/build/scss/components/codeEditor.module.scss' as codeEditor;
3
+
4
+ .root {
5
+ position: relative;
6
+
7
+ display: flex;
8
+ flex-direction: column;
9
+
10
+ width: 100%;
11
+ min-width: 0;
12
+ height: 100%;
13
+
14
+ &[data-background] {
15
+ background-color: base.$sn-theme-color-neutral-background;
16
+ }
17
+ }
18
+
19
+ .loadingOverlay {
20
+ display: flex;
21
+ flex: 1;
22
+ align-items: center;
23
+ justify-content: center;
24
+
25
+ min-height: base.$sn-primitive-dimension-48;
26
+ }
27
+
28
+ .header {
29
+ position: relative;
30
+ z-index: 0;
31
+
32
+ display: flex;
33
+ gap: base.simple-var(codeEditor.$codeEditor, 'anatomy', 'size', 'header', 'gap');
34
+ align-items: center;
35
+ justify-content: space-between;
36
+
37
+ padding:
38
+ base.simple-var(codeEditor.$codeEditor, 'anatomy', 'size', 'header', 'padding-top')
39
+ base.simple-var(codeEditor.$codeEditor, 'anatomy', 'size', 'header', 'padding-right')
40
+ base.simple-var(codeEditor.$codeEditor, 'anatomy', 'size', 'header', 'padding-bottom')
41
+ base.simple-var(codeEditor.$codeEditor, 'anatomy', 'size', 'header', 'padding-left');
42
+ border-bottom: base.$sn-primitive-strokeWeight-strokeRegular solid base.$sn-theme-color-available-borderColor;
43
+
44
+ background-color: base.$sn-theme-color-neutral-background;
45
+ }
46
+
47
+ .language {
48
+ color: base.$sn-theme-color-available-version-textSecondary;
49
+ }
50
+
51
+ .editorWrap {
52
+ position: relative;
53
+
54
+ overflow: hidden;
55
+ flex: 1;
56
+
57
+ min-height: 0;
58
+ padding-top: base.simple-var(codeEditor.$codeEditor, 'anatomy', 'size', 'content', 'padding-top');
59
+ padding-bottom: base.simple-var(codeEditor.$codeEditor, 'anatomy', 'size', 'content', 'padding-bottom');
60
+
61
+ background-color: inherit;
62
+ }
63
+
64
+ .editor {
65
+ background-color: inherit;
66
+ }
@@ -0,0 +1,39 @@
1
+ import { Spinner } from '@cloud-ru/ds-loader';
2
+ import { lazy, Suspense } from 'react';
3
+
4
+ import { AsyncCodeEditor } from '../AsyncCodeEditor';
5
+ import { CodeEditorProps } from '../CodeEditor';
6
+ import styles from './styles.module.scss';
7
+
8
+ const CodeEditor = lazy(() => AsyncCodeEditor());
9
+
10
+ export type LazyCodeEditorProps = CodeEditorProps;
11
+
12
+ function Loader({ width, height }: { width?: number | string; height?: number | string }) {
13
+ // Прокидываем width/height из пропсов потребителя в fallback, чтобы при
14
+ // <LazyCodeEditor height='100%' /> внутри fixed-height контейнера спиннер
15
+ // не «схлопывался» в min-height и не было layout-прыжка при появлении monaco.
16
+ return (
17
+ <div className={styles.fallback} style={{ width, height }}>
18
+ <Spinner />
19
+ </div>
20
+ );
21
+ }
22
+
23
+ /**
24
+ * Готовый preset на базе `AsyncCodeEditor` + `Suspense`.
25
+ *
26
+ * @example
27
+ * ```tsx
28
+ * import { LazyCodeEditor } from '@cloud-ru/ds-code-editor'
29
+ *
30
+ * const MyComponent = () => <LazyCodeEditor language='json' value='' />
31
+ * ```
32
+ */
33
+ export function LazyCodeEditor(props: LazyCodeEditorProps) {
34
+ return (
35
+ <Suspense fallback={<Loader width={props.width} height={props.height} />}>
36
+ <CodeEditor {...props} />
37
+ </Suspense>
38
+ );
39
+ }
@@ -0,0 +1 @@
1
+ export * from './LazyCodeEditor';
@@ -0,0 +1,10 @@
1
+ @use '@cloud-ru/ds-figma-variables/build/scss/styles/styles.module' as base;
2
+
3
+ .fallback {
4
+ display: flex;
5
+ align-items: center;
6
+ justify-content: center;
7
+
8
+ width: 100%;
9
+ min-height: base.$sn-primitive-dimension-120;
10
+ }
@@ -0,0 +1,3 @@
1
+ export * from './CodeEditor';
2
+ export * from './AsyncCodeEditor';
3
+ export * from './LazyCodeEditor';