@coze-editor/preset-code 0.1.0-alpha.0fd19e

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.
@@ -0,0 +1,1194 @@
1
+ // src/index.ts
2
+ import universal from "@coze-editor/preset-universal";
3
+ import {
4
+ scrollBeyondLastLine,
5
+ colorizationBrackets,
6
+ matchingBrackets
7
+ } from "@coze-editor/extensions";
8
+ import { scrollbar } from "@coze-editor/extension-scrollbar";
9
+ import { icons } from "@coze-editor/extension-completion-icons";
10
+ import { maxHeight, minHeight, height } from "@coze-editor/core-plugins";
11
+ import {
12
+ api,
13
+ extension,
14
+ option
15
+ } from "@coze-editor/core";
16
+ import {
17
+ uriFacet,
18
+ languageIdFacet,
19
+ transformerFacet,
20
+ textDocumentField as textDocumentField2
21
+ } from "@coze-editor/code-language-shared";
22
+ import { EditorView as EditorView4, lineNumbers } from "@codemirror/view";
23
+ import { Prec } from "@codemirror/state";
24
+ import { foldGutter } from "@codemirror/language";
25
+
26
+ // src/themes.ts
27
+ var Themes = class {
28
+ _store = /* @__PURE__ */ Object.create(null);
29
+ register(name, theme) {
30
+ this._store[name] = theme;
31
+ }
32
+ get(name) {
33
+ return this._store[name];
34
+ }
35
+ };
36
+ var symbol = Symbol.for("codemirror.themes");
37
+ if (!globalThis[symbol]) {
38
+ globalThis[symbol] = new Themes();
39
+ }
40
+ var themes = globalThis[symbol];
41
+
42
+ // src/theme-vscode.ts
43
+ import {
44
+ darkSyntaxTheme,
45
+ darkTheme,
46
+ lightSyntaxTheme,
47
+ lightTheme
48
+ } from "@coze-editor/vscode";
49
+ import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";
50
+ var vscodeLight = [
51
+ syntaxHighlighting(HighlightStyle.define(lightSyntaxTheme)),
52
+ lightTheme()
53
+ ];
54
+ var vscodeDark = [
55
+ syntaxHighlighting(HighlightStyle.define(darkSyntaxTheme)),
56
+ darkTheme()
57
+ ];
58
+
59
+ // src/language-registry.ts
60
+ import {
61
+ MarkupContent as MarkupContent2
62
+ } from "vscode-languageserver-types";
63
+ import shiki from "codemirror-shiki";
64
+ import { linter } from "@coze-editor/extension-lint";
65
+ import { links } from "@coze-editor/extension-links";
66
+ import {
67
+ MarkerTag,
68
+ textDocumentField
69
+ } from "@coze-editor/code-language-shared";
70
+ import {
71
+ EditorView as EditorView2,
72
+ hoverTooltip,
73
+ ViewPlugin as ViewPlugin3
74
+ } from "@codemirror/view";
75
+ import {
76
+ EditorSelection,
77
+ StateField as StateField2
78
+ } from "@codemirror/state";
79
+ import { LanguageSupport } from "@codemirror/language";
80
+ import {
81
+ autocompletion,
82
+ insertCompletionText,
83
+ snippet
84
+ } from "@codemirror/autocomplete";
85
+
86
+ // src/signature-help.ts
87
+ import {
88
+ MarkupContent
89
+ } from "vscode-languageserver-types";
90
+ import {
91
+ EditorView,
92
+ ViewPlugin,
93
+ keymap,
94
+ showTooltip
95
+ } from "@codemirror/view";
96
+ import {
97
+ Facet,
98
+ StateEffect,
99
+ StateField
100
+ } from "@codemirror/state";
101
+
102
+ // src/markdown.ts
103
+ import markedShiki from "marked-shiki";
104
+ import { Marked } from "marked";
105
+
106
+ // src/highlighter.ts
107
+ import { createHighlighter } from "shiki";
108
+ var highlighterPromise = createHighlighter({
109
+ langs: ["md", "js", "ts", "python"],
110
+ themes: ["github-dark", "one-dark-pro"]
111
+ });
112
+
113
+ // src/const.ts
114
+ var LINT_REFRESH_USER_EVENT = "sdk.lint.refresh";
115
+ var DEFAULT_SYNTAX_THEME = "one-dark-pro";
116
+
117
+ // src/markdown.ts
118
+ var marked = new Marked().use(
119
+ markedShiki({
120
+ async highlight(code, lang, props) {
121
+ const highlighter = await highlighterPromise;
122
+ return (await highlighter).codeToHtml(code, {
123
+ lang,
124
+ theme: DEFAULT_SYNTAX_THEME,
125
+ transformers: [
126
+ {
127
+ pre(node) {
128
+ delete node.properties.style;
129
+ node.properties.style = "white-space: pre-wrap;";
130
+ }
131
+ }
132
+ ]
133
+ });
134
+ }
135
+ })
136
+ ).use({
137
+ renderer: {
138
+ link(link) {
139
+ return `<a title="${link.title ?? ""}" target="_blank" href="${link.href}">${link.text}</a>`;
140
+ }
141
+ }
142
+ });
143
+ async function renderMarkdown(content) {
144
+ return await marked.parse(content);
145
+ }
146
+
147
+ // src/signature-help.ts
148
+ var setSignatureHelpRequestPosition = StateEffect.define({});
149
+ var setSignatureHelpResult = StateEffect.define({});
150
+ var SignatureHelpState = class {
151
+ pos;
152
+ // maybe stale
153
+ result;
154
+ constructor(pos, result) {
155
+ if (result && pos === -1) {
156
+ throw new Error("Invalid state");
157
+ }
158
+ this.pos = pos;
159
+ this.result = result;
160
+ }
161
+ };
162
+ var signatureHelpTooltipField = StateField.define({
163
+ create: () => new SignatureHelpState(-1, null),
164
+ update(state, tr) {
165
+ let { pos, result } = state;
166
+ for (const effect of tr.effects) {
167
+ if (effect.is(setSignatureHelpRequestPosition)) {
168
+ pos = effect.value;
169
+ } else if (effect.is(setSignatureHelpResult)) {
170
+ result = effect.value;
171
+ if (!result) {
172
+ pos = -1;
173
+ }
174
+ }
175
+ }
176
+ if (pos === -1) {
177
+ result = null;
178
+ }
179
+ pos = pos === -1 ? -1 : tr.changes.mapPos(pos);
180
+ if (state.pos === pos && state.result === result) {
181
+ return state;
182
+ }
183
+ return new SignatureHelpState(pos, result);
184
+ },
185
+ provide: (f) => showTooltip.compute([f], (state) => {
186
+ const val = state.field(signatureHelpTooltipField);
187
+ const { result, pos } = val;
188
+ if (result) {
189
+ return {
190
+ pos,
191
+ above: true,
192
+ create: () => {
193
+ const dom = document.createElement("div");
194
+ dom.className = "cm-signature-tooltip";
195
+ dom.style.cssText = "font-size: 12px;max-width: 320px;";
196
+ const div = document.createElement("div");
197
+ div.innerHTML = result;
198
+ dom.appendChild(div);
199
+ return { dom };
200
+ }
201
+ };
202
+ }
203
+ return null;
204
+ })
205
+ });
206
+ async function renderSignatureHelp(state, help) {
207
+ const {
208
+ signatures,
209
+ activeSignature: activeSignatureIndex,
210
+ activeParameter: activeParameterIndex
211
+ } = help;
212
+ if (typeof activeSignatureIndex !== "number" || typeof activeParameterIndex !== "number") {
213
+ return;
214
+ }
215
+ const activeSignature = signatures[activeSignatureIndex];
216
+ if (!activeSignature || !Array.isArray(activeSignature.parameters)) {
217
+ return;
218
+ }
219
+ const { label } = activeSignature;
220
+ const keyword = getParameterLabel(
221
+ activeSignature.label,
222
+ activeSignature.parameters[activeParameterIndex]
223
+ );
224
+ const documentation = MarkupContent.is(activeSignature.documentation) ? activeSignature.documentation.value : activeSignature.documentation ?? "";
225
+ const rendered = await renderMarkdown(highlightByKeyword(label, keyword)) + await renderMarkdown(documentation.trim().split("\n")[0]);
226
+ return rendered;
227
+ }
228
+ function getParameterLabel(fullText, parameter) {
229
+ let keyword = (parameter == null ? void 0 : parameter.label) ?? "";
230
+ if (Array.isArray(keyword)) {
231
+ const [from, to] = keyword;
232
+ keyword = fullText.slice(from, to);
233
+ }
234
+ return keyword;
235
+ }
236
+ function highlightByKeyword(content, keyword) {
237
+ if (!keyword) {
238
+ return content;
239
+ }
240
+ return content.split(keyword).join(`<span class="cm-signature-parameter-active">${keyword}</span>`);
241
+ }
242
+ var closeSignatureHelp = (view2) => {
243
+ if (view2.state.field(signatureHelpTooltipField).pos !== -1) {
244
+ view2.dispatch({
245
+ effects: setSignatureHelpRequestPosition.of(-1)
246
+ });
247
+ return true;
248
+ }
249
+ return false;
250
+ };
251
+ var signatureHelpKeymap = [
252
+ { key: "Escape", run: closeSignatureHelp }
253
+ ];
254
+ var SignatureHelpView = class {
255
+ constructor(view2) {
256
+ this.view = view2;
257
+ }
258
+ update(update) {
259
+ if ((update.docChanged || update.selectionSet) && this.view.state.field(signatureHelpTooltipField).pos !== -1) {
260
+ triggerSignatureHelpRequest(this.view, update.state);
261
+ } else if (update.docChanged) {
262
+ const last = update.transactions[update.transactions.length - 1];
263
+ if (last.isUserEvent("input")) {
264
+ update.changes.iterChanges((_fromA, _toA, _fromB, _toB, inserted) => {
265
+ if (inserted.sliceString(0).trim().endsWith("()") || inserted.toString() === ",") {
266
+ triggerSignatureHelpRequest(this.view, update.state);
267
+ }
268
+ });
269
+ }
270
+ }
271
+ }
272
+ };
273
+ var doSignatureHelpFacet = Facet.define({
274
+ combine(values) {
275
+ return values[values.length - 1];
276
+ }
277
+ });
278
+ var triggerSignatureHelpRequest = async (view2, state) => {
279
+ const doSignatureHelp = state.facet(doSignatureHelpFacet);
280
+ const pos = state.selection.main.from;
281
+ try {
282
+ queueMicrotask(() => {
283
+ view2.dispatch({
284
+ effects: [setSignatureHelpRequestPosition.of(pos)]
285
+ });
286
+ });
287
+ const info = await doSignatureHelp(state, pos);
288
+ if (!info || !info.signatures || info.signatures.length === 0) {
289
+ queueMicrotask(() => {
290
+ view2.dispatch({
291
+ effects: [setSignatureHelpResult.of(null)]
292
+ });
293
+ });
294
+ return;
295
+ }
296
+ const result = await renderSignatureHelp(state, info) ?? "";
297
+ queueMicrotask(() => {
298
+ view2.dispatch({
299
+ effects: [setSignatureHelpResult.of(result)]
300
+ });
301
+ });
302
+ } catch (e) {
303
+ queueMicrotask(() => {
304
+ view2.dispatch({
305
+ effects: [setSignatureHelpResult.of(null)]
306
+ });
307
+ });
308
+ }
309
+ };
310
+ var signatureHelpToolTipBaseTheme = EditorView.baseTheme({
311
+ ".cm-tooltip.cm-signature-tooltip": {
312
+ padding: "3px 9px",
313
+ width: "max-content",
314
+ maxWidth: "500px"
315
+ },
316
+ ".cm-tooltip .cm-signature-parameter-active": {
317
+ fontWeight: "bold"
318
+ }
319
+ });
320
+ function signatureHelp(doSignatureHelp) {
321
+ return [
322
+ doSignatureHelpFacet.of(doSignatureHelp),
323
+ ViewPlugin.fromClass(SignatureHelpView),
324
+ signatureHelpTooltipField,
325
+ signatureHelpToolTipBaseTheme,
326
+ keymap.of(signatureHelpKeymap),
327
+ EditorView.domEventHandlers({
328
+ blur(event, view2) {
329
+ if (!(event.relatedTarget instanceof Element) || !event.relatedTarget.closest(".cm-signature-tooltip")) {
330
+ queueMicrotask(() => {
331
+ view2.dispatch({
332
+ effects: setSignatureHelpRequestPosition.of(-1)
333
+ });
334
+ });
335
+ }
336
+ }
337
+ })
338
+ ];
339
+ }
340
+
341
+ // src/goto-definition.ts
342
+ import { FacetCombineStrategy } from "@coze-editor/utils";
343
+ import { ViewPlugin as ViewPlugin2 } from "@codemirror/view";
344
+ import { Facet as Facet2 } from "@codemirror/state";
345
+ var handlerFacet = Facet2.define({
346
+ combine: FacetCombineStrategy.Last
347
+ });
348
+ var view = ViewPlugin2.fromClass(
349
+ class {
350
+ dispose;
351
+ constructor(view2) {
352
+ function trigger(e) {
353
+ const target = e.target;
354
+ if (!e.metaKey || !target.closest(".cm-content")) {
355
+ return;
356
+ }
357
+ const pos = view2.posAtCoords({
358
+ x: e.clientX,
359
+ y: e.clientY
360
+ });
361
+ if (typeof pos !== "number") {
362
+ return;
363
+ }
364
+ const handler = view2.state.facet(handlerFacet);
365
+ handler({
366
+ view: view2,
367
+ pos
368
+ });
369
+ }
370
+ document.addEventListener("click", trigger, false);
371
+ this.dispose = () => {
372
+ document.removeEventListener("click", trigger, false);
373
+ };
374
+ }
375
+ destroy() {
376
+ if (typeof this.dispose === "function") {
377
+ this.dispose();
378
+ }
379
+ }
380
+ }
381
+ );
382
+ function gotoDefinition(handler) {
383
+ return [handlerFacet.of(handler), view];
384
+ }
385
+
386
+ // src/language-registry.ts
387
+ function formatContents(contents) {
388
+ if (MarkupContent2.is(contents)) {
389
+ const { value } = contents;
390
+ if (contents.kind === "markdown") {
391
+ }
392
+ return value;
393
+ } else if (Array.isArray(contents)) {
394
+ return contents.map((c) => `${formatContents(c)}
395
+
396
+ `).join("");
397
+ } else if (typeof contents === "string") {
398
+ return contents;
399
+ }
400
+ return "";
401
+ }
402
+ var LanguagesRegistry = class {
403
+ languages = {};
404
+ register(id, options) {
405
+ if (!this.languages[id]) {
406
+ this.languages[id] = options;
407
+ }
408
+ return () => {
409
+ delete this.languages[id];
410
+ };
411
+ }
412
+ get(languageId) {
413
+ return this.languages[languageId];
414
+ }
415
+ getExtension(id) {
416
+ var _a;
417
+ if (!this.languages[id]) {
418
+ return [];
419
+ }
420
+ const { languageService, language, extensions } = this.languages[id];
421
+ const langaugeExtensions = [];
422
+ langaugeExtensions.push(new LanguageSupport(language));
423
+ if (id === "typescript" || id === "python") {
424
+ langaugeExtensions.push(
425
+ shiki({
426
+ highlighter: highlighterPromise,
427
+ language: id,
428
+ theme: DEFAULT_SYNTAX_THEME
429
+ })
430
+ );
431
+ }
432
+ langaugeExtensions.push(
433
+ StateField2.define({
434
+ create(state) {
435
+ if (languageService == null ? void 0 : languageService.onTextDocumentDidChange) {
436
+ const { textDocument } = state.field(textDocumentField);
437
+ languageService.onTextDocumentDidChange({
438
+ textDocument
439
+ });
440
+ }
441
+ },
442
+ update(_value, tr) {
443
+ if (tr.docChanged) {
444
+ if (languageService == null ? void 0 : languageService.onTextDocumentDidChange) {
445
+ const { textDocument } = tr.state.field(textDocumentField);
446
+ languageService.onTextDocumentDidChange({
447
+ textDocument
448
+ });
449
+ }
450
+ }
451
+ }
452
+ })
453
+ );
454
+ if (languageService && languageService.doValidation) {
455
+ langaugeExtensions.push(
456
+ ViewPlugin3.fromClass(
457
+ class {
458
+ toDispose;
459
+ constructor(view2) {
460
+ var _a2;
461
+ function onRefreshDiagnostics() {
462
+ view2.dispatch({
463
+ userEvent: LINT_REFRESH_USER_EVENT
464
+ });
465
+ }
466
+ (_a2 = languageService.events) == null ? void 0 : _a2.on(
467
+ "refresh-diagnostics",
468
+ onRefreshDiagnostics
469
+ );
470
+ this.toDispose = () => {
471
+ var _a3;
472
+ (_a3 = languageService.events) == null ? void 0 : _a3.off(
473
+ "refresh-diagnostics",
474
+ onRefreshDiagnostics
475
+ );
476
+ };
477
+ }
478
+ destroy() {
479
+ if (typeof this.toDispose === "function") {
480
+ this.toDispose();
481
+ }
482
+ }
483
+ }
484
+ ),
485
+ EditorView2.theme({
486
+ ".cm-tooltip-lint": {
487
+ maxWidth: "360px"
488
+ },
489
+ ".cm-lint-tag-unnecessary": {
490
+ opacity: "0.5"
491
+ },
492
+ ".cm-lint-tag-deprecated": {
493
+ textDecoration: "line-through"
494
+ },
495
+ ".cm-lintRange-hint.cm-lint-tag-deprecated": {
496
+ backgroundImage: "unset"
497
+ },
498
+ ".cm-lintRange-hint.cm-lint-tag-unnecessary": {
499
+ backgroundImage: "unset"
500
+ }
501
+ })
502
+ );
503
+ langaugeExtensions.push(
504
+ linter(
505
+ async (view2) => {
506
+ var _a2;
507
+ const { textDocument, originalRangeFor } = view2.state.field(textDocumentField);
508
+ const diagnostics = await languageService.doValidation({
509
+ textDocument
510
+ });
511
+ const finalDiagnostics = diagnostics.map((diagnostic) => {
512
+ var _a3, _b;
513
+ const range = originalRangeFor({
514
+ from: diagnostic.from,
515
+ to: diagnostic.to
516
+ });
517
+ if (range) {
518
+ let markClass = "";
519
+ if ((_a3 = diagnostic.tags) == null ? void 0 : _a3.includes(MarkerTag.Unnecessary)) {
520
+ markClass += "cm-lint-tag-unnecessary";
521
+ }
522
+ if ((_b = diagnostic.tags) == null ? void 0 : _b.includes(MarkerTag.Deprecated)) {
523
+ markClass += "cm-lint-tag-deprecated";
524
+ }
525
+ return {
526
+ ...diagnostic,
527
+ markClass,
528
+ ...range
529
+ };
530
+ }
531
+ }).filter((v) => isDiagnostic(v));
532
+ (_a2 = languageService.events) == null ? void 0 : _a2.emit("diagnostics", {
533
+ uri: textDocument.uri,
534
+ diagnostics: finalDiagnostics.map((d) => ({
535
+ from: d.from,
536
+ to: d.to,
537
+ message: d.message,
538
+ severity: d.severity
539
+ }))
540
+ });
541
+ return finalDiagnostics;
542
+ },
543
+ {
544
+ delay: ((_a = languageService.options) == null ? void 0 : _a.lintDelay) ?? 100,
545
+ needsRefresh(update) {
546
+ return update.transactions.some(
547
+ (tr) => tr.isUserEvent(LINT_REFRESH_USER_EVENT)
548
+ );
549
+ }
550
+ }
551
+ )
552
+ );
553
+ }
554
+ if (languageService == null ? void 0 : languageService.doHover) {
555
+ langaugeExtensions.push(
556
+ hoverTooltip(async (view2, pos) => {
557
+ const { textDocument, generatedOffsetFor } = view2.state.field(textDocumentField);
558
+ const offset = generatedOffsetFor(pos);
559
+ if (typeof offset !== "number") {
560
+ return null;
561
+ }
562
+ const result = await languageService.doHover({
563
+ textDocument,
564
+ offset
565
+ });
566
+ if (!result) {
567
+ return null;
568
+ }
569
+ const html = await renderMarkdown(formatContents(result));
570
+ const word = view2.state.wordAt(offset);
571
+ return {
572
+ pos: (word == null ? void 0 : word.from) ?? offset,
573
+ end: (word == null ? void 0 : word.to) ?? offset,
574
+ create() {
575
+ const dom = document.createElement("div");
576
+ dom.classList.add("cm-code-hover");
577
+ dom.innerHTML = html;
578
+ dom.style.cssText = "padding: 5px 10px;max-width: 360px;";
579
+ return {
580
+ dom
581
+ };
582
+ }
583
+ };
584
+ }),
585
+ EditorView2.theme({
586
+ ".cm-code-hover a": {
587
+ color: "#3b98ff"
588
+ },
589
+ ".cm-code-hover pre": {
590
+ margin: "0"
591
+ }
592
+ })
593
+ );
594
+ }
595
+ if (languageService == null ? void 0 : languageService.doSignatureHelp) {
596
+ langaugeExtensions.push(
597
+ signatureHelp(async (state, pos) => {
598
+ const { textDocument, generatedRangeFor } = state.field(textDocumentField);
599
+ const range = generatedRangeFor({ from: pos, to: pos });
600
+ const offset = range == null ? void 0 : range.from;
601
+ if (typeof offset !== "number") {
602
+ return null;
603
+ }
604
+ const result = await languageService.doSignatureHelp({
605
+ textDocument,
606
+ offset
607
+ });
608
+ return result;
609
+ })
610
+ );
611
+ }
612
+ if (languageService == null ? void 0 : languageService.doComplete) {
613
+ langaugeExtensions.push(
614
+ autocompletion({
615
+ override: [
616
+ async function({ state, pos, view: view2 }) {
617
+ const { textDocument, originalRangeFor, generatedRangeFor } = state.field(textDocumentField);
618
+ const range = generatedRangeFor({ from: pos, to: pos });
619
+ const offset = range == null ? void 0 : range.from;
620
+ if (typeof offset !== "number") {
621
+ return null;
622
+ }
623
+ const completionResult = await languageService.doComplete({
624
+ textDocument,
625
+ offset
626
+ });
627
+ if (!completionResult || !Array.isArray(completionResult.items) || completionResult.items.length === 0) {
628
+ return null;
629
+ }
630
+ const completionOptions = [];
631
+ const mapping = /* @__PURE__ */ new WeakMap();
632
+ const resolveCompletion = createResolveCompletion(
633
+ view2,
634
+ languageService,
635
+ mapping
636
+ );
637
+ for (const item of completionResult.items) {
638
+ const { kind, label, textEdit, textEditText } = item;
639
+ const completion = {
640
+ label,
641
+ type: defaultFromCompletionItemKind(kind),
642
+ detail: item.detail ?? ""
643
+ };
644
+ mapping.set(completion, item);
645
+ if (textEdit) {
646
+ const range2 = "range" in textEdit ? textEdit.range : textEdit.replace;
647
+ const from = textDocument.offsetAt(range2.start);
648
+ const to = textDocument.offsetAt(range2.end);
649
+ const oRange = originalRangeFor({
650
+ from,
651
+ to
652
+ });
653
+ if (!oRange) {
654
+ continue;
655
+ }
656
+ const insert = textEdit.newText;
657
+ const { insertTextFormat } = item;
658
+ completion.apply = (view3) => {
659
+ if (insertTextFormat === 2) {
660
+ snippet(
661
+ addAnchor(
662
+ insert.replace(/\$(\d+)/g, "$${$1}").replace(/\\\$/g, "$")
663
+ )
664
+ )(view3, completion, oRange.from, oRange.to);
665
+ } else {
666
+ view3.dispatch(
667
+ insertCompletionText(
668
+ view3.state,
669
+ insert,
670
+ oRange.from,
671
+ oRange.to
672
+ )
673
+ );
674
+ }
675
+ };
676
+ } else if (textEditText) {
677
+ completion.apply = textEditText;
678
+ }
679
+ completion.info = resolveCompletion;
680
+ completionOptions.push(completion);
681
+ }
682
+ return {
683
+ from: pos,
684
+ options: completionOptions,
685
+ filter: false
686
+ };
687
+ }
688
+ ]
689
+ })
690
+ );
691
+ }
692
+ if (languageService == null ? void 0 : languageService.findDefinition) {
693
+ langaugeExtensions.push(
694
+ gotoDefinition(async ({ pos, view: view2 }) => {
695
+ const { textDocument, originalRangeFor, generatedRangeFor } = view2.state.field(textDocumentField);
696
+ const range = generatedRangeFor({ from: pos, to: pos });
697
+ const offset = range == null ? void 0 : range.from;
698
+ if (typeof offset !== "number") {
699
+ return null;
700
+ }
701
+ const definitions = await languageService.findDefinition({
702
+ textDocument,
703
+ offset
704
+ });
705
+ if (!Array.isArray(definitions) || definitions.length === 0) {
706
+ return;
707
+ }
708
+ const definition = definitions[0];
709
+ const oRange = originalRangeFor({
710
+ from: definition.from,
711
+ to: definition.to
712
+ });
713
+ if (!oRange) {
714
+ return;
715
+ }
716
+ view2.dispatch({
717
+ effects: EditorView2.scrollIntoView(oRange.from, {
718
+ y: "center"
719
+ }),
720
+ selection: EditorSelection.range(oRange.from, oRange.to)
721
+ });
722
+ })
723
+ );
724
+ }
725
+ if (languageService == null ? void 0 : languageService.findLinks) {
726
+ langaugeExtensions.push(
727
+ links(async (view2) => {
728
+ const { textDocument, originalRangeFor } = view2.state.field(textDocumentField);
729
+ const links2 = await languageService.findLinks({
730
+ textDocument
731
+ });
732
+ return links2.map((link) => {
733
+ const range = originalRangeFor(link.range);
734
+ if (!range) {
735
+ return;
736
+ }
737
+ return {
738
+ range,
739
+ target: link.target
740
+ };
741
+ }).filter((v) => isLink(v));
742
+ })
743
+ );
744
+ }
745
+ if (extensions) {
746
+ langaugeExtensions.push(extensions);
747
+ }
748
+ return langaugeExtensions;
749
+ }
750
+ };
751
+ function createResolveCompletion(view2, languageService, mapping) {
752
+ const dom = document.createElement("div");
753
+ let controller = new AbortController();
754
+ function hideDOM(controller2) {
755
+ if (!controller2.signal.aborted) {
756
+ dom.style.display = "none";
757
+ }
758
+ }
759
+ function showDOM(html, controller2) {
760
+ if (!controller2.signal.aborted) {
761
+ dom.innerHTML = html;
762
+ dom.style.display = "block";
763
+ }
764
+ }
765
+ return (completion) => {
766
+ controller.abort();
767
+ controller = new AbortController();
768
+ const closureController = controller;
769
+ (async () => {
770
+ const completionItem = mapping.get(completion);
771
+ if (!view2 || !completionItem || typeof languageService.resolveCompletionItem !== "function") {
772
+ hideDOM(closureController);
773
+ return;
774
+ }
775
+ const { textDocument, originalRangeFor } = view2.state.field(textDocumentField);
776
+ const oRange = originalRangeFor({
777
+ from: view2.state.selection.main.from,
778
+ to: view2.state.selection.main.from
779
+ });
780
+ if (!oRange) {
781
+ hideDOM(closureController);
782
+ return;
783
+ }
784
+ const details = await languageService.resolveCompletionItem(
785
+ {
786
+ textDocument,
787
+ offset: oRange.from
788
+ },
789
+ completionItem
790
+ );
791
+ if (!details.detail && !details.documentation) {
792
+ hideDOM(closureController);
793
+ return;
794
+ }
795
+ const documentationString = MarkupContent2.is(details.documentation) ? await renderMarkdown(details.documentation.value) : details.documentation ?? "";
796
+ const html = [
797
+ `<div style="opacity: 0.8;white-space: pre-wrap;">${details.detail ?? ""}</div>`,
798
+ details.documentation ? "<br />" : "",
799
+ `<div>${documentationString}</div>`
800
+ ].join("");
801
+ if (!closureController.signal.aborted) {
802
+ showDOM(html, closureController);
803
+ }
804
+ })();
805
+ return dom;
806
+ };
807
+ }
808
+ function isDiagnostic(v) {
809
+ return Boolean(v);
810
+ }
811
+ function isLink(v) {
812
+ return Boolean(v);
813
+ }
814
+ function addAnchor(str) {
815
+ if (!str.includes("${")) {
816
+ return `${str}\${0}`;
817
+ }
818
+ return str;
819
+ }
820
+ function defaultFromCompletionItemKind(kind) {
821
+ switch (kind) {
822
+ case 1:
823
+ return "text";
824
+ case 15:
825
+ return "snippet";
826
+ case 2:
827
+ return "method";
828
+ case 3:
829
+ return "function";
830
+ case 4:
831
+ return "constructor";
832
+ case 7:
833
+ return "class";
834
+ case 5:
835
+ return "field";
836
+ case 10:
837
+ return "property";
838
+ case 6:
839
+ return "variable";
840
+ case 18:
841
+ return "reference";
842
+ case 23:
843
+ return "event";
844
+ case 8:
845
+ return "interface";
846
+ case 22:
847
+ return "struct";
848
+ case 25:
849
+ return "typeParameter";
850
+ case 9:
851
+ return "module";
852
+ case 12:
853
+ return "value";
854
+ case 13:
855
+ case 20:
856
+ return "enum";
857
+ case 11:
858
+ return "unit";
859
+ case 14:
860
+ return "keyword";
861
+ case 24:
862
+ return "operator";
863
+ case 16:
864
+ return "color";
865
+ case 21:
866
+ return "constant";
867
+ default:
868
+ return "value";
869
+ }
870
+ }
871
+ var languages = new LanguagesRegistry();
872
+
873
+ // src/extension/tab-size/index.ts
874
+ import { EditorState } from "@codemirror/state";
875
+ import { indentUnit } from "@codemirror/language";
876
+ var tabSize = (size = 2) => [
877
+ EditorState.tabSize.of(size),
878
+ indentUnit.of(" ".repeat(size))
879
+ ];
880
+
881
+ // src/extension/basic-setup.ts
882
+ import {
883
+ crosshairCursor,
884
+ drawSelection,
885
+ dropCursor,
886
+ highlightActiveLine,
887
+ highlightActiveLineGutter,
888
+ highlightSpecialChars,
889
+ keymap as keymap2,
890
+ rectangularSelection
891
+ } from "@codemirror/view";
892
+ import { EditorState as EditorState2 } from "@codemirror/state";
893
+ import {
894
+ defaultHighlightStyle,
895
+ foldKeymap,
896
+ indentOnInput,
897
+ syntaxHighlighting as syntaxHighlighting2
898
+ } from "@codemirror/language";
899
+ import {
900
+ defaultKeymap,
901
+ history,
902
+ historyKeymap,
903
+ indentWithTab
904
+ } from "@codemirror/commands";
905
+ import {
906
+ acceptCompletion,
907
+ autocompletion as autocompletion2,
908
+ closeBrackets,
909
+ closeBracketsKeymap,
910
+ completionKeymap
911
+ } from "@codemirror/autocomplete";
912
+ var basicSetup = (() => [
913
+ highlightActiveLineGutter(),
914
+ highlightSpecialChars(),
915
+ history(),
916
+ drawSelection(),
917
+ dropCursor(),
918
+ EditorState2.allowMultipleSelections.of(true),
919
+ indentOnInput(),
920
+ syntaxHighlighting2(defaultHighlightStyle, { fallback: true }),
921
+ closeBrackets(),
922
+ autocompletion2(),
923
+ rectangularSelection(),
924
+ crosshairCursor(),
925
+ highlightActiveLine(),
926
+ keymap2.of([
927
+ ...defaultKeymap,
928
+ ...closeBracketsKeymap,
929
+ ...historyKeymap,
930
+ ...foldKeymap,
931
+ ...completionKeymap,
932
+ indentWithTab,
933
+ { key: "Tab", run: acceptCompletion }
934
+ ])
935
+ ])();
936
+
937
+ // src/create-theme.ts
938
+ import { EditorView as EditorView3 } from "@codemirror/view";
939
+ import {
940
+ HighlightStyle as HighlightStyle2,
941
+ syntaxHighlighting as syntaxHighlighting3
942
+ } from "@codemirror/language";
943
+ var createTheme = ({ variant, settings, styles }) => {
944
+ const bracketTheme = (settings.bracketColors ?? []).reduce(
945
+ (memo, color, index) => ({
946
+ ...memo,
947
+ [`.colorization-bracket-${index}`]: { color },
948
+ [`.colorization-bracket-${index} > span`]: { color }
949
+ }),
950
+ {}
951
+ );
952
+ const tooltipTheme = {
953
+ ".cm-tooltip": settings.tooltip ?? {},
954
+ ".cm-tooltip-autocomplete": settings.tooltipCompletion ?? {},
955
+ ".cm-tooltip a": settings.link ?? {
956
+ color: "#4daafc"
957
+ }
958
+ };
959
+ const completionTheme = {
960
+ ".cm-tooltip-autocomplete ul li[aria-selected]": settings.completionItemSelected ?? {},
961
+ ".cm-tooltip-autocomplete ul li:not([aria-selected]):hover": settings.completionItemHover ?? {},
962
+ ".cm-completionIcon": settings.completionItemIcon ?? {},
963
+ ".cm-completionLabel": settings.completionItemLabel ?? {},
964
+ ".cm-completionDetail": settings.completionItemDetail ?? {},
965
+ ".cm-completionInfo": settings.completionItemInfo ?? {}
966
+ };
967
+ const theme = EditorView3.theme(
968
+ {
969
+ "&": {
970
+ backgroundColor: settings.background,
971
+ color: settings.foreground
972
+ },
973
+ ".cm-content": {
974
+ caretColor: settings.caret
975
+ },
976
+ ".cm-cursor, .cm-dropCursor": {
977
+ borderLeftColor: settings.caret
978
+ },
979
+ "&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": {
980
+ backgroundColor: settings.selection
981
+ },
982
+ ".cm-activeLine": {
983
+ backgroundColor: settings.lineHighlight
984
+ },
985
+ ".cm-gutters": {
986
+ backgroundColor: settings.gutterBackground,
987
+ color: settings.gutterForeground,
988
+ borderRightColor: settings.gutterBorderColor,
989
+ borderRightWidth: `${settings.gutterBorderWidth}px`
990
+ },
991
+ ".cm-activeLineGutter": {
992
+ backgroundColor: settings.lineHighlight
993
+ },
994
+ ...bracketTheme,
995
+ ...tooltipTheme,
996
+ ...completionTheme
997
+ },
998
+ {
999
+ dark: variant === "dark"
1000
+ }
1001
+ );
1002
+ const highlightStyle = HighlightStyle2.define(styles);
1003
+ const extension2 = [theme, syntaxHighlighting3(highlightStyle)];
1004
+ return extension2;
1005
+ };
1006
+ var create_theme_default = createTheme;
1007
+
1008
+ // src/index.ts
1009
+ import "@coze-editor/extension-scrollbar/dist/index.css";
1010
+ import "@coze-editor/extension-completion-icons/dist/index.css";
1011
+
1012
+ // src/transformer.ts
1013
+ import { Text } from "text-mapping";
1014
+ var transformerCreator = (processor) => (source) => {
1015
+ const text = processor(new Text(source));
1016
+ return {
1017
+ code: text.toString(),
1018
+ mapping: {
1019
+ originalRangeFor: text.originalRangeFor.bind(text),
1020
+ generatedRangeFor: text.generatedRangeFor.bind(text),
1021
+ originalOffsetFor: text.originalOffsetFor.bind(text),
1022
+ generatedOffsetFor: text.generatedOffsetFor.bind(text)
1023
+ }
1024
+ };
1025
+ };
1026
+
1027
+ // src/index.ts
1028
+ import { tags } from "@lezer/highlight";
1029
+ var SVG_FOLD_CLOSE = '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16"><path fill="currentColor" fill-rule="evenodd" d="M10.072 8.024L5.715 3.667l.618-.62L11 7.716v.618L6.333 13l-.618-.619z" clip-rule="evenodd"/></svg>';
1030
+ var SVG_FOLD_OPEN = '<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 16 16"><path fill="currentColor" fill-rule="evenodd" d="m7.976 10.072l4.357-4.357l.62.618L8.284 11h-.618L3 6.333l.619-.618z" clip-rule="evenodd"/></svg>';
1031
+ var preset = [
1032
+ ...universal,
1033
+ extension([
1034
+ basicSetup,
1035
+ matchingBrackets,
1036
+ // indentGuides(),
1037
+ icons,
1038
+ textDocumentField2,
1039
+ Prec.low(
1040
+ EditorView4.theme({
1041
+ ".cm-foldGutter .cm-gutterElement": {
1042
+ display: "flex",
1043
+ alignItems: "center",
1044
+ cursor: "pointer"
1045
+ }
1046
+ })
1047
+ ),
1048
+ Prec.low(
1049
+ EditorView4.theme({
1050
+ ".cm-link": {
1051
+ textDecoration: "underline"
1052
+ }
1053
+ })
1054
+ ),
1055
+ Prec.low(
1056
+ EditorView4.theme({
1057
+ ".cm-tooltip": {
1058
+ borderRadius: "5px",
1059
+ fontSize: "12px"
1060
+ },
1061
+ ".cm-diagnostic-error": {
1062
+ borderLeft: "none"
1063
+ },
1064
+ ".cm-diagnostic": {
1065
+ padding: "5px 10px"
1066
+ },
1067
+ ".cm-lineNumbers": {
1068
+ userSelect: "none"
1069
+ },
1070
+ ".cm-tooltip.cm-tooltip-autocomplete > ul": {
1071
+ width: "264px",
1072
+ padding: "4px"
1073
+ },
1074
+ ".cm-completionInfo": {
1075
+ minWidth: "200px",
1076
+ margin: "0 2px"
1077
+ },
1078
+ ".cm-completionInfo p:last-child": {
1079
+ display: "inline-block"
1080
+ },
1081
+ ".cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected]": {
1082
+ color: "inherit"
1083
+ },
1084
+ ".cm-tooltip.cm-tooltip-autocomplete > ul > li": {
1085
+ padding: "1px 9px",
1086
+ height: "24px",
1087
+ display: "flex",
1088
+ alignItems: "center",
1089
+ borderRadius: "5px"
1090
+ },
1091
+ ".cm-tooltip.cm-tooltip-autocomplete > ul > li:not(:first-child)": {
1092
+ marginTop: "2px"
1093
+ },
1094
+ ".cm-completionIcon": {
1095
+ fontSize: "11px",
1096
+ opacity: "1",
1097
+ display: "flex"
1098
+ },
1099
+ ".cm-completionLabel": {
1100
+ flex: 1,
1101
+ overflow: "hidden",
1102
+ textOverflow: "ellipsis"
1103
+ },
1104
+ ".cm-completionDetail": {
1105
+ maxWidth: "86px",
1106
+ overflow: "hidden",
1107
+ textOverflow: "ellipsis",
1108
+ textAlign: "right",
1109
+ fontStyle: "initial"
1110
+ },
1111
+ ".cm-tooltip-autocomplete": {
1112
+ borderRadius: "8px"
1113
+ },
1114
+ ".cm-tooltip-hover": {
1115
+ overflowY: "auto",
1116
+ maxHeight: "360px",
1117
+ wordBreak: "break-word"
1118
+ },
1119
+ ".cm-tooltip-section:not(:first-child)": {
1120
+ "border-top": "solid 0.5px #666666ab"
1121
+ }
1122
+ })
1123
+ )
1124
+ ]),
1125
+ option("tabSize", tabSize),
1126
+ option("height", height),
1127
+ option("minHeight", minHeight),
1128
+ option("maxHeight", maxHeight),
1129
+ option(
1130
+ "scrollBeyondLastLine",
1131
+ (use) => use ? scrollBeyondLastLine() : []
1132
+ ),
1133
+ option("uri", (id) => uriFacet.of(id)),
1134
+ option("theme", (themeName) => themes.get(themeName) ?? []),
1135
+ option("languageId", (id) => [
1136
+ languageIdFacet.of(id),
1137
+ languages.getExtension(id)
1138
+ ]),
1139
+ option(
1140
+ "transformer",
1141
+ (transformer) => transformerFacet.of(transformer)
1142
+ ),
1143
+ option("overlayScrollbar", (enable = true) => enable ? [scrollbar()] : []),
1144
+ option(
1145
+ "lineNumbersGutter",
1146
+ (enable = true) => enable ? lineNumbers({
1147
+ domEventHandlers: {
1148
+ // avoid blur
1149
+ mousedown: (view2, line, event) => {
1150
+ event.preventDefault();
1151
+ return false;
1152
+ }
1153
+ }
1154
+ }) : []
1155
+ ),
1156
+ option(
1157
+ "foldGutter",
1158
+ (enable = true) => enable ? foldGutter({
1159
+ markerDOM(open) {
1160
+ const dom = document.createElement("div");
1161
+ dom.innerHTML = open ? SVG_FOLD_OPEN : SVG_FOLD_CLOSE;
1162
+ return dom;
1163
+ },
1164
+ domEventHandlers: {
1165
+ // avoid blur
1166
+ mousedown: (view2, line, event) => {
1167
+ event.preventDefault();
1168
+ return false;
1169
+ }
1170
+ }
1171
+ }) : []
1172
+ ),
1173
+ option(
1174
+ "colorizeBrackets",
1175
+ (enable = true) => enable ? colorizationBrackets : []
1176
+ ),
1177
+ api("validate", ({ view: view2 }) => () => {
1178
+ view2.dispatch({
1179
+ userEvent: LINT_REFRESH_USER_EVENT
1180
+ });
1181
+ })
1182
+ ];
1183
+ themes.register("_light", vscodeLight);
1184
+ themes.register("_dark", vscodeDark);
1185
+ var index_default = preset;
1186
+ export {
1187
+ create_theme_default as createTheme,
1188
+ index_default as default,
1189
+ languages,
1190
+ tags,
1191
+ themes,
1192
+ transformerCreator
1193
+ };
1194
+ //# sourceMappingURL=index.js.map