@aleph-alpha/chat-kit 6.1.1 → 6.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/{CkHistory.vue_vue_type_script_setup_true_lang-Cr8vF94e.js → CkHistory.vue_vue_type_script_setup_true_lang-gV-lp0ZB.js} +345 -164
  2. package/dist/adapters/responses-api.js +1 -1
  3. package/dist/chat-kit.css +111 -28
  4. package/dist/code-palette-DAJUTnR-.js +21598 -0
  5. package/dist/components/base/CkCodeEditor/CkCodeEditor.stories.d.ts +43 -0
  6. package/dist/components/base/CkCodeEditor/CkCodeEditor.stories.d.ts.map +1 -0
  7. package/dist/components/base/CkCodeEditor/CkCodeEditor.vue.d.ts +39 -0
  8. package/dist/components/base/CkCodeEditor/CkCodeEditor.vue.d.ts.map +1 -0
  9. package/dist/components/base/CkCodeEditor/createCodeMirror.d.ts +44 -0
  10. package/dist/components/base/CkCodeEditor/createCodeMirror.d.ts.map +1 -0
  11. package/dist/components/base/CkCodeEditor/index.d.ts +3 -0
  12. package/dist/components/base/CkCodeEditor/index.d.ts.map +1 -0
  13. package/dist/components/base/CkCodeEditor/types.d.ts +129 -0
  14. package/dist/components/base/CkCodeEditor/types.d.ts.map +1 -0
  15. package/dist/components/base/CkMilkdownEditor/CkMilkdownEditor.stories.d.ts +6 -0
  16. package/dist/components/base/CkMilkdownEditor/CkMilkdownEditor.stories.d.ts.map +1 -1
  17. package/dist/components/base/CkMilkdownEditor/CkMilkdownEditor.vue.d.ts +1 -0
  18. package/dist/components/base/CkMilkdownEditor/CkMilkdownEditor.vue.d.ts.map +1 -1
  19. package/dist/components/base/CkMilkdownEditor/createCrepeEditor.d.ts +1 -0
  20. package/dist/components/base/CkMilkdownEditor/createCrepeEditor.d.ts.map +1 -1
  21. package/dist/components/base/CkMilkdownEditor/types.d.ts +8 -0
  22. package/dist/components/base/CkMilkdownEditor/types.d.ts.map +1 -1
  23. package/dist/components/base/index.d.ts +2 -0
  24. package/dist/components/base/index.d.ts.map +1 -1
  25. package/dist/components/index.d.ts +2 -2
  26. package/dist/components/index.d.ts.map +1 -1
  27. package/dist/components/index.js +27 -26
  28. package/dist/composables/index.js +1 -1
  29. package/dist/createCodeMirror-BkV6FEPn.js +101 -0
  30. package/dist/{createCrepeEditor-CFbvSH3s.js → createCrepeEditor-Ci5FHHIV.js} +1434 -24739
  31. package/dist/handlers/index.js +2 -2
  32. package/dist/handlers/useChatKitLabels.d.ts +6 -0
  33. package/dist/handlers/useChatKitLabels.d.ts.map +1 -1
  34. package/dist/{components/base/CkMilkdownEditor/codeMirrorTheme.d.ts → helpers/codemirror/theme.d.ts} +1 -1
  35. package/dist/helpers/codemirror/theme.d.ts.map +1 -0
  36. package/dist/helpers/index.d.ts +1 -0
  37. package/dist/helpers/index.d.ts.map +1 -1
  38. package/dist/helpers/markdownToPlainText.d.ts +18 -0
  39. package/dist/helpers/markdownToPlainText.d.ts.map +1 -0
  40. package/dist/{index-BWvkps_G.js → index-B2tew8uf.js} +3 -3
  41. package/dist/{index-DhY_9bdS.js → index-BLVAx_f8.js} +2 -2
  42. package/dist/{index-B0ldhzaj.js → index-BUCqcTPA.js} +2 -2
  43. package/dist/{index-DdlzabmR.js → index-BhvbqYsK.js} +2 -2
  44. package/dist/{index-gzleljO6.js → index-BoUJGvvQ.js} +2 -2
  45. package/dist/{index-sKO1lHHC.js → index-BtY1uxn6.js} +3 -2
  46. package/dist/{index-BVOjyn3y.js → index-BvG6l44n.js} +3 -2
  47. package/dist/{index-BoqzHVNB.js → index-CB6xZVsf.js} +2 -2
  48. package/dist/{index-BaS8OW8V.js → index-CIF93PZF.js} +3 -3
  49. package/dist/index-CLdXUpL8.js +9560 -0
  50. package/dist/{index-DSq3gvqU.js → index-CN8d3yl1.js} +1 -1
  51. package/dist/{index-CRfGWVdQ.js → index-CYk7AB8M.js} +4 -4
  52. package/dist/{index-C72e57-5.js → index-CZFx44C7.js} +2 -2
  53. package/dist/{index-Tj3pzx-E.js → index-Cxs6kPho.js} +3 -3
  54. package/dist/index-D6ftdiLa.js +1825 -0
  55. package/dist/{index-CMJGuXap.js → index-DgCcFC3N.js} +3 -3
  56. package/dist/{index-DSU7cBGz.js → index-DhwsowEf.js} +2 -2
  57. package/dist/{index-C_gTb50u.js → index-Dl24CCB3.js} +4 -4
  58. package/dist/{index-BlHHEbV-.js → index-DqGDenO9.js} +2 -2
  59. package/dist/{index-naWlQpaL.js → index-DufAP1JF.js} +3 -2
  60. package/dist/{index-Dm6C1blN.js → index-DxTzaHLr.js} +4 -4
  61. package/dist/{index-A5rWjRtZ.js → index-MfXW4ZyN.js} +3 -2
  62. package/dist/{index-C6zYjwIQ.js → index-ZHg2R9iD.js} +3 -2
  63. package/dist/{index-ZeRS5rER.js → index-gYt3E3Cp.js} +2 -2
  64. package/dist/{index-Da3777l2.js → index-w2yzH7vs.js} +3 -3
  65. package/dist/index.d.ts +3 -3
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +33 -30
  68. package/dist/markdownToPlainText-BOtlQ_BY.js +34 -0
  69. package/dist/{useChatKitLabels-Ww1Q7xUr.js → useChatKitLabels-CatQSpfL.js} +881 -10428
  70. package/dist/{useMessageHandler-Tellov3w.js → useMessageHandler-nnsort0-.js} +1 -1
  71. package/package.json +5 -3
  72. package/src/components/base/CkCodeEditor/CkCodeEditor.spec.ts +223 -0
  73. package/src/components/base/CkCodeEditor/CkCodeEditor.stories.ts +311 -0
  74. package/src/components/base/CkCodeEditor/CkCodeEditor.vue +238 -0
  75. package/src/components/base/CkCodeEditor/createCodeMirror.ts +188 -0
  76. package/src/components/base/CkCodeEditor/index.ts +2 -0
  77. package/src/components/base/CkCodeEditor/types.ts +128 -0
  78. package/src/components/base/CkMilkdownEditor/CkMilkdownEditor.spec.ts +13 -0
  79. package/src/components/base/CkMilkdownEditor/CkMilkdownEditor.stories.ts +34 -0
  80. package/src/components/base/CkMilkdownEditor/CkMilkdownEditor.vue +3 -1
  81. package/src/components/base/CkMilkdownEditor/createCrepeEditor.ts +2 -1
  82. package/src/components/base/CkMilkdownEditor/milkdown-theme.css +39 -26
  83. package/src/components/base/CkMilkdownEditor/types.ts +8 -0
  84. package/src/components/base/index.ts +6 -0
  85. package/src/components/index.ts +4 -0
  86. package/src/handlers/useChatKitLabels.ts +6 -0
  87. package/src/helpers/codemirror/code-palette.css +49 -0
  88. package/src/{components/base/CkMilkdownEditor/codeMirrorTheme.ts → helpers/codemirror/theme.ts} +23 -12
  89. package/src/helpers/index.ts +1 -0
  90. package/src/helpers/markdownToPlainText.spec.ts +107 -0
  91. package/src/helpers/markdownToPlainText.ts +69 -0
  92. package/src/index.ts +5 -1
  93. package/dist/components/base/CkMilkdownEditor/codeMirrorTheme.d.ts.map +0 -1
  94. package/dist/generateId-BHf0W4Rq.js +0 -6
@@ -0,0 +1,238 @@
1
+ <script setup lang="ts">
2
+ import {
3
+ computed,
4
+ onBeforeUnmount,
5
+ onMounted,
6
+ ref,
7
+ useTemplateRef,
8
+ watch,
9
+ } from 'vue';
10
+ import { UiButton, UiIcon } from '@aleph-alpha/ui-library';
11
+ import { useChatKitLabels } from '../../../handlers/useChatKitLabels';
12
+ import type { CodeMirrorHandle } from './createCodeMirror';
13
+ import type { CkCodeEditorEmits, CkCodeEditorProps } from './types';
14
+
15
+ defineOptions({ name: 'CkCodeEditor' });
16
+
17
+ const props = withDefaults(defineProps<CkCodeEditorProps>(), {
18
+ modelValue: '',
19
+ language: 'text',
20
+ filename: undefined,
21
+ placeholder: undefined,
22
+ readonly: false,
23
+ disabled: false,
24
+ ariaLabel: undefined,
25
+ showHeader: true,
26
+ showCopyButton: true,
27
+ showLineNumbers: true,
28
+ lineWrapping: false,
29
+ maxHeight: undefined,
30
+ autofocus: false,
31
+ writeToClipboard: undefined,
32
+ });
33
+
34
+ const emit = defineEmits<CkCodeEditorEmits>();
35
+
36
+ const labels = useChatKitLabels();
37
+ const rootRef = useTemplateRef<HTMLDivElement>('rootRef');
38
+ const hostRef = useTemplateRef<HTMLDivElement>('hostRef');
39
+ const isLocked = computed(() => props.readonly || props.disabled);
40
+ const isReady = ref(false);
41
+ const isCopied = ref(false);
42
+
43
+ // `UiCodeBlock` labels the block with the filename when there is one and hides
44
+ // the label entirely for plain text; mirror that so the two headers match.
45
+ const headerLabel = computed(() => {
46
+ const label = props.filename || props.language;
47
+ return label === 'text' ? '' : label;
48
+ });
49
+
50
+ const copyLabel = computed(() =>
51
+ isCopied.value
52
+ ? (labels.value.codeEditorCopied ?? 'Copied')
53
+ : (labels.value.codeEditorCopy ?? 'Copy code'),
54
+ );
55
+
56
+ let editor: CodeMirrorHandle | undefined;
57
+ let destroyed = false;
58
+ // Last value emitted or applied, so an echo from the parent is not re-applied.
59
+ let lastKnownCode = props.modelValue;
60
+ let copyTimer: ReturnType<typeof setTimeout> | undefined;
61
+
62
+ function handleChange(value: string): void {
63
+ if (value === lastKnownCode) return;
64
+ lastKnownCode = value;
65
+ emit('update:modelValue', value);
66
+ }
67
+
68
+ onMounted(async () => {
69
+ const parent = hostRef.value;
70
+ if (!parent) return;
71
+
72
+ // Lazy: CodeMirror and its grammars load only once an editor is shown.
73
+ const { createCodeMirror } = await import('./createCodeMirror');
74
+ if (destroyed) return;
75
+
76
+ const initialCode = props.modelValue;
77
+ lastKnownCode = initialCode;
78
+ const handle = await createCodeMirror({
79
+ parent,
80
+ doc: initialCode,
81
+ language: props.language,
82
+ placeholder: props.placeholder,
83
+ ariaLabel: props.ariaLabel,
84
+ readonly: isLocked.value,
85
+ showLineNumbers: props.showLineNumbers,
86
+ lineWrapping: props.lineWrapping,
87
+ onChange: handleChange,
88
+ onFocus: () => emit('focus'),
89
+ onBlur: () => emit('blur'),
90
+ });
91
+
92
+ // Unmounted while the grammar was loading.
93
+ if (destroyed) {
94
+ handle.destroy();
95
+ return;
96
+ }
97
+
98
+ editor = handle;
99
+ // Props may have moved on while the grammar loaded; catch up.
100
+ if (props.modelValue !== initialCode) handle.setCode(props.modelValue);
101
+ isReady.value = true;
102
+ if (props.autofocus) handle.focus();
103
+ });
104
+
105
+ watch(
106
+ () => props.modelValue,
107
+ (next) => {
108
+ if (next === lastKnownCode) return;
109
+ lastKnownCode = next;
110
+ editor?.setCode(next);
111
+ },
112
+ );
113
+
114
+ watch(
115
+ () => props.language,
116
+ (next) => {
117
+ // Loading a grammar is async; nothing waits on it, and a failure already
118
+ // falls back to plain text inside `setLanguage`.
119
+ editor?.setLanguage(next).catch(() => undefined);
120
+ },
121
+ );
122
+ watch(isLocked, (locked) => editor?.setReadonly(locked));
123
+ watch(
124
+ () => props.showLineNumbers,
125
+ (show) => editor?.setShowLineNumbers(show),
126
+ );
127
+ watch(
128
+ () => props.lineWrapping,
129
+ (wrap) => editor?.setLineWrapping(wrap),
130
+ );
131
+
132
+ onBeforeUnmount(() => {
133
+ destroyed = true;
134
+ clearTimeout(copyTimer);
135
+ editor?.destroy();
136
+ editor = undefined;
137
+ });
138
+
139
+ async function handleCopy(): Promise<void> {
140
+ const write =
141
+ props.writeToClipboard ??
142
+ ((text: string) => globalThis.navigator.clipboard.writeText(text));
143
+ try {
144
+ await write(getCode());
145
+ isCopied.value = true;
146
+ clearTimeout(copyTimer);
147
+ copyTimer = setTimeout(() => {
148
+ isCopied.value = false;
149
+ }, 2000);
150
+ emit('copy', { success: true });
151
+ } catch {
152
+ emit('copy', { success: false });
153
+ }
154
+ }
155
+
156
+ function isInsideRoot(target: EventTarget | null): boolean {
157
+ return target instanceof Node && (rootRef.value?.contains(target) ?? false);
158
+ }
159
+
160
+ // CodeMirror reports focus on its own content; the header's copy button is
161
+ // outside that, so only a move out of the whole component counts as a blur.
162
+ function onFocusOut(event: FocusEvent): void {
163
+ if (!isInsideRoot(event.relatedTarget)) emit('blur');
164
+ }
165
+
166
+ function focus(): void {
167
+ editor?.focus();
168
+ }
169
+
170
+ function getCode(): string {
171
+ return editor?.getCode() ?? props.modelValue;
172
+ }
173
+
174
+ defineExpose({ focus, getCode });
175
+ </script>
176
+
177
+ <template>
178
+ <div
179
+ ref="rootRef"
180
+ :class="[
181
+ 'ck-code-editor ck-code-surface border-border-surface-default min-w-0 overflow-hidden rounded-lg border',
182
+ isReady && 'ck-code-editor--ready',
183
+ isLocked && 'ck-code-editor--readonly',
184
+ disabled && 'ck-code-editor--disabled',
185
+ ]"
186
+ :aria-disabled="disabled || undefined"
187
+ @focusout="onFocusOut"
188
+ >
189
+ <div
190
+ v-if="showHeader"
191
+ class="border-border-surface-default bg-background-surface-muted flex items-center justify-between border-b px-4 py-2"
192
+ >
193
+ <span class="text-content-on-surface-secondary font-mono text-sm">
194
+ {{ headerLabel }}
195
+ </span>
196
+ <UiButton
197
+ v-if="showCopyButton"
198
+ variant="ghost"
199
+ size="icon-sm"
200
+ :aria-label="copyLabel"
201
+ @click="handleCopy"
202
+ >
203
+ <UiIcon :name="isCopied ? 'check' : 'copy'" :size="14" />
204
+ </UiButton>
205
+ </div>
206
+
207
+ <div
208
+ ref="hostRef"
209
+ class="ck-code-editor__host"
210
+ :style="maxHeight ? { '--ck-code-max-height': maxHeight } : undefined"
211
+ />
212
+ </div>
213
+ </template>
214
+
215
+ <style scoped>
216
+ /* The editor fills the panel; `:deep` is needed because CodeMirror builds its
217
+ * own DOM, which scoped styles do not reach. */
218
+ .ck-code-editor__host :deep(.cm-editor) {
219
+ background: var(--ck-cm-bg);
220
+ color: var(--ck-cm-foreground);
221
+ }
222
+
223
+ .ck-code-editor__host :deep(.cm-scroller) {
224
+ max-height: var(--ck-code-max-height, none);
225
+ }
226
+
227
+ /* Nothing is being edited, so the active-line band would only be noise. */
228
+ .ck-code-editor--readonly .ck-code-editor__host :deep(.cm-activeLine),
229
+ .ck-code-editor--readonly .ck-code-editor__host :deep(.cm-activeLineGutter) {
230
+ background: transparent;
231
+ }
232
+
233
+ .ck-code-editor--disabled {
234
+ opacity: 0.6;
235
+ cursor: not-allowed;
236
+ pointer-events: none;
237
+ }
238
+ </style>
@@ -0,0 +1,188 @@
1
+ import {
2
+ defaultKeymap,
3
+ history,
4
+ historyKeymap,
5
+ indentWithTab,
6
+ } from '@codemirror/commands';
7
+ import {
8
+ bracketMatching,
9
+ indentOnInput,
10
+ indentUnit,
11
+ type LanguageSupport,
12
+ } from '@codemirror/language';
13
+ import { languages } from '@codemirror/language-data';
14
+ import { Compartment, EditorState, type Extension } from '@codemirror/state';
15
+ import {
16
+ EditorView,
17
+ drawSelection,
18
+ highlightActiveLine,
19
+ highlightSpecialChars,
20
+ keymap,
21
+ lineNumbers,
22
+ placeholder as placeholderExt,
23
+ } from '@codemirror/view';
24
+ import { ckCodeMirrorTheme } from '../../../helpers/codemirror/theme';
25
+ import '../../../helpers/codemirror/code-palette.css';
26
+
27
+ export interface CreateCodeMirrorOptions {
28
+ /** Element the view is mounted into. */
29
+ parent: HTMLElement;
30
+ doc: string;
31
+ language: string;
32
+ placeholder?: string;
33
+ ariaLabel?: string;
34
+ readonly: boolean;
35
+ showLineNumbers: boolean;
36
+ lineWrapping: boolean;
37
+ /** Called synchronously whenever the document changes. */
38
+ onChange: (value: string) => void;
39
+ onFocus: () => void;
40
+ onBlur: () => void;
41
+ }
42
+
43
+ /** Imperative surface `CkCodeEditor` drives; keeps CodeMirror out of the SFC. */
44
+ export interface CodeMirrorHandle {
45
+ view: EditorView;
46
+ getCode: () => string;
47
+ /** Replace the whole document, keeping the cursor where it still fits. */
48
+ setCode: (value: string) => void;
49
+ setLanguage: (language: string) => Promise<void>;
50
+ setReadonly: (readonly: boolean) => void;
51
+ setShowLineNumbers: (show: boolean) => void;
52
+ setLineWrapping: (wrap: boolean) => void;
53
+ focus: () => void;
54
+ destroy: () => void;
55
+ }
56
+
57
+ /** Plain text, and the value `UiCodeBlock` also treats as "no language". */
58
+ const PLAIN_ALIASES = new Set(['text', 'txt', 'plain', 'plaintext', '']);
59
+
60
+ /**
61
+ * Resolve a language id the way a reader would expect: by name, by alias, or by
62
+ * file extension, all case-insensitively. Returns `null` for plain text and for
63
+ * anything CodeMirror does not know, so an unrecognised id degrades to
64
+ * unhighlighted code instead of throwing.
65
+ */
66
+ export async function resolveLanguage(
67
+ language: string,
68
+ ): Promise<LanguageSupport | null> {
69
+ const id = language.trim().toLowerCase();
70
+ if (PLAIN_ALIASES.has(id)) return null;
71
+
72
+ const description = languages.find(
73
+ (candidate) =>
74
+ candidate.name.toLowerCase() === id ||
75
+ candidate.alias.includes(id) ||
76
+ candidate.extensions.includes(id),
77
+ );
78
+ if (!description) return null;
79
+
80
+ try {
81
+ return await description.load();
82
+ } catch {
83
+ // A grammar that fails to load must not take the editor down with it.
84
+ return null;
85
+ }
86
+ }
87
+
88
+ // `readOnly` rejects edits while keeping the text selectable; `editable`
89
+ // additionally drops `contenteditable`, which hides the caret and keeps the
90
+ // editor out of the tab order.
91
+ function readonlyState(readonly: boolean): Extension {
92
+ return [EditorState.readOnly.of(readonly), EditorView.editable.of(!readonly)];
93
+ }
94
+
95
+ function baseExtensions(options: CreateCodeMirrorOptions): Extension[] {
96
+ return [
97
+ // Deliberately not CodeMirror's `basicSetup`: it also brings autocomplete,
98
+ // search, folding and bracket closing, none of which suit a snippet field,
99
+ // and its fold gutter would sit next to the line numbers.
100
+ history(),
101
+ drawSelection(),
102
+ highlightSpecialChars(),
103
+ highlightActiveLine(),
104
+ bracketMatching(),
105
+ indentOnInput(),
106
+ indentUnit.of(' '),
107
+ keymap.of([...defaultKeymap, ...historyKeymap, indentWithTab]),
108
+ ckCodeMirrorTheme,
109
+ EditorView.contentAttributes.of({
110
+ role: 'textbox',
111
+ 'aria-multiline': 'true',
112
+ ...(options.ariaLabel ? { 'aria-label': options.ariaLabel } : {}),
113
+ }),
114
+ EditorView.updateListener.of((update) => {
115
+ if (update.docChanged) options.onChange(update.state.doc.toString());
116
+ if (update.focusChanged) {
117
+ if (update.view.hasFocus) options.onFocus();
118
+ else options.onBlur();
119
+ }
120
+ }),
121
+ ...(options.placeholder ? [placeholderExt(options.placeholder)] : []),
122
+ ];
123
+ }
124
+
125
+ /**
126
+ * Build a CodeMirror view themed like `UiCodeBlock`. Loaded lazily by
127
+ * `CkCodeEditor` so CodeMirror stays out of the package's main chunk.
128
+ */
129
+ export async function createCodeMirror(
130
+ options: CreateCodeMirrorOptions,
131
+ ): Promise<CodeMirrorHandle> {
132
+ // One set per view: a compartment is the key a reconfigure targets, so
133
+ // sharing them across editors would make the instances interfere.
134
+ const languageSlot = new Compartment();
135
+ const readonlySlot = new Compartment();
136
+ const lineNumbersSlot = new Compartment();
137
+ const wrappingSlot = new Compartment();
138
+
139
+ const support = await resolveLanguage(options.language);
140
+
141
+ const view = new EditorView({
142
+ parent: options.parent,
143
+ state: EditorState.create({
144
+ doc: options.doc,
145
+ extensions: [
146
+ ...baseExtensions(options),
147
+ languageSlot.of(support ? [support] : []),
148
+ readonlySlot.of(readonlyState(options.readonly)),
149
+ lineNumbersSlot.of(options.showLineNumbers ? lineNumbers() : []),
150
+ wrappingSlot.of(options.lineWrapping ? EditorView.lineWrapping : []),
151
+ ],
152
+ }),
153
+ });
154
+
155
+ function reconfigure(slot: Compartment, extension: Extension): void {
156
+ view.dispatch({ effects: slot.reconfigure(extension) });
157
+ }
158
+
159
+ return {
160
+ view,
161
+ getCode: () => view.state.doc.toString(),
162
+ setCode: (value) => {
163
+ if (value === view.state.doc.toString()) return;
164
+ // Replacing the whole document would otherwise send the cursor home
165
+ // whenever a parent echoes the value back; clamp it to the new length.
166
+ const cursor = Math.min(view.state.selection.main.head, value.length);
167
+ view.dispatch({
168
+ changes: { from: 0, to: view.state.doc.length, insert: value },
169
+ selection: { anchor: cursor },
170
+ });
171
+ },
172
+ setLanguage: async (language) => {
173
+ const next = await resolveLanguage(language);
174
+ reconfigure(languageSlot, next ? [next] : []);
175
+ },
176
+ setReadonly: (readonly) => {
177
+ reconfigure(readonlySlot, readonlyState(readonly));
178
+ },
179
+ setShowLineNumbers: (show) => {
180
+ reconfigure(lineNumbersSlot, show ? lineNumbers() : []);
181
+ },
182
+ setLineWrapping: (wrap) => {
183
+ reconfigure(wrappingSlot, wrap ? EditorView.lineWrapping : []);
184
+ },
185
+ focus: () => view.focus(),
186
+ destroy: () => view.destroy(),
187
+ };
188
+ }
@@ -0,0 +1,2 @@
1
+ export { default as CkCodeEditor } from './CkCodeEditor.vue';
2
+ export type * from './types';
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Single-document code editor built on [CodeMirror 6](https://codemirror.net/).
3
+ * Its surface is the one `UiCodeBlock` renders for fenced code inside
4
+ * {@link CkMarkdownRenderer}: the same bordered, rounded panel, the same muted
5
+ * header carrying the language and a copy button, the same monospace metrics,
6
+ * and syntax colours approximating Shiki's `github-light` / `github-dark`. A
7
+ * snippet therefore looks the same whether it is being read in a reply or
8
+ * edited here.
9
+ *
10
+ * Use it wherever a whole document *is* code — a snippet field, a config or
11
+ * template editor, a "create skill" form. For prose that merely contains code,
12
+ * use {@link CkMilkdownEditor}, whose fenced blocks share this same theme.
13
+ *
14
+ * Grammars load on demand from CodeMirror's language data, so only the
15
+ * languages actually opened are fetched, and the editor itself loads lazily on
16
+ * mount so importing the component costs nothing until one is shown.
17
+ *
18
+ * @category Form Inputs
19
+ * @useCases edit a code snippet, config or template editor, code field in a form, review and tweak generated code
20
+ * @keywords code, editor, codemirror, syntax highlighting, snippet, v-model, monospace, language
21
+ * @related CkMilkdownEditor, CkMarkdownRenderer
22
+ */
23
+ export interface CkCodeEditorProps {
24
+ /**
25
+ * The code. Supports `v-model`.
26
+ *
27
+ * Unlike {@link CkMilkdownEditor}, updates are emitted synchronously on every
28
+ * change, with no debounce and no reformatting of what you pass in.
29
+ *
30
+ * @default ''
31
+ */
32
+ modelValue?: string;
33
+ /**
34
+ * Language id used for both syntax highlighting and the header label, for
35
+ * example `typescript`, `python`, `json` or `bash`. Matching is on the names,
36
+ * aliases and extensions CodeMirror knows; an unknown value still renders as
37
+ * plain text rather than failing.
38
+ *
39
+ * @default 'text'
40
+ */
41
+ language?: string;
42
+ /**
43
+ * Filename shown in the header instead of the language, mirroring the prop of
44
+ * the same name on `UiCodeBlock`.
45
+ */
46
+ filename?: string;
47
+ /** Text shown while the document is empty. */
48
+ placeholder?: string;
49
+ /**
50
+ * Render the code without allowing edits. The caret and the active-line
51
+ * highlight are hidden, but the text stays selectable and copyable.
52
+ *
53
+ * @default false
54
+ */
55
+ readonly?: boolean;
56
+ /**
57
+ * Like `readonly`, but also mutes the editor and marks it `aria-disabled`.
58
+ *
59
+ * @default false
60
+ */
61
+ disabled?: boolean;
62
+ /** Accessible name for the editable region. */
63
+ ariaLabel?: string;
64
+ /**
65
+ * Show the header bar with the language or filename and the copy button. Set
66
+ * it to `false` for a bare editing surface.
67
+ *
68
+ * @default true
69
+ */
70
+ showHeader?: boolean;
71
+ /**
72
+ * Show the copy button in the header.
73
+ *
74
+ * @default true
75
+ */
76
+ showCopyButton?: boolean;
77
+ /**
78
+ * Show the line-number gutter. On by default, which is what a dedicated code
79
+ * editor is expected to do; `UiCodeBlock` and `CkMilkdownEditor` default to
80
+ * `false` because their code is being read rather than written.
81
+ *
82
+ * @default true
83
+ */
84
+ showLineNumbers?: boolean;
85
+ /**
86
+ * Wrap long lines instead of scrolling horizontally. `UiCodeBlock` scrolls,
87
+ * so the default keeps the two consistent.
88
+ *
89
+ * @default false
90
+ */
91
+ lineWrapping?: boolean;
92
+ /**
93
+ * Maximum height of the scrollable code area, as any CSS length, for example
94
+ * `'24rem'`. Unset, the editor grows with its content.
95
+ */
96
+ maxHeight?: string;
97
+ /**
98
+ * Move focus into the editor once it has been created.
99
+ *
100
+ * @default false
101
+ */
102
+ autofocus?: boolean;
103
+ /**
104
+ * Clipboard writer for the copy button. Injected for tests and for hosts that
105
+ * proxy clipboard access; defaults to `navigator.clipboard.writeText`.
106
+ */
107
+ writeToClipboard?: (text: string) => Promise<void>;
108
+ }
109
+
110
+ /** Events emitted by {@link CkCodeEditor}. */
111
+ export interface CkCodeEditorEmits {
112
+ /** Emitted on every document change, with the full code. */
113
+ 'update:modelValue': [value: string];
114
+ /** Emitted when the editing area gains focus. */
115
+ focus: [];
116
+ /** Emitted when focus leaves the editor entirely, header included. */
117
+ blur: [];
118
+ /** Emitted after the copy button runs, whether or not the write succeeded. */
119
+ copy: [payload: { success: boolean }];
120
+ }
121
+
122
+ /** Methods exposed by {@link CkCodeEditor} through a template ref. */
123
+ export interface CkCodeEditorExposed {
124
+ /** Focus the editing area. No-op until the editor has been created. */
125
+ focus: () => void;
126
+ /** Read the current document synchronously. */
127
+ getCode: () => string;
128
+ }
@@ -142,6 +142,19 @@ describe('CkMilkdownEditor', () => {
142
142
  ).toBe('false');
143
143
  });
144
144
 
145
+ it('toggles the line-number gutter with `showLineNumbers`', async () => {
146
+ const { container, rerender } = await renderEditor({
147
+ modelValue: 'Hello',
148
+ showLineNumbers: true,
149
+ });
150
+
151
+ const root = () => container.querySelector('.ck-milkdown');
152
+ expect(root()?.className).toContain('ck-milkdown--line-numbers');
153
+
154
+ await rerender({ modelValue: 'Hello', showLineNumbers: false });
155
+ expect(root()?.className).not.toContain('ck-milkdown--line-numbers');
156
+ });
157
+
145
158
  it('exposes the editable region as a labelled textbox', async () => {
146
159
  const { container } = await renderEditor({
147
160
  modelValue: 'Hello',
@@ -25,6 +25,7 @@ const meta: Meta<typeof CkMilkdownEditor> = {
25
25
  readonly: { control: 'boolean' },
26
26
  disabled: { control: 'boolean' },
27
27
  autofocus: { control: 'boolean' },
28
+ showLineNumbers: { control: 'boolean' },
28
29
  },
29
30
  };
30
31
 
@@ -109,6 +110,21 @@ const markdown = '# Read me\\n\\nThis document **cannot** be edited.';
109
110
  <CkMilkdownEditor :model-value="markdown" readonly aria-label="Read-only document" />
110
111
  </template>`;
111
112
 
113
+ const withLineNumbersTemplateSource = `<script setup lang="ts">
114
+ import { ref } from 'vue';
115
+ import { CkMilkdownEditor } from '@aleph-alpha/chat-kit';
116
+
117
+ const markdown = ref('# Notes\\n\\nA fenced block with a gutter.');
118
+ </script>
119
+
120
+ <template>
121
+ <CkMilkdownEditor
122
+ v-model="markdown"
123
+ show-line-numbers
124
+ aria-label="Editor with line numbers"
125
+ />
126
+ </template>`;
127
+
112
128
  const disabledTemplateSource = `<script setup lang="ts">
113
129
  import { CkMilkdownEditor } from '@aleph-alpha/chat-kit';
114
130
 
@@ -210,6 +226,24 @@ export const Readonly: Story = {
210
226
  parameters: { docs: { source: { code: readonlyTemplateSource } } },
211
227
  };
212
228
 
229
+ /**
230
+ * `showLineNumbers` reveals the line-number gutter on fenced code blocks. It
231
+ * matches the prop of the same name on `UiCodeBlock`, so the same flag can keep
232
+ * the editor and the rendered message consistent.
233
+ */
234
+ export const WithLineNumbers: Story = {
235
+ render: (args) => ({
236
+ components: { CkMilkdownEditor },
237
+ setup() {
238
+ const markdown = ref(args.modelValue ?? '');
239
+ return { args, markdown };
240
+ },
241
+ template: `<CkMilkdownEditor v-bind="args" v-model="markdown" aria-label="Editor with line numbers" />`,
242
+ }),
243
+ args: { modelValue: richContent, showLineNumbers: true },
244
+ parameters: { docs: { source: { code: withLineNumbersTemplateSource } } },
245
+ };
246
+
213
247
  /**
214
248
  * `disabled` also mutes the content and blocks pointer interaction, and sets
215
249
  * `aria-disabled` on the root.
@@ -22,6 +22,7 @@ const props = withDefaults(defineProps<CkMilkdownEditorProps>(), {
22
22
  ariaLabel: undefined,
23
23
  classes: () => ({}),
24
24
  autofocus: false,
25
+ showLineNumbers: false,
25
26
  });
26
27
 
27
28
  const emit = defineEmits<CkMilkdownEditorEmits>();
@@ -132,9 +133,10 @@ defineExpose({ focus, getMarkdown });
132
133
  <div
133
134
  ref="rootRef"
134
135
  :class="[
135
- 'ck-milkdown min-w-0 break-words',
136
+ 'ck-milkdown ck-code-surface min-w-0 break-words',
136
137
  isReady && 'ck-milkdown--ready',
137
138
  disabled && 'ck-milkdown--disabled',
139
+ showLineNumbers && 'ck-milkdown--line-numbers',
138
140
  ]"
139
141
  :aria-disabled="disabled || undefined"
140
142
  @focusin="onFocusIn"
@@ -6,7 +6,7 @@ import {
6
6
  type ChatKitLabels,
7
7
  } from '../../../handlers/useChatKitLabels';
8
8
  import type { CkMarkdownElementClasses } from '../CkMarkdownRenderer';
9
- import { ckCodeMirrorTheme } from './codeMirrorTheme';
9
+ import { ckCodeMirrorTheme } from '../../../helpers/codemirror/theme';
10
10
  import { crepeIcons } from './crepeIcons';
11
11
  import { applyMarkdownClasses } from './markdownClassAttrs';
12
12
 
@@ -24,6 +24,7 @@ import '@milkdown/crepe/theme/common/list-item.css';
24
24
  import '@milkdown/crepe/theme/common/link-tooltip.css';
25
25
  import '@milkdown/crepe/theme/common/toolbar.css';
26
26
  import '@milkdown/crepe/theme/common/code-mirror.css';
27
+ import '../../../helpers/codemirror/code-palette.css';
27
28
  import './milkdown-theme.css';
28
29
 
29
30
  export interface CreateCrepeEditorOptions {