dioxus_codemirror 0.2.0

A Dioxus web component that wraps the CodeMirror 6 editor.
Documentation
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
// Bridge between Dioxus (Rust/WASM) and CodeMirror 6.
//
// This script is run once per editor via `document::eval` and kept alive for
// the editor's lifetime, acting as a bidirectional message channel:
//
//   Rust -> JS   `await dioxus.recv()`  receives a `Cmd`:
//     { type: "init", mount_id, doc, line_numbers, language, lsp_uri }  (first)
//     { type: "doc_set", doc }
//     { type: "lsp_message_send", json }
//     { type: "destroy" }
//
//   JS -> Rust   `dioxus.send(..)`      sends an `Evt`:
//     { type: "ready" }
//     { type: "doc_changed", doc }
//     { type: "lsp_message_recv", json }
//
// NOTE: `document::eval` runs this code via `new Function(..)`, where dynamic
// `import()` does not work. So CodeMirror is loaded once by an injected
// `<script type="module">` (which has proper module context) that imports the
// vendored modules and stashes them on `window.__dxcm`; this script just waits
// for them. The modules live in a Dioxus folder asset (`cm_base`) and are
// refreshed with `cargo run -p xtask -- vendor`.

// Module script that imports the vendored CodeMirror entry file (relative to
// `base`) and exposes its exports on `window.__dxcm`. Importing the entry pulls
// in its siblings, so the core `state`/`view` modules load exactly once and are
// shared (CodeMirror requires a single instance of each).
function codeMirrorLoaderScript(base) {
  // Import only the single entry. Dioxus bundles each vendored `.js` with
  // esbuild (inlining its imports), so importing several entry files would load
  // several copies of `@codemirror/state` and trip its "multiple instances"
  // check. One entry => one bundle => one shared `state` instance.
  //
  // The entry (generated by `cargo run -p xtask -- vendor`) exposes the core
  // symbols plus a `languages` map holding every bundled language factory keyed
  // by name. Spread the whole namespace so this script needs no per-language
  // edits.
  const indexUrl = JSON.stringify(`${base}/index.js`);
  return `
(async () => {
  try {
    const cm = await import(${indexUrl});
    window.__dxcm = { ...cm };
  } catch (error) {
    window.__dxcmError = String(error);
    console.error("dioxus_codemirror: failed to load vendored CodeMirror", error);
  }
})();
`;
}

// Inject the loader once, then wait until the modules are available.
async function codeMirrorLoad(base) {
  if (!window.__dxcmInjected) {
    window.__dxcmInjected = true;
    const script = document.createElement("script");
    script.type = "module";
    script.textContent = codeMirrorLoaderScript(base);
    document.head.appendChild(script);
  }
  for (let attempt = 0; attempt < 1200; attempt += 1) {
    if (window.__dxcm) {
      return window.__dxcm;
    }
    if (window.__dxcmError) {
      throw new Error(`dioxus_codemirror: ${window.__dxcmError}`);
    }
    await new Promise((resolve) => requestAnimationFrame(resolve));
  }
  throw new Error("dioxus_codemirror: timed out loading CodeMirror");
}

// Resolve the mount element, which may not be in the DOM yet on first render.
async function elementWait(id) {
  for (let attempt = 0; attempt < 1200; attempt += 1) {
    const element = document.getElementById(id);
    if (element) {
      return element;
    }
    await new Promise((resolve) => requestAnimationFrame(resolve));
  }
  throw new Error(`dioxus_codemirror: mount element #${id} not found`);
}

// The themeable CSS variables and their per-scheme source colors, each defined
// exactly once. `name` is the variable suffix, e.g. `syntax-keyword`; `light`
// and `dark` are that variable's source color in each scheme, e.g. `#cf222e` /
// `#ff7b72`. The stylesheet emits these as `--dxcm-light-<name>` /
// `--dxcm-dark-<name>` and then aliases the active `--dxcm-<name>` -- the only
// variables the chrome rules and the syntax `HighlightStyle` read -- to one
// scheme's sources or the other, so the colors are never duplicated.
const THEME_PALETTE = [
  { name: "bg", light: "#ffffff", dark: "#0d1117" },
  { name: "fg", light: "#1f2328", dark: "#e6edf3" },
  { name: "caret", light: "#1f2328", dark: "#e6edf3" },
  { name: "selection", light: "#c7d2e0", dark: "#3a4250" },
  { name: "selection-focused", light: "#9ec2ff", dark: "#3a619c" },
  { name: "selection-match", light: "#3dd3ff55", dark: "#2299d255" },
  { name: "selection-match-main", light: "#3dd3ff99", dark: "#2299d299" },
  { name: "gutter-bg", light: "#f6f8fa", dark: "#0d1117" },
  { name: "gutter-fg", light: "#8c959f", dark: "#6e7681" },
  { name: "highlight-space", light: "#d0d3d6", dark: "#363b42" },
  { name: "active-line", light: "#f0f3f6", dark: "#161b22" },
  { name: "active-line-gutter-bg", light: "#eaeef2", dark: "#161b22" },
  { name: "border", light: "#d0d7de", dark: "#30363d" },
  { name: "tooltip-bg", light: "#ffffff", dark: "#161b22" },
  { name: "tooltip-fg", light: "#1f2328", dark: "#e6edf3" },
  { name: "tooltip-selected-bg", light: "#0969da", dark: "#094771" },
  { name: "tooltip-selected-fg", light: "#ffffff", dark: "#ffffff" },
  { name: "tooltip-info-bg", light: "#f6f8fa", dark: "#0d1117" },
  { name: "syntax-keyword", light: "#cf222e", dark: "#ff7b72" },
  { name: "syntax-string", light: "#0a3069", dark: "#a5d6ff" },
  { name: "syntax-comment", light: "#6e7781", dark: "#8b949e" },
  { name: "syntax-number", light: "#0550ae", dark: "#79c0ff" },
  { name: "syntax-function", light: "#8250df", dark: "#d2a8ff" },
  { name: "syntax-type", light: "#953800", dark: "#ffa657" },
  { name: "syntax-constant", light: "#0550ae", dark: "#79c0ff" },
  { name: "syntax-operator", light: "#0550ae", dark: "#79c0ff" },
  { name: "syntax-property", light: "#116329", dark: "#7ee787" },
  { name: "syntax-heading", light: "#0550ae", dark: "#79c0ff" },
  { name: "syntax-link", light: "#0a3069", dark: "#a5d6ff" },
  { name: "syntax-invalid", light: "#cf222e", dark: "#ffa198" },
];

// `--dxcm-light-<name>: <light>; --dxcm-dark-<name>: <dark>;` for every entry --
// both palettes declared once.
const themePaletteSource = THEME_PALETTE.map(
  ({ name, light, dark }) => `  --dxcm-light-${name}: ${light};\n  --dxcm-dark-${name}: ${dark};`,
).join("\n");

// `--dxcm-<name>: var(--dxcm-<scheme>-<name>);` for every entry -- points the
// active variables at the chosen scheme's sources, with no color duplicated.
function themeActivate(scheme) {
  return THEME_PALETTE.map(({ name }) => `  --dxcm-${name}: var(--dxcm-${scheme}-${name});`).join(
    "\n",
  );
}

// Inject the editor chrome stylesheet once. Colors come from the active
// `--dxcm-<name>` variables, whose scheme follows the mount element's
// `data-theme` attribute (set from the `Theme` prop): `auto` (or absent) tracks
// the OS color scheme (`prefers-color-scheme`), while `light`/`dark` pin a
// palette regardless of the OS. So a single editor reads correctly in both
// modes with no consumer configuration, yet can be pinned per editor. Rules are
// scoped under `.dioxus-codemirror` (the mount div's class) so they win over
// CodeMirror's single-class base theme and never leak to the host page. Syntax
// token colors are applied separately, in JS, via a `HighlightStyle` (see
// `themeHighlightStyle`) because CodeMirror generates those token class names
// dynamically and they cannot be targeted from here.
function themeStylesInject() {
  if (window.__dxcmStyleInjected) {
    return;
  }
  window.__dxcmStyleInjected = true;
  const style = document.createElement("style");
  style.id = "dioxus-codemirror-theme";
  style.textContent = `
/* Both palette sources, plus the default (light) active aliases. */
.dioxus-codemirror {
${themePaletteSource}
${themeActivate("light")}
}

/* \`theme: Auto\` on a dark OS: re-alias the active variables to the dark
   sources. The \`:not\` leaves editors pinned to \`theme: Light\` untouched. */
@media (prefers-color-scheme: dark) {
  .dioxus-codemirror:not([data-theme="light"]) {
${themeActivate("dark")}
  }
}

/* \`theme: Dark\`: dark regardless of the OS. */
.dioxus-codemirror[data-theme="dark"] {
${themeActivate("dark")}
}

.dioxus-codemirror .cm-editor {
  background: var(--dxcm-bg);
  color: var(--dxcm-fg);
}
.dioxus-codemirror .cm-editor.cm-focused {
  outline: 1px solid var(--dxcm-border);
}
.dioxus-codemirror .cm-content {
  caret-color: var(--dxcm-caret);
}
.dioxus-codemirror .cm-cursor,
.dioxus-codemirror .cm-dropCursor {
  border-left-color: var(--dxcm-caret);
}
/* Selection background, drawn by \`drawSelection\` as \`.cm-selectionBackground\`
   layers. CodeMirror's base theme styles these with high-specificity selectors
   (\`&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground\`,
   ~5 classes) and keys light/dark off its own \`darkTheme\` facet -- which we do
   not set, so it would always apply its light colors regardless of our scheme.
   We therefore match its structure (and add \`.cm-editor\` to outweigh it) so our
   variables win in both focus states and both schemes. */
.dioxus-codemirror .cm-selectionLayer .cm-selectionBackground,
.dioxus-codemirror .cm-content ::selection {
  background: var(--dxcm-selection);
}
.dioxus-codemirror .cm-editor .cm-scroller .cm-highlightSpace {
  background-image: radial-gradient(circle at 50% 55%, var(--dxcm-highlight-space) 20%, transparent 5%);
}
.dioxus-codemirror .cm-editor.cm-focused .cm-scroller .cm-selectionLayer .cm-selectionBackground {
  background: var(--dxcm-selection-focused);
}
/* Occurrences of the selected text, marked by \`selectionMatchHighlighter\` and
   themed so they track the color scheme. Other occurrences get the match tint;
   the actively selected occurrence (\`-main\`) is left to its (more prominent)
   selection background instead, so it reads as the selection rather than as a
   match. */
.dioxus-codemirror .cm-selectionMatch {
  background: var(--dxcm-selection-match);
}
.dioxus-codemirror .cm-selectionMatch.cm-selectionMatch-main {
  background: var(--dxcm-selection-match-main);
}
.dioxus-codemirror .cm-gutters {
  background: var(--dxcm-gutter-bg);
  color: var(--dxcm-gutter-fg);
  border-right-color: var(--dxcm-border);
}
.dioxus-codemirror .cm-activeLine {
  background: var(--dxcm-active-line);
}
.dioxus-codemirror .cm-activeLineGutter {
  background: var(--dxcm-active-line-gutter-bg);
  color: var(--dxcm-fg);
}

/* Autocomplete and hover tooltips. CodeMirror renders these inside the editor
   DOM (so they fall under \`.dioxus-codemirror\`) with only a single-class base
   theme, which these scoped rules outweigh. */
.dioxus-codemirror .cm-tooltip {
  background: var(--dxcm-tooltip-bg);
  color: var(--dxcm-tooltip-fg);
  border: 1px solid var(--dxcm-border);
  border-radius: 6px;
}
.dioxus-codemirror .cm-tooltip-autocomplete ul li {
  color: var(--dxcm-tooltip-fg);
}
.dioxus-codemirror .cm-tooltip-autocomplete ul li[aria-selected] {
  background: var(--dxcm-tooltip-selected-bg);
  color: var(--dxcm-tooltip-selected-fg);
}
.dioxus-codemirror .cm-completionInfo {
  background: var(--dxcm-tooltip-info-bg);
  color: var(--dxcm-tooltip-fg);
  border: 1px solid var(--dxcm-border);
}

/* Code-action menu (triggered by Mod-.). Positioned absolutely within the
   editor and themed with the tooltip variables. */
.dioxus-codemirror .cm-dxcm-codeaction-menu {
  position: absolute;
  z-index: 20;
  margin: 0;
  padding: 2px;
  list-style: none;
  min-width: 12em;
  max-height: 16em;
  overflow-y: auto;
  background: var(--dxcm-tooltip-bg);
  color: var(--dxcm-tooltip-fg);
  border: 1px solid var(--dxcm-border);
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  font-family: monospace;
  font-size: 90%;
}
.dioxus-codemirror .cm-dxcm-codeaction-item {
  padding: 2px 8px;
  border-radius: 4px;
  white-space: nowrap;
  cursor: pointer;
}
.dioxus-codemirror .cm-dxcm-codeaction-item[aria-selected="true"] {
  background: var(--dxcm-tooltip-selected-bg);
  color: var(--dxcm-tooltip-selected-fg);
}
`;
  document.head.appendChild(style);
}

// Syntax highlighting whose colors are the `--dxcm-syntax-*` CSS variables, so
// token colors track the OS color scheme alongside the chrome (see
// `themeStylesInject`). Layered after `minimalSetup`'s fallback default style,
// which then only applies to tags this style leaves unstyled.
function themeHighlightStyle() {
  return HighlightStyle.define([
    { tag: tags.keyword, color: "var(--dxcm-syntax-keyword)" },
    {
      tag: [tags.name, tags.deleted, tags.character, tags.macroName],
      color: "var(--dxcm-fg)",
    },
    {
      tag: [tags.propertyName, tags.attributeName],
      color: "var(--dxcm-syntax-property)",
    },
    {
      tag: [tags.function(tags.variableName), tags.labelName],
      color: "var(--dxcm-syntax-function)",
    },
    {
      tag: [tags.color, tags.constant(tags.name), tags.standard(tags.name)],
      color: "var(--dxcm-syntax-constant)",
    },
    {
      tag: [
        tags.typeName,
        tags.className,
        tags.namespace,
        tags.changed,
        tags.annotation,
        tags.modifier,
        tags.self,
      ],
      color: "var(--dxcm-syntax-type)",
    },
    {
      tag: [tags.number, tags.integer, tags.float, tags.atom, tags.bool],
      color: "var(--dxcm-syntax-number)",
    },
    {
      tag: [
        tags.operator,
        tags.operatorKeyword,
        tags.escape,
        tags.regexp,
        tags.special(tags.string),
      ],
      color: "var(--dxcm-syntax-operator)",
    },
    {
      tag: [tags.meta, tags.comment],
      color: "var(--dxcm-syntax-comment)",
      fontStyle: "italic",
    },
    {
      tag: [tags.string, tags.inserted, tags.processingInstruction],
      color: "var(--dxcm-syntax-string)",
    },
    {
      tag: [tags.url, tags.link],
      color: "var(--dxcm-syntax-link)",
      textDecoration: "underline",
    },
    { tag: tags.heading, color: "var(--dxcm-syntax-heading)", fontWeight: "bold" },
    { tag: tags.strong, fontWeight: "bold" },
    { tag: tags.emphasis, fontStyle: "italic" },
    { tag: tags.strikethrough, textDecoration: "line-through" },
    { tag: tags.invalid, color: "var(--dxcm-syntax-invalid)" },
  ]);
}

// `Mod-d` command: add the next occurrence of the current selection as an extra
// selection range. Unlike CodeMirror's `selectNextOccurrence`, this matches
// substrings -- it does not restrict a whole-word selection to whole-word
// matches -- so selecting "hello" also extends into "helloabcd". Requires
// `allow_multiple_selections`.
function selectNextMatch(view) {
  const { state } = view;
  const { selection } = state;
  const main = selection.main;

  // First press on a bare cursor: select the word under it (the term to extend).
  if (main.empty) {
    const word = state.wordAt(main.head);
    if (!word) {
      return false;
    }
    view.dispatch({
      selection: EditorSelection.create(
        selection.ranges.map((range, index) =>
          index === selection.mainIndex ? EditorSelection.range(word.from, word.to) : range,
        ),
        selection.mainIndex,
      ),
    });
    return true;
  }

  // Every existing range must hold the same text, else there is no single term
  // to extend (mirrors CodeMirror's behaviour).
  const query = state.sliceDoc(main.from, main.to);
  const sameText = selection.ranges.every(
    (range) => state.sliceDoc(range.from, range.to) === query,
  );
  if (!query || !sameText) {
    return false;
  }

  const next = selectNextMatchFind(state, query, selection.ranges);
  if (!next) {
    return false;
  }

  view.dispatch({
    selection: selection.addRange(EditorSelection.range(next.from, next.to)),
    scrollIntoView: true,
  });
  return true;
}

// Next occurrence of `query` after the last selection range, wrapping around to
// the start, skipping ranges that are already selected.
function selectNextMatchFind(state, query, ranges) {
  const taken = new Set(ranges.map((range) => `${range.from}:${range.to}`));
  const after = ranges[ranges.length - 1].to;
  const scan = (from, to) => {
    const cursor = new SearchCursor(state.doc, query, from, to);
    while (!cursor.next().done) {
      if (!taken.has(`${cursor.value.from}:${cursor.value.to}`)) {
        return cursor.value;
      }
    }
    return null;
  };
  return scan(after, state.doc.length) ?? scan(0, after);
}

// `Mod-F2` command: select every occurrence of the current selection (or the
// word under a bare cursor) at once, substring matches included. Requires
// `allow_multiple_selections`.
function selectAllMatches(view) {
  const { state } = view;
  const main = state.selection.main;

  // The term to match: the selected text, or the word under a bare cursor.
  let term;
  if (main.empty) {
    const word = state.wordAt(main.head);
    term = word && state.sliceDoc(word.from, word.to);
  } else {
    term = state.sliceDoc(main.from, main.to);
  }
  if (!term) {
    return false;
  }

  const ranges = [];
  const cursor = new SearchCursor(state.doc, term);
  while (!cursor.next().done) {
    ranges.push(EditorSelection.range(cursor.value.from, cursor.value.to));
  }
  if (ranges.length === 0) {
    return false;
  }

  // Keep the caret on the first match at or after the original selection.
  const mainIndex = ranges.findIndex((range) => range.from >= main.from);
  view.dispatch({
    selection: EditorSelection.create(ranges, mainIndex < 0 ? 0 : mainIndex),
    scrollIntoView: true,
  });
  return true;
}

// View plugin that marks every visible occurrence of the actively selected text
// with the `cm-selectionMatch` class -- the selected range included. This is
// used instead of CodeMirror's `highlightSelectionMatches`, which never marks
// the selection's own range (so the selected word loses its highlight) and bails
// out entirely once there is more than one selection. A bare cursor (no
// selection) highlights nothing -- only an explicit selection does.
function selectionMatchHighlighter() {
  // Other occurrences get `cm-selectionMatch`; an occurrence that coincides with
  // a selection range also gets `cm-selectionMatch-main`, so the actively
  // selected match can be styled apart from the rest.
  const matchDeco = Decoration.mark({ class: "cm-selectionMatch" });
  const mainDeco = Decoration.mark({
    class: "cm-selectionMatch cm-selectionMatch-main",
  });
  const compute = (view) => {
    const { state } = view;
    const main = state.selection.main;
    if (main.empty) {
      return Decoration.none;
    }
    const term = state.sliceDoc(main.from, main.to);
    // Occurrences coinciding with a selection range are "main".
    const selected = new Set();
    for (const range of state.selection.ranges) {
      if (!range.empty) {
        selected.add(`${range.from}:${range.to}`);
      }
    }
    const ranges = [];
    for (const visible of view.visibleRanges) {
      const cursor = new SearchCursor(state.doc, term, visible.from, visible.to);
      while (!cursor.next().done) {
        const { from, to } = cursor.value;
        const deco = selected.has(`${from}:${to}`) ? mainDeco : matchDeco;
        ranges.push(deco.range(from, to));
      }
    }
    return ranges.length ? Decoration.set(ranges, true) : Decoration.none;
  };
  return ViewPlugin.fromClass(
    class {
      constructor(view) {
        this.decorations = compute(view);
      }
      update(update) {
        if (update.selectionSet || update.docChanged || update.viewportChanged) {
          this.decorations = compute(update.view);
        }
      }
    },
    { decorations: (plugin) => plugin.decorations },
  );
}

// The currently open code-action menu's teardown handle, or `null`. Only one
// menu is open at a time (per page); opening a new one closes the previous.
let codeActionMenuActive = null;

// `Mod-.` command: request LSP code actions for the current selection and, if
// any are returned, present them in a menu. Choosing one applies its edit.
// Requires an attached LSP client (see `config.code_actions` / `config.lsp_uri`);
// returns `false` (so `.` types normally) when there is none.
function codeActionCommand(view) {
  const plugin = LSPPlugin.get(view);
  if (!plugin) {
    return false;
  }

  // Flush pending edits so the server computes actions against the current text.
  try {
    plugin.client.sync();
  } catch (_error) {
    // Best-effort; the request below still carries the current range.
  }

  const selection = view.state.selection.main;
  const params = {
    textDocument: { uri: plugin.uri },
    range: {
      start: plugin.toPosition(selection.from),
      end: plugin.toPosition(selection.to),
    },
    context: { diagnostics: [] },
  };

  plugin.client
    .request("textDocument/codeAction", params)
    .then((actions) => {
      const applicable = (actions || []).filter(
        (action) => action && (action.edit || action.command),
      );
      if (applicable.length > 0) {
        codeActionMenuShow(view, plugin, applicable);
      }
    })
    .catch((error) => {
      plugin.reportError("Code action request failed", error);
    });

  // The request is async, but the keypress is handled (default `.` suppressed).
  return true;
}

// Shows a keyboard-navigable menu of `actions` near the caret. Arrow keys move
// the selection, Enter / Tab apply it, Escape (or a click outside) dismisses.
function codeActionMenuShow(view, plugin, actions) {
  codeActionMenuClose();

  const menu = document.createElement("ul");
  menu.className = "cm-dxcm-codeaction-menu";
  menu.setAttribute("role", "listbox");

  // Position just below the caret, relative to the (position: relative) editor.
  const coords = view.coordsAtPos(view.state.selection.main.head);
  const editorRect = view.dom.getBoundingClientRect();
  if (coords) {
    menu.style.top = `${Math.round(coords.bottom - editorRect.top)}px`;
    menu.style.left = `${Math.round(coords.left - editorRect.left)}px`;
  }

  let selectedIndex = 0;
  const items = actions.map((action, index) => {
    const item = document.createElement("li");
    item.className = "cm-dxcm-codeaction-item";
    item.setAttribute("role", "option");
    item.textContent = action.title || "(code action)";
    item.addEventListener("mousedown", (event) => {
      // Keep editor focus and stop the outside-click handler from firing.
      event.preventDefault();
      event.stopPropagation();
      choose(index);
    });
    item.addEventListener("mousemove", () => setSelected(index));
    menu.appendChild(item);
    return item;
  });

  function setSelected(index) {
    selectedIndex = index;
    items.forEach((item, itemIndex) => {
      if (itemIndex === index) {
        item.setAttribute("aria-selected", "true");
      } else {
        item.removeAttribute("aria-selected");
      }
    });
  }
  setSelected(0);

  function choose(index) {
    const action = actions[index];
    codeActionMenuClose();
    if (action) {
      codeActionApply(view, plugin, action);
    }
  }

  function onKeyDown(event) {
    switch (event.key) {
      case "ArrowDown":
        setSelected((selectedIndex + 1) % actions.length);
        break;
      case "ArrowUp":
        setSelected((selectedIndex - 1 + actions.length) % actions.length);
        break;
      case "Enter":
      case "Tab":
        choose(selectedIndex);
        break;
      case "Escape":
        codeActionMenuClose();
        break;
      default:
        // Any other key dismisses the menu and is left for the editor.
        codeActionMenuClose();
        return;
    }
    event.preventDefault();
    event.stopPropagation();
  }

  function onPointerDownOutside(event) {
    if (!menu.contains(event.target)) {
      codeActionMenuClose();
    }
  }

  // Capture phase so these intercept before CodeMirror's own key handling.
  view.contentDOM.addEventListener("keydown", onKeyDown, true);
  document.addEventListener("mousedown", onPointerDownOutside, true);
  view.dom.appendChild(menu);

  codeActionMenuActive = () => {
    view.contentDOM.removeEventListener("keydown", onKeyDown, true);
    document.removeEventListener("mousedown", onPointerDownOutside, true);
    menu.remove();
  };
}

// Closes the open code-action menu, if any.
function codeActionMenuClose() {
  if (codeActionMenuActive) {
    const teardown = codeActionMenuActive;
    codeActionMenuActive = null;
    teardown();
  }
}

// Applies a code action's `WorkspaceEdit` to the editor for the current file.
// Only edits are handled (the `disposition` server returns edit-based actions);
// command-only actions are ignored.
function codeActionApply(view, plugin, action) {
  const edit = action.edit;
  if (!edit) {
    return;
  }

  const doc = view.state.doc;
  const textEdits = [];
  if (edit.changes && edit.changes[plugin.uri]) {
    textEdits.push(...edit.changes[plugin.uri]);
  }
  if (Array.isArray(edit.documentChanges)) {
    for (const change of edit.documentChanges) {
      if (
        change &&
        change.textDocument &&
        change.textDocument.uri === plugin.uri &&
        Array.isArray(change.edits)
      ) {
        textEdits.push(...change.edits);
      }
    }
  }
  if (textEdits.length === 0) {
    return;
  }

  // CodeMirror requires change specs sorted by `from`; LSP edits are
  // non-overlapping but unordered.
  const changes = textEdits
    .map((textEdit) => ({
      from: plugin.fromPosition(textEdit.range.start, doc),
      to: plugin.fromPosition(textEdit.range.end, doc),
      insert: textEdit.newText,
    }))
    .sort((a, b) => a.from - b.from);

  // For a single edit (the common case, e.g. a list flow/block conversion),
  // place the caret at the start of the rewritten list -- before the `[` of an
  // inline list, or before the first `-` of a block list. Positions in a
  // transaction's `selection` are relative to the post-change document, and a
  // lone edit does not shift its own start, so the offset is `from` plus the
  // marker's index within the inserted text.
  let selection;
  if (changes.length === 1) {
    const markerIndex = listMarkerIndex(changes[0].insert);
    if (markerIndex >= 0) {
      selection = { anchor: changes[0].from + markerIndex };
    }
  }

  view.dispatch(selection ? { changes, selection, scrollIntoView: true } : { changes });
  view.focus();
}

// Index within `text` of a converted list's caret target: the `[` of an inline
// list, or the first line-leading `-` of a block list. Returns `-1` when
// neither is present (so the caret is left to its default mapping).
function listMarkerIndex(text) {
  const bracket = text.indexOf("[");
  if (bracket >= 0) {
    return bracket;
  }
  const blockItem = /(?:^|\n)([ \t]*)-/.exec(text);
  return blockItem ? blockItem.index + blockItem[0].length - 1 : -1;
}

// The first message from Rust is always the init config.
const config = await dioxus.recv();

const {
  EditorView,
  minimalSetup,
  EditorState,
  EditorSelection,
  Annotation,
  lineNumbers,
  highlightActiveLineGutter,
  highlightActiveLine,
  highlightWhitespace,
  rectangularSelection,
  crosshairCursor,
  keymap,
  Decoration,
  ViewPlugin,
  HighlightStyle,
  syntaxHighlighting,
  bracketMatching,
  indentOnInput,
  SearchCursor,
  closeBrackets,
  closeBracketsKeymap,
  indentWithTab,
  tags,
  LSPClient,
  LSPPlugin,
  languageServerExtensions,
  // Map of bundled language factories keyed by name, e.g. `{ yaml, markdown }`.
  // Which languages are present depends on the enabled `lang-*` Cargo features.
  languages,
} = await codeMirrorLoad(config.cm_base);

// Guard so programmatic `doc_set` updates do not echo back as `doc_changed`.
let applyingRemote = false;
const remoteAnnotation = Annotation.define();

// Inject the chrome stylesheet before the editor mounts so its first paint is
// already themed.
themeStylesInject();

// `minimalSetup` keeps the editor editable (history, default keymap, syntax
// highlighting) without imposing a line-number gutter. `themeHighlightStyle`
// follows it so its token colors take precedence over the fallback default,
// and both track the OS color scheme via the injected CSS variables.
const extensions = [
  minimalSetup,
  syntaxHighlighting(themeHighlightStyle()),
  EditorView.updateListener.of((update) => {
    if (update.docChanged && !applyingRemote) {
      dioxus.send({ type: "doc_changed", doc: update.state.doc.toString() });
    }
  }),
];

if (config.line_numbers) {
  extensions.push(lineNumbers(), highlightActiveLineGutter());
}

// === Optional editor features === //
// Each maps to the CodeMirror extension of the same name, toggled by a flag in
// the init config (see the matching `CodeMirror` props). `minimalSetup` already
// includes `drawSelection` and the default keymap, so multiple selections only
// need the facet and added keymaps layer on top of the defaults.
if (config.allow_multiple_selections) {
  // Enable the facet, then bind `Mod-d` to add the next occurrence of the
  // selection and `Mod-F2` to add all occurrences (`Mod` is Cmd on macOS, Ctrl
  // elsewhere). Both match substrings, unlike the search keymap's
  // `selectNextOccurrence`. These produce extra cursors, so they belong with the
  // facet rather than with `highlightSelectionMatches` (which is visual only).
  extensions.push(
    EditorState.allowMultipleSelections.of(true),
    keymap.of([
      { key: "Mod-d", run: selectNextMatch, preventDefault: true },
      { key: "Mod-F2", run: selectAllMatches, preventDefault: true },
    ]),
  );
}
if (config.highlight_active_line) {
  extensions.push(highlightActiveLine());
}
if (config.highlight_selection_matches) {
  // Highlight all occurrences of the selected text, the selection included
  // (visual only; the match-selecting keymaps live under
  // `allow_multiple_selections`).
  extensions.push(selectionMatchHighlighter());
}
if (config.bracket_matching) {
  extensions.push(bracketMatching());
}
if (config.close_brackets) {
  extensions.push(closeBrackets(), keymap.of(closeBracketsKeymap));
}
if (config.rectangular_selection) {
  extensions.push(rectangularSelection(), crosshairCursor());
}
if (config.indent_on_input) {
  extensions.push(indentOnInput());
}
if (config.highlight_whitespace) {
  extensions.push(highlightWhitespace());
}
if (config.line_wrapping) {
  extensions.push(EditorView.lineWrapping);
}
if (config.indent_with_tab) {
  // Bind Tab/Shift-Tab to indent, so Tab inserts indentation instead of moving
  // focus out of the editor. Off by default to keep Tab as a focus escape for
  // keyboard accessibility.
  extensions.push(keymap.of([indentWithTab]));
}
if (config.read_only) {
  extensions.push(EditorState.readOnly.of(true));
}
if (typeof config.tab_size === "number") {
  extensions.push(EditorState.tabSize.of(config.tab_size));
}

// Apply the syntax extension for the requested language, if it was bundled. A
// language is bundled only when its `lang-*` Cargo feature is enabled; an
// un-bundled language falls back to plain text rather than failing.
if (config.language) {
  const languageFactory = languages?.[config.language];
  if (languageFactory) {
    extensions.push(languageFactory());
  } else {
    console.warn(
      `dioxus_codemirror: language "${config.language}" is not bundled; ` +
        `enable its Cargo feature (lang-${config.language}) on dioxus_codemirror`,
    );
  }
}

// === LSP wiring === //
// A message-based Transport that bridges the editor's LSP client to Rust:
// the client's outbound messages become `lsp_message_recv` events, and
// `lsp_message_send` commands are delivered to the client's subscribers.
let lspHandlers = [];
if (config.lsp_uri) {
  try {
    const transport = {
      send(message) {
        dioxus.send({ type: "lsp_message_recv", json: message });
      },
      subscribe(handler) {
        lspHandlers.push(handler);
      },
      unsubscribe(handler) {
        lspHandlers = lspHandlers.filter((h) => h !== handler);
      },
    };

    const client = new LSPClient({
      rootUri: config.lsp_uri.replace(/\/[^/]*$/, "") || config.lsp_uri,
      // Generous timeout: the request/response round trip crosses the Rust
      // (WASM) boundary and is driven by the Dioxus runtime, which can be slow
      // during initial page load. The default is 3s.
      timeout: 30000,
      extensions: languageServerExtensions(),
    }).connect(transport);

    extensions.push(client.plugin(config.lsp_uri));

    // Bind `Mod-.` (Cmd-. on macOS, Ctrl-. elsewhere) to request code actions
    // for the current selection and offer them in a menu.
    if (config.code_actions) {
      extensions.push(
        keymap.of([{ key: "Mod-.", run: codeActionCommand, preventDefault: true }]),
      );
    }
  } catch (error) {
    console.warn("dioxus_codemirror: LSP client setup failed", error);
  }
}

const parent = await elementWait(config.mount_id);
let view;
try {
  view = new EditorView({
    state: EditorState.create({ doc: config.doc ?? "", extensions }),
    parent,
  });
} catch (error) {
  console.error("dioxus_codemirror: editor creation failed for", config.mount_id, error);
  throw error;
}

dioxus.send({ type: "ready" });

// === Command loop === //
while (true) {
  let cmd;
  try {
    cmd = await dioxus.recv();
  } catch (error) {
    // Channel closed -- the component unmounted.
    break;
  }

  switch (cmd.type) {
    case "doc_set": {
      const current = view.state.doc.toString();
      if (current === cmd.doc) {
        break;
      }
      applyingRemote = true;
      view.dispatch({
        changes: { from: 0, to: current.length, insert: cmd.doc },
        annotations: remoteAnnotation.of(true),
      });
      applyingRemote = false;
      break;
    }
    case "lsp_message_send": {
      for (const handler of lspHandlers) {
        handler(cmd.json);
      }
      break;
    }
    case "destroy": {
      view.destroy();
      return;
    }
    default:
      console.warn("dioxus_codemirror: unknown command", cmd);
  }
}