刘光辉
7 小时以前 cf11e63b659afcc9792ab3e395f1b45d844431a8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
<script lang="ts" setup>
import type { Diagnostic as CodeMirrorDiagnostic } from '@codemirror/lint';
 
import type { FormulaResourceKind } from './formulaLanguage';
 
import type { FormulaFunction, FormulaRule, FormulaValidation, ParameterSlot } from '#/api/x/eln/formulas';
 
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
 
import { autocompletion, completionStatus, startCompletion } from '@codemirror/autocomplete';
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands';
import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language';
import { linter, setDiagnostics } from '@codemirror/lint';
import { EditorState } from '@codemirror/state';
import { placeholder as editorPlaceholder, EditorView, keymap } from '@codemirror/view';
 
import { formulaCompletionSource, formulaLanguage } from './formulaLanguage';
import { toEditorDiagnostics } from './formulaRules';
import { useFormulaValidation } from './useFormulaValidation';
 
defineOptions({ name: 'ElnFormulaEditor' });
 
const props = withDefaults(
  defineProps<{
    functions?: FormulaFunction[];
    modelValue: string;
    parameters?: ParameterSlot[];
    readonly?: boolean;
    rule: FormulaRule;
  }>(),
  { functions: () => [], parameters: () => [], readonly: false },
);
const emit = defineEmits<{
  'update:modelValue': [value: string];
  validation: [value: FormulaValidation];
}>();
 
const editorElement = ref<HTMLElement>();
const { error, loading, result, retry, schedule, validateNow } = useFormulaValidation();
const latestValidation = computed(() => result.value);
const validationStatusText = computed(() => {
  if (loading.value) return '校验中';
  if (error.value) return '校验失败';
  if (latestValidation.value?.diagnostics.some((diagnostic) => diagnostic.severity === 'ERROR')) return '存在错误';
  if (latestValidation.value) return '语法通过';
  return '';
});
let editorView: EditorView | undefined;
let syncingModelValue = false;
let activeResourceKind: FormulaResourceKind = 'all';
 
function clearValidation() {
  if (editorView) editorView.dispatch(setDiagnostics(editorView.state, []));
  emit('validation', { diagnostics: [], latex: null });
}
 
function scheduleValidation(rule: FormulaRule) {
  clearValidation();
  schedule(rule);
}
 
onMounted(() => {
  if (!editorElement.value) return;
  editorView = new EditorView({
    parent: editorElement.value,
    state: EditorState.create({
      doc: props.modelValue,
      extensions: [
        history(),
        keymap.of([...defaultKeymap, ...historyKeymap]),
        bracketMatching(),
        formulaLanguage,
        syntaxHighlighting(defaultHighlightStyle),
        editorPlaceholder('请输入公式表达式'),
        autocompletion({ override: [(context) => formulaCompletionSource(props.parameters, props.functions, () => activeResourceKind)(context)] }),
        linter(() => []),
        EditorView.lineWrapping,
        EditorView.editable.of(!props.readonly),
        EditorView.updateListener.of((update) => {
          if (completionStatus(update.startState) && !completionStatus(update.state)) activeResourceKind = 'all';
          if (!update.docChanged || syncingModelValue) return;
          const value = update.state.doc.toString();
          emit('update:modelValue', value);
          scheduleValidation({ ...props.rule, biaodashi: value });
        }),
      ],
    }),
  });
});
 
watch(
  () => props.modelValue,
  (value) => {
    if (!editorView || value === editorView.state.doc.toString()) return;
    syncingModelValue = true;
    editorView.dispatch({ changes: { from: 0, insert: value, to: editorView.state.doc.length } });
    syncingModelValue = false;
  },
);
 
const nonExpressionRuleSignature = computed(() =>
  JSON.stringify({
    jieguoLeixing: props.rule.jieguoLeixing,
    parameters: props.rule.parameters.map((slot) => ({
      canshuBianma: slot.canshuBianma,
      paixu: slot.paixu,
      shifouBitian: slot.shifouBitian,
      shujuLeixing: slot.shujuLeixing,
    })),
    xiuyueMoshi: props.rule.xiuyueMoshi,
    xiuyueXiaoshuWei: props.rule.xiuyueXiaoshuWei,
  }),
);
 
watch(nonExpressionRuleSignature, () => {
  const expression = editorView?.state.doc.toString() || props.modelValue;
  scheduleValidation({ ...props.rule, biaodashi: expression });
});
 
watch(latestValidation, (validationResult) => {
  if (!validationResult) return;
  const mappedDiagnostics = toEditorDiagnostics(validationResult.diagnostics, editorView?.state.doc.length);
  const diagnostics: CodeMirrorDiagnostic[] = mappedDiagnostics.map((diagnostic) => ({
    from: diagnostic.from,
    message: diagnostic.message || diagnostic.code || '公式校验失败',
    severity: diagnostic.severity === 'ERROR' ? 'error' : 'warning',
    to: diagnostic.to,
  }));
  if (editorView) editorView.dispatch(setDiagnostics(editorView.state, diagnostics));
  const hasSyntaxError = validationResult.diagnostics.some((diagnostic) => diagnostic.severity === 'ERROR');
  emit('validation', { ...validationResult, latex: hasSyntaxError ? null : validationResult.latex });
});
 
function insert(text: string) {
  if (!editorView || props.readonly) return;
  const range = editorView.state.selection.main;
  editorView.dispatch({
    changes: { from: range.from, insert: text, to: range.to },
    selection: { anchor: range.from + text.length },
  });
  editorView.focus();
}
 
function openResourceMenu(kind: Exclude<FormulaResourceKind, 'all'>) {
  if (!editorView || props.readonly) return;
  activeResourceKind = kind;
  editorView.focus();
  startCompletion(editorView);
}
 
async function validate() {
  const expression = editorView?.state.doc.toString() || props.modelValue;
  await validateNow({ ...props.rule, biaodashi: expression });
}
 
onBeforeUnmount(() => {
  editorView?.destroy();
  editorView = undefined;
});
 
defineExpose({ insert, validate });
</script>
 
<template>
  <div class="formula-editor" :class="{ 'is-readonly': readonly }">
    <div v-if="!readonly" class="formula-editor__toolbar">
      <a-button size="small" @click="openResourceMenu('parameter')">插入参数</a-button>
      <a-button size="small" @click="openResourceMenu('function')">插入函数</a-button>
      <span v-if="validationStatusText" class="formula-editor__validation-status" :class="{ 'is-error': error || validationStatusText === '存在错误' }">
        {{ validationStatusText }}
      </span>
    </div>
    <div ref="editorElement" class="formula-editor__surface"></div>
    <div v-if="error" class="formula-editor__error">
      <a-alert :message="error" show-icon type="error" />
      <a-button size="small" type="link" @click="retry">重试</a-button>
    </div>
  </div>
</template>
 
<style lang="scss" scoped>
.formula-editor__surface {
  min-height: 180px;
  max-height: 360px;
  overflow: auto;
  border: 1px solid var(--border-color-base);
  border-top: 0;
}
 
.formula-editor.is-readonly .formula-editor__surface {
  border-top: 1px solid var(--border-color-base);
}
 
.formula-editor__toolbar {
  display: flex;
  align-items: center;
  gap: 8px;
  min-height: 40px;
  padding: 4px 8px;
  background: var(--app-content-background);
  border: 1px solid var(--border-color-base);
}
 
.formula-editor__validation-status {
  margin-left: auto;
  color: var(--success-color);
  font-size: 12px;
 
  &.is-error {
    color: var(--error-color);
  }
}
 
.formula-editor__error {
  display: flex;
  align-items: center;
  gap: 8px;
  padding-top: 8px;
}
</style>