@olenbetong/synergi-react 4.2.7 → 4.3.1

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.
@@ -15,3 +15,11 @@ export declare function getColorSchemePreference(): ColorSchemePreference;
15
15
  export declare function setColorSchemePreference(preference: ColorSchemePreference): void;
16
16
  /** Reads the stored preference and keeps it in sync with other toggles on the page. */
17
17
  export declare function useColorSchemePreference(): [ColorSchemePreference, (value: ColorSchemePreference) => void];
18
+ /** The scheme Designsystemet is rendering with right now: the preference, with `auto` resolved. */
19
+ export declare function getResolvedColorScheme(): "light" | "dark";
20
+ /**
21
+ * Tracks the color scheme Designsystemet is rendering with. The article template
22
+ * sets `data-color-scheme` on `<body>`, so watch that attribute as well as the
23
+ * OS preference (used when the scheme is `auto`).
24
+ */
25
+ export declare function useResolvedColorScheme(): "light" | "dark";
package/es/colorScheme.js CHANGED
@@ -52,3 +52,37 @@ export function useColorSchemePreference() {
52
52
  }, []);
53
53
  return [preference, setValue];
54
54
  }
55
+ /** The scheme Designsystemet is rendering with right now: the preference, with `auto` resolved. */
56
+ export function getResolvedColorScheme() {
57
+ if (typeof document === "undefined")
58
+ return "light";
59
+ let scheme = document.body?.dataset.colorScheme ?? document.documentElement?.dataset.colorScheme ?? "light";
60
+ if (scheme === "auto") {
61
+ return globalThis.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
62
+ }
63
+ return scheme === "dark" ? "dark" : "light";
64
+ }
65
+ /**
66
+ * Tracks the color scheme Designsystemet is rendering with. The article template
67
+ * sets `data-color-scheme` on `<body>`, so watch that attribute as well as the
68
+ * OS preference (used when the scheme is `auto`).
69
+ */
70
+ export function useResolvedColorScheme() {
71
+ let [scheme, setScheme] = useState(() => getResolvedColorScheme());
72
+ useEffect(() => {
73
+ function update() {
74
+ setScheme(getResolvedColorScheme());
75
+ }
76
+ update();
77
+ let observer = new MutationObserver(update);
78
+ observer.observe(document.body, { attributes: true, attributeFilter: ["data-color-scheme"] });
79
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-color-scheme"] });
80
+ let media = globalThis.matchMedia?.("(prefers-color-scheme: dark)");
81
+ media?.addEventListener("change", update);
82
+ return () => {
83
+ observer.disconnect();
84
+ media?.removeEventListener("change", update);
85
+ };
86
+ }, []);
87
+ return scheme;
88
+ }
@@ -0,0 +1,6 @@
1
+ .ObCodeEditor-root {
2
+ min-height: 10rem;
3
+ border: 1px solid var(--ds-color-neutral-border-subtle);
4
+ border-radius: var(--ds-border-radius-md);
5
+ overflow: hidden;
6
+ }
@@ -0,0 +1,35 @@
1
+ import * as monaco from "monaco-editor";
2
+ import "./CodeEditor.css";
3
+ export type CodeEditorHandle = {
4
+ /** The Monaco editor instance, once mounted. */
5
+ editor: monaco.editor.IStandaloneCodeEditor | null;
6
+ /** Replaces the selection (or inserts at the cursor) and focuses the editor. */
7
+ insertText(text: string): void;
8
+ focus(): void;
9
+ };
10
+ export type CodeEditorProps = {
11
+ /** The text shown. The editor is controlled: `onChange` reports every edit. */
12
+ value: string;
13
+ onChange?: (value: string) => void;
14
+ /** Monaco language ID, e.g. `html`, `css`, `javascript`, `json`, `sql`, `xml`. */
15
+ language?: string;
16
+ /**
17
+ * Identifies the document. When it changes, the editor gets a fresh model, so undo history
18
+ * does not leak from one record to the next. Without it, a new `value` is applied as an edit
19
+ * that can be undone.
20
+ */
21
+ docKey?: string;
22
+ readOnly?: boolean;
23
+ /** Ctrl/Cmd+S inside the editor. */
24
+ onSave?: () => void;
25
+ /** Extra Monaco options, applied on mount and whenever the object changes. */
26
+ options?: monaco.editor.IEditorOptions;
27
+ className?: string;
28
+ style?: React.CSSProperties;
29
+ "aria-label"?: string;
30
+ };
31
+ /**
32
+ * Monaco code editor that follows the site's colour scheme. The element fills its parent's size
33
+ * through `className`/`style`; give it a height.
34
+ */
35
+ export declare const CodeEditor: import("react").ForwardRefExoticComponent<CodeEditorProps & import("react").RefAttributes<CodeEditorHandle>>;
@@ -0,0 +1,114 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import clsx from "clsx";
3
+ import * as monaco from "monaco-editor";
4
+ import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
5
+ import { useResolvedColorScheme } from "../../colorScheme.js";
6
+ import "./CodeEditor.css";
7
+ /**
8
+ * Monaco code editor that follows the site's colour scheme. The element fills its parent's size
9
+ * through `className`/`style`; give it a height.
10
+ */
11
+ export const CodeEditor = forwardRef(function CodeEditor({ value, onChange, language = "plaintext", docKey, readOnly = false, onSave, options, className, style, "aria-label": ariaLabel, }, ref) {
12
+ let container = useRef(null);
13
+ let editor = useRef(null);
14
+ // Latest callbacks without re-creating the editor.
15
+ let callbacks = useRef({ onChange, onSave });
16
+ callbacks.current = { onChange, onSave };
17
+ // Set while the editor applies a `value` from props, so that edit is not reported back.
18
+ let applyingValue = useRef(false);
19
+ let shownDoc = useRef(undefined);
20
+ let colorScheme = useResolvedColorScheme();
21
+ useEffect(() => {
22
+ if (!container.current)
23
+ return;
24
+ let instance = monaco.editor.create(container.current, {
25
+ value,
26
+ language,
27
+ theme: colorScheme === "dark" ? "vs-dark" : "vs",
28
+ automaticLayout: true,
29
+ minimap: { enabled: false },
30
+ scrollBeyondLastLine: false,
31
+ fixedOverflowWidgets: true,
32
+ ariaLabel,
33
+ readOnly,
34
+ ...options,
35
+ });
36
+ editor.current = instance;
37
+ shownDoc.current = docKey;
38
+ let changeListener = instance.onDidChangeModelContent(() => {
39
+ if (!applyingValue.current) {
40
+ callbacks.current.onChange?.(instance.getValue());
41
+ }
42
+ });
43
+ instance.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => callbacks.current.onSave?.());
44
+ return () => {
45
+ changeListener.dispose();
46
+ instance.getModel()?.dispose();
47
+ instance.dispose();
48
+ editor.current = null;
49
+ };
50
+ // The editor is created once; every prop is synced by the effects below.
51
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
52
+ }, []);
53
+ useEffect(() => {
54
+ let instance = editor.current;
55
+ if (!instance)
56
+ return;
57
+ applyingValue.current = true;
58
+ try {
59
+ if (shownDoc.current !== docKey) {
60
+ // New document: a new model, so undo history stays with the document it belongs to.
61
+ let old = instance.getModel();
62
+ instance.setModel(monaco.editor.createModel(value, language));
63
+ old?.dispose();
64
+ shownDoc.current = docKey;
65
+ }
66
+ else if (instance.getValue() !== value) {
67
+ // Same document, changed from outside (cancel, reload): one undoable edit.
68
+ let model = instance.getModel();
69
+ if (model) {
70
+ instance.executeEdits("external", [{ range: model.getFullModelRange(), text: value }]);
71
+ }
72
+ }
73
+ }
74
+ finally {
75
+ applyingValue.current = false;
76
+ }
77
+ }, [docKey, value, language]);
78
+ useEffect(() => {
79
+ let model = editor.current?.getModel();
80
+ if (model && model.getLanguageId() !== language) {
81
+ monaco.editor.setModelLanguage(model, language);
82
+ }
83
+ }, [language]);
84
+ useEffect(() => {
85
+ editor.current?.updateOptions({ readOnly, ariaLabel, ...options });
86
+ }, [readOnly, ariaLabel, options]);
87
+ useEffect(() => {
88
+ // The theme is global to every editor on the page.
89
+ monaco.editor.setTheme(colorScheme === "dark" ? "vs-dark" : "vs");
90
+ }, [colorScheme]);
91
+ useImperativeHandle(ref, () => ({
92
+ get editor() {
93
+ return editor.current;
94
+ },
95
+ insertText(text) {
96
+ let instance = editor.current;
97
+ if (!instance)
98
+ return;
99
+ let range = instance.getSelection() ?? new monaco.Range(1, 1, 1, 1);
100
+ instance.executeEdits("insert", [{ range, text, forceMoveMarkers: true }]);
101
+ instance.focus();
102
+ },
103
+ focus() {
104
+ editor.current?.focus();
105
+ },
106
+ }));
107
+ /*
108
+ * `monaco-component`: Monaco renders the context menu in a shadow root attached to this
109
+ * container, a parent of `.monaco-editor`. Its colours are theme variables Monaco defines on
110
+ * `.monaco-editor, .monaco-diff-editor, .monaco-component` only, so without the class the
111
+ * menu inherits none of them and has no background.
112
+ */
113
+ return _jsx("div", { ref: container, className: clsx("ObCodeEditor-root", "monaco-component", className), style: style });
114
+ });
@@ -0,0 +1 @@
1
+ export { CodeEditor, type CodeEditorHandle, type CodeEditorProps } from "./CodeEditor.js";
@@ -0,0 +1 @@
1
+ export { CodeEditor } from "./CodeEditor.js";
@@ -3,6 +3,8 @@ import { Box, Button, DialogActions, LinearProgress, Link, Typography } from "@m
3
3
  import { ResponsiveDialog } from "@olenbetong/appframe-mui";
4
4
  import { useEffect, useRef, useState } from "react";
5
5
  import { getLocalizedString } from "../../i18n.js";
6
+ /** Waits between reconnects; together they cover a server restart of about half a minute. */
7
+ const RECONNECT_DELAYS_MS = [1000, 2000, 3000, 5000, 8000, 13000];
6
8
  function formatRemaining(ms) {
7
9
  if (ms < 60_000)
8
10
  return `~${Math.ceil(ms / 1000)}s`;
@@ -31,6 +33,7 @@ export function MergeProgressDialog({ open, onClose, getMergerId, mergeType = "p
31
33
  doneRef.current = false;
32
34
  let cancelled = false;
33
35
  let es = null;
36
+ let retryTimer;
34
37
  async function start() {
35
38
  try {
36
39
  let mergerId = await getMergerId();
@@ -42,43 +45,59 @@ export function MergeProgressDialog({ open, onClose, getMergerId, mergeType = "p
42
45
  let { jobId } = await response.json();
43
46
  if (cancelled)
44
47
  return;
45
- es = new EventSource(`/api/ob/merger/events/${jobId}`);
46
- esRef.current = es;
47
- es.addEventListener("progress", (e) => {
48
- let d = JSON.parse(e.data);
49
- setPhase((prev) => ({
50
- kind: "processing",
51
- completed: d.completed,
52
- total: d.total,
53
- currentFile: d.currentFile ?? "",
54
- startedAt: prev.kind === "processing" ? prev.startedAt : Date.now(),
55
- }));
56
- setNow(Date.now());
57
- });
58
- es.addEventListener("done", (e) => {
59
- doneRef.current = true;
60
- es?.close();
61
- let d = JSON.parse(e.data);
62
- setPhase({ kind: "completed", jobId, fileName: d.fileName ?? "" });
63
- window.open(`/api/ob/merger/download/${jobId}`);
64
- });
65
- // Catches both server-sent "event: error" and connection errors.
66
- // After a "done" event the server closes the stream, which also fires error —
67
- // doneRef guards against treating that as a failure.
68
- es.addEventListener("error", (e) => {
69
- if (doneRef.current)
70
- return;
71
- es?.close();
72
- let message = getLocalizedString("Unknown error");
73
- let data = e.data;
74
- if (data) {
75
- try {
76
- message = JSON.parse(data).message ?? message;
48
+ // The server keeps a job's state on disk and runs it again when the process running it
49
+ // goes away (a deploy or an app pool recycle), so a dropped connection is retried with
50
+ // a backoff before the merge is reported as failed. EventSource only reconnects by
51
+ // itself after a clean drop, not after the 502/503 a restarting server answers with.
52
+ let attempt = 0;
53
+ function connect() {
54
+ es = new EventSource(`/api/ob/merger/events/${jobId}`);
55
+ esRef.current = es;
56
+ es.addEventListener("progress", (e) => {
57
+ attempt = 0;
58
+ let d = JSON.parse(e.data);
59
+ setPhase((prev) => ({
60
+ kind: "processing",
61
+ completed: d.completed,
62
+ total: d.total,
63
+ currentFile: d.currentFile ?? "",
64
+ startedAt: prev.kind === "processing" ? prev.startedAt : Date.now(),
65
+ }));
66
+ setNow(Date.now());
67
+ });
68
+ es.addEventListener("done", (e) => {
69
+ doneRef.current = true;
70
+ es?.close();
71
+ let d = JSON.parse(e.data);
72
+ setPhase({ kind: "completed", jobId, fileName: d.fileName ?? "" });
73
+ window.open(`/api/ob/merger/download/${jobId}`);
74
+ });
75
+ // Catches both server-sent "event: error" (with data) and connection errors.
76
+ // After a "done" event the server closes the stream, which also fires error —
77
+ // doneRef guards against treating that as a failure.
78
+ es.addEventListener("error", (e) => {
79
+ if (doneRef.current)
80
+ return;
81
+ es?.close();
82
+ let data = e.data;
83
+ if (!data && attempt < RECONNECT_DELAYS_MS.length) {
84
+ retryTimer = setTimeout(() => {
85
+ if (!cancelled && !doneRef.current)
86
+ connect();
87
+ }, RECONNECT_DELAYS_MS[attempt++]);
88
+ return;
77
89
  }
78
- catch { }
79
- }
80
- setPhase({ kind: "failed", error: message });
81
- });
90
+ let message = getLocalizedString("Unknown error");
91
+ if (data) {
92
+ try {
93
+ message = JSON.parse(data).message ?? message;
94
+ }
95
+ catch { }
96
+ }
97
+ setPhase({ kind: "failed", error: message });
98
+ });
99
+ }
100
+ connect();
82
101
  }
83
102
  catch (err) {
84
103
  if (!cancelled) {
@@ -89,6 +108,7 @@ export function MergeProgressDialog({ open, onClose, getMergerId, mergeType = "p
89
108
  start();
90
109
  return () => {
91
110
  cancelled = true;
111
+ clearTimeout(retryTimer);
92
112
  es?.close();
93
113
  esRef.current = null;
94
114
  };
package/es/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { AppShell, type AppShellProps, hasSiteChrome } from "./chrome/AppShell/index.js";
2
2
  export { Checkbox, type CheckboxProps } from "./components/Checkbox/index.js";
3
- export { COLOR_SCHEME_CHANGE_EVENT, type ColorSchemePreference, getColorSchemePreference, setColorSchemePreference, useColorSchemePreference, } from "./colorScheme.js";
3
+ export { COLOR_SCHEME_CHANGE_EVENT, type ColorSchemePreference, getColorSchemePreference, getResolvedColorScheme, setColorSchemePreference, useColorSchemePreference, useResolvedColorScheme, } from "./colorScheme.js";
4
4
  export { CardColumn, CardDetail, CardLabel, CardStep, CardStepList, ColorCard } from "./components/ColorCard/index.js";
5
5
  export { DateNavigator } from "./components/DateNavigator/index.js";
6
6
  export * from "./components/FilePond.js";
package/es/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // loaded once per page by the site template rather than bundled into every app.
3
3
  export { AppShell, hasSiteChrome } from "./chrome/AppShell/index.js";
4
4
  export { Checkbox } from "./components/Checkbox/index.js";
5
- export { COLOR_SCHEME_CHANGE_EVENT, getColorSchemePreference, setColorSchemePreference, useColorSchemePreference, } from "./colorScheme.js";
5
+ export { COLOR_SCHEME_CHANGE_EVENT, getColorSchemePreference, getResolvedColorScheme, setColorSchemePreference, useColorSchemePreference, useResolvedColorScheme, } from "./colorScheme.js";
6
6
  export { CardColumn, CardDetail, CardLabel, CardStep, CardStepList, ColorCard } from "./components/ColorCard/index.js";
7
7
  export { DateNavigator } from "./components/DateNavigator/index.js";
8
8
  export * from "./components/FilePond.js";
@@ -2,37 +2,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { StyledEngineProvider, ThemeProvider } from "@mui/material";
3
3
  import { createTheme as muiCreateTheme } from "@mui/material/styles";
4
4
  import { useEffect, useState } from "react";
5
- function getColorScheme() {
6
- let scheme = document.body?.dataset.colorScheme ?? document.documentElement?.dataset.colorScheme ?? "light";
7
- if (scheme === "auto") {
8
- return globalThis.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
9
- }
10
- return scheme === "dark" ? "dark" : "light";
11
- }
12
- /**
13
- * Tracks the color scheme Designsystemet is rendering with. The article template
14
- * sets `data-color-scheme` on `<body>`, so watch that attribute as well as the
15
- * OS preference (used when the scheme is `auto`).
16
- */
17
- function useColorScheme() {
18
- let [scheme, setScheme] = useState(() => getColorScheme());
19
- useEffect(() => {
20
- function update() {
21
- setScheme(getColorScheme());
22
- }
23
- update();
24
- let observer = new MutationObserver(update);
25
- observer.observe(document.body, { attributes: true, attributeFilter: ["data-color-scheme"] });
26
- observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-color-scheme"] });
27
- let media = globalThis.matchMedia?.("(prefers-color-scheme: dark)");
28
- media?.addEventListener("change", update);
29
- return () => {
30
- observer.disconnect();
31
- media?.removeEventListener("change", update);
32
- };
33
- }, []);
34
- return scheme;
35
- }
5
+ import { useResolvedColorScheme as useColorScheme } from "../colorScheme.js";
36
6
  function buildMuiTheme(mode) {
37
7
  const s = getComputedStyle(document.body);
38
8
  const get = (v) => s.getPropertyValue(v).trim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@olenbetong/synergi-react",
3
- "version": "4.2.7",
3
+ "version": "4.3.1",
4
4
  "description": "Standalone React component for SynergiWeb and Partner Portal",
5
5
  "type": "module",
6
6
  "exports": {
@@ -19,6 +19,10 @@
19
19
  "./pdf": {
20
20
  "types": "./es/components/PdfViewer/index.d.ts",
21
21
  "import": "./es/components/PdfViewer/index.js"
22
+ },
23
+ "./code-editor": {
24
+ "types": "./es/components/CodeEditor/index.d.ts",
25
+ "import": "./es/components/CodeEditor/index.js"
22
26
  }
23
27
  },
24
28
  "files": [
@@ -40,9 +44,9 @@
40
44
  "@mui/icons-material": "9.4.0",
41
45
  "@mui/material": "9.4.0",
42
46
  "@olenbetong/appframe-core": "^2.15.2",
43
- "@olenbetong/appframe-data": "^1.8.2",
44
- "@olenbetong/appframe-ds": "^1.4.1",
45
- "@olenbetong/appframe-mui": "^7.0.10",
47
+ "@olenbetong/appframe-data": "^1.8.3",
48
+ "@olenbetong/appframe-ds": "^1.5.0",
49
+ "@olenbetong/appframe-mui": "^7.0.11",
46
50
  "@olenbetong/appframe-react": "^2.2.7",
47
51
  "clsx": "^2.1.1",
48
52
  "filepond": "^4.32.12",
@@ -53,6 +57,7 @@
53
57
  "filepond-plugin-image-transform": "^3.8.8",
54
58
  "localforage": "^1.10.0",
55
59
  "mitt": "^3.0.1",
60
+ "monaco-editor": "0.57.0",
56
61
  "pdf-lib": "1.17.1",
57
62
  "pdfjs-dist": "5.7.284",
58
63
  "react": "19.3.0",
@@ -79,3 +79,47 @@ export function useColorSchemePreference(): [ColorSchemePreference, (value: Colo
79
79
 
80
80
  return [preference, setValue];
81
81
  }
82
+
83
+ /** The scheme Designsystemet is rendering with right now: the preference, with `auto` resolved. */
84
+ export function getResolvedColorScheme(): "light" | "dark" {
85
+ if (typeof document === "undefined") return "light";
86
+
87
+ let scheme = document.body?.dataset.colorScheme ?? document.documentElement?.dataset.colorScheme ?? "light";
88
+
89
+ if (scheme === "auto") {
90
+ return globalThis.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
91
+ }
92
+
93
+ return scheme === "dark" ? "dark" : "light";
94
+ }
95
+
96
+ /**
97
+ * Tracks the color scheme Designsystemet is rendering with. The article template
98
+ * sets `data-color-scheme` on `<body>`, so watch that attribute as well as the
99
+ * OS preference (used when the scheme is `auto`).
100
+ */
101
+ export function useResolvedColorScheme(): "light" | "dark" {
102
+ let [scheme, setScheme] = useState<"light" | "dark">(() => getResolvedColorScheme());
103
+
104
+ useEffect(() => {
105
+ function update() {
106
+ setScheme(getResolvedColorScheme());
107
+ }
108
+
109
+ update();
110
+
111
+ let observer = new MutationObserver(update);
112
+ observer.observe(document.body, { attributes: true, attributeFilter: ["data-color-scheme"] });
113
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-color-scheme"] });
114
+
115
+ let media = globalThis.matchMedia?.("(prefers-color-scheme: dark)");
116
+ media?.addEventListener("change", update);
117
+
118
+ return () => {
119
+ observer.disconnect();
120
+ media?.removeEventListener("change", update);
121
+ };
122
+ }, []);
123
+
124
+ return scheme;
125
+ }
@@ -0,0 +1,6 @@
1
+ .ObCodeEditor-root {
2
+ min-height: 10rem;
3
+ border: 1px solid var(--ds-color-neutral-border-subtle);
4
+ border-radius: var(--ds-border-radius-md);
5
+ overflow: hidden;
6
+ }
@@ -0,0 +1,173 @@
1
+ import clsx from "clsx";
2
+ import * as monaco from "monaco-editor";
3
+ import { forwardRef, useEffect, useImperativeHandle, useRef } from "react";
4
+
5
+ import { useResolvedColorScheme } from "../../colorScheme.js";
6
+ import "./CodeEditor.css";
7
+
8
+ /*
9
+ * Monaco on the 2026 templates comes from the platform bundle through the import map. The
10
+ * platform entry sets `MonacoEnvironment` (the editor and language workers, served next to it)
11
+ * and links Monaco's stylesheet on first import, so this component only drives the editor.
12
+ * Off the platform (the Vite dev server, a legacy template) Monaco is bundled from npm: its
13
+ * stylesheets come with it, and without `MonacoEnvironment` the language services run on the
14
+ * main thread with a console warning. That is fine for development; it is why this lives in its
15
+ * own entry point and is not re-exported from the package root.
16
+ */
17
+
18
+ export type CodeEditorHandle = {
19
+ /** The Monaco editor instance, once mounted. */
20
+ editor: monaco.editor.IStandaloneCodeEditor | null;
21
+ /** Replaces the selection (or inserts at the cursor) and focuses the editor. */
22
+ insertText(text: string): void;
23
+ focus(): void;
24
+ };
25
+
26
+ export type CodeEditorProps = {
27
+ /** The text shown. The editor is controlled: `onChange` reports every edit. */
28
+ value: string;
29
+ onChange?: (value: string) => void;
30
+ /** Monaco language ID, e.g. `html`, `css`, `javascript`, `json`, `sql`, `xml`. */
31
+ language?: string;
32
+ /**
33
+ * Identifies the document. When it changes, the editor gets a fresh model, so undo history
34
+ * does not leak from one record to the next. Without it, a new `value` is applied as an edit
35
+ * that can be undone.
36
+ */
37
+ docKey?: string;
38
+ readOnly?: boolean;
39
+ /** Ctrl/Cmd+S inside the editor. */
40
+ onSave?: () => void;
41
+ /** Extra Monaco options, applied on mount and whenever the object changes. */
42
+ options?: monaco.editor.IEditorOptions;
43
+ className?: string;
44
+ style?: React.CSSProperties;
45
+ "aria-label"?: string;
46
+ };
47
+
48
+ /**
49
+ * Monaco code editor that follows the site's colour scheme. The element fills its parent's size
50
+ * through `className`/`style`; give it a height.
51
+ */
52
+ export const CodeEditor = forwardRef<CodeEditorHandle, CodeEditorProps>(function CodeEditor(
53
+ {
54
+ value,
55
+ onChange,
56
+ language = "plaintext",
57
+ docKey,
58
+ readOnly = false,
59
+ onSave,
60
+ options,
61
+ className,
62
+ style,
63
+ "aria-label": ariaLabel,
64
+ },
65
+ ref,
66
+ ) {
67
+ let container = useRef<HTMLDivElement>(null);
68
+ let editor = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
69
+ // Latest callbacks without re-creating the editor.
70
+ let callbacks = useRef({ onChange, onSave });
71
+ callbacks.current = { onChange, onSave };
72
+ // Set while the editor applies a `value` from props, so that edit is not reported back.
73
+ let applyingValue = useRef(false);
74
+ let shownDoc = useRef<string | undefined>(undefined);
75
+ let colorScheme = useResolvedColorScheme();
76
+
77
+ useEffect(() => {
78
+ if (!container.current) return;
79
+ let instance = monaco.editor.create(container.current, {
80
+ value,
81
+ language,
82
+ theme: colorScheme === "dark" ? "vs-dark" : "vs",
83
+ automaticLayout: true,
84
+ minimap: { enabled: false },
85
+ scrollBeyondLastLine: false,
86
+ fixedOverflowWidgets: true,
87
+ ariaLabel,
88
+ readOnly,
89
+ ...options,
90
+ });
91
+ editor.current = instance;
92
+ shownDoc.current = docKey;
93
+ let changeListener = instance.onDidChangeModelContent(() => {
94
+ if (!applyingValue.current) {
95
+ callbacks.current.onChange?.(instance.getValue());
96
+ }
97
+ });
98
+ instance.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => callbacks.current.onSave?.());
99
+
100
+ return () => {
101
+ changeListener.dispose();
102
+ instance.getModel()?.dispose();
103
+ instance.dispose();
104
+ editor.current = null;
105
+ };
106
+ // The editor is created once; every prop is synced by the effects below.
107
+ // oxlint-disable-next-line react-hooks/exhaustive-deps
108
+ }, []);
109
+
110
+ useEffect(() => {
111
+ let instance = editor.current;
112
+ if (!instance) return;
113
+
114
+ applyingValue.current = true;
115
+ try {
116
+ if (shownDoc.current !== docKey) {
117
+ // New document: a new model, so undo history stays with the document it belongs to.
118
+ let old = instance.getModel();
119
+ instance.setModel(monaco.editor.createModel(value, language));
120
+ old?.dispose();
121
+ shownDoc.current = docKey;
122
+ } else if (instance.getValue() !== value) {
123
+ // Same document, changed from outside (cancel, reload): one undoable edit.
124
+ let model = instance.getModel();
125
+ if (model) {
126
+ instance.executeEdits("external", [{ range: model.getFullModelRange(), text: value }]);
127
+ }
128
+ }
129
+ } finally {
130
+ applyingValue.current = false;
131
+ }
132
+ }, [docKey, value, language]);
133
+
134
+ useEffect(() => {
135
+ let model = editor.current?.getModel();
136
+ if (model && model.getLanguageId() !== language) {
137
+ monaco.editor.setModelLanguage(model, language);
138
+ }
139
+ }, [language]);
140
+
141
+ useEffect(() => {
142
+ editor.current?.updateOptions({ readOnly, ariaLabel, ...options });
143
+ }, [readOnly, ariaLabel, options]);
144
+
145
+ useEffect(() => {
146
+ // The theme is global to every editor on the page.
147
+ monaco.editor.setTheme(colorScheme === "dark" ? "vs-dark" : "vs");
148
+ }, [colorScheme]);
149
+
150
+ useImperativeHandle(ref, () => ({
151
+ get editor() {
152
+ return editor.current;
153
+ },
154
+ insertText(text: string) {
155
+ let instance = editor.current;
156
+ if (!instance) return;
157
+ let range = instance.getSelection() ?? new monaco.Range(1, 1, 1, 1);
158
+ instance.executeEdits("insert", [{ range, text, forceMoveMarkers: true }]);
159
+ instance.focus();
160
+ },
161
+ focus() {
162
+ editor.current?.focus();
163
+ },
164
+ }));
165
+
166
+ /*
167
+ * `monaco-component`: Monaco renders the context menu in a shadow root attached to this
168
+ * container, a parent of `.monaco-editor`. Its colours are theme variables Monaco defines on
169
+ * `.monaco-editor, .monaco-diff-editor, .monaco-component` only, so without the class the
170
+ * menu inherits none of them and has no background.
171
+ */
172
+ return <div ref={container} className={clsx("ObCodeEditor-root", "monaco-component", className)} style={style} />;
173
+ });
@@ -0,0 +1 @@
1
+ export { CodeEditor, type CodeEditorHandle, type CodeEditorProps } from "./CodeEditor.js";
@@ -17,6 +17,9 @@ type MergePhase =
17
17
  | { kind: "completed"; jobId: string; fileName: string }
18
18
  | { kind: "failed"; error: string };
19
19
 
20
+ /** Waits between reconnects; together they cover a server restart of about half a minute. */
21
+ const RECONNECT_DELAYS_MS = [1000, 2000, 3000, 5000, 8000, 13000];
22
+
20
23
  function formatRemaining(ms: number) {
21
24
  if (ms < 60_000) return `~${Math.ceil(ms / 1000)}s`;
22
25
  let mins = Math.floor(ms / 60_000);
@@ -47,6 +50,7 @@ export function MergeProgressDialog({ open, onClose, getMergerId, mergeType = "p
47
50
 
48
51
  let cancelled = false;
49
52
  let es: EventSource | null = null;
53
+ let retryTimer: ReturnType<typeof setTimeout> | undefined;
50
54
 
51
55
  async function start() {
52
56
  try {
@@ -58,44 +62,61 @@ export function MergeProgressDialog({ open, onClose, getMergerId, mergeType = "p
58
62
  let { jobId } = await response.json();
59
63
  if (cancelled) return;
60
64
 
61
- es = new EventSource(`/api/ob/merger/events/${jobId}`);
62
- esRef.current = es;
63
-
64
- es.addEventListener("progress", (e) => {
65
- let d = JSON.parse((e as MessageEvent).data);
66
- setPhase((prev) => ({
67
- kind: "processing",
68
- completed: d.completed,
69
- total: d.total,
70
- currentFile: d.currentFile ?? "",
71
- startedAt: prev.kind === "processing" ? prev.startedAt : Date.now(),
72
- }));
73
- setNow(Date.now());
74
- });
75
-
76
- es.addEventListener("done", (e) => {
77
- doneRef.current = true;
78
- es?.close();
79
- let d = JSON.parse((e as MessageEvent).data);
80
- setPhase({ kind: "completed", jobId, fileName: d.fileName ?? "" });
81
- window.open(`/api/ob/merger/download/${jobId}`);
82
- });
83
-
84
- // Catches both server-sent "event: error" and connection errors.
85
- // After a "done" event the server closes the stream, which also fires error —
86
- // doneRef guards against treating that as a failure.
87
- es.addEventListener("error", (e) => {
88
- if (doneRef.current) return;
89
- es?.close();
90
- let message = getLocalizedString("Unknown error");
91
- let data = (e as MessageEvent).data;
92
- if (data) {
93
- try {
94
- message = JSON.parse(data).message ?? message;
95
- } catch {}
96
- }
97
- setPhase({ kind: "failed", error: message });
98
- });
65
+ // The server keeps a job's state on disk and runs it again when the process running it
66
+ // goes away (a deploy or an app pool recycle), so a dropped connection is retried with
67
+ // a backoff before the merge is reported as failed. EventSource only reconnects by
68
+ // itself after a clean drop, not after the 502/503 a restarting server answers with.
69
+ let attempt = 0;
70
+
71
+ function connect() {
72
+ es = new EventSource(`/api/ob/merger/events/${jobId}`);
73
+ esRef.current = es;
74
+
75
+ es.addEventListener("progress", (e) => {
76
+ attempt = 0;
77
+ let d = JSON.parse((e as MessageEvent).data);
78
+ setPhase((prev) => ({
79
+ kind: "processing",
80
+ completed: d.completed,
81
+ total: d.total,
82
+ currentFile: d.currentFile ?? "",
83
+ startedAt: prev.kind === "processing" ? prev.startedAt : Date.now(),
84
+ }));
85
+ setNow(Date.now());
86
+ });
87
+
88
+ es.addEventListener("done", (e) => {
89
+ doneRef.current = true;
90
+ es?.close();
91
+ let d = JSON.parse((e as MessageEvent).data);
92
+ setPhase({ kind: "completed", jobId, fileName: d.fileName ?? "" });
93
+ window.open(`/api/ob/merger/download/${jobId}`);
94
+ });
95
+
96
+ // Catches both server-sent "event: error" (with data) and connection errors.
97
+ // After a "done" event the server closes the stream, which also fires error —
98
+ // doneRef guards against treating that as a failure.
99
+ es.addEventListener("error", (e) => {
100
+ if (doneRef.current) return;
101
+ es?.close();
102
+ let data = (e as MessageEvent).data;
103
+ if (!data && attempt < RECONNECT_DELAYS_MS.length) {
104
+ retryTimer = setTimeout(() => {
105
+ if (!cancelled && !doneRef.current) connect();
106
+ }, RECONNECT_DELAYS_MS[attempt++]);
107
+ return;
108
+ }
109
+ let message = getLocalizedString("Unknown error");
110
+ if (data) {
111
+ try {
112
+ message = JSON.parse(data).message ?? message;
113
+ } catch {}
114
+ }
115
+ setPhase({ kind: "failed", error: message });
116
+ });
117
+ }
118
+
119
+ connect();
99
120
  } catch (err: unknown) {
100
121
  if (!cancelled) {
101
122
  setPhase({ kind: "failed", error: (err as Error)?.message ?? String(err) });
@@ -107,6 +128,7 @@ export function MergeProgressDialog({ open, onClose, getMergerId, mergeType = "p
107
128
 
108
129
  return () => {
109
130
  cancelled = true;
131
+ clearTimeout(retryTimer);
110
132
  es?.close();
111
133
  esRef.current = null;
112
134
  };
package/src/index.ts CHANGED
@@ -6,8 +6,10 @@ export {
6
6
  COLOR_SCHEME_CHANGE_EVENT,
7
7
  type ColorSchemePreference,
8
8
  getColorSchemePreference,
9
+ getResolvedColorScheme,
9
10
  setColorSchemePreference,
10
11
  useColorSchemePreference,
12
+ useResolvedColorScheme,
11
13
  } from "./colorScheme.js";
12
14
  export { CardColumn, CardDetail, CardLabel, CardStep, CardStepList, ColorCard } from "./components/ColorCard/index.js";
13
15
  export { DateNavigator } from "./components/DateNavigator/index.js";
@@ -2,46 +2,7 @@ import { StyledEngineProvider, ThemeProvider } from "@mui/material";
2
2
  import { createTheme as muiCreateTheme } from "@mui/material/styles";
3
3
  import { type ReactNode, useEffect, useState } from "react";
4
4
 
5
- function getColorScheme(): "light" | "dark" {
6
- let scheme = document.body?.dataset.colorScheme ?? document.documentElement?.dataset.colorScheme ?? "light";
7
-
8
- if (scheme === "auto") {
9
- return globalThis.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";
10
- }
11
-
12
- return scheme === "dark" ? "dark" : "light";
13
- }
14
-
15
- /**
16
- * Tracks the color scheme Designsystemet is rendering with. The article template
17
- * sets `data-color-scheme` on `<body>`, so watch that attribute as well as the
18
- * OS preference (used when the scheme is `auto`).
19
- */
20
- function useColorScheme() {
21
- let [scheme, setScheme] = useState<"light" | "dark">(() => getColorScheme());
22
-
23
- useEffect(() => {
24
- function update() {
25
- setScheme(getColorScheme());
26
- }
27
-
28
- update();
29
-
30
- let observer = new MutationObserver(update);
31
- observer.observe(document.body, { attributes: true, attributeFilter: ["data-color-scheme"] });
32
- observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-color-scheme"] });
33
-
34
- let media = globalThis.matchMedia?.("(prefers-color-scheme: dark)");
35
- media?.addEventListener("change", update);
36
-
37
- return () => {
38
- observer.disconnect();
39
- media?.removeEventListener("change", update);
40
- };
41
- }, []);
42
-
43
- return scheme;
44
- }
5
+ import { useResolvedColorScheme as useColorScheme } from "../colorScheme.js";
45
6
 
46
7
  function buildMuiTheme(mode: "light" | "dark") {
47
8
  const s = getComputedStyle(document.body);