/** * Codemirror extension wrappers for multi-language code editing. */ import { indentWithTab } from '@codemirror/commands'; import { goLanguage } from '@codemirror/lang-go'; import { json } from '@codemirror/lang-json'; import { pythonLanguage } from '@codemirror/lang-python'; import { StandardSQL } from '@codemirror/lang-sql'; import { LanguageSupport } from '@codemirror/language'; import { unifiedMergeView, updateOriginalDoc } from '@codemirror/merge'; import { Annotation, ChangeSet, EditorState, type Extension, StateEffect, StateField, type Transaction, } from '@codemirror/state'; import { EditorView, keymap } from '@codemirror/view'; import { basicSetup } from 'codemirror'; import { json5 } from 'codemirror-json5'; export type Language = 'json' | 'json5' | 'python' | 'go' | 'sql'; /** * Theme overrides for CodeMirror tooltips, autocomplete, and inline * diagnostics so they match the app's design system. * * Color values are taken from the PRIME theme tokens (prime/theme.ts). */ const tooltipTheme = EditorView.baseTheme({ '.cm-tooltip-hover': { maxWidth: 'min(560px, 80vw)', border: 'none', boxShadow: '0 1px 4px rgba(0,0,0,0.1), 0 0 0 1px rgba(0,0,0,0.08)', background: '#fff', }, '.cm-tooltip-hover .cm-lsp-hover-tooltip': { fontFamily: 'inherit', fontSize: '12px', lineHeight: '1.6', padding: '10px 12px', color: '#282829', maxHeight: '320px', overflowY: 'auto', }, '.cm-tooltip-hover .cm-lsp-hover-tooltip:empty': { display: 'none', }, '.cm-tooltip-hover .cm-lsp-hover-tooltip p': { margin: '4px 0', }, '.cm-tooltip-hover .cm-lsp-hover-tooltip pre': { fontFamily: 'var(--font-roboto-mono, monospace)', fontSize: '11px', lineHeight: '1.5', background: '#fbfbfc', padding: '8px 10px', margin: '6px 0', overflowX: 'auto', }, '.cm-tooltip-hover .cm-lsp-hover-tooltip code': { fontFamily: 'var(--font-roboto-mono, monospace)', fontSize: '11px', background: '#edeef0', padding: '1.5px 4px', borderRadius: '4px', wordBreak: 'break-word', color: '#282829', }, '.cm-tooltip-hover .cm-lsp-hover-tooltip pre code': { background: 'transparent', padding: '0', borderRadius: '0', wordBreak: 'normal', }, '.cm-tooltip-hover .cm-lsp-hover-tooltip hr': { border: 'none', borderTop: '1px solid #e4e4e6', margin: '8px 0', }, '.cm-tooltip-autocomplete': { border: 'none', boxShadow: '0 1px 4px rgba(0,0,0,0.1), 0 0 0 1px rgba(0,0,0,0.08)', background: '#fff', }, '.cm-tooltip-autocomplete .cm-completionLabel': { fontSize: '12px', }, '.cm-tooltip-autocomplete .cm-completionDetail': { fontSize: '11px', color: '#7a7c80', overflow: 'hidden', textOverflow: 'ellipsis', }, '.cm-completionInfo': { maxWidth: '400px', maxHeight: '250px', overflowY: 'auto', border: 'none', borderLeft: '1px solid #e4e4e6', boxShadow: '2px 1px 4px rgba(0,0,0,0.06)', background: '#fff', }, '.cm-completionInfo .cm-lsp-documentation': { fontFamily: 'inherit', fontSize: '12px', lineHeight: '1.6', color: '#282829', whiteSpace: 'pre-wrap', wordBreak: 'break-word', }, '.cm-completionInfo .cm-lsp-documentation pre': { fontFamily: 'var(--font-roboto-mono, monospace)', fontSize: '11px', lineHeight: '1.5', background: '#fbfbfc', padding: '8px 10px', margin: '6px 0', overflowX: 'auto', whiteSpace: 'pre', wordBreak: 'normal', }, '.cm-tooltip-lint': { border: 'none', boxShadow: '0 1px 4px rgba(0,0,0,0.1), 0 0 0 1px rgba(0,0,0,0.08)', background: '#fff', padding: '0', }, '.cm-tooltip-hover .cm-tooltip-lint': { boxShadow: 'none', borderTop: '1px solid #e4e4e6', }, '.cm-diagnostic': { fontFamily: 'inherit', fontSize: '12px', lineHeight: '1.5', padding: '6px 10px', borderLeft: '3px solid', }, '.cm-diagnostic-error': { borderLeftColor: '#be3536', background: '#fcecea', }, '.cm-diagnostic-warning': { borderLeftColor: '#ddab3f', background: '#fef3e0', }, '.cm-diagnostic-info': { borderLeftColor: '#2e67d3', background: '#e1f3ff', }, '.cm-diagnostic-hint': { borderLeftColor: '#7a7c80', background: '#fbfbfc', }, }); // Annotation to mark external updates that shouldn't trigger onChange export const externalUpdate = Annotation.define(); /** Options and initial values for a code editor's extensions. */ export interface ExtensionOptions { label: string; errorMessageID?: string | undefined; isInvalid?: boolean | undefined; readonly?: boolean; onFocus?: (event: FocusEvent) => void; onBlur?: (event: FocusEvent) => void; diffOriginal?: string | undefined; lineWrapping?: boolean; language?: Language; extraExtensions?: Extension[]; } /** Create an editor StateField and updater function. */ const createSource = (): [ source: StateField, update: (view: EditorView | undefined, nextValue: T | undefined) => void, ] => { const updateEffect = StateEffect.define(); const source = StateField.define({ create: () => undefined, update: (prevValue, transaction) => { let nextValue = prevValue; for (const effect of transaction.effects) { if (effect.is(updateEffect)) { nextValue = effect.value; } } return nextValue; }, }); const update = (view: EditorView | undefined, nextValue: T | undefined) => { view?.dispatch({ effects: [updateEffect.of(nextValue)] }); }; return [source, update]; }; const [readonly, setReadOnly] = createSource(); const [label, setLabel] = createSource(); const [errorMessageID, setErrorMessageID] = createSource(); const [isInvalid, setIsInvalid] = createSource(); const setDiffOriginal = ( view: EditorView | undefined, nextOriginal: string | undefined ) => { if (nextOriginal !== undefined) { view?.dispatch({ effects: updateOriginalDoc.of({ doc: view.state.toText(nextOriginal), changes: ChangeSet.empty(0), }), }); } }; /** * Get the language extension for the specified language. */ const getLanguageExtension = (language: Language = 'json'): Extension => { switch (language) { case 'json5': { return json5(); } case 'python': { return new LanguageSupport(pythonLanguage); } case 'go': { return new LanguageSupport(goLanguage); } case 'sql': { return new LanguageSupport(StandardSQL.language); } default: { return json(); } } }; const stripUndefinedAttrs = ( attrs: Record ): Record => { const result: Record = {}; for (const [key, value] of Object.entries(attrs)) { if (value !== undefined) { result[key] = value; } } return result; }; /** * Create a CodeMirror extension list for a code editor. * * Adds various state fields and effects so that props changes * can be hooked to the editor without needing to completely * reconfigure or recreate the extensions list. * * @param options Initial values for editor state * @returns The extension list and hooks to reactively update the state */ export const createCodeExtensions = ( options: ExtensionOptions ): readonly Extension[] => { const languageExtension = getLanguageExtension(options.language); const extensions = [ readonly.init(() => options.readonly), label.init(() => options.label), errorMessageID.init(() => options.errorMessageID), isInvalid.init(() => options.isInvalid), basicSetup, languageExtension, tooltipTheme, EditorView.contentAttributes.compute( [label, errorMessageID, isInvalid], (state) => stripUndefinedAttrs({ 'aria-label': state.field(label), 'aria-invalid': state.field(isInvalid) === true ? 'true' : undefined, 'aria-errormessage': state.field(errorMessageID), }) ), EditorView.editable.from(readonly, (readonlyValue) => !readonlyValue), EditorState.readOnly.from(readonly), EditorView.domEventObservers({ blur: options.onBlur, focus: options.onFocus, }), ]; // Only enable tab-as-spaces for Python and Go if (options.language === 'python' || options.language === 'go') { extensions.push(keymap.of([indentWithTab])); } if (options.diffOriginal !== undefined) { extensions.push( unifiedMergeView({ original: options.diffOriginal, mergeControls: false, }) ); } if (options.lineWrapping) { extensions.push(EditorView.lineWrapping); } // Add custom extensions (like LSP) if (options.extraExtensions) { extensions.push(...options.extraExtensions); } return extensions; }; /** * Dispatch change events when the contents of the editor change. * * Create a new dispatch function whenever the editor is re-created */ export const createDispatchTransactions = ( onChange: (nextValue: string) => unknown, language: Language = 'json' ) => { let currentValue: string | undefined; return (transactions: readonly Transaction[], view: EditorView) => { view.update(transactions); let nextValue = view.state.doc.toString(); // Only apply default empty object for JSON/JSON5 if (nextValue === '' && (language === 'json' || language === 'json5')) { nextValue = '{}'; } currentValue ??= nextValue; // Check if this is an external update (e.g., syncing with initialValue) const isExternalUpdate = transactions.some((tr) => tr.annotation(externalUpdate) ); if (nextValue !== currentValue && !isExternalUpdate) { currentValue = nextValue; onChange(currentValue); } else if (isExternalUpdate) { // Update currentValue for external updates without triggering onChange currentValue = nextValue; } }; }; export { setDiffOriginal, setErrorMessageID, setIsInvalid, setLabel, setReadOnly, };