The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Preserve CodeEditor contracts (#27845)
Raphaël Bosi7bfb8e8a5da5
diff --git a/packages/twenty-docs/snippets/ui/generated/components/code-editor/code-editor.mdx b/packages/twenty-docs/snippets/ui/generated/components/code-editor/code-editor.mdxindex 53ea0106e7f..079fb46714f 100644--- a/packages/twenty-docs/snippets/ui/generated/components/code-editor/code-editor.mdx+++ b/packages/twenty-docs/snippets/ui/generated/components/code-editor/code-editor.mdx@@ -15,28 +15,64 @@Grows the editor to fit its content instead of using `height`. Ignored when `resizable` is set.</ParamField>+<ParamField body="beforeMount" type="BeforeMount">+ Called with Monaco before editor creation, after the Twenty theme has been defined. Use it to register custom themes or languages.+</ParamField>++<ParamField body="className" type="string">+ Class applied to the Monaco editor-container div.+</ParamField>++<ParamField body="containerProps" type="Omit<Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "ref">, "children">">+ Native props, className and style for the outer Twenty group div. Its default `display: contents` preserves the Monaco section's parent sizing and flex layout without creating a layout box. Background, border, padding and dimensions require overriding `display`. Prefer `wrapperProps` for section layout styles. Its keyboard handler runs before focused editor keystrokes stop propagating.+</ParamField>+<ParamField body="contentPadding" type=""comfortable" | "default"" default="default">- `default` pads the top and bottom of the content. `comfortable` also widens the gap between line numbers and code.+ `default` supplies top and bottom padding. `comfortable` also widens the gap between line numbers and code. Explicit Monaco options override these defaults.+</ParamField>++<ParamField body="defaultLanguage" type="string">+ Initial Monaco language for a newly created model.+</ParamField>++<ParamField body="defaultPath" type="string">+ Initial model URI, used when `path` is omitted.+</ParamField>++<ParamField body="defaultValue" type="string">+ Initial content for a model created by Monaco React.</ParamField><ParamField body="height" type="string | number" default="450">- Editor height in pixels or as a CSS length. With `resizable`, a numeric height sets the initial height.+ Editor height in pixels or as a CSS length, defaulting to 450px. Resizing starts from this rendered height and resets when this prop changes. Auto-height uses it until content is measured.</ParamField><ParamField body="isLoading" type="boolean" default="false">Shows a loader at the editor height instead of the editor. A loader also shows while Monaco loads.</ParamField>+<ParamField body="keepCurrentModel" type="boolean" default="false">+ Keeps the current model when the editor unmounts. Defaults to false. The caller owns disposal of retained models.+</ParamField>+<ParamField body="language" type="string">Monaco language identifier for highlighting and language services, such as `json` or `typescript`.</ParamField>-<ParamField body="onChange" type="((value: string) => void)">- Called with the full content whenever it changes.+<ParamField body="line" type="number">+ Line revealed when the editor mounts or this prop changes.+</ParamField>++<ParamField body="loading" type="ReactNode" default="<Loader />">+ Content shown while Monaco loads or `isLoading` is true. Defaults to the Twenty Loader.+</ParamField>++<ParamField body="onChange" type="OnChange">+ Monaco React callback with the full content (string or undefined) and the original IModelContentChangedEvent.</ParamField><ParamField body="onMount" type="OnMount">- Called when the editor is ready, with the editor instance and the Monaco namespace. The Twenty theme is already applied.+ Called when the editor is ready, with the editor instance and the Monaco namespace. The selected theme is already applied.</ParamField><ParamField body="onValidate" type="OnValidate">@@ -44,19 +80,39 @@</ParamField><ParamField body="options" type="IStandaloneEditorConstructionOptions">- Monaco editor options merged over the Twenty defaults. `padding` is ignored; use `contentPadding` instead.+ Monaco editor options merged over Twenty defaults. Explicit values, including padding, replace the corresponding defaults. The `theme` prop takes precedence over `options.theme`.+</ParamField>++<ParamField body="overrideServices" type="IEditorOverrideServices">+ Monaco services passed through when the editor is created.+</ParamField>++<ParamField body="path" type="string">+ URI of the current model. Changing it selects or creates a model using Monaco React behavior.+</ParamField>++<ParamField body="ref" type="Ref<HTMLDivElement>">+ Ref to the outer Twenty group div, which has no measurable layout box with its default `display: contents`. Use `wrapperProps` for a measurable section ref or `onMount` for the Monaco editor instance.</ParamField><ParamField body="resizable" type="boolean" default="false">- Adds a handle below the editor to drag its height.+ Adds a height resize handle after Monaco mounts, bounded from 50px to 500px. Takes precedence over autoHeight. A changed height prop resets the resized height within these bounds.</ParamField><ParamField body="resizeLabel" type="string" default="Resize editor">Accessible name of the resize handle. Pass a localized label when `resizable` is enabled.</ParamField>+<ParamField body="saveViewState" type="boolean" default="true">+ Preserves Monaco React view state between model changes. Defaults to true.+</ParamField>+<ParamField body="setMarkers" type="((value: string) => IMarkerData[])">- Returns custom validation markers for the content. Runs when the editor mounts and after every change, replacing the previous custom markers.+ Returns custom validation markers for the current model content. Runs on mount, model selection and content changes, including controlled updates.+</ParamField>++<ParamField body="theme" type="string" default="Twenty theme">+ Monaco theme name. Takes precedence over `options.theme`, which takes precedence over the Twenty theme. Define custom themes in `beforeMount`.</ParamField><ParamField body="transparentBackground" type="boolean">@@ -70,3 +126,11 @@<ParamField body="variant" type=""borderless" | "default" | "with-header"" default="default">Border treatment: `default` draws a rounded border, `with-header` attaches the editor below a `CodeEditorHeader`, and `borderless` removes the border.</ParamField>++<ParamField body="width" type="string | number" default="100%">+ Width of the Monaco React section, in pixels or as a CSS length.+</ParamField>++<ParamField body="wrapperProps" type="object">+ Native props passed unchanged to the Monaco React section around the editor and Monaco React loading content. Use this section for layout styles and a measurable native ref. Not applied to the separate Twenty loader during initial Monaco configuration or `isLoading`. Native styles can override the section sizing.+</ParamField>diff --git a/packages/twenty-docs/ui/components/code-editor/code-editor.mdx b/packages/twenty-docs/ui/components/code-editor/code-editor.mdxindex e0a4d384776..0fc10c453fa 100644--- a/packages/twenty-docs/ui/components/code-editor/code-editor.mdx+++ b/packages/twenty-docs/ui/components/code-editor/code-editor.mdx@@ -31,6 +31,7 @@ The code editor does not run inside [front components](/developers/extend/apps/l```tsximport { useState } from 'react';+import { isDefined } from 'twenty-ui/utilities';import { CodeEditor } from 'twenty-ui/components/code-editor';export const PayloadEditor = () => {@@ -40,14 +41,67 @@ export const PayloadEditor = () => {<CodeEditorlanguage="json"value={payload}- onChange={setPayload}+ onChange={(value) => {+ if (isDefined(value)) {+ setPayload(value);+ }+ }}height={200}/>);};```-`onChange` receives the full content on every change. A loader shows until Monaco has loaded. Set `isLoading` to keep showing it while your own data loads.+`CodeEditorProps` includes the installed Monaco React editor contract. `onChange(value, event)` receives the content (`string | undefined`) and the original `IModelContentChangedEvent`, including changed ranges, version and undo/redo details. Guard an undefined value at the boundary where your application requires a string.++`beforeMount(monaco)` runs after the Twenty theme is defined and before editor creation. `onMount(editor, monaco)` receives the editor instance after the selected theme is applied. `onValidate(markers)` receives Monaco diagnostics unchanged. `overrideServices` passes through to editor creation.++A Twenty `Loader` shows until Monaco loads. Pass `loading` to customize that content, or set `isLoading` to keep it visible while your own data loads. `isLoading` unmounts an existing editor and follows Monaco React's model disposal rules.++## Models and values++Use `defaultValue`, `defaultLanguage` and `defaultPath` to initialize an uncontrolled model, or `value`, `language` and `path` for updates. These props retain Monaco React's behavior, including its rules for choosing initial values and reusing an existing model URI. Changing `defaultValue` does not overwrite a model that already exists.++Changing `path` selects or creates a model. `saveViewState` defaults to true and restores the model's cursor and scroll state when switching back. `line` reveals a line when the editor mounts or the prop changes. `keepCurrentModel` defaults to false; when true, the caller owns disposal of the retained model.++```tsx+import { CodeEditor } from 'twenty-ui/components/code-editor';++export const FileEditor = () => (+ <CodeEditor+ defaultPath="file:///workspace/settings.json"+ defaultLanguage="json"+ defaultValue={'{\n "name": "Acme"\n}'}+ saveViewState+ />+);+```++## Native integration++`ref` points to the outer Twenty group div, which uses `display: contents` by default. This keeps the Monaco section in the parent's sizing and flex layout. The outer div has no measurable layout box.++Use `containerProps` for the outer div's native attributes, event handlers, class and style. Background, border, padding and dimensions require overriding its `display`. Prefer Monaco React's `wrapperProps` section for layout styles and a measurable native ref. `className` targets the editor-container div inside that section; use `onMount` for the Monaco editor instance.++The Monaco React section contains its own loading content until the editor is ready. During initial bundled Monaco configuration or `isLoading`, Twenty renders a separate loader without `wrapperProps` or `className`. The outer `containerProps` and `ref` remain available in these states.++```tsx+import { useRef } from 'react';+import { CodeEditor } from 'twenty-ui/components/code-editor';++export const NamedEditor = () => {+ const containerRef = useRef<HTMLDivElement>(null);++ return (+ <CodeEditor+ ref={containerRef}+ containerProps={{ id: 'payload-editor' }}+ wrapperProps={{ 'data-editor-surface': 'payload' }}+ options={{ ariaLabel: 'Payload code' }}+ />+ );+};+```## Add a header@@ -81,15 +135,25 @@ The header accepts node content in `title`, `startElement`, and `endElement`. Us## Size and appearance-The editor is 450px tall by default. Set `height` to a number of pixels or a CSS length. `autoHeight` grows the editor with its content, and `resizable` adds a handle below it to drag the height. When both are set, `resizable` applies.+The editor is 450px tall and 100% wide by default. `width` and `height` accept pixels or a CSS length.++Sizing follows this order:++1. `resizable` starts from the rendered height, including CSS lengths, within the resize handle's 50px to 500px bounds. It adds a handle after Monaco mounts. Dragging or keyboard input then sets a pixel height. Changing `height` resets it within the same bounds.+2. Otherwise, `autoHeight` uses Monaco's content height. The explicit or default height is used until content is measured.+3. Otherwise, the explicit or default `height` applies.++Monaco React enables `automaticLayout` by default. If you disable it in `options`, your application must call `editor.layout()` when the container changes size. Native `wrapperProps.style` is passed unchanged and can override the section's width or height.Pass a localized `resizeLabel` to name the resize handle for screen readers.-`contentPadding="comfortable"` widens the gap between line numbers and code. `transparentBackground` lets the surrounding surface show through.+Twenty supplies font, formatting, scrollbar, minimap and padding defaults. `contentPadding="comfortable"` also widens the gap between line numbers and code. Caller `options` replace the corresponding defaults, including the whole `padding` object and `lineDecorationsWidth`.++An explicit `theme` takes precedence over `options.theme`; otherwise the editor follows Twenty's light or dark theme. Define custom Monaco themes in `beforeMount`. Monaco themes are global, so changing one affects other Monaco editors on the same page. `transparentBackground` controls the Twenty wrapper appearance independently.## Validation-Monaco reports its own diagnostics, such as JSON syntax errors, through `onValidate`. To add your own, return marker data from `setMarkers`. It runs when the editor mounts and after every change, and replaces the markers it set before.+Monaco reports its own diagnostics, such as JSON syntax errors, through `onValidate`. To add your own, return marker data from `setMarkers`. It runs on mount, model selection and every model content change, including controlled value updates, and replaces the custom markers for the current model.## Keyboarddiff --git a/packages/twenty-docs/ui/primitives/layout/resize-handle.mdx b/packages/twenty-docs/ui/primitives/layout/resize-handle.mdxindex d027ec617f3..4917e88f0a7 100644--- a/packages/twenty-docs/ui/primitives/layout/resize-handle.mdx+++ b/packages/twenty-docs/ui/primitives/layout/resize-handle.mdx@@ -159,11 +159,15 @@ Set `direction="normal"` or `direction="reverse"` when increasing size must foll`onResizeStart` receives the first bounded candidate after the pointer passes `dragThreshold`. The threshold defaults to `5` with `edge` and `0` otherwise, measured in physical pixels. `onResizeEnd` receives `{ cancelled, value }` for a started drag. Escape, pointer cancellation, lost pointer capture and unmounting cancel the gesture without committing; disabling the handle cancels it on its next pointer event. Cancellation calls `onValueChange` with the starting value, clamped to the current bounds. `onResizeEnd` receives that restored value.-Supply `onActivate` to handle a click without dragging, Enter or Space. Crossing the threshold prevents the following pointer click from activating, even when the pointer returns to its starting position. Native event handlers can prevent the default interaction.+Supply `onActivate` to handle a click without dragging, Enter or Space. Crossing the threshold prevents the following pointer click from activating, even when the pointer returns to its starting position.++Native handlers run before the handle's interaction. Calling `preventDefault()` in `onPointerDown` or `onKeyDown` skips that interaction. Preventing `onPointerMove` skips only that update and leaves the gesture active. Preventing `onPointerUp` cancels the drag, restores the starting bounded value and skips `onValueCommitted`. Pointer cancellation and lost capture still end the gesture.## Custom handle-`children` replaces the visible grip, and `children={null}` hides it; it does not replace the separator behavior. `render` can replace the root element. Custom wrappers must [forward the supplied props and ref](/ui/primitives/overview#custom-components) so focus, pointer capture, keyboard handlers, and accessibility attributes reach the same element.+`ref`, native attributes, `className`, `style` and native event handlers target the separator root, a `div` by default. The ref does not target the resized panel or the visible grip.++`children` replaces the visible grip, and `children={null}` hides it; it does not replace the separator behavior. `render` can replace the root element, and the ref then targets that replacement. Custom wrappers must [forward the supplied props and ref](/ui/primitives/overview#custom-components) so focus, pointer capture, keyboard handlers, and accessibility attributes reach the same element.## Propsdiff --git a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/RawJsonFieldInput.tsx b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/RawJsonFieldInput.tsxindex 9075361cb2e..592518a435d 100644--- a/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/RawJsonFieldInput.tsx+++ b/packages/twenty-front/src/modules/object-record/record-field/ui/meta-types/input/components/RawJsonFieldInput.tsx@@ -8,6 +8,7 @@ import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';import { useContext, useRef, useState } from 'react';import { Key } from 'ts-key-enum';+import { isDefined } from 'twenty-shared/utils';import { JsonTree } from 'twenty-ui/components/data-display';import { IconButton } from 'twenty-ui/components/input';import { CodeEditor } from 'twenty-ui/components/code-editor';@@ -102,7 +103,11 @@ export const RawJsonFieldInput = () => {onShiftTab?.({ newValue: value, skipPersist: !success });};- const handleChange = (newText: string) => {+ const handleChange = (newText: string | undefined) => {+ if (!isDefined(newText)) {+ return;+ }+setDraftValue(newText);};diff --git a/packages/twenty-front/src/modules/settings/admin-panel/config-variables/components/ConfigVariableDatabaseInput.tsx b/packages/twenty-front/src/modules/settings/admin-panel/config-variables/components/ConfigVariableDatabaseInput.tsxindex fbbe57ae79c..014b131527d 100644--- a/packages/twenty-front/src/modules/settings/admin-panel/config-variables/components/ConfigVariableDatabaseInput.tsx+++ b/packages/twenty-front/src/modules/settings/admin-panel/config-variables/components/ConfigVariableDatabaseInput.tsx@@ -8,7 +8,7 @@ import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContentimport { styled } from '@linaria/react';import { t } from '@lingui/core/macro';import { type ConfigVariableValue } from 'twenty-shared/types';-import { CustomError } from 'twenty-shared/utils';+import { CustomError, isDefined } from 'twenty-shared/utils';import { Dropdown } from 'twenty-ui/components/navigation';import { CodeEditor } from 'twenty-ui/components/code-editor';import { themeCssVariables } from 'twenty-ui/theme';@@ -225,6 +225,10 @@ export const ConfigVariableDatabaseInput = ({readOnly: disabled === true,}}onChange={(text) => {+ if (!isDefined(text)) {+ return;+ }+try {onChange(JSON.parse(text) as Record<string, unknown>);} catch {diff --git a/packages/twenty-front/src/modules/settings/logic-functions/components/SettingsLogicFunctionCodeEditor.tsx b/packages/twenty-front/src/modules/settings/logic-functions/components/SettingsLogicFunctionCodeEditor.tsxindex e76793173e6..e506a3e1fe9 100644--- a/packages/twenty-front/src/modules/settings/logic-functions/components/SettingsLogicFunctionCodeEditor.tsx+++ b/packages/twenty-front/src/modules/settings/logic-functions/components/SettingsLogicFunctionCodeEditor.tsx@@ -1,56 +1,69 @@import { useGetAvailablePackages } from '@/logic-functions/hooks/useGetAvailablePackages';-import { type EditorProps, type Monaco } from '@monaco-editor/react';+import { SettingsLogicFunctionCodeEditorModelsEffect } from '@/settings/logic-functions/components/SettingsLogicFunctionCodeEditorModelsEffect';+import { type SettingsLogicFunctionCodeEditorFile } from '@/settings/logic-functions/types/SettingsLogicFunctionCodeEditorFile';+import { createSettingsLogicFunctionCodeEditorModels } from '@/settings/logic-functions/utils/createSettingsLogicFunctionCodeEditorModels';+import { getSettingsLogicFunctionCodeEditorModelPath } from '@/settings/logic-functions/utils/getSettingsLogicFunctionCodeEditorModelPath';import { type editor } from 'monaco-editor';import { AutoTypings } from 'monaco-editor-auto-typings';+import { useState } from 'react';import { useParams } from 'react-router-dom';import { isDefined } from 'twenty-shared/utils';-import { CodeEditor } from 'twenty-ui/components/code-editor';+import {+ CodeEditor,+ type CodeEditorProps,+} from 'twenty-ui/components/code-editor';-export type File = {- language: string;- content: string;- path: string;-};--type SettingsLogicFunctionCodeEditorProps = Omit<EditorProps, 'onChange'> & {+type SettingsLogicFunctionCodeEditorProps = Omit<+ CodeEditorProps,+ | 'value'+ | 'defaultValue'+ | 'language'+ | 'defaultLanguage'+ | 'path'+ | 'defaultPath'+> & {currentFilePath: string;- files: File[];- onChange: (value: string) => void;+ files: SettingsLogicFunctionCodeEditorFile[];applicationVariableKeys?: string[];};export const SettingsLogicFunctionCodeEditor = ({currentFilePath,files,- onChange,+ beforeMount,+ onMount,+ keepCurrentModel = false,height = 450,- options = undefined,+ variant = 'with-header',applicationVariableKeys,+ ...codeEditorProps}: SettingsLogicFunctionCodeEditorProps) => {const { logicFunctionId = '' } = useParams();const { availablePackages } = useGetAvailablePackages({id: logicFunctionId,});+ const [editor, setEditor] = useState<editor.IStandaloneCodeEditor>();+ const [ownedModels, setOwnedModels] = useState<editor.ITextModel[]>([]);const currentFile = files.find((file) => file.path === currentFilePath);- const handleEditorDidMount = async (- editor: editor.IStandaloneCodeEditor,- monaco: Monaco,+ const handleEditorWillMount: NonNullable<CodeEditorProps['beforeMount']> = (+ monaco,) => {- if (files.length > 1) {- files.forEach((file) => {- const model = monaco.editor.getModel(monaco.Uri.file(file.path));+ beforeMount?.(monaco);+ setOwnedModels(+ createSettingsLogicFunctionCodeEditorModels({ monaco, files }),+ );+ };- if (!isDefined(model)) {- monaco.editor.createModel(- file.content,- file.language,- monaco.Uri.file(file.path),- );- }- });+ const handleEditorDidMount: NonNullable<CodeEditorProps['onMount']> = async (+ editor,+ monaco,+ ) => {+ setEditor(editor);+ onMount?.(editor, monaco);+ if (files.length > 1) {monaco.languages.typescript.typescriptDefaults.setCompilerOptions({...monaco.languages.typescript.typescriptDefaults.getCompilerOptions(),moduleResolution:@@ -107,15 +120,25 @@ export const SettingsLogicFunctionCodeEditor = ({return (isDefined(currentFile) &&isDefined(availablePackages) && (- <CodeEditor- height={height}- value={currentFile.content}- language={currentFile.language}- onMount={handleEditorDidMount}- onChange={onChange}- options={options}- variant="with-header"- />+ <>+ <CodeEditor+ // oxlint-disable-next-line react/jsx-props-no-spreading+ {...codeEditorProps}+ height={height}+ value={currentFile.content}+ language={currentFile.language}+ path={getSettingsLogicFunctionCodeEditorModelPath(currentFile.path)}+ beforeMount={handleEditorWillMount}+ onMount={handleEditorDidMount}+ keepCurrentModel={keepCurrentModel}+ variant={variant}+ />+ <SettingsLogicFunctionCodeEditorModelsEffect+ editor={editor}+ ownedModels={ownedModels}+ keepCurrentModel={keepCurrentModel}+ />+ </>));};diff --git a/packages/twenty-front/src/modules/settings/logic-functions/components/SettingsLogicFunctionCodeEditorModelsEffect.tsx b/packages/twenty-front/src/modules/settings/logic-functions/components/SettingsLogicFunctionCodeEditorModelsEffect.tsxnew file mode 100644index 00000000000..b002ca602dc--- /dev/null+++ b/packages/twenty-front/src/modules/settings/logic-functions/components/SettingsLogicFunctionCodeEditorModelsEffect.tsx@@ -0,0 +1,33 @@+import { type editor } from 'monaco-editor';+import { useEffect } from 'react';+import { isDefined } from 'twenty-shared/utils';++type SettingsLogicFunctionCodeEditorModelsEffectProps = {+ editor: editor.IStandaloneCodeEditor | undefined;+ ownedModels: editor.ITextModel[];+ keepCurrentModel: boolean;+};++export const SettingsLogicFunctionCodeEditorModelsEffect = ({+ editor,+ ownedModels,+ keepCurrentModel,+}: SettingsLogicFunctionCodeEditorModelsEffectProps) => {+ useEffect(() => {+ if (!isDefined(editor) || keepCurrentModel) {+ return;+ }++ const subscription = editor.onDidDispose(() => {+ for (const model of ownedModels) {+ if (!model.isDisposed()) {+ model.dispose();+ }+ }+ });++ return () => subscription.dispose();+ }, [editor, ownedModels, keepCurrentModel]);++ return null;+};diff --git a/packages/twenty-front/src/modules/settings/logic-functions/components/__stories__/ReopeningSettingsLogicFunctionCodeEditor.tsx b/packages/twenty-front/src/modules/settings/logic-functions/components/__stories__/ReopeningSettingsLogicFunctionCodeEditor.tsxnew file mode 100644index 00000000000..7617853abb0--- /dev/null+++ b/packages/twenty-front/src/modules/settings/logic-functions/components/__stories__/ReopeningSettingsLogicFunctionCodeEditor.tsx@@ -0,0 +1,99 @@+import { useState } from 'react';+import { isDefined } from 'twenty-shared/utils';+import { Button } from 'twenty-ui/primitives/input';+import { type CodeEditorProps } from 'twenty-ui/components/code-editor';++import { SettingsLogicFunctionCodeEditor } from '@/settings/logic-functions/components/SettingsLogicFunctionCodeEditor';+import { type SettingsLogicFunctionCodeEditorFile } from '@/settings/logic-functions/types/SettingsLogicFunctionCodeEditorFile';++type ReopeningSettingsLogicFunctionCodeEditorProps = {+ filePathPrefix: string;+ keepCurrentModel?: boolean;+ beforeMount?: CodeEditorProps['beforeMount'];+ onMount: NonNullable<CodeEditorProps['onMount']>;+ onChange: NonNullable<CodeEditorProps['onChange']>;+};++export const ReopeningSettingsLogicFunctionCodeEditor = ({+ filePathPrefix,+ keepCurrentModel,+ beforeMount,+ onMount,+ onChange,+}: ReopeningSettingsLogicFunctionCodeEditorProps) => {+ const indexFilePath = `${filePathPrefix}/index.ts`;+ const helperFilePath = `${filePathPrefix}/helper.ts`;+ const [isOpen, setIsOpen] = useState(true);+ const [currentFilePath, setCurrentFilePath] = useState(indexFilePath);+ const [files, setFiles] = useState<SettingsLogicFunctionCodeEditorFile[]>([+ {+ path: indexFilePath,+ language: 'typescript',+ content: "export const source = 'initial';",+ },+ {+ path: helperFilePath,+ language: 'typescript',+ content: "export const helper = 'secondary';",+ },+ ]);++ const handleChange: NonNullable<CodeEditorProps['onChange']> = (+ value,+ event,+ ) => {+ onChange(value, event);++ if (!isDefined(value)) {+ return;+ }++ setFiles((currentFiles) =>+ currentFiles.map((file) =>+ file.path === currentFilePath ? { ...file, content: value } : file,+ ),+ );+ };++ const reopenEditor = () => {+ setFiles((currentFiles) =>+ currentFiles.map((file) =>+ file.path === indexFilePath+ ? { ...file, content: "export const source = 'updated';" }+ : file,+ ),+ );+ setCurrentFilePath(indexFilePath);+ setIsOpen(true);+ };++ return (+ <>+ <Button+ onClick={() => setCurrentFilePath(helperFilePath)}+ disabled={!isOpen}+ >+ Select helper file+ </Button>+ <Button onClick={() => setIsOpen(false)} disabled={!isOpen}>+ Close editor+ </Button>+ <Button onClick={reopenEditor} disabled={isOpen}>+ Reopen with updated source+ </Button>+ {isOpen && (+ <SettingsLogicFunctionCodeEditor+ currentFilePath={currentFilePath}+ files={files}+ beforeMount={beforeMount}+ onMount={onMount}+ onChange={handleChange}+ keepCurrentModel={keepCurrentModel}+ options={{ occurrencesHighlight: 'off' }}+ variant="borderless"+ height={180}+ />+ )}+ </>+ );+};diff --git a/packages/twenty-front/src/modules/settings/logic-functions/components/__stories__/SettingsLogicFunctionCodeEditor.stories.tsx b/packages/twenty-front/src/modules/settings/logic-functions/components/__stories__/SettingsLogicFunctionCodeEditor.stories.tsxnew file mode 100644index 00000000000..52214d59968--- /dev/null+++ b/packages/twenty-front/src/modules/settings/logic-functions/components/__stories__/SettingsLogicFunctionCodeEditor.stories.tsx@@ -0,0 +1,247 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { graphql, HttpResponse } from 'msw';+import { expect, fn, userEvent, waitFor, within } from 'storybook/test';+import { isDefined } from 'twenty-shared/utils';+import { type CodeEditorProps } from 'twenty-ui/components/code-editor';+import { ComponentDecorator } from 'twenty-ui/testing';++import { getSettingsLogicFunctionCodeEditorModelPath } from '@/settings/logic-functions/utils/getSettingsLogicFunctionCodeEditorModelPath';+import { ReopeningSettingsLogicFunctionCodeEditor } from '@/settings/logic-functions/components/__stories__/ReopeningSettingsLogicFunctionCodeEditor';+import { MemoryRouterDecorator } from '~/testing/decorators/MemoryRouterDecorator';++const handleMount = fn<NonNullable<CodeEditorProps['onMount']>>();+const handleChange = fn<NonNullable<CodeEditorProps['onChange']>>();+const EDITOR_LOAD_TIMEOUT_IN_MS = 20_000;+const BORROWED_FILE_PATH_PREFIX = '/logic-function-borrowed-model-story';++const getMountedEditor = () => {+ const mountedEditor = handleMount.mock.calls.at(-1);++ if (!isDefined(mountedEditor)) {+ throw new Error('The logic function editor has not mounted');+ }++ const [editor, monaco] = mountedEditor;++ return { editor, monaco };+};++const waitForRenderedSource = async ({+ canvasElement,+ expectedSource,+}: {+ canvasElement: HTMLElement;+ expectedSource: string;+}) => {+ await waitFor(+ () => {+ expect(handleMount).toHaveBeenCalled();+ expect(canvasElement.querySelector('.view-lines')).toHaveTextContent(+ expectedSource,+ { normalizeWhitespace: false },+ );+ },+ { timeout: EDITOR_LOAD_TIMEOUT_IN_MS },+ );+};++const meta: Meta<typeof ReopeningSettingsLogicFunctionCodeEditor> = {+ title: 'Modules/Settings/LogicFunctions/SettingsLogicFunctionCodeEditor',+ component: ReopeningSettingsLogicFunctionCodeEditor,+ decorators: [ComponentDecorator, MemoryRouterDecorator],+ args: {+ filePathPrefix: '/logic-function-reopen-story',+ onMount: handleMount,+ onChange: handleChange,+ },+ parameters: {+ msw: {+ handlers: [+ graphql.query('FindManyAvailablePackages', () =>+ HttpResponse.json({ data: { getAvailablePackages: {} } }),+ ),+ ],+ },+ },+ beforeEach: () => {+ handleMount.mockClear();+ handleChange.mockClear();+ },+};++export default meta;+type Story = StoryObj<typeof ReopeningSettingsLogicFunctionCodeEditor>;++export const ReopenAfterFileSwitch: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await waitForRenderedSource({+ canvasElement,+ expectedSource: "export const source = 'initial';",+ });++ const { monaco } = getMountedEditor();+ const indexModelUri = monaco.Uri.parse(+ getSettingsLogicFunctionCodeEditorModelPath(+ `${args.filePathPrefix}/index.ts`,+ ),+ );+ const helperModelUri = monaco.Uri.parse(+ getSettingsLogicFunctionCodeEditorModelPath(+ `${args.filePathPrefix}/helper.ts`,+ ),+ );+ const indexModel = monaco.editor.getModel(indexModelUri);+ const helperModel = monaco.editor.getModel(helperModelUri);++ await userEvent.click(+ canvas.getByRole('button', { name: 'Select helper file' }),+ );+ await waitForRenderedSource({+ canvasElement,+ expectedSource: "export const helper = 'secondary';",+ });++ await userEvent.click(canvas.getByRole('button', { name: 'Close editor' }));+ await waitFor(() => {+ expect(canvas.queryByRole('textbox')).not.toBeInTheDocument();+ expect(indexModel?.isDisposed()).toBe(true);+ expect(helperModel?.isDisposed()).toBe(true);+ expect(monaco.editor.getModel(indexModelUri)).toBeNull();+ expect(monaco.editor.getModel(helperModelUri)).toBeNull();+ });++ handleMount.mockClear();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Reopen with updated source' }),+ );+ await waitForRenderedSource({+ canvasElement,+ expectedSource: "export const source = 'updated';",+ });+ const { editor } = getMountedEditor();+ expect(editor.getValue()).toBe("export const source = 'updated';");+ expect(editor.getModel()).not.toBe(indexModel);+ editor.setPosition({ lineNumber: 1, column: 1 });+ canvas.getByRole('textbox').focus();+ handleChange.mockClear();+ await userEvent.keyboard('x');+ await waitFor(() => {+ expect(handleChange).toHaveBeenLastCalledWith(+ "xexport const source = 'updated';",+ expect.any(Object),+ );+ expect(editor.getValue()).toBe("xexport const source = 'updated';");+ });+ await waitForRenderedSource({+ canvasElement,+ expectedSource: "xexport const source = 'updated';",+ });+ },+};++export const KeepCurrentModel: Story = {+ args: {+ filePathPrefix: '/logic-function-retained-model-story',+ keepCurrentModel: true,+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await waitForRenderedSource({+ canvasElement,+ expectedSource: "export const source = 'initial';",+ });+ const { monaco } = getMountedEditor();+ const modelUris = ['index.ts', 'helper.ts'].map((filename) =>+ monaco.Uri.parse(+ getSettingsLogicFunctionCodeEditorModelPath(+ `${args.filePathPrefix}/${filename}`,+ ),+ ),+ );+ const models = modelUris.map((modelUri) =>+ monaco.editor.getModel(modelUri),+ );++ try {+ await userEvent.click(+ canvas.getByRole('button', { name: 'Select helper file' }),+ );+ await waitForRenderedSource({+ canvasElement,+ expectedSource: "export const helper = 'secondary';",+ });+ await userEvent.click(+ canvas.getByRole('button', { name: 'Close editor' }),+ );+ await waitFor(() => {+ expect(canvas.queryByRole('textbox')).not.toBeInTheDocument();++ for (const [index, modelUri] of modelUris.entries()) {+ expect(models[index]?.isDisposed()).toBe(false);+ expect(monaco.editor.getModel(modelUri)).toBe(models[index]);+ }+ });+ handleChange.mockClear();++ for (const model of models) {+ model?.setValue('Updated after closing');+ }++ expect(handleChange).not.toHaveBeenCalled();+ } finally {+ for (const model of models) {+ model?.dispose();+ }+ }+ },+};++export const BorrowedModel: Story = {+ args: {+ filePathPrefix: BORROWED_FILE_PATH_PREFIX,+ beforeMount: (monaco) => {+ monaco.editor.createModel(+ "export const helper = 'secondary';",+ 'typescript',+ monaco.Uri.parse(+ getSettingsLogicFunctionCodeEditorModelPath(+ `${BORROWED_FILE_PATH_PREFIX}/helper.ts`,+ ),+ ),+ );+ },+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ await waitForRenderedSource({+ canvasElement,+ expectedSource: "export const source = 'initial';",+ });+ const { editor, monaco } = getMountedEditor();+ const indexModel = editor.getModel();+ const helperModelUri = monaco.Uri.parse(+ getSettingsLogicFunctionCodeEditorModelPath(+ `${args.filePathPrefix}/helper.ts`,+ ),+ );+ const helperModel = monaco.editor.getModel(helperModelUri);++ try {+ await userEvent.click(+ canvas.getByRole('button', { name: 'Close editor' }),+ );+ await waitFor(() => {+ expect(canvas.queryByRole('textbox')).not.toBeInTheDocument();+ expect(indexModel?.isDisposed()).toBe(true);+ expect(helperModel?.isDisposed()).toBe(false);+ expect(monaco.editor.getModel(helperModelUri)).toBe(helperModel);+ });+ } finally {+ helperModel?.dispose();+ }+ },+};diff --git a/packages/twenty-front/src/modules/settings/logic-functions/components/tabs/SettingsLogicFunctionCodeEditorTab.tsx b/packages/twenty-front/src/modules/settings/logic-functions/components/tabs/SettingsLogicFunctionCodeEditorTab.tsxindex db9ba26d0c3..b446610147d 100644--- a/packages/twenty-front/src/modules/settings/logic-functions/components/tabs/SettingsLogicFunctionCodeEditorTab.tsx+++ b/packages/twenty-front/src/modules/settings/logic-functions/components/tabs/SettingsLogicFunctionCodeEditorTab.tsx@@ -1,13 +1,12 @@-import {- type File,- SettingsLogicFunctionCodeEditor,-} from '@/settings/logic-functions/components/SettingsLogicFunctionCodeEditor';+import { SettingsLogicFunctionCodeEditor } from '@/settings/logic-functions/components/SettingsLogicFunctionCodeEditor';+import { type SettingsLogicFunctionCodeEditorFile } from '@/settings/logic-functions/types/SettingsLogicFunctionCodeEditorFile';import { SETTINGS_LOGIC_FUNCTION_TAB_LIST_COMPONENT_ID } from '@/settings/logic-functions/constants/SettingsLogicFunctionTabListComponentId';import { TabList } from '@/ui/layout/tab-list/components/TabList';import { activeTabIdComponentState } from '@/ui/layout/tab-list/states/activeTabIdComponentState';import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';import { styled } from '@linaria/react';import { t } from '@lingui/core/macro';+import { isDefined } from 'twenty-shared/utils';import { Section } from 'twenty-ui/components/layout';import { CodeEditorHeader } from 'twenty-ui/components/code-editor';import { IconPlayerPlay } from 'twenty-ui/icon';@@ -26,7 +25,7 @@ export const SettingsLogicFunctionCodeEditorTab = ({isTesting = false,applicationVariableKeys,}: {- files: File[];+ files: SettingsLogicFunctionCodeEditorFile[];handleExecute: () => void;onChange: (value: string) => void;isTesting?: boolean;@@ -70,7 +69,13 @@ export const SettingsLogicFunctionCodeEditorTab = ({<SettingsLogicFunctionCodeEditorfiles={files}currentFilePath={activeTabId}- onChange={(newCodeValue: string) => onChange(newCodeValue)}+ onChange={(newCodeValue) => {+ if (!isDefined(newCodeValue)) {+ return;+ }++ onChange(newCodeValue);+ }}applicationVariableKeys={applicationVariableKeys}/>)}diff --git a/packages/twenty-front/src/modules/settings/logic-functions/components/tabs/SettingsLogicFunctionTestTab.tsx b/packages/twenty-front/src/modules/settings/logic-functions/components/tabs/SettingsLogicFunctionTestTab.tsxindex a464256f35d..4023c811222 100644--- a/packages/twenty-front/src/modules/settings/logic-functions/components/tabs/SettingsLogicFunctionTestTab.tsx+++ b/packages/twenty-front/src/modules/settings/logic-functions/components/tabs/SettingsLogicFunctionTestTab.tsx@@ -96,7 +96,11 @@ export const SettingsLogicFunctionTestTab = ({triggerButtons.push({ kind: 'tool', label: t`AI tool`, Icon: IconTool });}- const onChange = (value: string) => {+ const onChange = (value: string | undefined) => {+ if (!isDefined(value)) {+ return;+ }+try {updateLogicFunctionInput(JSON.parse(value));} catch {diff --git a/packages/twenty-front/src/modules/settings/logic-functions/types/SettingsLogicFunctionCodeEditorFile.ts b/packages/twenty-front/src/modules/settings/logic-functions/types/SettingsLogicFunctionCodeEditorFile.tsnew file mode 100644index 00000000000..7ae63689982--- /dev/null+++ b/packages/twenty-front/src/modules/settings/logic-functions/types/SettingsLogicFunctionCodeEditorFile.ts@@ -0,0 +1,5 @@+export type SettingsLogicFunctionCodeEditorFile = {+ language: string;+ content: string;+ path: string;+};diff --git a/packages/twenty-front/src/modules/settings/logic-functions/utils/__tests__/getSettingsLogicFunctionCodeEditorModelPath.test.ts b/packages/twenty-front/src/modules/settings/logic-functions/utils/__tests__/getSettingsLogicFunctionCodeEditorModelPath.test.tsnew file mode 100644index 00000000000..373cef5df73--- /dev/null+++ b/packages/twenty-front/src/modules/settings/logic-functions/utils/__tests__/getSettingsLogicFunctionCodeEditorModelPath.test.ts@@ -0,0 +1,23 @@+import { getSettingsLogicFunctionCodeEditorModelPath } from '@/settings/logic-functions/utils/getSettingsLogicFunctionCodeEditorModelPath';++describe('getSettingsLogicFunctionCodeEditorModelPath', () => {+ it('creates a file URI for a root filename', () => {+ expect(getSettingsLogicFunctionCodeEditorModelPath('index.ts')).toBe(+ 'file:///index.ts',+ );+ });++ it('preserves nested directories in the model path', () => {+ expect(+ getSettingsLogicFunctionCodeEditorModelPath(+ 'src/logic-functions/index.ts',+ ),+ ).toBe('file:///src/logic-functions/index.ts');+ });++ it('encodes spaces, hash characters, and question marks as filename content', () => {+ expect(+ getSettingsLogicFunctionCodeEditorModelPath('src/my file#draft?.ts'),+ ).toBe('file:///src/my%20file%23draft%3F.ts');+ });+});diff --git a/packages/twenty-front/src/modules/settings/logic-functions/utils/createSettingsLogicFunctionCodeEditorModels.ts b/packages/twenty-front/src/modules/settings/logic-functions/utils/createSettingsLogicFunctionCodeEditorModels.tsnew file mode 100644index 00000000000..d7626c60ce4--- /dev/null+++ b/packages/twenty-front/src/modules/settings/logic-functions/utils/createSettingsLogicFunctionCodeEditorModels.ts@@ -0,0 +1,31 @@+import { type SettingsLogicFunctionCodeEditorFile } from '@/settings/logic-functions/types/SettingsLogicFunctionCodeEditorFile';+import { getSettingsLogicFunctionCodeEditorModelPath } from '@/settings/logic-functions/utils/getSettingsLogicFunctionCodeEditorModelPath';+import { type Monaco } from '@monaco-editor/react';+import { type editor } from 'monaco-editor';+import { isDefined } from 'twenty-shared/utils';++export const createSettingsLogicFunctionCodeEditorModels = ({+ monaco,+ files,+}: {+ monaco: Monaco;+ files: SettingsLogicFunctionCodeEditorFile[];+}): editor.ITextModel[] => {+ const ownedModels: editor.ITextModel[] = [];++ for (const file of files) {+ const modelUri = monaco.Uri.parse(+ getSettingsLogicFunctionCodeEditorModelPath(file.path),+ );++ if (isDefined(monaco.editor.getModel(modelUri))) {+ continue;+ }++ ownedModels.push(+ monaco.editor.createModel(file.content, file.language, modelUri),+ );+ }++ return ownedModels;+};diff --git a/packages/twenty-front/src/modules/settings/logic-functions/utils/getSettingsLogicFunctionCodeEditorModelPath.ts b/packages/twenty-front/src/modules/settings/logic-functions/utils/getSettingsLogicFunctionCodeEditorModelPath.tsnew file mode 100644index 00000000000..6859e100cf1--- /dev/null+++ b/packages/twenty-front/src/modules/settings/logic-functions/utils/getSettingsLogicFunctionCodeEditorModelPath.ts@@ -0,0 +1,10 @@+const FILE_MODEL_BASE_URL = 'file:///';++export const getSettingsLogicFunctionCodeEditorModelPath = (+ filePath: string,+) => {+ const modelUrl = new URL(FILE_MODEL_BASE_URL);+ modelUrl.pathname = filePath;++ return modelUrl.toString();+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowCodeEditor.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowCodeEditor.tsxindex 3731f4b2f32..a225662c3fc 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowCodeEditor.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowCodeEditor.tsx@@ -1,10 +1,11 @@import { getWrongExportedFunctionMarkers } from '@/workflow/workflow-steps/workflow-actions/code-action/utils/getWrongExportedFunctionMarkers';import { styled } from '@linaria/react';import { useLingui } from '@lingui/react/macro';-import { type Monaco } from '@monaco-editor/react';-import { type editor } from 'monaco-editor';import { LightIconButton } from 'twenty-ui/components/input';-import { CodeEditor } from 'twenty-ui/components/code-editor';+import {+ CodeEditor,+ type CodeEditorProps,+} from 'twenty-ui/components/code-editor';import { IconMaximize } from 'twenty-ui/icon';import { themeCssVariables } from 'twenty-ui/theme';@@ -28,9 +29,9 @@ const StyledFullScreenButtonContainer = styled.div`type WorkflowCodeEditorProps = {value?: string;- onChange: (value: string) => void;- onMount: (editor: editor.IStandaloneCodeEditor, monaco: Monaco) => void;- options: editor.IStandaloneEditorConstructionOptions;+ onChange: NonNullable<CodeEditorProps['onChange']>;+ onMount: NonNullable<CodeEditorProps['onMount']>;+ options: NonNullable<CodeEditorProps['options']>;readonly?: boolean;fullScreenMode?: boolean;onEnterFullScreen?: () => void;diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCode.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCode.tsxindex ae733c17885..3a015f3e0ce 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCode.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowEditActionCode.tsx@@ -273,8 +273,12 @@ export const WorkflowEditActionCode = ({500,);- const handleCodeChange = async (newCode: string) => {- if (actionOptions.readonly === true || !isDefined(workflow)) {+ const handleCodeChange = async (newCode: string | undefined) => {+ if (+ actionOptions.readonly === true ||+ !isDefined(workflow) ||+ !isDefined(newCode)+ ) {return;}diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/__stories__/HttpRequestExecutionResult.stories.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/__stories__/HttpRequestExecutionResult.stories.tsxindex b275a1adfd5..75a6a46a712 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/__stories__/HttpRequestExecutionResult.stories.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/http-request-action/components/__stories__/HttpRequestExecutionResult.stories.tsx@@ -1,5 +1,5 @@import { type Meta, type StoryObj } from '@storybook/react-vite';-import { expect, within } from 'storybook/test';+import { expect, waitFor, within } from 'storybook/test';import { ComponentDecorator } from 'twenty-ui/testing';import { ARGOS_CAPTURE_DISABLED } from '~/testing/constants/ArgosCaptureDisabled';@@ -8,6 +8,9 @@ import { ToastDecorator } from '~/testing/decorators/ToastDecorator';import { HttpRequestExecutionResult } from '@/workflow/workflow-steps/workflow-actions/http-request-action/components/HttpRequestExecutionResult';import type { HttpRequestTestData } from '@/workflow/workflow-steps/workflow-actions/http-request-action/types/HttpRequestTestData';+const NON_BREAKING_SPACE = ' ';+const CODE_EDITOR_LOAD_TIMEOUT_IN_MS = 20_000;+const meta: Meta<typeof HttpRequestExecutionResult> = {title: 'Modules/Workflow/Actions/HttpRequest/ExecutionResult',component: HttpRequestExecutionResult,@@ -237,9 +240,15 @@ export const NetworkError: Story = {expect(await canvas.findByText('Request Failed')).toBeVisible();expect(await canvas.findByText('An error occurred')).toBeVisible();- const codeEditorValue = await canvas.findByTestId('code-editor-value');- expect(codeEditorValue).toHaveValue(- 'Network connection failed: timeout after 30 seconds',+ await waitFor(+ () => {+ const renderedLines = canvasElement.querySelector('.view-lines');++ expect(+ renderedLines?.textContent?.split(NON_BREAKING_SPACE).join(' '),+ ).toContain('Network connection failed: timeout after 30 seconds');+ },+ { timeout: CODE_EDITOR_LOAD_TIMEOUT_IN_MS },);},};diff --git a/packages/twenty-ui/docs/codeEditorPropDescriptions.ts b/packages/twenty-ui/docs/codeEditorPropDescriptions.tsindex ca470d475d1..c795d6cf4ca 100644--- a/packages/twenty-ui/docs/codeEditorPropDescriptions.ts+++ b/packages/twenty-ui/docs/codeEditorPropDescriptions.ts@@ -1,32 +1,58 @@import { type CodeEditorProps } from '../src/components/code-editor/CodeEditor/types/CodeEditorProps';export const CODE_EDITOR_PROP_DESCRIPTIONS = {+ defaultValue: 'Initial content for a model created by Monaco React.',+ defaultLanguage: 'Initial Monaco language for a newly created model.',+ defaultPath: 'Initial model URI, used when `path` is omitted.',value:'Content of the editor. Pair it with `onChange` to control the editor.',language:'Monaco language identifier for highlighting and language services, such as `json` or `typescript`.',height:- 'Editor height in pixels or as a CSS length. With `resizable`, a numeric height sets the initial height.',+ 'Editor height in pixels or as a CSS length, defaulting to 450px. Resizing starts from this rendered height and resets when this prop changes. Auto-height uses it until content is measured.',+ width: 'Width of the Monaco React section, in pixels or as a CSS length.',+ path: 'URI of the current model. Changing it selects or creates a model using Monaco React behavior.',+ theme:+ 'Monaco theme name. Takes precedence over `options.theme`, which takes precedence over the Twenty theme. Define custom themes in `beforeMount`.',+ loading:+ 'Content shown while Monaco loads or `isLoading` is true. Defaults to the Twenty Loader.',+ line: 'Line revealed when the editor mounts or this prop changes.',options:- 'Monaco editor options merged over the Twenty defaults. `padding` is ignored; use `contentPadding` instead.',+ 'Monaco editor options merged over Twenty defaults. Explicit values, including padding, replace the corresponding defaults. The `theme` prop takes precedence over `options.theme`.',+ overrideServices:+ 'Monaco services passed through when the editor is created.',+ saveViewState:+ 'Preserves Monaco React view state between model changes. Defaults to true.',+ keepCurrentModel:+ 'Keeps the current model when the editor unmounts. Defaults to false. The caller owns disposal of retained models.',+ className: 'Class applied to the Monaco editor-container div.',+ wrapperProps:+ 'Native props passed unchanged to the Monaco React section around the editor and Monaco React loading content. Use this section for layout styles and a measurable native ref. Not applied to the separate Twenty loader during initial Monaco configuration or `isLoading`. Native styles can override the section sizing.',+ containerProps:+ "Native props, className and style for the outer Twenty group div. Its default `display: contents` preserves the Monaco section's parent sizing and flex layout without creating a layout box. Background, border, padding and dimensions require overriding `display`. Prefer `wrapperProps` for section layout styles. Its keyboard handler runs before focused editor keystrokes stop propagating.",+ ref: 'Ref to the outer Twenty group div, which has no measurable layout box with its default `display: contents`. Use `wrapperProps` for a measurable section ref or `onMount` for the Monaco editor instance.',+ beforeMount:+ 'Called with Monaco before editor creation, after the Twenty theme has been defined. Use it to register custom themes or languages.',onMount:- 'Called when the editor is ready, with the editor instance and the Monaco namespace. The Twenty theme is already applied.',+ 'Called when the editor is ready, with the editor instance and the Monaco namespace. The selected theme is already applied.',onValidate:'Called with the markers Monaco reports after validating the content, such as JSON syntax errors.',- onChange: 'Called with the full content whenever it changes.',+ onChange:+ 'Monaco React callback with the full content (string or undefined) and the original IModelContentChangedEvent.',setMarkers:- 'Returns custom validation markers for the content. Runs when the editor mounts and after every change, replacing the previous custom markers.',+ 'Returns custom validation markers for the current model content. Runs on mount, model selection and content changes, including controlled updates.',variant:'Border treatment: `default` draws a rounded border, `with-header` attaches the editor below a `CodeEditorHeader`, and `borderless` removes the border.',isLoading:'Shows a loader at the editor height instead of the editor. A loader also shows while Monaco loads.',transparentBackground:'Removes the editor background so the surrounding surface shows through.',- resizable: 'Adds a handle below the editor to drag its height.',+ resizable:+ 'Adds a height resize handle after Monaco mounts, bounded from 50px to 500px. Takes precedence over autoHeight. A changed height prop resets the resized height within these bounds.',resizeLabel:'Accessible name of the resize handle. Pass a localized label when `resizable` is enabled.',contentPadding:- '`default` pads the top and bottom of the content. `comfortable` also widens the gap between line numbers and code.',+ '`default` supplies top and bottom padding. `comfortable` also widens the gap between line numbers and code. Explicit Monaco options override these defaults.',autoHeight:'Grows the editor to fit its content instead of using `height`. Ignored when `resizable` is set.',} satisfies Partial<Record<keyof CodeEditorProps, string>>;diff --git a/packages/twenty-ui/docs/components.ts b/packages/twenty-ui/docs/components.tsindex bdfe0161114..392d8f9771c 100644--- a/packages/twenty-ui/docs/components.ts+++ b/packages/twenty-ui/docs/components.ts@@ -806,6 +806,7 @@ export const DOCUMENTED_COMPONENTS = [entryPoint: 'twenty-ui/components/code-editor',slug: 'components/code-editor/code-editor',propDescriptions: CODE_EDITOR_PROP_DESCRIPTIONS,+ propDefaults: { theme: 'Twenty theme', saveViewState: 'true' },},{name: 'CodeEditorHeader',diff --git a/packages/twenty-ui/generated/components.docs.json b/packages/twenty-ui/generated/components.docs.jsonindex 55deee04361..38f0f1a4459 100644--- a/packages/twenty-ui/generated/components.docs.json+++ b/packages/twenty-ui/generated/components.docs.json@@ -12044,19 +12044,61 @@"defaultValue": "false","description": "Grows the editor to fit its content instead of using `height`. Ignored when `resizable` is set."},+ {+ "name": "beforeMount",+ "type": "BeforeMount",+ "required": false,+ "defaultValue": null,+ "description": "Called with Monaco before editor creation, after the Twenty theme has been defined. Use it to register custom themes or languages."+ },+ {+ "name": "className",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "Class applied to the Monaco editor-container div."+ },+ {+ "name": "containerProps",+ "type": "Omit<Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, \"ref\">, \"children\">",+ "required": false,+ "defaultValue": null,+ "description": "Native props, className and style for the outer Twenty group div. Its default `display: contents` preserves the Monaco section's parent sizing and flex layout without creating a layout box. Background, border, padding and dimensions require overriding `display`. Prefer `wrapperProps` for section layout styles. Its keyboard handler runs before focused editor keystrokes stop propagating."+ },{"name": "contentPadding","type": "\"comfortable\" | \"default\"","required": false,"defaultValue": "default",- "description": "`default` pads the top and bottom of the content. `comfortable` also widens the gap between line numbers and code."+ "description": "`default` supplies top and bottom padding. `comfortable` also widens the gap between line numbers and code. Explicit Monaco options override these defaults."+ },+ {+ "name": "defaultLanguage",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "Initial Monaco language for a newly created model."+ },+ {+ "name": "defaultPath",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "Initial model URI, used when `path` is omitted."+ },+ {+ "name": "defaultValue",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "Initial content for a model created by Monaco React."},{"name": "height","type": "string | number","required": false,"defaultValue": "450",- "description": "Editor height in pixels or as a CSS length. With `resizable`, a numeric height sets the initial height."+ "description": "Editor height in pixels or as a CSS length, defaulting to 450px. Resizing starts from this rendered height and resets when this prop changes. Auto-height uses it until content is measured."},{"name": "isLoading",@@ -12065,6 +12107,13 @@"defaultValue": "false","description": "Shows a loader at the editor height instead of the editor. A loader also shows while Monaco loads."},+ {+ "name": "keepCurrentModel",+ "type": "boolean",+ "required": false,+ "defaultValue": "false",+ "description": "Keeps the current model when the editor unmounts. Defaults to false. The caller owns disposal of retained models."+ },{"name": "language","type": "string",@@ -12072,19 +12121,33 @@"defaultValue": null,"description": "Monaco language identifier for highlighting and language services, such as `json` or `typescript`."},+ {+ "name": "line",+ "type": "number",+ "required": false,+ "defaultValue": null,+ "description": "Line revealed when the editor mounts or this prop changes."+ },+ {+ "name": "loading",+ "type": "ReactNode",+ "required": false,+ "defaultValue": "<Loader />",+ "description": "Content shown while Monaco loads or `isLoading` is true. Defaults to the Twenty Loader."+ },{"name": "onChange",- "type": "((value: string) => void)",+ "type": "OnChange","required": false,"defaultValue": null,- "description": "Called with the full content whenever it changes."+ "description": "Monaco React callback with the full content (string or undefined) and the original IModelContentChangedEvent."},{"name": "onMount","type": "OnMount","required": false,"defaultValue": null,- "description": "Called when the editor is ready, with the editor instance and the Monaco namespace. The Twenty theme is already applied."+ "description": "Called when the editor is ready, with the editor instance and the Monaco namespace. The selected theme is already applied."},{"name": "onValidate",@@ -12098,14 +12161,35 @@"type": "IStandaloneEditorConstructionOptions","required": false,"defaultValue": null,- "description": "Monaco editor options merged over the Twenty defaults. `padding` is ignored; use `contentPadding` instead."+ "description": "Monaco editor options merged over Twenty defaults. Explicit values, including padding, replace the corresponding defaults. The `theme` prop takes precedence over `options.theme`."+ },+ {+ "name": "overrideServices",+ "type": "IEditorOverrideServices",+ "required": false,+ "defaultValue": null,+ "description": "Monaco services passed through when the editor is created."+ },+ {+ "name": "path",+ "type": "string",+ "required": false,+ "defaultValue": null,+ "description": "URI of the current model. Changing it selects or creates a model using Monaco React behavior."+ },+ {+ "name": "ref",+ "type": "Ref<HTMLDivElement>",+ "required": false,+ "defaultValue": null,+ "description": "Ref to the outer Twenty group div, which has no measurable layout box with its default `display: contents`. Use `wrapperProps` for a measurable section ref or `onMount` for the Monaco editor instance."},{"name": "resizable","type": "boolean","required": false,"defaultValue": "false",- "description": "Adds a handle below the editor to drag its height."+ "description": "Adds a height resize handle after Monaco mounts, bounded from 50px to 500px. Takes precedence over autoHeight. A changed height prop resets the resized height within these bounds."},{"name": "resizeLabel",@@ -12114,12 +12198,26 @@"defaultValue": "Resize editor","description": "Accessible name of the resize handle. Pass a localized label when `resizable` is enabled."},+ {+ "name": "saveViewState",+ "type": "boolean",+ "required": false,+ "defaultValue": "true",+ "description": "Preserves Monaco React view state between model changes. Defaults to true."+ },{"name": "setMarkers","type": "((value: string) => IMarkerData[])","required": false,"defaultValue": null,- "description": "Returns custom validation markers for the content. Runs when the editor mounts and after every change, replacing the previous custom markers."+ "description": "Returns custom validation markers for the current model content. Runs on mount, model selection and content changes, including controlled updates."+ },+ {+ "name": "theme",+ "type": "string",+ "required": false,+ "defaultValue": "Twenty theme",+ "description": "Monaco theme name. Takes precedence over `options.theme`, which takes precedence over the Twenty theme. Define custom themes in `beforeMount`."},{"name": "transparentBackground",@@ -12141,6 +12239,20 @@"required": false,"defaultValue": "default","description": "Border treatment: `default` draws a rounded border, `with-header` attaches the editor below a `CodeEditorHeader`, and `borderless` removes the border."+ },+ {+ "name": "width",+ "type": "string | number",+ "required": false,+ "defaultValue": "100%",+ "description": "Width of the Monaco React section, in pixels or as a CSS length."+ },+ {+ "name": "wrapperProps",+ "type": "object",+ "required": false,+ "defaultValue": null,+ "description": "Native props passed unchanged to the Monaco React section around the editor and Monaco React loading content. Use this section for layout styles and a measurable native ref. Not applied to the separate Twenty loader during initial Monaco configuration or `isLoading`. Native styles can override the section sizing."}]},diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/CodeEditor.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/CodeEditor.tsxindex 6f9d4428d60..e9c2da8774f 100644--- a/packages/twenty-ui/src/components/code-editor/CodeEditor/CodeEditor.tsx+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/CodeEditor.tsx@@ -1,13 +1,24 @@import Editor, { loader, type Monaco } from '@monaco-editor/react';+import { isNumber } from '@sniptt/guards';+import { clsx } from 'clsx';+import { type editor } from 'monaco-editor';+import { type KeyboardEvent, useId, useState } from 'react';+import { Loader } from '@ui/primitives/feedback/Loader/Loader';-import { BASE_CODE_EDITOR_THEME_ID } from '@ui/components/code-editor/CodeEditor/internal/constants/BaseCodeEditorThemeId';-import { getBaseCodeEditorTheme } from '@ui/components/code-editor/CodeEditor/internal/utils/getBaseCodeEditorTheme';import { ResizeHandle } from '@ui/primitives/layout/ResizeHandle/ResizeHandle';-import { useTheme, useThemeColorScheme, type ThemeType } from '@ui/theme';-import { type editor } from 'monaco-editor';-import { type KeyboardEvent, useEffect, useId, useState } from 'react';+import { useTheme, useThemeColorScheme } from '@ui/theme';import { isDefined } from '@ui/utilities/utils/isDefined';+import { BASE_CODE_EDITOR_THEME_ID } from './internal/constants/BaseCodeEditorThemeId';+import { CODE_EDITOR_DEFAULT_HEIGHT } from './internal/constants/CodeEditorDefaultHeight';+import { CodeEditorAutoHeightEffect } from './internal/CodeEditorAutoHeightEffect';+import { CodeEditorLifecycleEffect } from './internal/CodeEditorLifecycleEffect';+import { CodeEditorLoaderConfigurationEffect } from './internal/CodeEditorLoaderConfigurationEffect';+import { CodeEditorMarkersEffect } from './internal/CodeEditorMarkersEffect';+import { CodeEditorResizableHeightEffect } from './internal/CodeEditorResizableHeightEffect';+import { CodeEditorThemeEffect } from './internal/CodeEditorThemeEffect';+import { useCodeEditorHeight } from './internal/useCodeEditorHeight';+import { defineCodeEditorDefaultTheme } from './internal/utils/defineCodeEditorDefaultTheme';import styles from './CodeEditor.module.scss';import { type CodeEditorProps } from './types/CodeEditorProps';@@ -39,26 +50,14 @@ const configureMonacoLoader = () => {return monacoLoaderConfiguration;};-const setCodeEditorTheme = (- monaco: Monaco,- theme: ThemeType,- colorScheme: 'light' | 'dark',-) => {- monaco.editor.defineTheme(- BASE_CODE_EDITOR_THEME_ID,- getBaseCodeEditorTheme(theme, colorScheme),- );- monaco.editor.setTheme(BASE_CODE_EDITOR_THEME_ID);-};-export const CodeEditor = ({- value,- language,onMount,- onChange,+ beforeMount,setMarkers,- onValidate,- height = 450,+ height = CODE_EDITOR_DEFAULT_HEIGHT,+ width = '100%',+ theme: requestedTheme,+ loading = <Loader />,variant = 'default',transparentBackground,isLoading = false,@@ -67,200 +66,139 @@ export const CodeEditor = ({resizeLabel = 'Resize editor',contentPadding = 'default',autoHeight = false,+ containerProps,+ ref,+ ...editorProps}: CodeEditorProps) => {const theme = useTheme();const colorScheme = useThemeColorScheme();- const [monaco, setMonaco] = useState<Monaco | undefined>(undefined);- const [editor, setEditor] = useState<- editor.IStandaloneCodeEditor | undefined- >(undefined);- const [isEditorFocused, setIsEditorFocused] = useState(false);+ const [monaco, setMonaco] = useState<Monaco>();+ const [editor, setEditor] = useState<editor.IStandaloneCodeEditor>();const [isMonacoLoaderConfigured, setIsMonacoLoaderConfigured] =useState(false);- const [autoHeightContentHeight, setAutoHeightContentHeight] = useState<- number | undefined- >(undefined);-- const numericHeight = typeof height === 'number' ? height : 450;- const [resizableHeight, setResizableHeight] = useState(numericHeight);+ const [isEditorFocused, setIsEditorFocused] = useState(false);const editorContainerId = useId();-- const shouldAutoHeight = autoHeight && !resizable;- const codeEditorPadding =- typeof theme.spacingMultiplicator === 'number'- ? theme.spacingMultiplicator * 4- : undefined;- const currentHeight = shouldAutoHeight- ? (autoHeightContentHeight ?? height)- : resizable- ? resizableHeight- : height;- const contentPaddingOptions = {- ...(contentPadding === 'comfortable'- ? {- lineDecorationsWidth: codeEditorPadding,- }- : {}),- padding: {- bottom: codeEditorPadding,- top: codeEditorPadding,- },- };- const { padding: _callerPadding, ...editorOptions } = options ?? {};-- const setModelMarkers = (- editor: editor.IStandaloneCodeEditor | undefined,- monaco: Monaco | undefined,- ) => {- const model = editor?.getModel();- if (!isDefined(model)) {- return;- }- const customMarkers = setMarkers?.(model.getValue());- if (isDefined(customMarkers)) {- monaco?.editor.setModelMarkers(model, 'customMarker', customMarkers);- }- };+ const editorTheme =+ requestedTheme ?? options?.theme ?? BASE_CODE_EDITOR_THEME_ID;+ const {+ currentHeight,+ resizableHeight,+ setResizableHeight,+ setResizedHeight,+ setContentHeight,+ shouldAutoHeight,+ } = useCodeEditorHeight({ height, resizable, autoHeight });+ const codeEditorPadding = isNumber(theme.spacingMultiplicator)+ ? theme.spacingMultiplicator * 4+ : undefined;const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ containerProps?.onKeyDown?.(event);+if (isEditorFocused) {event.stopPropagation();}};- useEffect(() => {- let isStillMounted = true;-- configureMonacoLoader().then(() => {- if (isStillMounted) {- setIsMonacoLoaderConfigured(true);- }- });-- return () => {- isStillMounted = false;- };- }, []);-- useEffect(() => {- if (!isDefined(monaco)) {- return;- }-- setCodeEditorTheme(monaco, theme, colorScheme);- }, [colorScheme, monaco, theme]);-- // Drive the container height from Monaco's content height; the editor's- // default automaticLayout then re-fits the canvas (no manual layout needed).- useEffect(() => {- if (!shouldAutoHeight || !isDefined(editor)) {- setAutoHeightContentHeight(undefined);- return;- }-- const updateAutoHeight = () => {- const nextHeight = editor.getContentHeight();-- if (!Number.isFinite(nextHeight) || nextHeight <= 0) {- return;- }-- setAutoHeightContentHeight((currentHeight) =>- currentHeight === nextHeight ? currentHeight : nextHeight,- );- };-- updateAutoHeight();-- const disposable = editor.onDidContentSizeChange(updateAutoHeight);-- return () => {- disposable.dispose();- };- }, [editor, shouldAutoHeight]);-- return isLoading || !isMonacoLoaderConfigured ? (+ return (<div- className={styles.editorLoader}- data-variant={variant}- style={- {- '--code-editor-height':- typeof currentHeight === 'number'- ? `${currentHeight}px`- : currentHeight,- } as React.CSSProperties- }+ role="group"+ // oxlint-disable-next-line react/jsx-props-no-spreading+ {...containerProps}+ ref={ref}+ className={clsx(styles.container, containerProps?.className)}+ onKeyDown={handleKeyDown}>- <Loader />- </div>- ) : (- // oxlint-disable-next-line jsx-a11y/no-static-element-interactions- <div className={styles.container} onKeyDown={handleKeyDown}>- <input- type="hidden"- data-testid="code-editor-value"- value={value ?? ''}- readOnly+ <CodeEditorLoaderConfigurationEffect+ configureMonacoLoader={configureMonacoLoader}+ setIsMonacoLoaderConfigured={setIsMonacoLoaderConfigured}/>- <div- id={editorContainerId}- className={styles.editorWrapper}- data-variant={variant}- data-transparent-background={transparentBackground || undefined}- >- <Editor- height={currentHeight}- value={value}- language={language}- loading=""- onMount={(editor, monaco) => {- setMonaco(monaco);- setEditor(editor);-- setCodeEditorTheme(monaco, theme, colorScheme);-- editor.onDidFocusEditorWidget(() => {- setIsEditorFocused(true);- });- editor.onDidBlurEditorWidget(() => {- setIsEditorFocused(false);- });-- onMount?.(editor, monaco);- setModelMarkers(editor, monaco);- }}- onChange={(value) => {- if (isDefined(value)) {- onChange?.(value);- setModelMarkers(editor, monaco);- }- }}- onValidate={(markers) => {- onValidate?.(markers);- }}- options={{- formatOnPaste: true,- formatOnType: true,- fontFamily: theme.code.font.family,- bracketPairColorization: {- enabled: false,- },- overviewRulerLanes: 0,- scrollBeyondLastLine: false,- scrollbar: {- vertical: 'hidden',- horizontal: 'hidden',- },- minimap: {- enabled: false,- },- ...editorOptions,- ...contentPaddingOptions,- }}- />- </div>- {resizable && (+ <CodeEditorResizableHeightEffect+ height={height}+ resizable={resizable}+ editor={editor}+ setResizedHeight={setResizedHeight}+ />+ <CodeEditorAutoHeightEffect+ shouldAutoHeight={shouldAutoHeight}+ editor={editor}+ setContentHeight={setContentHeight}+ />+ <CodeEditorLifecycleEffect+ editor={editor}+ setEditor={setEditor}+ setMonaco={setMonaco}+ setIsEditorFocused={setIsEditorFocused}+ />+ <CodeEditorMarkersEffect+ editor={editor}+ monaco={monaco}+ setMarkers={setMarkers}+ />+ <CodeEditorThemeEffect+ monaco={monaco}+ theme={theme}+ colorScheme={colorScheme}+ editorTheme={editorTheme}+ />+ {isLoading || !isMonacoLoaderConfigured ? (+ <div+ className={styles.editorLoader}+ data-variant={variant}+ style={+ {+ width,+ '--code-editor-height': isNumber(currentHeight)+ ? `${currentHeight}px`+ : currentHeight,+ } as React.CSSProperties+ }+ >+ {loading}+ </div>+ ) : (+ <div+ id={editorContainerId}+ className={styles.editorWrapper}+ data-variant={variant}+ data-transparent-background={transparentBackground || undefined}+ >+ <Editor+ // oxlint-disable-next-line react/jsx-props-no-spreading+ {...editorProps}+ height={currentHeight}+ width={width}+ theme={editorTheme}+ loading={loading}+ beforeMount={(monaco) => {+ defineCodeEditorDefaultTheme({ monaco, theme, colorScheme });+ beforeMount?.(monaco);+ }}+ onMount={(editor, monaco) => {+ setMonaco(monaco);+ setEditor(editor);+ onMount?.(editor, monaco);+ }}+ options={{+ formatOnPaste: true,+ formatOnType: true,+ fontFamily: theme.code.font.family,+ bracketPairColorization: { enabled: false },+ overviewRulerLanes: 0,+ scrollBeyondLastLine: false,+ scrollbar: { vertical: 'hidden', horizontal: 'hidden' },+ minimap: { enabled: false },+ ...(contentPadding === 'comfortable'+ ? { lineDecorationsWidth: codeEditorPadding }+ : {}),+ padding: { bottom: codeEditorPadding, top: codeEditorPadding },+ ...options,+ theme: editorTheme,+ }}+ />+ </div>+ )}+ {resizable && !isLoading && isDefined(editor) && (<ResizeHandlearia-label={resizeLabel}aria-controls={editorContainerId}diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/CodeEditor.stories.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/CodeEditor.stories.tsxindex 67e41effd88..64f52572f66 100644--- a/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/CodeEditor.stories.tsx+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/CodeEditor.stories.tsx@@ -1,11 +1,23 @@+import {+ type BeforeMount,+ type OnChange,+ type OnMount,+ type OnValidate,+} from '@monaco-editor/react';import { type Meta, type StoryObj } from '@storybook/react-vite';import { expect, fn, userEvent, waitFor, within } from 'storybook/test';import { CodeEditorHeader } from '@ui/components/code-editor/CodeEditorHeader/CodeEditorHeader';import { Button } from '@ui/primitives/input/Button/Button';import { A11Y_DEFER_COLOR_CONTRAST, ComponentDecorator } from '@ui/testing';+import { isDefined } from '@ui/utilities/utils/isDefined';import { CodeEditor } from '../CodeEditor';+import { ControlledCodeEditor } from './ControlledCodeEditor';+import { ModelCodeEditor } from './ModelCodeEditor';+import { ResizableCodeEditor } from './ResizableCodeEditor';+import { ThemedCodeEditor } from './ThemedCodeEditor';+import { UnmountingCodeEditor } from './UnmountingCodeEditor';import { waitForCodeEditorContent } from './waitForCodeEditorContent';const WORKSPACE_SETTINGS_JSON = JSON.stringify(@@ -13,8 +25,64 @@ const WORKSPACE_SETTINGS_JSON = JSON.stringify(null,2,);+const INITIAL_EDITOR_VALUE = 'Initial editor content';+const CALLER_THEME_ID = 'code-editor-caller-theme';+let mountedEditor: Parameters<OnMount> | undefined;+let latestChange: Parameters<OnChange> | undefined;+let latestValidatedMarkers: Parameters<OnValidate>[0] | undefined;+let containerElement: HTMLDivElement | null | undefined;+let lifecycleOrder: ('beforeMount' | 'onMount')[] = [];+const handleChange = fn((...change: Parameters<OnChange>) => {+ latestChange = change;+});+const handleMount = fn((...editor: Parameters<OnMount>) => {+ mountedEditor = editor;+ lifecycleOrder.push('onMount');+});+const handleValidate = fn((markers: Parameters<OnValidate>[0]) => {+ latestValidatedMarkers = markers;+});+const handleContainerRef = fn((element: HTMLDivElement | null) => {+ containerElement = element;+});+const handleBeforeMount = fn<BeforeMount>((monaco) => {+ lifecycleOrder.push('beforeMount');+ monaco.editor.defineTheme(CALLER_THEME_ID, {+ base: 'vs',+ inherit: true,+ rules: [],+ colors: {+ 'editor.background': '#123456',+ 'editor.foreground': '#ffffff',+ },+ });+});-const handleChange = fn();+const getMountedEditor = () => {+ if (!isDefined(mountedEditor)) {+ throw new Error('Code editor has not mounted');+ }++ const [editor, monaco] = mountedEditor;++ return { editor, monaco };+};++const getLatestChange = () => {+ if (!isDefined(latestChange)) {+ throw new Error('Code editor has not emitted a change');+ }++ return latestChange;+};++const getLatestValidatedMarkers = () => {+ if (!isDefined(latestValidatedMarkers)) {+ throw new Error('Code editor has not emitted validation markers');+ }++ return latestValidatedMarkers;+};const meta: Meta<typeof CodeEditor> = {id: 'ui-components-codeeditor',@@ -24,11 +92,25 @@ const meta: Meta<typeof CodeEditor> = {value: WORKSPACE_SETTINGS_JSON,language: 'json',height: 160,+ beforeMount: handleBeforeMount,+ onMount: handleMount,},parameters: {a11y: A11Y_DEFER_COLOR_CONTRAST,container: { width: 480 },},+ beforeEach: () => {+ handleChange.mockClear();+ handleMount.mockClear();+ handleValidate.mockClear();+ handleContainerRef.mockClear();+ handleBeforeMount.mockClear();+ mountedEditor = undefined;+ latestChange = undefined;+ latestValidatedMarkers = undefined;+ containerElement = undefined;+ lifecycleOrder = [];+ },render: (args) => (<div style={{ width: '100%' }}><CodeEditor {...args} />@@ -43,16 +125,28 @@ type Story = StoryObj<typeof CodeEditor>;export const Default: Story = {decorators: [ComponentDecorator],play: async ({ canvasElement }) => {- await waitForCodeEditorContent(canvasElement, '"name": "Acme"');+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: '"name": "Acme"',+ });},};export const Resizable: Story = {...Default,- args: { resizable: true, resizeLabel: 'Resize code sample' },+ args: {+ resizable: true,+ autoHeight: true,+ resizeLabel: 'Resize code sample',+ },+ render: (args) => <ResizableCodeEditor {...args} />,play: async ({ canvasElement }) => {- await waitForCodeEditorContent(canvasElement, '"name": "Acme"');- const handle = within(canvasElement).getByRole('separator', {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: '"name": "Acme"',+ });+ const canvas = within(canvasElement);+ const handle = canvas.getByRole('separator', {name: 'Resize code sample',});@@ -60,11 +154,87 @@ export const Resizable: Story = {await userEvent.keyboard('{ArrowDown}');await expect(handle).toHaveAttribute('aria-valuenow', '170');await waitFor(() => {- const editor = within(canvasElement)- .getByRole('textbox')- .closest('.monaco-editor');+ expect(+ canvasElement.querySelector('.monaco-editor')?.getBoundingClientRect()+ .height,+ ).toBe(170);+ });++ await userEvent.click(+ canvas.getByRole('button', { name: 'Set height to 240' }),+ );+ await expect(handle).toHaveAttribute('aria-valuenow', '240');+ await waitFor(() => {+ expect(+ canvasElement.querySelector('.monaco-editor')?.getBoundingClientRect()+ .height,+ ).toBe(240);+ });+ },+};- expect(editor?.getBoundingClientRect().height).toBe(170);+export const CssHeightResizable: Story = {+ ...Resizable,+ args: {+ ...Resizable.args,+ height: '100%',+ },+ play: async ({ canvasElement }) => {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: '"name": "Acme"',+ });+ const handle = within(canvasElement).getByRole('separator', {+ name: 'Resize code sample',+ });++ await waitFor(() => {+ expect(handle).toHaveAttribute('aria-valuenow', '220');+ });+ handle.focus();+ await userEvent.keyboard('{ArrowDown}');+ await expect(handle).toHaveAttribute('aria-valuenow', '230');+ await waitFor(() => {+ expect(+ canvasElement.querySelector('.monaco-editor')?.getBoundingClientRect()+ .height,+ ).toBe(230);+ });+ },+};++export const BoundedResizable: Story = {+ ...Resizable,+ args: {+ ...Resizable.args,+ height: 800,+ },+ play: async ({ canvasElement }) => {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: '\"name\": \"Acme\"',+ });+ const handle = within(canvasElement).getByRole('separator', {+ name: 'Resize code sample',+ });++ await waitFor(() => {+ expect(handle).toHaveAttribute('aria-valuenow', '500');+ expect(+ canvasElement.querySelector('.monaco-editor')?.getBoundingClientRect()+ .height,+ ).toBe(500);+ });+ handle.focus();+ await userEvent.keyboard('{ArrowDown}');+ await expect(handle).toHaveAttribute('aria-valuenow', '500');+ await userEvent.keyboard('{ArrowUp}');+ await expect(handle).toHaveAttribute('aria-valuenow', '490');+ await waitFor(() => {+ expect(+ canvasElement.querySelector('.monaco-editor')?.getBoundingClientRect()+ .height,+ ).toBe(490);});},};@@ -97,23 +267,404 @@ export const Dark: Story = {export const Editing: Story = {...Default,args: {- language: 'plaintext',+ value: undefined,+ language: undefined,+ defaultValue: INITIAL_EDITOR_VALUE,+ defaultLanguage: 'plaintext',+ defaultPath: 'file:///code-editor-editing.txt',onChange: handleChange,+ onValidate: handleValidate,+ setMarkers: () => [+ {+ severity: 4,+ message: 'Review workspace configuration',+ startLineNumber: 1,+ startColumn: 1,+ endLineNumber: 1,+ endColumn: 2,+ },+ ],options: { occurrencesHighlight: 'off', cursorBlinking: 'solid' },},play: async ({ canvasElement }) => {- handleChange.mockClear();+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: INITIAL_EDITOR_VALUE,+ });+ await expect(handleMount).toHaveBeenCalledTimes(1);+ await expect(handleBeforeMount).toHaveBeenCalledTimes(1);+ await expect(lifecycleOrder).toEqual(['beforeMount', 'onMount']);+ const { editor, monaco } = getMountedEditor();+ const model = editor.getModel();- await waitForCodeEditorContent(canvasElement, '"name": "Acme"');+ await expect(handleBeforeMount).toHaveBeenCalledWith(monaco);+ await expect(model?.getValue()).toBe(INITIAL_EDITOR_VALUE);+ await expect(model?.getLanguageId()).toBe('plaintext');+ await expect(model?.uri.toString()).toBe('file:///code-editor-editing.txt');within(canvasElement).getByRole('textbox').focus();await userEvent.keyboard('x');await waitFor(() => {- expect(handleChange).toHaveBeenLastCalledWith(- `x${WORKSPACE_SETTINGS_JSON}`,+ expect(handleChange).toHaveBeenCalled();+ const [value, event] = getLatestChange();+ const [change] = event.changes;++ if (!isDefined(change)) {+ throw new Error('Code editor change has no content details');+ }++ expect(value).toBe(`x${INITIAL_EDITOR_VALUE}`);+ expect(event.changes).toHaveLength(1);+ expect(change.text).toBe('x');+ expect(change.rangeOffset).toBe(0);+ expect(change.rangeLength).toBe(0);+ expect(change.range.startLineNumber).toBe(1);+ expect(change.range.startColumn).toBe(1);+ expect(event.isFlush).toBe(false);+ expect(event.isUndoing).toBe(false);+ expect(event.isRedoing).toBe(false);+ expect(event.versionId).toBeGreaterThan(1);+ expect(handleValidate).toHaveBeenCalled();+ const markers = getLatestValidatedMarkers();+ const [marker] = markers;++ if (!isDefined(marker)) {+ throw new Error('Code editor validation has no marker');+ }++ expect(markers).toHaveLength(1);+ expect(marker.owner).toBe('customMarker');+ expect(marker.resource).toBe(model?.uri);+ expect(marker.severity).toBe(monaco.MarkerSeverity.Warning);+ expect(marker.message).toBe('Review workspace configuration');+ expect(marker.startLineNumber).toBe(1);+ expect(marker.endColumn).toBe(2);+ });+ },+};++export const ModelLifecycle: Story = {+ ...Default,+ args: {+ value: undefined,+ language: undefined,+ saveViewState: true,+ options: { occurrencesHighlight: 'off' },+ },+ render: (args) => <ModelCodeEditor {...args} />,+ play: async ({ canvasElement }) => {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: 'Workspace notes',+ });+ const canvas = within(canvasElement);+ const { editor } = getMountedEditor();+ const notesModel = editor.getModel();++ editor.setPosition({ lineNumber: 3, column: 1 });+ canvas.getByRole('textbox').focus();+ await userEvent.keyboard('x');+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: 'xPlan: Pro',+ });+ const notesPosition = editor.getPosition();++ await userEvent.click(+ canvas.getByRole('button', { name: 'Open query.ts' }),+ );+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: 'export const seats = 12;',+ });+ const queryModel = editor.getModel();++ try {+ await expect(queryModel?.getLanguageId()).toBe('typescript');+ await expect(queryModel?.uri.toString()).toBe(+ 'file:///code-editor-model-query.ts',);+ await expect(queryModel).not.toBe(notesModel);++ await userEvent.click(+ canvas.getByRole('button', { name: 'Open notes.txt' }),+ );+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: 'xPlan: Pro',+ });+ await expect(editor.getModel()).toBe(notesModel);+ await expect(editor.getModel()?.getLanguageId()).toBe('plaintext');+ await expect(editor.getPosition()).toEqual(notesPosition);+ await expect(handleMount).toHaveBeenCalledTimes(1);+ } finally {+ editor.setModel(notesModel);+ queryModel?.dispose();+ }+ },+};++export const ControlledValue: Story = {+ ...Default,+ args: {+ onChange: handleChange,+ options: {+ occurrencesHighlight: 'off',+ padding: { top: 3, bottom: 19 },+ },+ setMarkers: (value) => [+ {+ severity: 4,+ message: `Review ${value}`,+ startLineNumber: 1,+ startColumn: 1,+ endLineNumber: 1,+ endColumn: 2,+ },+ ],+ },+ render: (args) => <ControlledCodeEditor {...args} />,+ play: async ({ canvasElement }) => {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: 'Initial controlled value',+ });+ const canvas = within(canvasElement);+ const { editor, monaco } = getMountedEditor();+ const model = editor.getModel();++ canvas.getByRole('textbox').focus();+ await userEvent.keyboard('x');+ const [value, event] = getLatestChange();++ await expect(value).toBe('xInitial controlled value');+ await expect(event.isFlush).toBe(false);+ handleChange.mockClear();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Append controlled value' }),+ );+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: 'xInitial controlled value (updated)',+ });+ await expect(editor.getModel()).toBe(model);+ await expect(handleChange).not.toHaveBeenCalled();+ await userEvent.click(+ canvas.getByRole('button', { name: 'Replace controlled value' }),+ );+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: 'export const seats = 24;',+ });+ await expect(editor.getModel()).toBe(model);+ await expect(model?.getLanguageId()).toBe('typescript');+ await waitFor(() => {+ expect(editor.getOption(monaco.editor.EditorOption.padding)).toEqual({+ top: 7,+ bottom: 21,+ });+ expect(+ monaco.editor.getModelMarkers({+ owner: 'customMarker',+ resource: model?.uri,+ }),+ ).toEqual([+ expect.objectContaining({ message: 'Review export const seats = 24;' }),+ ]);+ });+ await expect(handleChange).not.toHaveBeenCalled();+ },+};++export const CallerOptionsAndNativeTargets: Story = {+ ...Default,+ args: {+ height: 180,+ width: 320,+ contentPadding: 'comfortable',+ className: 'code-editor-monaco-container',+ containerProps: {+ id: 'code-editor-outer',+ title: 'Outer editor container',+ },+ wrapperProps: { id: 'code-editor-section', title: 'Monaco wrapper' },+ ref: handleContainerRef,+ options: {+ padding: { top: 3, bottom: 19 },+ fontSize: 16,+ lineNumbers: 'off',+ lineDecorationsWidth: 4,+ minimap: { enabled: true },+ },+ },+ play: async ({ canvasElement }) => {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: '"name": "Acme"',+ });+ const canvas = within(canvasElement);+ const outerContainer = canvas.getByTitle('Outer editor container');+ const monacoWrapper = canvas.getByTitle('Monaco wrapper');+ const { editor, monaco } = getMountedEditor();++ await expect(outerContainer.tagName).toBe('DIV');+ await expect(containerElement).toBe(outerContainer);+ await expect(monacoWrapper.tagName).toBe('SECTION');+ await expect(outerContainer).toContainElement(monacoWrapper);+ await expect(+ monacoWrapper.querySelector('.code-editor-monaco-container'),+ ).toContainElement(editor.getDomNode());+ await expect(editor.getOption(monaco.editor.EditorOption.padding)).toEqual({+ top: 3,+ bottom: 19,+ });+ await expect(editor.getOption(monaco.editor.EditorOption.fontSize)).toBe(+ 16,+ );+ await expect(+ editor.getOption(monaco.editor.EditorOption.minimap).enabled,+ ).toBe(true);+ await expect(+ editor.getOption(monaco.editor.EditorOption.lineDecorationsWidth),+ ).toBe(4);+ await expect(monacoWrapper.getBoundingClientRect().width).toBe(320);+ await expect(monacoWrapper.getBoundingClientRect().height).toBe(180);+ },+};++export const ThemePrecedence: Story = {+ ...Default,+ args: { theme: CALLER_THEME_ID, options: { theme: 'vs-dark' } },+ render: (args) => <ThemedCodeEditor {...args} />,+ play: async ({ canvasElement }) => {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: '"name": "Acme"',+ });+ const canvas = within(canvasElement);++ await expect(+ canvasElement.querySelector('.monaco-editor-background'),+ ).toHaveStyle({ backgroundColor: 'rgb(18, 52, 86)' });+ await userEvent.click(+ canvas.getByRole('button', { name: 'Use option theme' }),+ );+ await waitFor(() => {+ expect(+ canvasElement.querySelector('.monaco-editor-background'),+ ).toHaveStyle({+ backgroundColor: 'rgb(30, 30, 30)',+ });+ });+ await userEvent.click(+ canvas.getByRole('button', { name: 'Use Twenty theme' }),+ );+ await waitFor(() => {+ expect(+ canvasElement.querySelector('.monaco-editor-background'),+ ).toHaveStyle({+ backgroundColor: 'rgba(0, 0, 0, 0)',+ });+ });+ },+};++export const AutoHeight: Story = {+ ...Default,+ args: {+ value: undefined,+ language: 'plaintext',+ defaultValue: 'Workspace notes\nPlan: Pro',+ height: 300,+ autoHeight: true,+ options: { occurrencesHighlight: 'off' },+ },+ play: async ({ canvasElement }) => {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: 'Workspace notes',});+ const { editor } = getMountedEditor();++ await waitFor(() => {+ expect(editor.getDomNode()?.getBoundingClientRect().height).toBe(+ editor.getContentHeight(),+ );+ expect(editor.getContentHeight()).toBeLessThan(300);+ });+ const initialHeight = editor.getContentHeight();+ within(canvasElement).getByRole('textbox').focus();+ await userEvent.keyboard('{Enter}');+ await waitFor(() => {+ expect(editor.getContentHeight()).toBeGreaterThan(initialHeight);+ expect(editor.getDomNode()?.getBoundingClientRect().height).toBe(+ editor.getContentHeight(),+ );+ });+ },+};++export const ModelDisposal: Story = {+ ...Default,+ args: {+ path: 'file:///code-editor-disposal.json',+ autoHeight: true,+ ref: handleContainerRef,+ },+ render: (args) => <UnmountingCodeEditor {...args} />,+ play: async ({ canvasElement }) => {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: '"name": "Acme"',+ });+ const canvas = within(canvasElement);+ const { editor } = getMountedEditor();+ const model = editor.getModel();++ await userEvent.click(+ canvas.getByRole('button', { name: 'Unmount editor' }),+ );+ await expect(canvas.queryByRole('textbox')).not.toBeInTheDocument();+ await expect(model?.isDisposed()).toBe(true);+ await expect(containerElement).toBeNull();+ },+};++export const RetainedModel: Story = {+ ...ModelDisposal,+ args: {+ path: 'file:///code-editor-retained.json',+ autoHeight: true,+ keepCurrentModel: true,+ onChange: handleChange,+ },+ play: async ({ canvasElement }) => {+ await waitForCodeEditorContent({+ canvasElement,+ expectedContent: '"name": "Acme"',+ });+ const canvas = within(canvasElement);+ const { editor, monaco } = getMountedEditor();+ const model = editor.getModel();++ try {+ await userEvent.click(+ canvas.getByRole('button', { name: 'Unmount editor' }),+ );+ await expect(canvas.queryByRole('textbox')).not.toBeInTheDocument();+ await expect(model?.isDisposed()).toBe(false);+ await expect(+ monaco.editor.getModel(+ monaco.Uri.parse('file:///code-editor-retained.json'),+ ),+ ).toBe(model);+ handleChange.mockClear();+ model?.setValue('Retained after unmount');+ await expect(handleChange).not.toHaveBeenCalled();+ } finally {+ model?.dispose();+ }},};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ControlledCodeEditor.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ControlledCodeEditor.tsxnew file mode 100644index 00000000000..b749a9efd77--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ControlledCodeEditor.tsx@@ -0,0 +1,51 @@+import { useState } from 'react';++import { Button } from '@ui/primitives/input/Button/Button';+import { isDefined } from '@ui/utilities/utils/isDefined';++import { CodeEditor } from '../CodeEditor';+import { type CodeEditorProps } from '../types/CodeEditorProps';++export const ControlledCodeEditor = (props: CodeEditorProps) => {+ const [value, setValue] = useState('Initial controlled value');+ const [language, setLanguage] = useState('plaintext');+ const [options, setOptions] = useState(props.options);++ const handleChange: NonNullable<CodeEditorProps['onChange']> = (+ ...change+ ) => {+ const [nextValue] = change;++ if (isDefined(nextValue)) {+ setValue(nextValue);+ }++ props.onChange?.(...change);+ };++ return (+ <>+ <CodeEditor+ {...props}+ value={value}+ onChange={handleChange}+ language={language}+ options={options}+ />+ <Button+ onClick={() => setValue((currentValue) => `${currentValue} (updated)`)}+ >+ Append controlled value+ </Button>+ <Button+ onClick={() => {+ setValue('export const seats = 24;');+ setLanguage('typescript');+ setOptions({ ...props.options, padding: { top: 7, bottom: 21 } });+ }}+ >+ Replace controlled value+ </Button>+ </>+ );+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ModelCodeEditor.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ModelCodeEditor.tsxnew file mode 100644index 00000000000..90f0d912bf7--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ModelCodeEditor.tsx@@ -0,0 +1,36 @@+import { useState } from 'react';++import { Button } from '@ui/primitives/input/Button/Button';++import { CodeEditor } from '../CodeEditor';+import { type CodeEditorProps } from '../types/CodeEditorProps';++const NOTES_MODEL_PATH = 'file:///code-editor-model-notes.txt';+const QUERY_MODEL_PATH = 'file:///code-editor-model-query.ts';+const NOTES_MODEL_VALUE = 'Workspace notes\nSeats: 12\nPlan: Pro';+const QUERY_MODEL_VALUE = 'export const seats = 12;';++export const ModelCodeEditor = (props: CodeEditorProps) => {+ const [isQueryModelSelected, setIsQueryModelSelected] = useState(false);++ return (+ <>+ <CodeEditor+ {...props}+ value={undefined}+ language={undefined}+ path={isQueryModelSelected ? QUERY_MODEL_PATH : NOTES_MODEL_PATH}+ defaultLanguage={isQueryModelSelected ? 'typescript' : 'plaintext'}+ defaultValue={+ isQueryModelSelected ? QUERY_MODEL_VALUE : NOTES_MODEL_VALUE+ }+ />+ <Button onClick={() => setIsQueryModelSelected(true)}>+ Open query.ts+ </Button>+ <Button onClick={() => setIsQueryModelSelected(false)}>+ Open notes.txt+ </Button>+ </>+ );+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ResizableCodeEditor.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ResizableCodeEditor.tsxnew file mode 100644index 00000000000..019687b23a7--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ResizableCodeEditor.tsx@@ -0,0 +1,19 @@+import { useState } from 'react';++import { Button } from '@ui/primitives/input/Button/Button';++import { CodeEditor } from '../CodeEditor';+import { type CodeEditorProps } from '../types/CodeEditorProps';++export const ResizableCodeEditor = (props: CodeEditorProps) => {+ const [height, setHeight] = useState(props.height);++ return (+ <>+ <div style={{ height: 220, width: '100%' }}>+ <CodeEditor {...props} height={height} />+ </div>+ <Button onClick={() => setHeight(240)}>Set height to 240</Button>+ </>+ );+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ThemedCodeEditor.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ThemedCodeEditor.tsxnew file mode 100644index 00000000000..2cdf3b706ad--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/ThemedCodeEditor.tsx@@ -0,0 +1,31 @@+import { useState } from 'react';++import { Button } from '@ui/primitives/input/Button/Button';++import { CodeEditor } from '../CodeEditor';+import { type CodeEditorProps } from '../types/CodeEditorProps';++export const ThemedCodeEditor = (props: CodeEditorProps) => {+ const [themeSource, setThemeSource] = useState<+ 'explicit' | 'options' | 'default'+ >('explicit');++ return (+ <>+ <CodeEditor+ {...props}+ theme={themeSource === 'explicit' ? props.theme : undefined}+ options={{+ ...props.options,+ theme: themeSource === 'default' ? undefined : props.options?.theme,+ }}+ />+ <Button onClick={() => setThemeSource('options')}>+ Use option theme+ </Button>+ <Button onClick={() => setThemeSource('default')}>+ Use Twenty theme+ </Button>+ </>+ );+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/UnmountingCodeEditor.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/UnmountingCodeEditor.tsxnew file mode 100644index 00000000000..98f295dd9be--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/UnmountingCodeEditor.tsx@@ -0,0 +1,17 @@+import { useState } from 'react';++import { Button } from '@ui/primitives/input/Button/Button';++import { CodeEditor } from '../CodeEditor';+import { type CodeEditorProps } from '../types/CodeEditorProps';++export const UnmountingCodeEditor = (props: CodeEditorProps) => {+ const [isEditorMounted, setIsEditorMounted] = useState(true);++ return (+ <>+ {isEditorMounted && <CodeEditor {...props} />}+ <Button onClick={() => setIsEditorMounted(false)}>Unmount editor</Button>+ </>+ );+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/waitForCodeEditorContent.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/waitForCodeEditorContent.tsindex eee8e4a03a5..24928dd6f87 100644--- a/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/waitForCodeEditorContent.ts+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/__stories__/waitForCodeEditorContent.ts@@ -3,10 +3,13 @@ import { expect, waitFor } from 'storybook/test';const NON_BREAKING_SPACE = ' ';const CODE_EDITOR_LOAD_TIMEOUT_IN_MS = 20_000;-export const waitForCodeEditorContent = async (- canvasElement: HTMLElement,- expectedContent: string,-) => {+export const waitForCodeEditorContent = async ({+ canvasElement,+ expectedContent,+}: {+ canvasElement: HTMLElement;+ expectedContent: string;+}) => {await waitFor(() => {const renderedLines = canvasElement.querySelector('.view-lines');diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorAutoHeightEffect.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorAutoHeightEffect.tsxnew file mode 100644index 00000000000..13a7b2904ee--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorAutoHeightEffect.tsx@@ -0,0 +1,41 @@+import { type editor } from 'monaco-editor';+import { type Dispatch, type SetStateAction, useEffect } from 'react';++import { isDefined } from '@ui/utilities/utils/isDefined';++type CodeEditorAutoHeightEffectProps = {+ shouldAutoHeight: boolean;+ editor: editor.IStandaloneCodeEditor | undefined;+ setContentHeight: Dispatch<SetStateAction<number | undefined>>;+};++export const CodeEditorAutoHeightEffect = ({+ shouldAutoHeight,+ editor,+ setContentHeight,+}: CodeEditorAutoHeightEffectProps) => {+ useEffect(() => {+ if (!shouldAutoHeight || !isDefined(editor)) {+ setContentHeight(undefined);+ return;+ }++ const updateContentHeight = () => {+ const nextHeight = editor.getContentHeight();++ if (!Number.isFinite(nextHeight) || nextHeight <= 0) {+ return;+ }++ setContentHeight(nextHeight);+ };++ updateContentHeight();++ const subscription = editor.onDidContentSizeChange(updateContentHeight);++ return () => subscription.dispose();+ }, [editor, shouldAutoHeight, setContentHeight]);++ return null;+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorLifecycleEffect.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorLifecycleEffect.tsxnew file mode 100644index 00000000000..f0995e17c2e--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorLifecycleEffect.tsx@@ -0,0 +1,45 @@+import { type Monaco } from '@monaco-editor/react';+import { type editor } from 'monaco-editor';+import { type Dispatch, type SetStateAction, useEffect } from 'react';++import { isDefined } from '@ui/utilities/utils/isDefined';++type CodeEditorLifecycleEffectProps = {+ editor: editor.IStandaloneCodeEditor | undefined;+ setEditor: Dispatch<SetStateAction<editor.IStandaloneCodeEditor | undefined>>;+ setMonaco: Dispatch<SetStateAction<Monaco | undefined>>;+ setIsEditorFocused: Dispatch<SetStateAction<boolean>>;+};++export const CodeEditorLifecycleEffect = ({+ editor,+ setEditor,+ setMonaco,+ setIsEditorFocused,+}: CodeEditorLifecycleEffectProps) => {+ useEffect(() => {+ if (!isDefined(editor)) {+ setIsEditorFocused(false);+ return;+ }++ setIsEditorFocused(editor.hasWidgetFocus());++ const subscriptions = [+ editor.onDidFocusEditorWidget(() => setIsEditorFocused(true)),+ editor.onDidBlurEditorWidget(() => setIsEditorFocused(false)),+ editor.onDidDispose(() => {+ setEditor(undefined);+ setMonaco(undefined);+ }),+ ];++ return () => {+ for (const subscription of subscriptions) {+ subscription.dispose();+ }+ };+ }, [editor, setEditor, setMonaco, setIsEditorFocused]);++ return null;+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorLoaderConfigurationEffect.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorLoaderConfigurationEffect.tsxnew file mode 100644index 00000000000..011176f06b1--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorLoaderConfigurationEffect.tsx@@ -0,0 +1,27 @@+import { type Dispatch, type SetStateAction, useEffect } from 'react';++type CodeEditorLoaderConfigurationEffectProps = {+ configureMonacoLoader: () => Promise<void>;+ setIsMonacoLoaderConfigured: Dispatch<SetStateAction<boolean>>;+};++export const CodeEditorLoaderConfigurationEffect = ({+ configureMonacoLoader,+ setIsMonacoLoaderConfigured,+}: CodeEditorLoaderConfigurationEffectProps) => {+ useEffect(() => {+ let isStillMounted = true;++ configureMonacoLoader().then(() => {+ if (isStillMounted) {+ setIsMonacoLoaderConfigured(true);+ }+ });++ return () => {+ isStillMounted = false;+ };+ }, [configureMonacoLoader, setIsMonacoLoaderConfigured]);++ return null;+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorMarkersEffect.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorMarkersEffect.tsxnew file mode 100644index 00000000000..2b320bd8321--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorMarkersEffect.tsx@@ -0,0 +1,54 @@+import { type Monaco } from '@monaco-editor/react';+import { type editor } from 'monaco-editor';+import { useEffect } from 'react';++import { isDefined } from '@ui/utilities/utils/isDefined';++import { type CodeEditorProps } from '../types/CodeEditorProps';++type CodeEditorMarkersEffectProps = {+ editor: editor.IStandaloneCodeEditor | undefined;+ monaco: Monaco | undefined;+ setMarkers: CodeEditorProps['setMarkers'];+};++export const CodeEditorMarkersEffect = ({+ editor,+ monaco,+ setMarkers,+}: CodeEditorMarkersEffectProps) => {+ useEffect(() => {+ if (!isDefined(editor) || !isDefined(monaco) || !isDefined(setMarkers)) {+ return;+ }++ const updateMarkers = () => {+ const model = editor.getModel();++ if (!isDefined(model)) {+ return;+ }++ monaco.editor.setModelMarkers(+ model,+ 'customMarker',+ setMarkers(model.getValue()),+ );+ };++ updateMarkers();++ const subscriptions = [+ editor.onDidChangeModel(updateMarkers),+ editor.onDidChangeModelContent(updateMarkers),+ ];++ return () => {+ for (const subscription of subscriptions) {+ subscription.dispose();+ }+ };+ }, [editor, monaco, setMarkers]);++ return null;+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorResizableHeightEffect.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorResizableHeightEffect.tsxnew file mode 100644index 00000000000..153667082ac--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorResizableHeightEffect.tsx@@ -0,0 +1,44 @@+import { type editor } from 'monaco-editor';+import { type Dispatch, type SetStateAction, useEffect } from 'react';++import { isDefined } from '@ui/utilities/utils/isDefined';++import { type ResizedCodeEditorHeight } from './types/ResizedCodeEditorHeight';+import { getBoundedCodeEditorHeight } from './utils/getBoundedCodeEditorHeight';++type CodeEditorResizableHeightEffectProps = {+ height: number | string;+ resizable: boolean;+ editor: editor.IStandaloneCodeEditor | undefined;+ setResizedHeight: Dispatch<+ SetStateAction<ResizedCodeEditorHeight | undefined>+ >;+};++export const CodeEditorResizableHeightEffect = ({+ height,+ resizable,+ editor,+ setResizedHeight,+}: CodeEditorResizableHeightEffectProps) => {+ useEffect(() => {+ if (!resizable || !isDefined(editor)) {+ return;+ }++ const measuredHeight = editor+ .getContainerDomNode()+ .parentElement?.getBoundingClientRect().height;++ if (!isDefined(measuredHeight) || measuredHeight <= 0) {+ return;+ }++ setResizedHeight({+ sourceHeight: height,+ value: getBoundedCodeEditorHeight(measuredHeight),+ });+ }, [editor, height, resizable, setResizedHeight]);++ return null;+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorThemeEffect.tsx b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorThemeEffect.tsxnew file mode 100644index 00000000000..91242c08687--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/CodeEditorThemeEffect.tsx@@ -0,0 +1,32 @@+import { type Monaco } from '@monaco-editor/react';+import { useEffect } from 'react';++import { type ThemeType } from '@ui/theme';+import { isDefined } from '@ui/utilities/utils/isDefined';++import { defineCodeEditorDefaultTheme } from './utils/defineCodeEditorDefaultTheme';++type CodeEditorThemeEffectProps = {+ monaco: Monaco | undefined;+ theme: ThemeType;+ colorScheme: 'light' | 'dark';+ editorTheme: string;+};++export const CodeEditorThemeEffect = ({+ monaco,+ theme,+ colorScheme,+ editorTheme,+}: CodeEditorThemeEffectProps) => {+ useEffect(() => {+ if (!isDefined(monaco)) {+ return;+ }++ defineCodeEditorDefaultTheme({ monaco, theme, colorScheme });+ monaco.editor.setTheme(editorTheme);+ }, [colorScheme, editorTheme, monaco, theme]);++ return null;+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/constants/CodeEditorDefaultHeight.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/constants/CodeEditorDefaultHeight.tsnew file mode 100644index 00000000000..92f3325325e--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/constants/CodeEditorDefaultHeight.ts@@ -0,0 +1 @@+export const CODE_EDITOR_DEFAULT_HEIGHT = 450;diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/types/ResizedCodeEditorHeight.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/types/ResizedCodeEditorHeight.tsnew file mode 100644index 00000000000..5856c7215ec--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/types/ResizedCodeEditorHeight.ts@@ -0,0 +1,4 @@+export type ResizedCodeEditorHeight = {+ sourceHeight: number | string;+ value: number;+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/useCodeEditorHeight.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/useCodeEditorHeight.tsnew file mode 100644index 00000000000..d8b41972955--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/useCodeEditorHeight.ts@@ -0,0 +1,44 @@+import { isNumber } from '@sniptt/guards';+import { useState } from 'react';++import { type ResizedCodeEditorHeight } from './types/ResizedCodeEditorHeight';+import { getCurrentCodeEditorHeight } from './utils/getCurrentCodeEditorHeight';+import { getResizableCodeEditorHeight } from './utils/getResizableCodeEditorHeight';++export const useCodeEditorHeight = ({+ height,+ resizable,+ autoHeight,+}: {+ height: number | string;+ resizable: boolean;+ autoHeight: boolean;+}) => {+ const [resizedHeight, setResizedHeight] = useState<ResizedCodeEditorHeight>();+ const [contentHeight, setContentHeight] = useState<number>();+ const shouldAutoHeight = autoHeight && !resizable;+ const hasResizedHeight = resizedHeight?.sourceHeight === height;+ const shouldUseResizableHeight =+ resizable && (hasResizedHeight || isNumber(height));+ const resizableHeight = getResizableCodeEditorHeight({+ height,+ resizedHeight,+ });++ return {+ currentHeight: getCurrentCodeEditorHeight({+ height,+ resizableHeight,+ contentHeight,+ shouldUseResizableHeight,+ shouldAutoHeight,+ }),+ resizableHeight,+ setResizableHeight: (value: number) => {+ setResizedHeight({ sourceHeight: height, value });+ },+ setResizedHeight,+ setContentHeight,+ shouldAutoHeight,+ };+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/__tests__/getCurrentCodeEditorHeight.test.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/__tests__/getCurrentCodeEditorHeight.test.tsnew file mode 100644index 00000000000..2d782b7244f--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/__tests__/getCurrentCodeEditorHeight.test.ts@@ -0,0 +1,51 @@+import { getCurrentCodeEditorHeight } from '../getCurrentCodeEditorHeight';++describe('getCurrentCodeEditorHeight', () => {+ it('uses the resizable height before the content height', () => {+ expect(+ getCurrentCodeEditorHeight({+ height: 200,+ resizableHeight: 320,+ contentHeight: 120,+ shouldUseResizableHeight: true,+ shouldAutoHeight: true,+ }),+ ).toBe(320);+ });++ it('uses a measured zero content height when auto height is enabled', () => {+ expect(+ getCurrentCodeEditorHeight({+ height: 200,+ resizableHeight: 320,+ contentHeight: 0,+ shouldUseResizableHeight: false,+ shouldAutoHeight: true,+ }),+ ).toBe(0);+ });++ it('keeps the supplied height until content is measured', () => {+ expect(+ getCurrentCodeEditorHeight({+ height: '60vh',+ resizableHeight: 320,+ contentHeight: undefined,+ shouldUseResizableHeight: false,+ shouldAutoHeight: true,+ }),+ ).toBe('60vh');+ });++ it('ignores previous measurements when resizing and auto height are disabled', () => {+ expect(+ getCurrentCodeEditorHeight({+ height: 240,+ resizableHeight: 320,+ contentHeight: 120,+ shouldUseResizableHeight: false,+ shouldAutoHeight: false,+ }),+ ).toBe(240);+ });+});diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/__tests__/getResizableCodeEditorHeight.test.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/__tests__/getResizableCodeEditorHeight.test.tsnew file mode 100644index 00000000000..20aec6af508--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/__tests__/getResizableCodeEditorHeight.test.ts@@ -0,0 +1,61 @@+import { getResizableCodeEditorHeight } from '../getResizableCodeEditorHeight';++describe('getResizableCodeEditorHeight', () => {+ it.each([+ { height: 20, expectedHeight: 50 },+ { height: 260, expectedHeight: 260 },+ { height: 700, expectedHeight: 500 },+ ])(+ 'bounds the supplied numeric height $height to $expectedHeight',+ ({ height, expectedHeight }) => {+ expect(+ getResizableCodeEditorHeight({ height, resizedHeight: undefined }),+ ).toBe(expectedHeight);+ },+ );++ it('preserves the resized height while its source height is unchanged', () => {+ expect(+ getResizableCodeEditorHeight({+ height: 200,+ resizedHeight: { sourceHeight: 200, value: 320 },+ }),+ ).toBe(320);+ });++ it('uses the new numeric height after the source height changes', () => {+ expect(+ getResizableCodeEditorHeight({+ height: 260,+ resizedHeight: { sourceHeight: 200, value: 320 },+ }),+ ).toBe(260);+ });++ it('uses the default height before a CSS height is measured', () => {+ expect(+ getResizableCodeEditorHeight({+ height: '60vh',+ resizedHeight: undefined,+ }),+ ).toBe(450);+ });++ it('uses the measured height for the matching CSS height', () => {+ expect(+ getResizableCodeEditorHeight({+ height: '60vh',+ resizedHeight: { sourceHeight: '60vh', value: 320 },+ }),+ ).toBe(320);+ });++ it('discards the previous measurement after the CSS height changes', () => {+ expect(+ getResizableCodeEditorHeight({+ height: '80vh',+ resizedHeight: { sourceHeight: '60vh', value: 320 },+ }),+ ).toBe(450);+ });+});diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/defineCodeEditorDefaultTheme.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/defineCodeEditorDefaultTheme.tsnew file mode 100644index 00000000000..65df376ecab--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/defineCodeEditorDefaultTheme.ts@@ -0,0 +1,21 @@+import { type Monaco } from '@monaco-editor/react';++import { type ThemeType } from '@ui/theme';++import { BASE_CODE_EDITOR_THEME_ID } from '../constants/BaseCodeEditorThemeId';+import { getBaseCodeEditorTheme } from './getBaseCodeEditorTheme';++export const defineCodeEditorDefaultTheme = ({+ monaco,+ theme,+ colorScheme,+}: {+ monaco: Monaco;+ theme: ThemeType;+ colorScheme: 'light' | 'dark';+}) => {+ monaco.editor.defineTheme(+ BASE_CODE_EDITOR_THEME_ID,+ getBaseCodeEditorTheme({ theme, colorScheme }),+ );+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getBaseCodeEditorTheme.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getBaseCodeEditorTheme.tsindex feb036a5926..388f17108aa 100644--- a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getBaseCodeEditorTheme.ts+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getBaseCodeEditorTheme.ts@@ -38,10 +38,13 @@ const convertColorToHex = (color: string): string => {return color;};-export const getBaseCodeEditorTheme = (- theme: ThemeType,- colorScheme: 'light' | 'dark',-): editor.IStandaloneThemeData => {+export const getBaseCodeEditorTheme = ({+ theme,+ colorScheme,+}: {+ theme: ThemeType;+ colorScheme: 'light' | 'dark';+}): editor.IStandaloneThemeData => {return {base: colorScheme === 'dark' ? 'vs-dark' : 'vs',inherit: true,diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getBoundedCodeEditorHeight.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getBoundedCodeEditorHeight.tsnew file mode 100644index 00000000000..d5f959e1581--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getBoundedCodeEditorHeight.ts@@ -0,0 +1,6 @@+import { clamp } from '@base-ui/utils/clamp';++import { RESIZE_HANDLE_DEFAULTS } from '@ui/primitives/layout/ResizeHandle/internal/ResizeHandleDefaults.constant';++export const getBoundedCodeEditorHeight = (height: number) =>+ clamp(height, RESIZE_HANDLE_DEFAULTS.min, RESIZE_HANDLE_DEFAULTS.max);diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getCurrentCodeEditorHeight.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getCurrentCodeEditorHeight.tsnew file mode 100644index 00000000000..283669996f6--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getCurrentCodeEditorHeight.ts@@ -0,0 +1,23 @@+export const getCurrentCodeEditorHeight = ({+ height,+ resizableHeight,+ contentHeight,+ shouldUseResizableHeight,+ shouldAutoHeight,+}: {+ height: number | string;+ resizableHeight: number;+ contentHeight: number | undefined;+ shouldUseResizableHeight: boolean;+ shouldAutoHeight: boolean;+}) => {+ if (shouldUseResizableHeight) {+ return resizableHeight;+ }++ if (shouldAutoHeight) {+ return contentHeight ?? height;+ }++ return height;+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getResizableCodeEditorHeight.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getResizableCodeEditorHeight.tsnew file mode 100644index 00000000000..36ac9d9c5dd--- /dev/null+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/internal/utils/getResizableCodeEditorHeight.ts@@ -0,0 +1,23 @@+import { isNumber } from '@sniptt/guards';++import { CODE_EDITOR_DEFAULT_HEIGHT } from '../constants/CodeEditorDefaultHeight';+import { type ResizedCodeEditorHeight } from '../types/ResizedCodeEditorHeight';+import { getBoundedCodeEditorHeight } from './getBoundedCodeEditorHeight';++export const getResizableCodeEditorHeight = ({+ height,+ resizedHeight,+}: {+ height: number | string;+ resizedHeight: ResizedCodeEditorHeight | undefined;+}) => {+ if (resizedHeight?.sourceHeight === height) {+ return resizedHeight.value;+ }++ if (isNumber(height)) {+ return getBoundedCodeEditorHeight(height);+ }++ return CODE_EDITOR_DEFAULT_HEIGHT;+};diff --git a/packages/twenty-ui/src/components/code-editor/CodeEditor/types/CodeEditorProps.ts b/packages/twenty-ui/src/components/code-editor/CodeEditor/types/CodeEditorProps.tsindex 168043947eb..bb0d7c00085 100644--- a/packages/twenty-ui/src/components/code-editor/CodeEditor/types/CodeEditorProps.ts+++ b/packages/twenty-ui/src/components/code-editor/CodeEditor/types/CodeEditorProps.ts@@ -1,14 +1,13 @@import { type EditorProps } from '@monaco-editor/react';import { type editor } from 'monaco-editor';+import { type ComponentPropsWithoutRef, type Ref } from 'react';type CodeEditorVariant = 'default' | 'with-header' | 'borderless';type CodeEditorContentPadding = 'default' | 'comfortable';-export type CodeEditorProps = Pick<- EditorProps,- 'value' | 'language' | 'onMount' | 'onValidate' | 'height' | 'options'-> & {- onChange?: (value: string) => void;+export type CodeEditorProps = EditorProps & {+ containerProps?: Omit<ComponentPropsWithoutRef<'div'>, 'children'>;+ ref?: Ref<HTMLDivElement>;setMarkers?: (value: string) => editor.IMarkerData[];variant?: CodeEditorVariant;isLoading?: boolean;diff --git a/packages/twenty-ui/src/primitives/layout/ResizeHandle/__stories__/ResizeHandle.interactions.stories.tsx b/packages/twenty-ui/src/primitives/layout/ResizeHandle/__stories__/ResizeHandle.interactions.stories.tsxindex 63859bf720e..49861327a4f 100644--- a/packages/twenty-ui/src/primitives/layout/ResizeHandle/__stories__/ResizeHandle.interactions.stories.tsx+++ b/packages/twenty-ui/src/primitives/layout/ResizeHandle/__stories__/ResizeHandle.interactions.stories.tsx@@ -264,8 +264,29 @@ export const PreventedEvents: Story = {onPointerDown: (event) => event.preventDefault(),onKeyDown: (event) => event.preventDefault(),},+ render: (args) => (+ <>+ <ResizeHandle {...args} aria-label="Prevented resize" />+ <ResizeHandle+ {...args}+ aria-label="Cancelled drag"+ onPointerDown={undefined}+ onKeyDown={undefined}+ onPointerMove={(event) => {+ if (event.clientY >= 100) {+ event.preventDefault();+ }+ }}+ onPointerUp={(event) => event.preventDefault()}+ />+ </>+ ),play: async ({ canvasElement, args }) => {- const handle = within(canvasElement).getByRole('separator');+ const canvas = within(canvasElement);+ const handle = canvas.getByRole('separator', { name: 'Prevented resize' });+ const cancelledHandle = canvas.getByRole('separator', {+ name: 'Cancelled drag',+ });const pointer = userEvent.setup();await pointer.pointer({ target: handle, keys: '[MouseLeft>]' });@@ -275,6 +296,41 @@ export const PreventedEvents: Story = {await userEvent.keyboard('{ArrowDown}');await expect(handle).toHaveAttribute('aria-valuenow', '150');await expect(args.onValueChange).not.toHaveBeenCalled();++ await withMockPointerCapture({+ handle: cancelledHandle,+ run: async () => {+ await pointer.pointer({+ target: cancelledHandle,+ keys: '[MouseLeft>]',+ coords: { y: 10 },+ });+ await pointer.pointer({ target: cancelledHandle, coords: { y: 60 } });+ await expect(cancelledHandle).toHaveAttribute('aria-valuenow', '200');+ await pointer.pointer({ target: cancelledHandle, coords: { y: 100 } });+ await expect(cancelledHandle).toHaveAttribute('aria-valuenow', '200');+ await expect(args.onValueChange).toHaveBeenCalledTimes(1);+ await pointer.pointer({+ target: cancelledHandle,+ keys: '[/MouseLeft]',+ });+ await expect(cancelledHandle).toHaveAttribute('aria-valuenow', '150');+ await expect(args.onValueChange).toHaveBeenLastCalledWith(150);+ await expect(args.onValueCommitted).not.toHaveBeenCalled();+ await expect(args.onResizeEnd).toHaveBeenCalledWith({+ cancelled: true,+ value: 150,+ });+ await expect(+ cancelledHandle.releasePointerCapture,+ ).toHaveBeenCalledWith(1);+ },+ });++ cancelledHandle.focus();+ await userEvent.keyboard('{ArrowDown}');+ await expect(cancelledHandle).toHaveAttribute('aria-valuenow', '160');+ await expect(args.onValueCommitted).toHaveBeenCalledWith(160);},};