@openmrs/esm-implementer-tools-app 11.0.1-pre.6090 → 11.0.1-pre.6106

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.
@@ -1,79 +1,204 @@
1
- import React, { useCallback, useEffect, useState } from 'react';
1
+ import React, { useCallback, useEffect, useRef, useState } from 'react';
2
2
  import classNames from 'classnames';
3
- import AceEditor from 'react-ace';
3
+ import { isEqual, isPlainObject } from 'lodash-es';
4
+ import { basicSetup } from 'codemirror';
5
+ import { indentWithTab } from '@codemirror/commands';
6
+ import { json, jsonParseLinter } from '@codemirror/lang-json';
7
+ import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';
8
+ import { linter, lintGutter } from '@codemirror/lint';
9
+ import { EditorState, Prec } from '@codemirror/state';
10
+ import { EditorView, keymap } from '@codemirror/view';
11
+ import { tags } from '@lezer/highlight';
4
12
  import { Button } from '@carbon/react';
5
13
  import { useTranslation } from 'react-i18next';
6
14
  import { clearConfigErrors, temporaryConfigStore, useStore } from '@openmrs/esm-framework/src/internal';
7
15
  import styles from './json-editor.scss';
8
16
 
9
- import 'ace-builds/src-noconflict/mode-json';
10
- import 'ace-builds/src-noconflict/theme-dracula';
11
- import ace from 'ace-builds/src-noconflict/ace';
12
-
13
- // Configure ace to bundle workers locally (webpack 5 asset modules)
14
- // Using new URL() syntax instead of deprecated file-loader or CDN for offline compatibility
15
- ace.config.setModuleUrl(
16
- 'ace/mode/json_worker',
17
- new URL('ace-builds/src-noconflict/worker-json.js', import.meta.url).href,
18
- );
19
-
20
17
  export interface JsonEditorProps {
21
18
  /** A CSS value */
22
19
  height: string;
23
20
  }
24
21
 
22
+ /** Follows the surrounding Carbon theme through its CSS custom properties. */
23
+ const carbonTheme = EditorView.theme(
24
+ {
25
+ '&': {
26
+ backgroundColor: 'var(--cds-background)',
27
+ color: 'var(--cds-text-primary)',
28
+ fontSize: '1rem',
29
+ },
30
+ // Carbon's monospace stack, from @carbon/type.
31
+ '.cm-scroller': {
32
+ fontFamily: "'IBM Plex Mono', 'Menlo', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', Courier, monospace",
33
+ },
34
+ '.cm-content': { caretColor: 'var(--cds-text-primary)' },
35
+ '.cm-cursor, .cm-dropCursor': { borderLeftColor: 'var(--cds-text-primary)' },
36
+ '.cm-gutters': {
37
+ backgroundColor: 'var(--cds-layer-01)',
38
+ color: 'var(--cds-text-secondary)',
39
+ borderRight: '1px solid var(--cds-border-subtle-01)',
40
+ },
41
+ '.cm-activeLine': { backgroundColor: 'var(--cds-layer-hover-01)' },
42
+ '.cm-activeLineGutter': { backgroundColor: 'var(--cds-layer-hover-01)' },
43
+ '&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection': {
44
+ backgroundColor: 'var(--cds-highlight)',
45
+ },
46
+ '.cm-tooltip': {
47
+ backgroundColor: 'var(--cds-layer-02)',
48
+ color: 'var(--cds-text-primary)',
49
+ border: '1px solid var(--cds-border-subtle-01)',
50
+ },
51
+ },
52
+ { dark: true },
53
+ );
54
+
55
+ const jsonHighlighting = HighlightStyle.define([
56
+ { tag: tags.propertyName, class: styles.property },
57
+ { tag: tags.string, class: styles.string },
58
+ { tag: [tags.number, tags.bool, tags.null], class: styles.literal },
59
+ { tag: [tags.brace, tags.squareBracket, tags.separator, tags.punctuation], class: styles.punctuation },
60
+ ]);
61
+
62
+ function stringifyConfig(config: unknown) {
63
+ return JSON.stringify(config, null, 2);
64
+ }
65
+
66
+ /** Whether the editor's text already says the same thing as `config`, ignoring formatting. */
67
+ function representsConfig(text: string, config: unknown) {
68
+ try {
69
+ return isEqual(JSON.parse(text), config);
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+
25
75
  export default function JsonEditor({ height }: JsonEditorProps) {
26
76
  const { t } = useTranslation();
27
77
  const temporaryConfig = useStore(temporaryConfigStore);
28
- const [editorValue, setEditorValue] = useState('');
78
+ const containerRef = useRef<HTMLDivElement>(null);
79
+ const viewRef = useRef<EditorView | null>(null);
80
+ /** The text of the config the editor last loaded or submitted; any other text is unsubmitted edits. */
81
+ const savedTextRef = useRef('');
29
82
  const [error, setError] = useState('');
30
- const [key, setKey] = useState(`ace-editor`);
83
+ const [isChangedElsewhere, setIsChangedElsewhere] = useState(false);
31
84
 
32
85
  const updateTemporaryConfig = useCallback(() => {
86
+ const text = viewRef.current?.state.doc.toString() ?? '';
33
87
  let config;
34
88
  try {
35
- config = JSON.parse(editorValue);
89
+ config = JSON.parse(text);
36
90
  } catch (e) {
37
91
  setError(e instanceof Error ? e.message : 'Invalid JSON');
38
92
  return;
39
93
  }
94
+ if (!isPlainObject(config)) {
95
+ setError(t('configMustBeObject', 'The configuration must be a JSON object.'));
96
+ return;
97
+ }
40
98
  setError('');
41
99
  clearConfigErrors();
42
100
  temporaryConfigStore.setState({ config });
43
- }, [editorValue, temporaryConfig.config]);
101
+ }, [t]);
102
+
103
+ const loadConfig = useCallback((view: EditorView, config: unknown) => {
104
+ const text = stringifyConfig(config);
105
+ view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } });
106
+ savedTextRef.current = text;
107
+ setError('');
108
+ setIsChangedElsewhere(false);
109
+ }, []);
44
110
 
45
111
  useEffect(() => {
46
- if (editorValue != JSON.stringify(temporaryConfig.config, null, 2)) {
47
- setKey((k) => `${k}+`); // just keep appending plus signs
112
+ if (!containerRef.current) {
113
+ return;
114
+ }
115
+
116
+ savedTextRef.current = stringifyConfig(temporaryConfigStore.getState().config);
117
+ const view = new EditorView({
118
+ parent: containerRef.current,
119
+ state: EditorState.create({
120
+ doc: savedTextRef.current,
121
+ extensions: [
122
+ basicSetup,
123
+ keymap.of([indentWithTab]),
124
+ // Outranks the default keymap, which binds Mod-Enter to inserting a blank line.
125
+ Prec.highest(
126
+ keymap.of([
127
+ {
128
+ key: 'Mod-Enter',
129
+ run: () => {
130
+ updateTemporaryConfig();
131
+ return true;
132
+ },
133
+ },
134
+ ]),
135
+ ),
136
+ json(),
137
+ linter(jsonParseLinter()),
138
+ lintGutter(),
139
+ syntaxHighlighting(jsonHighlighting),
140
+ carbonTheme,
141
+ EditorState.tabSize.of(2),
142
+ EditorView.contentAttributes.of({ 'aria-label': t('jsonConfigEditor', 'JSON configuration editor') }),
143
+ ],
144
+ }),
145
+ });
146
+ viewRef.current = view;
147
+
148
+ return () => {
149
+ view.destroy();
150
+ viewRef.current = null;
151
+ };
152
+ // The editor owns its document after creation; later config changes are applied by the effect below.
153
+ }, []);
154
+
155
+ // Shows config changes made elsewhere, unless that would throw away unsubmitted edits, in which
156
+ // case the user is offered the choice instead.
157
+ useEffect(() => {
158
+ const view = viewRef.current;
159
+ if (!view) {
160
+ return;
161
+ }
162
+
163
+ const text = view.state.doc.toString();
164
+ if (representsConfig(text, temporaryConfig.config)) {
165
+ savedTextRef.current = text;
166
+ setIsChangedElsewhere(false);
167
+ } else if (text === savedTextRef.current) {
168
+ loadConfig(view, temporaryConfig.config);
169
+ } else {
170
+ setIsChangedElsewhere(true);
48
171
  }
49
- }, [temporaryConfig.config]);
172
+ }, [temporaryConfig.config, loadConfig]);
50
173
 
51
174
  return (
52
175
  <div>
53
- <AceEditor
54
- defaultValue={JSON.stringify(temporaryConfig.config, null, 2)}
55
- fontSize="1rem"
56
- height={`calc(${height} - 3rem)`}
57
- key={key}
58
- mode="json"
59
- onChange={(v) => setEditorValue(v)}
60
- showGutter
61
- showPrintMargin={false}
62
- tabSize={2}
63
- theme="dracula"
64
- width="100vw"
65
- />
176
+ <div className={styles.editor} ref={containerRef} style={{ height: `calc(${height} - 3rem)` }} />
66
177
  <div className={styles.toolbar}>
67
178
  <Button size="md" type="submit" onClick={updateTemporaryConfig}>
68
179
  {t('updateConfig', 'Update config')}
69
180
  </Button>
70
- <div
71
- className={classNames(styles.alert, {
72
- [styles.errorBackground]: error,
73
- })}
74
- >
75
- {error}
76
- </div>
181
+ {error || !isChangedElsewhere ? (
182
+ <div
183
+ className={classNames(styles.alert, {
184
+ [styles.errorBackground]: error,
185
+ })}
186
+ >
187
+ {error}
188
+ </div>
189
+ ) : null}
190
+ {isChangedElsewhere ? (
191
+ <div className={classNames(styles.alert, styles.warningBackground)}>
192
+ {t('configChangedElsewhere', 'The configuration was changed elsewhere.')}
193
+ <Button
194
+ kind="ghost"
195
+ size="md"
196
+ onClick={() => viewRef.current && loadConfig(viewRef.current, temporaryConfigStore.getState().config)}
197
+ >
198
+ {t('discardEditsAndReload', 'Discard my edits and reload')}
199
+ </Button>
200
+ </div>
201
+ ) : null}
77
202
  </div>
78
203
  </div>
79
204
  );
@@ -4,9 +4,34 @@
4
4
  // `.../components/button` would emit Carbon's entire button stylesheet; the tokens module emits none.
5
5
  @use '@carbon/styles/scss/components/button/tokens' as button;
6
6
 
7
+ .editor {
8
+ width: 100vw;
9
+
10
+ :global(.cm-editor) {
11
+ height: 100%;
12
+ }
13
+ }
14
+
15
+ // Syntax colours for the dark theme the tools use; Carbon has no syntax tokens.
16
+ .property {
17
+ color: colors.$cyan-30;
18
+ }
19
+
20
+ .string {
21
+ color: colors.$green-30;
22
+ }
23
+
24
+ .literal {
25
+ color: colors.$purple-30;
26
+ }
27
+
28
+ .punctuation {
29
+ color: colors.$gray-30;
30
+ }
31
+
7
32
  .toolbar {
8
33
  display: flex;
9
- button {
34
+ > button {
10
35
  background-color: button.$button-primary;
11
36
  &:hover {
12
37
  background-color: button.$button-primary-hover;
@@ -26,3 +51,13 @@
26
51
  .errorBackground {
27
52
  background-color: colors.$red-60;
28
53
  }
54
+
55
+ .warningBackground {
56
+ background-color: colors.$yellow-30;
57
+ color: colors.$gray-100;
58
+ justify-content: space-between;
59
+
60
+ :global(.cds--btn--ghost) {
61
+ color: colors.$gray-100;
62
+ }
63
+ }
@@ -0,0 +1,111 @@
1
+ import React, { act } from 'react';
2
+ import { beforeEach, describe, expect, it } from 'vitest';
3
+ import '@testing-library/jest-dom/vitest';
4
+ import { fireEvent, render, screen } from '@testing-library/react';
5
+ import userEvent from '@testing-library/user-event';
6
+ import { EditorView } from '@codemirror/view';
7
+ import { clearConfigErrors, temporaryConfigStore } from '@openmrs/esm-framework/src/internal';
8
+ import JsonEditor from './json-editor.component';
9
+
10
+ function getEditorText(container: HTMLElement) {
11
+ return Array.from(container.querySelectorAll('.cm-line'), (line) => line.textContent).join('\n');
12
+ }
13
+
14
+ function setEditorText(text: string) {
15
+ const view = EditorView.findFromDOM(screen.getByRole('textbox', { name: /json configuration editor/i }))!;
16
+ act(() => view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } }));
17
+ }
18
+
19
+ describe('JsonEditor', () => {
20
+ beforeEach(() => {
21
+ temporaryConfigStore.setState({ config: {} });
22
+ });
23
+
24
+ it('submits the config it was opened with when nothing has been edited', async () => {
25
+ const user = userEvent.setup();
26
+ const config = { '@openmrs/esm-login-app': { logo: { src: 'logo.png' } } };
27
+ temporaryConfigStore.setState({ config });
28
+
29
+ render(<JsonEditor height="20rem" />);
30
+ await user.click(screen.getByRole('button', { name: /update config/i }));
31
+
32
+ expect(clearConfigErrors).toHaveBeenCalled();
33
+ expect(screen.queryByText(/JSON/)).not.toBeInTheDocument();
34
+ expect(temporaryConfigStore.getState().config).toEqual(config);
35
+ });
36
+
37
+ it.each(['null', '[]', '"text"', '42'])('rejects %s, which is not a config object', async (text) => {
38
+ const user = userEvent.setup();
39
+ const config = { '@openmrs/esm-login-app': { chooseLocation: false } };
40
+ temporaryConfigStore.setState({ config });
41
+ render(<JsonEditor height="20rem" />);
42
+
43
+ setEditorText(text);
44
+ await user.click(screen.getByRole('button', { name: /update config/i }));
45
+
46
+ expect(temporaryConfigStore.getState().config).toEqual(config);
47
+ expect(screen.getByText('The configuration must be a JSON object.')).toBeInTheDocument();
48
+ });
49
+
50
+ it('submits on Mod-Enter', () => {
51
+ temporaryConfigStore.setState({ config: { '@openmrs/esm-login-app': {} } });
52
+ const { container } = render(<JsonEditor height="20rem" />);
53
+ const modifier = /Mac/.test(navigator.platform) ? { metaKey: true } : { ctrlKey: true };
54
+
55
+ fireEvent.keyDown(screen.getByRole('textbox', { name: /json configuration editor/i }), {
56
+ key: 'Enter',
57
+ keyCode: 13,
58
+ ...modifier,
59
+ });
60
+
61
+ expect(clearConfigErrors).toHaveBeenCalled();
62
+ expect(getEditorText(container)).not.toMatch(/^\s*$/m);
63
+ });
64
+
65
+ it('shows config changes made elsewhere', () => {
66
+ temporaryConfigStore.setState({ config: {} });
67
+ const { container } = render(<JsonEditor height="20rem" />);
68
+
69
+ act(() => temporaryConfigStore.setState({ config: { '@openmrs/esm-login-app': { chooseLocation: false } } }));
70
+
71
+ expect(JSON.parse(getEditorText(container))).toEqual({ '@openmrs/esm-login-app': { chooseLocation: false } });
72
+ });
73
+
74
+ it('keeps unsubmitted edits when the config is changed elsewhere', () => {
75
+ const { container } = render(<JsonEditor height="20rem" />);
76
+
77
+ setEditorText('{\n "@openmrs/esm-login-app": { "logo": { "src": "draft.png" } }\n}');
78
+ act(() => temporaryConfigStore.setState({ config: { '@openmrs/esm-home-app': {} } }));
79
+
80
+ expect(getEditorText(container)).toContain('draft.png');
81
+ expect(screen.getByText('The configuration was changed elsewhere.')).toBeInTheDocument();
82
+ });
83
+
84
+ it('replaces unsubmitted edits, and the parse error they caused, on reload', async () => {
85
+ const user = userEvent.setup();
86
+ const { container } = render(<JsonEditor height="20rem" />);
87
+
88
+ setEditorText('{"@openmrs/esm-login-app": ');
89
+ await user.click(screen.getByRole('button', { name: /update config/i }));
90
+ expect(screen.getByText(/JSON/)).toBeInTheDocument();
91
+
92
+ act(() => temporaryConfigStore.setState({ config: { '@openmrs/esm-login-app': { chooseLocation: false } } }));
93
+ await user.click(screen.getByRole('button', { name: 'Discard my edits and reload' }));
94
+
95
+ expect(JSON.parse(getEditorText(container))).toEqual({ '@openmrs/esm-login-app': { chooseLocation: false } });
96
+ expect(screen.queryByText(/JSON/)).not.toBeInTheDocument();
97
+ expect(screen.queryByText('The configuration was changed elsewhere.')).not.toBeInTheDocument();
98
+ });
99
+
100
+ it('submits unsubmitted edits over a config changed elsewhere', async () => {
101
+ const user = userEvent.setup();
102
+ render(<JsonEditor height="20rem" />);
103
+
104
+ setEditorText('{ "@openmrs/esm-login-app": { "chooseLocation": true } }');
105
+ act(() => temporaryConfigStore.setState({ config: { '@openmrs/esm-home-app': {} } }));
106
+ await user.click(screen.getByRole('button', { name: /update config/i }));
107
+
108
+ expect(temporaryConfigStore.getState().config).toEqual({ '@openmrs/esm-login-app': { chooseLocation: true } });
109
+ expect(screen.queryByText('The configuration was changed elsewhere.')).not.toBeInTheDocument();
110
+ });
111
+ });
@@ -8,8 +8,10 @@
8
8
  "checkImplementerToolsMessage": "Check the Backend Modules tab in the Implementer Tools for more details",
9
9
  "clearConfig": "Clear local config",
10
10
  "close": "Close",
11
+ "configChangedElsewhere": "The configuration was changed elsewhere.",
11
12
  "configDerivationFailed": "This configuration is out of date",
12
13
  "configDerivationFailedSubtitle": "The configuration could not be rebuilt, so what is shown below is the last version that did build.",
14
+ "configMustBeObject": "The configuration must be a JSON object.",
13
15
  "configuration": "Configuration",
14
16
  "copied": "Copied",
15
17
  "copyNeedsHttps": "Copying needs the page to be served over HTTPS",
@@ -18,6 +20,7 @@
18
20
  "couldNotLoadLanguage": "Could not load translations for this language.",
19
21
  "couldNotLoadNamespace": "Could not load this module’s translations.",
20
22
  "description": "Description",
23
+ "discardEditsAndReload": "Discard my edits and reload",
21
24
  "downloadConfig": "Download config",
22
25
  "downloadForTransifex": "Download for Transifex",
23
26
  "downloadOverrides": "Download overrides",
@@ -33,6 +36,7 @@
33
36
  "implementerTools": "Implementer Tools",
34
37
  "installedVersion": "Installed version",
35
38
  "itemDescriptionSourceDefaultText": "The current value is the default.",
39
+ "jsonConfigEditor": "JSON configuration editor",
36
40
  "jsonEditor": "JSON editor",
37
41
  "loading": "Loading",
38
42
  "loadingTranslations": "Loading translations…",