refactor(editor): Refactor code editors to composition API (no-changelog) (#9757)

This commit is contained in:
Elias Meire 2024-06-20 14:17:12 +02:00 committed by GitHub
parent f4e2c695f2
commit 202124152c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 1217 additions and 1254 deletions

View file

@ -1,6 +1,6 @@
<template> <template>
<div <div
ref="codeNodeEditorContainer" ref="codeNodeEditorContainerRef"
:class="['code-node-editor', $style['code-node-editor-container'], language]" :class="['code-node-editor', $style['code-node-editor-container'], language]"
@mouseover="onMouseOver" @mouseover="onMouseOver"
@mouseout="onMouseOut" @mouseout="onMouseOut"
@ -18,7 +18,7 @@
data-test-id="code-node-tab-code" data-test-id="code-node-tab-code"
> >
<div <div
ref="codeNodeEditor" ref="codeNodeEditorRef"
:class="['ph-no-capture', 'code-editor-tabs', $style.editorInput]" :class="['ph-no-capture', 'code-editor-tabs', $style.editorInput]"
/> />
<slot name="suffix" /> <slot name="suffix" />
@ -33,359 +33,364 @@
:key="activeTab" :key="activeTab"
:has-changes="hasChanges" :has-changes="hasChanges"
@replace-code="onReplaceCode" @replace-code="onReplaceCode"
@started-loading="isLoadingAIResponse = true" @started-loading="onAiLoadStart"
@finished-loading="isLoadingAIResponse = false" @finished-loading="onAiLoadEnd"
/> />
</el-tab-pane> </el-tab-pane>
</el-tabs> </el-tabs>
<!-- If AskAi not enabled, there's no point in rendering tabs --> <!-- If AskAi not enabled, there's no point in rendering tabs -->
<div v-else :class="$style.fillHeight"> <div v-else :class="$style.fillHeight">
<div ref="codeNodeEditor" :class="['ph-no-capture', $style.fillHeight]" /> <div ref="codeNodeEditorRef" :class="['ph-no-capture', $style.fillHeight]" />
<slot name="suffix" /> <slot name="suffix" />
</div> </div>
</div> </div>
</template> </template>
<script lang="ts"> <script setup lang="ts">
import { defineComponent } from 'vue'; import { javascript } from '@codemirror/lang-javascript';
import type { PropType } from 'vue'; import { python } from '@codemirror/lang-python';
import jsParser from 'prettier/plugins/babel';
import { format } from 'prettier';
import * as estree from 'prettier/plugins/estree';
import { mapStores } from 'pinia';
import type { LanguageSupport } from '@codemirror/language'; import type { LanguageSupport } from '@codemirror/language';
import type { Extension, Line } from '@codemirror/state'; import type { Extension, Line } from '@codemirror/state';
import { Compartment, EditorState } from '@codemirror/state'; import { Compartment, EditorState } from '@codemirror/state';
import type { ViewUpdate } from '@codemirror/view'; import type { ViewUpdate } from '@codemirror/view';
import { EditorView } from '@codemirror/view'; import { EditorView } from '@codemirror/view';
import { javascript } from '@codemirror/lang-javascript';
import { python } from '@codemirror/lang-python';
import type { CodeExecutionMode, CodeNodeEditorLanguage } from 'n8n-workflow'; import type { CodeExecutionMode, CodeNodeEditorLanguage } from 'n8n-workflow';
import { CODE_EXECUTION_MODES, CODE_LANGUAGES } from 'n8n-workflow'; import { format } from 'prettier';
import jsParser from 'prettier/plugins/babel';
import * as estree from 'prettier/plugins/estree';
import { type Ref, computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { ASK_AI_EXPERIMENT, CODE_NODE_TYPE } from '@/constants'; import { ASK_AI_EXPERIMENT, CODE_NODE_TYPE } from '@/constants';
import { codeNodeEditorEventBus } from '@/event-bus'; import { codeNodeEditorEventBus } from '@/event-bus';
import { useRootStore } from '@/stores/root.store'; import { useRootStore } from '@/stores/root.store';
import { usePostHog } from '@/stores/posthog.store'; import { usePostHog } from '@/stores/posthog.store';
import { readOnlyEditorExtensions, writableEditorExtensions } from './baseExtensions';
import { CODE_PLACEHOLDERS } from './constants';
import { linterExtension } from './linter';
import { completerExtension } from './completer';
import { codeNodeEditorTheme } from './theme';
import AskAI from './AskAI/AskAI.vue';
import { useMessage } from '@/composables/useMessage'; import { useMessage } from '@/composables/useMessage';
import { useSettingsStore } from '@/stores/settings.store'; import { useSettingsStore } from '@/stores/settings.store';
import AskAI from './AskAI/AskAI.vue';
import { readOnlyEditorExtensions, writableEditorExtensions } from './baseExtensions';
import { useCompleter } from './completer';
import { CODE_PLACEHOLDERS } from './constants';
import { useLinter } from './linter';
import { codeNodeEditorTheme } from './theme';
import { useI18n } from '@/composables/useI18n';
import { useTelemetry } from '@/composables/useTelemetry';
export default defineComponent({ type Props = {
name: 'CodeNodeEditor', mode: CodeExecutionMode;
components: { modelValue: string;
AskAI, aiButtonEnabled?: boolean;
}, fillParent?: boolean;
mixins: [linterExtension, completerExtension], language?: CodeNodeEditorLanguage;
props: { isReadOnly?: boolean;
aiButtonEnabled: { rows?: number;
type: Boolean, };
default: false,
},
fillParent: {
type: Boolean,
default: false,
},
mode: {
type: String as PropType<CodeExecutionMode>,
validator: (value: CodeExecutionMode): boolean => CODE_EXECUTION_MODES.includes(value),
required: true,
},
language: {
type: String as PropType<CodeNodeEditorLanguage>,
default: 'javaScript' as CodeNodeEditorLanguage,
validator: (value: CodeNodeEditorLanguage): boolean => CODE_LANGUAGES.includes(value),
},
isReadOnly: {
type: Boolean,
default: false,
},
rows: {
type: Number,
default: 4,
},
modelValue: {
type: String,
required: true,
},
},
setup() {
return {
...useMessage(),
};
},
data() {
return {
editor: null as EditorView | null,
languageCompartment: new Compartment(),
linterCompartment: new Compartment(),
isEditorHovered: false,
isEditorFocused: false,
tabs: ['code', 'ask-ai'],
activeTab: 'code',
hasChanges: false,
isLoadingAIResponse: false,
};
},
watch: {
mode(_newMode, previousMode: CodeExecutionMode) {
this.reloadLinter();
if ( const props = withDefaults(defineProps<Props>(), {
this.getCurrentEditorContent().trim() === CODE_PLACEHOLDERS[this.language]?.[previousMode] aiButtonEnabled: false,
) { fillParent: false,
this.refreshPlaceholder(); language: 'javaScript',
} isReadOnly: false,
}, rows: 4,
language(_newLanguage, previousLanguage: CodeNodeEditorLanguage) {
if (
this.getCurrentEditorContent().trim() === CODE_PLACEHOLDERS[previousLanguage]?.[this.mode]
) {
this.refreshPlaceholder();
}
const [languageSupport] = this.languageExtensions;
this.editor?.dispatch({
effects: this.languageCompartment.reconfigure(languageSupport),
});
},
aiEnabled: {
immediate: true,
async handler(isEnabled) {
if (isEnabled && !this.modelValue) {
this.$emit('update:modelValue', this.placeholder);
}
await this.$nextTick();
this.hasChanges = this.modelValue !== this.placeholder;
},
},
},
computed: {
...mapStores(useRootStore, usePostHog, useSettingsStore),
aiEnabled(): boolean {
const isAiExperimentEnabled = [ASK_AI_EXPERIMENT.gpt3, ASK_AI_EXPERIMENT.gpt4].includes(
(this.posthogStore.getVariant(ASK_AI_EXPERIMENT.name) ?? '') as string,
);
return (
isAiExperimentEnabled &&
this.settingsStore.settings.ai.enabled &&
this.language === 'javaScript'
);
},
placeholder(): string {
return CODE_PLACEHOLDERS[this.language]?.[this.mode] ?? '';
},
// eslint-disable-next-line vue/return-in-computed-property
languageExtensions(): [LanguageSupport, ...Extension[]] {
switch (this.language) {
case 'javaScript':
return [javascript(), this.autocompletionExtension('javaScript')];
case 'python':
return [python(), this.autocompletionExtension('python')];
}
},
},
beforeUnmount() {
if (!this.isReadOnly) codeNodeEditorEventBus.off('error-line-number', this.highlightLine);
},
mounted() {
if (!this.isReadOnly) codeNodeEditorEventBus.on('error-line-number', this.highlightLine);
const { isReadOnly, language } = this;
const extensions: Extension[] = [
...readOnlyEditorExtensions,
EditorState.readOnly.of(isReadOnly),
EditorView.editable.of(!isReadOnly),
codeNodeEditorTheme({
isReadOnly,
maxHeight: this.fillParent ? '100%' : '40vh',
minHeight: '20vh',
rows: this.rows,
}),
];
if (!isReadOnly) {
const linter = this.createLinter(language);
if (linter) {
extensions.push(this.linterCompartment.of(linter));
}
extensions.push(
...writableEditorExtensions,
EditorView.domEventHandlers({
focus: () => {
this.isEditorFocused = true;
},
blur: () => {
this.isEditorFocused = false;
},
}),
EditorView.updateListener.of((viewUpdate) => {
if (!viewUpdate.docChanged) return;
this.trackCompletion(viewUpdate);
this.$emit('update:modelValue', this.editor?.state.doc.toString());
this.hasChanges = true;
}),
);
}
const [languageSupport, ...otherExtensions] = this.languageExtensions;
extensions.push(this.languageCompartment.of(languageSupport), ...otherExtensions);
const state = EditorState.create({
doc: this.modelValue ?? this.placeholder,
extensions,
});
this.editor = new EditorView({
parent: this.$refs.codeNodeEditor as HTMLDivElement,
state,
});
// empty on first load, default param value
if (!this.modelValue) {
this.refreshPlaceholder();
this.$emit('update:modelValue', this.placeholder);
}
},
methods: {
getCurrentEditorContent() {
return this.editor?.state.doc.toString() ?? '';
},
async onBeforeTabLeave(_activeName: string, oldActiveName: string) {
// Confirm dialog if leaving ask-ai tab during loading
if (oldActiveName === 'ask-ai' && this.isLoadingAIResponse) {
const confirmModal = await this.alert(
this.$locale.baseText('codeNodeEditor.askAi.sureLeaveTab'),
{
title: this.$locale.baseText('codeNodeEditor.askAi.areYouSure'),
confirmButtonText: this.$locale.baseText('codeNodeEditor.askAi.switchTab'),
showClose: true,
showCancelButton: true,
},
);
if (confirmModal === 'confirm') {
return true;
}
return false;
}
return true;
},
async onReplaceCode(code: string) {
const formattedCode = await format(code, {
parser: 'babel',
plugins: [jsParser, estree],
});
this.editor?.dispatch({
changes: { from: 0, to: this.getCurrentEditorContent().length, insert: formattedCode },
});
this.activeTab = 'code';
this.hasChanges = false;
},
onMouseOver(event: MouseEvent) {
const fromElement = event.relatedTarget as HTMLElement;
const ref = this.$refs.codeNodeEditorContainer as HTMLDivElement | undefined;
if (!ref?.contains(fromElement)) this.isEditorHovered = true;
},
onMouseOut(event: MouseEvent) {
const fromElement = event.relatedTarget as HTMLElement;
const ref = this.$refs.codeNodeEditorContainer as HTMLDivElement | undefined;
if (!ref?.contains(fromElement)) this.isEditorHovered = false;
},
reloadLinter() {
if (!this.editor) return;
const linter = this.createLinter(this.language);
if (linter) {
this.editor.dispatch({
effects: this.linterCompartment.reconfigure(linter),
});
}
},
refreshPlaceholder() {
if (!this.editor) return;
this.editor.dispatch({
changes: { from: 0, to: this.getCurrentEditorContent().length, insert: this.placeholder },
});
},
line(lineNumber: number): Line | null {
try {
return this.editor?.state.doc.line(lineNumber) ?? null;
} catch {
return null;
}
},
highlightLine(lineNumber: number | 'final') {
if (!this.editor) return;
if (lineNumber === 'final') {
this.editor.dispatch({
selection: { anchor: (this.modelValue ?? this.getCurrentEditorContent()).length },
});
return;
}
const line = this.line(lineNumber);
if (!line) return;
this.editor.dispatch({
selection: { anchor: line.from },
});
},
trackCompletion(viewUpdate: ViewUpdate) {
const completionTx = viewUpdate.transactions.find((tx) => tx.isUserEvent('input.complete'));
if (!completionTx) return;
try {
// @ts-ignore - undocumented fields
const { fromA, toB } = viewUpdate?.changedRanges[0];
const full = this.getCurrentEditorContent().slice(fromA, toB);
const lastDotIndex = full.lastIndexOf('.');
let context = null;
let insertedText = null;
if (lastDotIndex === -1) {
context = '';
insertedText = full;
} else {
context = full.slice(0, lastDotIndex);
insertedText = full.slice(lastDotIndex + 1);
}
// TODO: Still has to get updated for Python and JSON
this.$telemetry.track('User autocompleted code', {
instance_id: this.rootStore.instanceId,
node_type: CODE_NODE_TYPE,
field_name: this.mode === 'runOnceForAllItems' ? 'jsCodeAllItems' : 'jsCodeEachItem',
field_type: 'code',
context,
inserted_text: insertedText,
});
} catch {}
},
},
}); });
const emit = defineEmits<{
(event: 'update:modelValue', value: string): void;
}>();
const message = useMessage();
const editor = ref(null) as Ref<EditorView | null>;
const languageCompartment = ref(new Compartment());
const linterCompartment = ref(new Compartment());
const isEditorHovered = ref(false);
const isEditorFocused = ref(false);
const tabs = ref(['code', 'ask-ai']);
const activeTab = ref('code');
const hasChanges = ref(false);
const isLoadingAIResponse = ref(false);
const codeNodeEditorRef = ref<HTMLDivElement>();
const codeNodeEditorContainerRef = ref<HTMLDivElement>();
const { autocompletionExtension } = useCompleter(() => props.mode, editor);
const { createLinter } = useLinter(() => props.mode, editor);
const rootStore = useRootStore();
const settingsStore = useSettingsStore();
const posthog = usePostHog();
const i18n = useI18n();
const telemetry = useTelemetry();
onMounted(() => {
if (!props.isReadOnly) codeNodeEditorEventBus.on('error-line-number', highlightLine);
const { isReadOnly, language } = props;
const extensions: Extension[] = [
...readOnlyEditorExtensions,
EditorState.readOnly.of(isReadOnly),
EditorView.editable.of(!isReadOnly),
codeNodeEditorTheme({
isReadOnly,
maxHeight: props.fillParent ? '100%' : '40vh',
minHeight: '20vh',
rows: props.rows,
}),
];
if (!isReadOnly) {
const linter = createLinter(language);
if (linter) {
extensions.push(linterCompartment.value.of(linter));
}
extensions.push(
...writableEditorExtensions,
EditorView.domEventHandlers({
focus: () => {
isEditorFocused.value = true;
},
blur: () => {
isEditorFocused.value = false;
},
}),
EditorView.updateListener.of((viewUpdate) => {
if (!viewUpdate.docChanged) return;
trackCompletion(viewUpdate);
const value = editor.value?.state.doc.toString();
if (value) {
emit('update:modelValue', value);
}
hasChanges.value = true;
}),
);
}
const [languageSupport, ...otherExtensions] = languageExtensions.value;
extensions.push(languageCompartment.value.of(languageSupport), ...otherExtensions);
const state = EditorState.create({
doc: props.modelValue ?? placeholder.value,
extensions,
});
editor.value = new EditorView({
parent: codeNodeEditorRef.value,
state,
});
// empty on first load, default param value
if (!props.modelValue) {
refreshPlaceholder();
emit('update:modelValue', placeholder.value);
}
});
onBeforeUnmount(() => {
if (!props.isReadOnly) codeNodeEditorEventBus.off('error-line-number', highlightLine);
});
const aiEnabled = computed(() => {
const isAiExperimentEnabled = [ASK_AI_EXPERIMENT.gpt3, ASK_AI_EXPERIMENT.gpt4].includes(
(posthog.getVariant(ASK_AI_EXPERIMENT.name) ?? '') as string,
);
return (
isAiExperimentEnabled && settingsStore.settings.ai.enabled && props.language === 'javaScript'
);
});
const placeholder = computed(() => {
return CODE_PLACEHOLDERS[props.language]?.[props.mode] ?? '';
});
// eslint-disable-next-line vue/return-in-computed-property
const languageExtensions = computed<[LanguageSupport, ...Extension[]]>(() => {
switch (props.language) {
case 'javaScript':
return [javascript(), autocompletionExtension('javaScript')];
case 'python':
return [python(), autocompletionExtension('python')];
}
});
watch(
() => props.mode,
(_newMode, previousMode: CodeExecutionMode) => {
reloadLinter();
if (getCurrentEditorContent().trim() === CODE_PLACEHOLDERS[props.language]?.[previousMode]) {
refreshPlaceholder();
}
},
);
watch(
() => props.language,
(_newLanguage, previousLanguage: CodeNodeEditorLanguage) => {
if (getCurrentEditorContent().trim() === CODE_PLACEHOLDERS[previousLanguage]?.[props.mode]) {
refreshPlaceholder();
}
const [languageSupport] = languageExtensions.value;
editor.value?.dispatch({
effects: languageCompartment.value.reconfigure(languageSupport),
});
reloadLinter();
},
);
watch(
aiEnabled,
async (isEnabled) => {
if (isEnabled && !props.modelValue) {
emit('update:modelValue', placeholder.value);
}
await nextTick();
hasChanges.value = props.modelValue !== placeholder.value;
},
{ immediate: true },
);
function getCurrentEditorContent() {
return editor.value?.state.doc.toString() ?? '';
}
async function onBeforeTabLeave(_activeName: string, oldActiveName: string) {
// Confirm dialog if leaving ask-ai tab during loading
if (oldActiveName === 'ask-ai' && isLoadingAIResponse.value) {
const confirmModal = await message.alert(i18n.baseText('codeNodeEditor.askAi.sureLeaveTab'), {
title: i18n.baseText('codeNodeEditor.askAi.areYouSure'),
confirmButtonText: i18n.baseText('codeNodeEditor.askAi.switchTab'),
showClose: true,
showCancelButton: true,
});
if (confirmModal === 'confirm') {
return true;
}
return false;
}
return true;
}
async function onReplaceCode(code: string) {
const formattedCode = await format(code, {
parser: 'babel',
plugins: [jsParser, estree],
});
editor.value?.dispatch({
changes: { from: 0, to: getCurrentEditorContent().length, insert: formattedCode },
});
activeTab.value = 'code';
hasChanges.value = false;
}
function onMouseOver(event: MouseEvent) {
const fromElement = event.relatedTarget as HTMLElement;
const containerRef = codeNodeEditorContainerRef.value;
if (!containerRef?.contains(fromElement)) isEditorHovered.value = true;
}
function onMouseOut(event: MouseEvent) {
const fromElement = event.relatedTarget as HTMLElement;
const containerRef = codeNodeEditorContainerRef.value;
if (!containerRef?.contains(fromElement)) isEditorHovered.value = false;
}
function reloadLinter() {
if (!editor.value) return;
const linter = createLinter(props.language);
if (linter) {
editor.value.dispatch({
effects: linterCompartment.value.reconfigure(linter),
});
}
}
function refreshPlaceholder() {
if (!editor.value) return;
editor.value.dispatch({
changes: { from: 0, to: getCurrentEditorContent().length, insert: placeholder.value },
});
}
function getLine(lineNumber: number): Line | null {
try {
return editor.value?.state.doc.line(lineNumber) ?? null;
} catch {
return null;
}
}
function highlightLine(lineNumber: number | 'final') {
if (!editor.value) return;
if (lineNumber === 'final') {
editor.value.dispatch({
selection: { anchor: (props.modelValue ?? getCurrentEditorContent()).length },
});
return;
}
const line = getLine(lineNumber);
if (!line) return;
editor.value.dispatch({
selection: { anchor: line.from },
});
}
function trackCompletion(viewUpdate: ViewUpdate) {
const completionTx = viewUpdate.transactions.find((tx) => tx.isUserEvent('input.complete'));
if (!completionTx) return;
try {
// @ts-expect-error - undocumented fields
const { fromA, toB } = viewUpdate?.changedRanges[0];
const full = getCurrentEditorContent().slice(fromA, toB);
const lastDotIndex = full.lastIndexOf('.');
let context = null;
let insertedText = null;
if (lastDotIndex === -1) {
context = '';
insertedText = full;
} else {
context = full.slice(0, lastDotIndex);
insertedText = full.slice(lastDotIndex + 1);
}
// TODO: Still has to get updated for Python and JSON
telemetry.track('User autocompleted code', {
instance_id: rootStore.instanceId,
node_type: CODE_NODE_TYPE,
field_name: props.mode === 'runOnceForAllItems' ? 'jsCodeAllItems' : 'jsCodeEachItem',
field_type: 'code',
context,
inserted_text: insertedText,
});
} catch {}
}
function onAiLoadStart() {
isLoadingAIResponse.value = true;
}
function onAiLoadEnd() {
isLoadingAIResponse.value = false;
}
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">

View file

@ -1,15 +1,15 @@
import type { PropType } from 'vue'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { defineComponent } from 'vue';
import { autocompletion } from '@codemirror/autocomplete'; import { autocompletion } from '@codemirror/autocomplete';
import { localCompletionSource } from '@codemirror/lang-javascript'; import { localCompletionSource } from '@codemirror/lang-javascript';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import type { Extension } from '@codemirror/state'; import type { Extension } from '@codemirror/state';
import type { MaybeRefOrGetter } from 'vue';
import { toValue } from 'vue';
import { useBaseCompletions } from './completions/base.completions'; import { useBaseCompletions } from './completions/base.completions';
import { jsSnippets } from './completions/js.snippets'; import { jsSnippets } from './completions/js.snippets';
import type { EditorView } from '@codemirror/view';
import type { CodeExecutionMode } from 'n8n-workflow'; import type { CodeExecutionMode } from 'n8n-workflow';
import { CODE_EXECUTION_MODES } from 'n8n-workflow';
import { useExecutionCompletions } from './completions/execution.completions'; import { useExecutionCompletions } from './completions/execution.completions';
import { useItemFieldCompletions } from './completions/itemField.completions'; import { useItemFieldCompletions } from './completions/itemField.completions';
import { useItemIndexCompletions } from './completions/itemIndex.completions'; import { useItemIndexCompletions } from './completions/itemIndex.completions';
@ -19,292 +19,283 @@ import { usePrevNodeCompletions } from './completions/prevNode.completions';
import { useRequireCompletions } from './completions/require.completions'; import { useRequireCompletions } from './completions/require.completions';
import { useVariablesCompletions } from './completions/variables.completions'; import { useVariablesCompletions } from './completions/variables.completions';
import { useWorkflowCompletions } from './completions/workflow.completions'; import { useWorkflowCompletions } from './completions/workflow.completions';
import type { EditorView } from '@codemirror/view';
export const completerExtension = defineComponent({ export const useCompleter = (
props: { mode: MaybeRefOrGetter<CodeExecutionMode>,
mode: { editor: MaybeRefOrGetter<EditorView | null>,
type: String as PropType<CodeExecutionMode>, ) => {
validator: (value: CodeExecutionMode): boolean => CODE_EXECUTION_MODES.includes(value), function autocompletionExtension(language: 'javaScript' | 'python'): Extension {
required: true, // Base completions
}, const { baseCompletions, itemCompletions, nodeSelectorCompletions } = useBaseCompletions(
}, toValue(mode),
data() { language,
return { );
editor: null as EditorView | null, const { executionCompletions } = useExecutionCompletions();
}; const { inputMethodCompletions, selectorMethodCompletions } = useItemFieldCompletions(language);
}, const { inputCompletions, selectorCompletions } = useItemIndexCompletions(mode);
methods: { const { inputJsonFieldCompletions, selectorJsonFieldCompletions } = useJsonFieldCompletions();
autocompletionExtension(language: 'javaScript' | 'python'): Extension { const { dateTimeCompletions, nowCompletions, todayCompletions } = useLuxonCompletions();
// Base completions const { prevNodeCompletions } = usePrevNodeCompletions();
const { baseCompletions, itemCompletions, nodeSelectorCompletions } = useBaseCompletions( const { requireCompletions } = useRequireCompletions();
this.mode, const { variablesCompletions } = useVariablesCompletions();
language, const { workflowCompletions } = useWorkflowCompletions();
);
const { executionCompletions } = useExecutionCompletions();
const { inputMethodCompletions, selectorMethodCompletions } =
useItemFieldCompletions(language);
const { inputCompletions, selectorCompletions } = useItemIndexCompletions(this.mode);
const { inputJsonFieldCompletions, selectorJsonFieldCompletions } = useJsonFieldCompletions();
const { dateTimeCompletions, nowCompletions, todayCompletions } = useLuxonCompletions();
const { prevNodeCompletions } = usePrevNodeCompletions();
const { requireCompletions } = useRequireCompletions();
const { variablesCompletions } = useVariablesCompletions();
const { workflowCompletions } = useWorkflowCompletions();
const completions = []; const completions = [];
if (language === 'javaScript') { if (language === 'javaScript') {
completions.push(jsSnippets, localCompletionSource); completions.push(jsSnippets, localCompletionSource);
} }
return autocompletion({ return autocompletion({
icons: false, icons: false,
compareCompletions: (a: Completion, b: Completion) => { compareCompletions: (a: Completion, b: Completion) => {
if (/\.json$|id$|id['"]\]$/.test(a.label)) return 0; if (/\.json$|id$|id['"]\]$/.test(a.label)) return 0;
return a.label.localeCompare(b.label); return a.label.localeCompare(b.label);
}, },
override: [ override: [
...completions, ...completions,
// core // core
itemCompletions, itemCompletions,
baseCompletions, baseCompletions,
requireCompletions, requireCompletions,
nodeSelectorCompletions, nodeSelectorCompletions,
prevNodeCompletions, prevNodeCompletions,
workflowCompletions, workflowCompletions,
variablesCompletions, variablesCompletions,
executionCompletions, executionCompletions,
// luxon
todayCompletions,
nowCompletions,
dateTimeCompletions,
// item index
inputCompletions,
selectorCompletions,
// item field
inputMethodCompletions,
selectorMethodCompletions,
// item json field
inputJsonFieldCompletions,
selectorJsonFieldCompletions,
// multiline
this.multilineCompletions,
],
});
},
/**
* Complete uses of variables to any of the supported completions.
*/
multilineCompletions(context: CompletionContext): CompletionResult | null {
if (!this.editor) return null;
let variablesToValues: Record<string, string> = {};
try {
variablesToValues = this.variablesToValues();
} catch {
return null;
}
if (Object.keys(variablesToValues).length === 0) return null;
/**
* Complete uses of extended variables, i.e. variables having
* one or more dotted segments already.
*
* const x = $input;
* x.first(). -> .json
* x.first().json. -> .field
*/
const docLines = this.editor.state.doc.toString().split('\n');
const varNames = Object.keys(variablesToValues);
const uses = this.extendedUses(docLines, varNames);
const { matcherItemFieldCompletions } = useItemFieldCompletions('javaScript');
for (const use of uses.itemField) {
const matcher = use.replace(/\.$/, '');
const completions = matcherItemFieldCompletions(context, matcher, variablesToValues);
if (completions) return completions;
}
for (const use of uses.jsonField) {
const matcher = use.replace(/(\.|\[)$/, '');
const completions = matcherItemFieldCompletions(context, matcher, variablesToValues);
if (completions) return completions;
}
/**
* Complete uses of unextended variables, i.e. variables having
* no dotted segment already.
*
* const x = $input;
* x. -> .first()
*
* const x = $input.first();
* x. -> .json
*
* const x = $input.first().json;
* x. -> .field
*/
const SELECTOR_REGEX = /^\$\((?<quotedNodeName>['"][\w\s]+['"])\)$/; // $('nodeName')
const INPUT_METHOD_REGEXES = Object.values({
first: /\$input\.first\(\)$/,
last: /\$input\.last\(\)$/,
item: /\$input\.item$/,
all: /\$input\.all\(\)\[(?<index>\w+)\]$/,
});
const SELECTOR_METHOD_REGEXES = Object.values({
first: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.first\(\)$/,
last: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.last\(\)$/,
item: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.item$/,
all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]$/,
});
const INPUT_JSON_REGEXES = Object.values({
first: /\$input\.first\(\)\.json$/,
last: /\$input\.last\(\)\.json$/,
item: /\$input\.item\.json$/,
all: /\$input\.all\(\)\[(?<index>\w+)\]\.json$/,
});
const SELECTOR_JSON_REGEXES = Object.values({
first: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.first\(\)\.json$/,
last: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.last\(\)\.json$/,
item: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.item\.json$/,
all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]\.json$/,
});
const { executionCompletions } = useExecutionCompletions();
const { inputCompletions, selectorCompletions } = useItemIndexCompletions(this.mode);
const { matcherJsonFieldCompletions } = useJsonFieldCompletions();
const { dateTimeCompletions, nowCompletions, todayCompletions } = useLuxonCompletions();
const { variablesCompletions } = useVariablesCompletions();
const { workflowCompletions } = useWorkflowCompletions();
for (const [variable, value] of Object.entries(variablesToValues)) {
const { prevNodeCompletions } = usePrevNodeCompletions(variable);
if (value === '$execution') return executionCompletions(context, variable);
if (value === '$vars') return variablesCompletions(context, variable);
if (value === '$workflow') return workflowCompletions(context, variable);
if (value === '$prevNode') return prevNodeCompletions(context);
// luxon // luxon
todayCompletions,
if (value === '$now') return nowCompletions(context, variable); nowCompletions,
if (value === '$today') return todayCompletions(context, variable); dateTimeCompletions,
if (value === 'DateTime') return dateTimeCompletions(context, variable);
// item index // item index
inputCompletions,
if (value === '$input') return inputCompletions(context, variable); selectorCompletions,
if (SELECTOR_REGEX.test(value)) return selectorCompletions(context, variable);
// json field
const inputJsonMatched = INPUT_JSON_REGEXES.some((regex) => regex.test(value));
const selectorJsonMatched = SELECTOR_JSON_REGEXES.some((regex) => regex.test(value));
if (inputJsonMatched || selectorJsonMatched) {
return matcherJsonFieldCompletions(context, variable, variablesToValues);
}
// item field // item field
inputMethodCompletions,
selectorMethodCompletions,
const inputMethodMatched = INPUT_METHOD_REGEXES.some((regex) => regex.test(value)); // item json field
const selectorMethodMatched = SELECTOR_METHOD_REGEXES.some((regex) => regex.test(value)); inputJsonFieldCompletions,
selectorJsonFieldCompletions,
if (inputMethodMatched || selectorMethodMatched) { // multiline
return matcherItemFieldCompletions(context, variable, variablesToValues); multilineCompletions,
} ],
});
}
/**
* Complete uses of variables to any of the supported completions.
*/
function multilineCompletions(context: CompletionContext): CompletionResult | null {
const editorValue = toValue(editor);
if (!editorValue) return null;
let variablesToValueMap: Record<string, string> = {};
try {
variablesToValueMap = variablesToValues();
} catch {
return null;
}
if (Object.keys(variablesToValueMap).length === 0) return null;
/**
* Complete uses of extended variables, i.e. variables having
* one or more dotted segments already.
*
* const x = $input;
* x.first(). -> .json
* x.first().json. -> .field
*/
const docLines = editorValue.state.doc.toString().split('\n');
const varNames = Object.keys(variablesToValueMap);
const uses = extendedUses(docLines, varNames);
const { matcherItemFieldCompletions } = useItemFieldCompletions('javaScript');
for (const use of uses.itemField) {
const matcher = use.replace(/\.$/, '');
const completions = matcherItemFieldCompletions(context, matcher, variablesToValueMap);
if (completions) return completions;
}
for (const use of uses.jsonField) {
const matcher = use.replace(/(\.|\[)$/, '');
const completions = matcherItemFieldCompletions(context, matcher, variablesToValueMap);
if (completions) return completions;
}
/**
* Complete uses of unextended variables, i.e. variables having
* no dotted segment already.
*
* const x = $input;
* x. -> .first()
*
* const x = $input.first();
* x. -> .json
*
* const x = $input.first().json;
* x. -> .field
*/
const SELECTOR_REGEX = /^\$\((?<quotedNodeName>['"][\w\s]+['"])\)$/; // $('nodeName')
const INPUT_METHOD_REGEXES = Object.values({
first: /\$input\.first\(\)$/,
last: /\$input\.last\(\)$/,
item: /\$input\.item$/,
all: /\$input\.all\(\)\[(?<index>\w+)\]$/,
});
const SELECTOR_METHOD_REGEXES = Object.values({
first: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.first\(\)$/,
last: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.last\(\)$/,
item: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.item$/,
all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]$/,
});
const INPUT_JSON_REGEXES = Object.values({
first: /\$input\.first\(\)\.json$/,
last: /\$input\.last\(\)\.json$/,
item: /\$input\.item\.json$/,
all: /\$input\.all\(\)\[(?<index>\w+)\]\.json$/,
});
const SELECTOR_JSON_REGEXES = Object.values({
first: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.first\(\)\.json$/,
last: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.last\(\)\.json$/,
item: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.item\.json$/,
all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]\.json$/,
});
const { executionCompletions } = useExecutionCompletions();
const { inputCompletions, selectorCompletions } = useItemIndexCompletions(mode);
const { matcherJsonFieldCompletions } = useJsonFieldCompletions();
const { dateTimeCompletions, nowCompletions, todayCompletions } = useLuxonCompletions();
const { variablesCompletions } = useVariablesCompletions();
const { workflowCompletions } = useWorkflowCompletions();
for (const [variable, value] of Object.entries(variablesToValueMap)) {
const { prevNodeCompletions } = usePrevNodeCompletions(variable);
if (value === '$execution') return executionCompletions(context, variable);
if (value === '$vars') return variablesCompletions(context, variable);
if (value === '$workflow') return workflowCompletions(context, variable);
if (value === '$prevNode') return prevNodeCompletions(context);
// luxon
if (value === '$now') return nowCompletions(context, variable);
if (value === '$today') return todayCompletions(context, variable);
if (value === 'DateTime') return dateTimeCompletions(context, variable);
// item index
if (value === '$input') return inputCompletions(context, variable);
if (SELECTOR_REGEX.test(value)) return selectorCompletions(context, variable);
// json field
const inputJsonMatched = INPUT_JSON_REGEXES.some((regex) => regex.test(value));
const selectorJsonMatched = SELECTOR_JSON_REGEXES.some((regex) => regex.test(value));
if (inputJsonMatched || selectorJsonMatched) {
return matcherJsonFieldCompletions(context, variable, variablesToValueMap);
} }
return null; // item field
},
// ---------------------------------- const inputMethodMatched = INPUT_METHOD_REGEXES.some((regex) => regex.test(value));
// helpers const selectorMethodMatched = SELECTOR_METHOD_REGEXES.some((regex) => regex.test(value));
// ----------------------------------
/** if (inputMethodMatched || selectorMethodMatched) {
* Create a map of variables and the values they point to. return matcherItemFieldCompletions(context, variable, variablesToValueMap);
*/ }
variablesToValues() { }
return this.variableDeclarationLines().reduce<Record<string, string>>((acc, line) => {
const [left, right] = line.split('=');
const varName = left.replace(/(var|let|const)/, '').trim(); return null;
const varValue = right.replace(/;/, '').trim(); }
acc[varName] = varValue; // ----------------------------------
// helpers
// ----------------------------------
/**
* Create a map of variables and the values they point to.
*/
function variablesToValues() {
return variableDeclarationLines().reduce<Record<string, string>>((acc, line) => {
const [left, right] = line.split('=');
const varName = left.replace(/(var|let|const)/, '').trim();
const varValue = right.replace(/;/, '').trim();
acc[varName] = varValue;
return acc;
}, {});
}
function variableDeclarationLines() {
const editorValue = toValue(editor);
if (!editorValue) return [];
const docLines = editorValue.state.doc.toString().split('\n');
const isVariableDeclarationLine = (line: string) =>
['var', 'const', 'let'].some((varType) => line.startsWith(varType));
return docLines.filter(isVariableDeclarationLine);
}
/**
* Collect uses of variables pointing to n8n syntax if they have been extended.
*
* x.first().
* x.first().json.
* x.json.
*/
function extendedUses(docLines: string[], varNames: string[]) {
return docLines.reduce<{ itemField: string[]; jsonField: string[] }>(
(acc, cur) => {
varNames.forEach((varName) => {
const accessorPattern = `(${varName}.first\\(\\)|${varName}.last\\(\\)|${varName}.item|${varName}.all\\(\\)\\[\\w+\\]).*`;
const methodMatch = cur.match(new RegExp(accessorPattern));
if (methodMatch) {
if (/json(\.|\[)$/.test(methodMatch[0])) {
acc.jsonField.push(methodMatch[0]);
} else {
acc.itemField.push(methodMatch[0]);
}
}
const jsonPattern = `^${varName}\\.json(\\.|\\[)$`;
const jsonMatch = cur.match(new RegExp(jsonPattern));
if (jsonMatch) {
acc.jsonField.push(jsonMatch[0]);
}
});
return acc; return acc;
}, {}); },
}, { itemField: [], jsonField: [] },
);
}
variableDeclarationLines() { return { autocompletionExtension };
if (!this.editor) return []; };
const docLines = this.editor.state.doc.toString().split('\n');
const isVariableDeclarationLine = (line: string) =>
['var', 'const', 'let'].some((varType) => line.startsWith(varType));
return docLines.filter(isVariableDeclarationLine);
},
/**
* Collect uses of variables pointing to n8n syntax if they have been extended.
*
* x.first().
* x.first().json.
* x.json.
*/
extendedUses(docLines: string[], varNames: string[]) {
return docLines.reduce<{ itemField: string[]; jsonField: string[] }>(
(acc, cur) => {
varNames.forEach((varName) => {
const accessorPattern = `(${varName}.first\\(\\)|${varName}.last\\(\\)|${varName}.item|${varName}.all\\(\\)\\[\\w+\\]).*`;
const methodMatch = cur.match(new RegExp(accessorPattern));
if (methodMatch) {
if (/json(\.|\[)$/.test(methodMatch[0])) {
acc.jsonField.push(methodMatch[0]);
} else {
acc.itemField.push(methodMatch[0]);
}
}
const jsonPattern = `^${varName}\\.json(\\.|\\[)$`;
const jsonMatch = cur.match(new RegExp(jsonPattern));
if (jsonMatch) {
acc.jsonField.push(jsonMatch[0]);
}
});
return acc;
},
{ itemField: [], jsonField: [] },
);
},
},
});

View file

@ -1,8 +1,10 @@
import { escape } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { useI18n } from '@/composables/useI18n'; import { useI18n } from '@/composables/useI18n';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import type { CodeExecutionMode } from 'n8n-workflow';
import { toValue, type MaybeRefOrGetter } from 'vue';
import { escape } from '../utils';
export function useItemIndexCompletions(mode: 'runOnceForEachItem' | 'runOnceForAllItems') { export function useItemIndexCompletions(mode: MaybeRefOrGetter<CodeExecutionMode>) {
const i18n = useI18n(); const i18n = useI18n();
/** /**
* - Complete `$input.` to `.first() .last() .all() .itemMatching()` in all-items mode. * - Complete `$input.` to `.first() .last() .all() .itemMatching()` in all-items mode.
@ -20,7 +22,7 @@ export function useItemIndexCompletions(mode: 'runOnceForEachItem' | 'runOnceFor
const options: Completion[] = []; const options: Completion[] = [];
if (mode === 'runOnceForAllItems') { if (toValue(mode) === 'runOnceForAllItems') {
options.push( options.push(
{ {
label: `${matcher}.first()`, label: `${matcher}.first()`,
@ -45,7 +47,7 @@ export function useItemIndexCompletions(mode: 'runOnceForEachItem' | 'runOnceFor
); );
} }
if (mode === 'runOnceForEachItem') { if (toValue(mode) === 'runOnceForEachItem') {
options.push({ options.push({
label: `${matcher}.item`, label: `${matcher}.item`,
type: 'variable', type: 'variable',
@ -97,7 +99,7 @@ export function useItemIndexCompletions(mode: 'runOnceForEachItem' | 'runOnceFor
}, },
]; ];
if (mode === 'runOnceForAllItems') { if (toValue(mode) === 'runOnceForAllItems') {
options.push( options.push(
{ {
label: `${replacementBase}.first()`, label: `${replacementBase}.first()`,
@ -122,7 +124,7 @@ export function useItemIndexCompletions(mode: 'runOnceForEachItem' | 'runOnceFor
); );
} }
if (mode === 'runOnceForEachItem') { if (toValue(mode) === 'runOnceForEachItem') {
options.push({ options.push({
label: `${replacementBase}.item`, label: `${replacementBase}.item`,
type: 'variable', type: 'variable',

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,11 @@
<template> <template>
<div :class="$style.editor"> <div :class="$style.editor">
<div ref="jsEditor" class="ph-no-capture js-editor"></div> <div ref="jsEditorRef" class="ph-no-capture js-editor"></div>
<slot name="suffix" /> <slot name="suffix" />
</div> </div>
</template> </template>
<script lang="ts"> <script setup lang="ts">
import { history, toggleComment } from '@codemirror/commands'; import { history, toggleComment } from '@codemirror/commands';
import { javascript } from '@codemirror/lang-javascript'; import { javascript } from '@codemirror/lang-javascript';
import { foldGutter, indentOnInput } from '@codemirror/language'; import { foldGutter, indentOnInput } from '@codemirror/language';
@ -21,9 +21,8 @@ import {
keymap, keymap,
lineNumbers, lineNumbers,
} from '@codemirror/view'; } from '@codemirror/view';
import { defineComponent } from 'vue'; import { computed, onMounted, ref } from 'vue';
import { codeNodeEditorTheme } from '../CodeNodeEditor/theme';
import { import {
autocompleteKeyMap, autocompleteKeyMap,
enterKeyMap, enterKeyMap,
@ -31,86 +30,72 @@ import {
tabKeyMap, tabKeyMap,
} from '@/plugins/codemirror/keymap'; } from '@/plugins/codemirror/keymap';
import { n8nAutocompletion } from '@/plugins/codemirror/n8nLang'; import { n8nAutocompletion } from '@/plugins/codemirror/n8nLang';
import { codeNodeEditorTheme } from '../CodeNodeEditor/theme';
export default defineComponent({ type Props = {
name: 'JsEditor', modelValue: string;
props: { isReadOnly?: boolean;
modelValue: { fillParent?: boolean;
type: String, rows?: number;
required: true, };
},
isReadOnly: { const props = withDefaults(defineProps<Props>(), { fillParent: false, isReadOnly: false, rows: 4 });
type: Boolean, const emit = defineEmits<{
default: false, (event: 'update:modelValue', value: string): void;
}, }>();
fillParent: {
type: Boolean, onMounted(() => {
default: false, const state = EditorState.create({ doc: props.modelValue, extensions: extensions.value });
}, const parent = jsEditorRef.value;
rows: { editor.value = new EditorView({ parent, state });
type: Number, editorState.value = editor.value.state;
default: 4, });
},
}, const jsEditorRef = ref<HTMLDivElement>();
data() { const editor = ref<EditorView | null>(null);
return { const editorState = ref<EditorState | null>(null);
editor: null as EditorView | null,
editorState: null as EditorState | null, const extensions = computed(() => {
}; const extensionsToApply: Extension[] = [
}, javascript(),
computed: { lineNumbers(),
doc(): string { EditorView.lineWrapping,
return this.editor?.state.doc.toString() ?? ''; EditorState.readOnly.of(props.isReadOnly),
}, EditorView.editable.of(!props.isReadOnly),
extensions(): Extension[] { codeNodeEditorTheme({
const { isReadOnly } = this; isReadOnly: props.isReadOnly,
const extensions: Extension[] = [ maxHeight: props.fillParent ? '100%' : '40vh',
javascript(), minHeight: '20vh',
lineNumbers(), rows: props.rows,
EditorView.lineWrapping, }),
EditorState.readOnly.of(isReadOnly), ];
EditorView.editable.of(!isReadOnly),
codeNodeEditorTheme({ if (!props.isReadOnly) {
isReadOnly, extensionsToApply.push(
maxHeight: this.fillParent ? '100%' : '40vh', history(),
minHeight: '20vh', Prec.highest(
rows: this.rows, keymap.of([
}), ...tabKeyMap(),
]; ...enterKeyMap,
if (!isReadOnly) { ...historyKeyMap,
extensions.push( ...autocompleteKeyMap,
history(), { key: 'Mod-/', run: toggleComment },
Prec.highest( ]),
keymap.of([ ),
...tabKeyMap(), lintGutter(),
...enterKeyMap, n8nAutocompletion(),
...historyKeyMap, indentOnInput(),
...autocompleteKeyMap, highlightActiveLine(),
{ key: 'Mod-/', run: toggleComment }, highlightActiveLineGutter(),
]), foldGutter(),
), dropCursor(),
lintGutter(), EditorView.updateListener.of((viewUpdate: ViewUpdate) => {
n8nAutocompletion(), if (!viewUpdate.docChanged || !editor.value) return;
indentOnInput(), emit('update:modelValue', editor.value?.state.doc.toString());
highlightActiveLine(), }),
highlightActiveLineGutter(), );
foldGutter(), }
dropCursor(), return extensionsToApply;
EditorView.updateListener.of((viewUpdate: ViewUpdate) => {
if (!viewUpdate.docChanged || !this.editor) return;
this.$emit('update:modelValue', this.editor?.state.doc.toString());
}),
);
}
return extensions;
},
},
mounted() {
const state = EditorState.create({ doc: this.modelValue, extensions: this.extensions });
const parent = this.$refs.jsEditor as HTMLDivElement;
this.editor = new EditorView({ parent, state });
this.editorState = this.editor.state;
},
}); });
</script> </script>

View file

@ -1,11 +1,11 @@
<template> <template>
<div :class="$style.editor"> <div :class="$style.editor">
<div ref="jsonEditor" class="ph-no-capture json-editor"></div> <div ref="jsonEditorRef" class="ph-no-capture json-editor"></div>
<slot name="suffix" /> <slot name="suffix" />
</div> </div>
</template> </template>
<script lang="ts"> <script setup lang="ts">
import { history } from '@codemirror/commands'; import { history } from '@codemirror/commands';
import { json, jsonParseLinter } from '@codemirror/lang-json'; import { json, jsonParseLinter } from '@codemirror/lang-json';
import { bracketMatching, foldGutter, indentOnInput } from '@codemirror/language'; import { bracketMatching, foldGutter, indentOnInput } from '@codemirror/language';
@ -21,7 +21,6 @@ import {
keymap, keymap,
lineNumbers, lineNumbers,
} from '@codemirror/view'; } from '@codemirror/view';
import { defineComponent } from 'vue';
import { codeNodeEditorTheme } from '../CodeNodeEditor/theme'; import { codeNodeEditorTheme } from '../CodeNodeEditor/theme';
import { import {
@ -31,103 +30,90 @@ import {
tabKeyMap, tabKeyMap,
} from '@/plugins/codemirror/keymap'; } from '@/plugins/codemirror/keymap';
import { n8nAutocompletion } from '@/plugins/codemirror/n8nLang'; import { n8nAutocompletion } from '@/plugins/codemirror/n8nLang';
import { computed, onMounted, ref, watch } from 'vue';
export default defineComponent({ type Props = {
name: 'JsonEditor', modelValue: string;
props: { isReadOnly?: boolean;
modelValue: { fillParent?: boolean;
type: String, rows?: number;
required: true, };
},
isReadOnly: {
type: Boolean,
default: false,
},
fillParent: {
type: Boolean,
default: false,
},
rows: {
type: Number,
default: 4,
},
},
data() {
return {
editor: null as EditorView | null,
editorState: null as EditorState | null,
};
},
computed: {
doc(): string {
return this.editor?.state.doc.toString() ?? '';
},
extensions(): Extension[] {
const { isReadOnly } = this;
const extensions: Extension[] = [
json(),
lineNumbers(),
EditorView.lineWrapping,
EditorState.readOnly.of(isReadOnly),
EditorView.editable.of(!isReadOnly),
codeNodeEditorTheme({
isReadOnly,
maxHeight: this.fillParent ? '100%' : '40vh',
minHeight: '20vh',
rows: this.rows,
}),
];
if (!isReadOnly) {
extensions.push(
history(),
Prec.highest(
keymap.of([...tabKeyMap(), ...enterKeyMap, ...historyKeyMap, ...autocompleteKeyMap]),
),
createLinter(jsonParseLinter()),
lintGutter(),
n8nAutocompletion(),
indentOnInput(),
highlightActiveLine(),
highlightActiveLineGutter(),
foldGutter(),
dropCursor(),
bracketMatching(),
EditorView.updateListener.of((viewUpdate: ViewUpdate) => {
if (!viewUpdate.docChanged || !this.editor) return;
this.$emit('update:modelValue', this.editor?.state.doc.toString());
}),
);
}
return extensions;
},
},
watch: {
modelValue(newValue: string) {
const editorValue = this.editor?.state?.doc.toString();
// If model value changes from outside the component const props = withDefaults(defineProps<Props>(), { fillParent: false, isReadOnly: false, rows: 4 });
if (editorValue && editorValue.length !== newValue.length && editorValue !== newValue) { const emit = defineEmits<{
this.destroyEditor(); (event: 'update:modelValue', value: string): void;
this.createEditor(); }>();
}
},
},
mounted() {
this.createEditor();
},
methods: {
createEditor() {
const state = EditorState.create({ doc: this.modelValue, extensions: this.extensions });
const parent = this.$refs.jsonEditor as HTMLDivElement;
this.editor = new EditorView({ parent, state }); const jsonEditorRef = ref<HTMLDivElement>();
this.editorState = this.editor.state; const editor = ref<EditorView | null>(null);
}, const editorState = ref<EditorState | null>(null);
destroyEditor() {
this.editor?.destroy(); const extensions = computed(() => {
}, const extensionsToApply: Extension[] = [
}, json(),
lineNumbers(),
EditorView.lineWrapping,
EditorState.readOnly.of(props.isReadOnly),
EditorView.editable.of(!props.isReadOnly),
codeNodeEditorTheme({
isReadOnly: props.isReadOnly,
maxHeight: props.fillParent ? '100%' : '40vh',
minHeight: '20vh',
rows: props.rows,
}),
];
if (!props.isReadOnly) {
extensionsToApply.push(
history(),
Prec.highest(
keymap.of([...tabKeyMap(), ...enterKeyMap, ...historyKeyMap, ...autocompleteKeyMap]),
),
createLinter(jsonParseLinter()),
lintGutter(),
n8nAutocompletion(),
indentOnInput(),
highlightActiveLine(),
highlightActiveLineGutter(),
foldGutter(),
dropCursor(),
bracketMatching(),
EditorView.updateListener.of((viewUpdate: ViewUpdate) => {
if (!viewUpdate.docChanged || !editor.value) return;
emit('update:modelValue', editor.value?.state.doc.toString());
}),
);
}
return extensionsToApply;
}); });
onMounted(() => {
createEditor();
});
watch(
() => props.modelValue,
(newValue: string) => {
const editorValue = editor.value?.state?.doc.toString();
// If model value changes from outside the component
if (editorValue && editorValue.length !== newValue.length && editorValue !== newValue) {
destroyEditor();
createEditor();
}
},
);
function createEditor() {
const state = EditorState.create({ doc: props.modelValue, extensions: extensions.value });
const parent = jsonEditorRef.value;
editor.value = new EditorView({ parent, state });
editorState.value = editor.value.state;
}
function destroyEditor() {
editor.value?.destroy();
}
</script> </script>
<style lang="scss" module> <style lang="scss" module>