@openmrs/esm-implementer-tools-app 11.0.1-pre.6015 → 11.0.1-pre.6024

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,74 @@
1
+ @use '@carbon/colors';
2
+ @use '@carbon/layout';
3
+ @use '@carbon/react/scss/themes';
4
+ @use '@carbon/react/scss/theme';
5
+ @use '@carbon/type';
6
+
7
+ /**
8
+ * The purple accent is not a theme token on purpose: it is how the inspector's highlight stays
9
+ * distinguishable from the UI editor's blue and green slot overlays when both modes are on.
10
+ */
11
+ $accent: colors.$purple-60;
12
+
13
+ .highlight {
14
+ position: fixed;
15
+ z-index: 99998;
16
+ pointer-events: none;
17
+ border: 1px dashed rgba($accent, 0.9);
18
+ background-color: rgba($accent, 0.1);
19
+ }
20
+
21
+ .card {
22
+ position: fixed;
23
+ z-index: 99999;
24
+ width: 20rem;
25
+ max-height: 13rem;
26
+ overflow-y: auto;
27
+ padding: layout.$spacing-03 layout.$spacing-04;
28
+ background-color: theme.$background;
29
+ border: 1px solid rgba($accent, 0.8);
30
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
31
+ color: theme.$text-primary;
32
+
33
+ /**
34
+ * The card floats over the application rather than sitting in the tools' own panel, so it carries
35
+ * the white theme's tokens; inheriting the surrounding `.darkTheme` put g90's near-white text on
36
+ * this light surface. The mixin emits nested rules, so it goes last to keep Sass from warning
37
+ * about declarations following them.
38
+ */
39
+ @include theme.theme(themes.$white);
40
+ }
41
+
42
+ /**
43
+ * Sits below the UI editor's exit button, which is at `layout.$spacing-10`, so that both stay
44
+ * reachable when both modes are on.
45
+ */
46
+ .exitButton {
47
+ position: fixed !important;
48
+ top: calc(#{layout.$spacing-10} + #{layout.$spacing-08});
49
+ right: layout.$spacing-05;
50
+ z-index: 999999;
51
+ }
52
+
53
+ .sighting + .sighting {
54
+ margin-top: layout.$spacing-03;
55
+ border-top: 1px solid theme.$border-subtle-01;
56
+ padding-top: layout.$spacing-03;
57
+ }
58
+
59
+ .key {
60
+ @include type.type-style('code-01');
61
+ color: theme.$text-primary;
62
+ word-break: break-all;
63
+ }
64
+
65
+ .namespace {
66
+ @include type.type-style('label-01');
67
+ color: theme.$text-secondary;
68
+ word-break: break-all;
69
+ }
70
+
71
+ .note {
72
+ @include type.type-style('label-01');
73
+ color: theme.$text-secondary;
74
+ }
@@ -0,0 +1,197 @@
1
+ import React, { Profiler } from 'react';
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import '@testing-library/jest-dom/vitest';
4
+ import { act, fireEvent, render, screen } from '@testing-library/react';
5
+ import {
6
+ disableTranslationInspector,
7
+ enableTranslationInspector,
8
+ matchTranslations,
9
+ type TranslationSighting,
10
+ } from '@openmrs/esm-framework/src/internal';
11
+ import { implementerToolsStore } from '../store';
12
+ import TranslationInspector, { getCardPosition } from './translation-inspector';
13
+
14
+ const rect = (top: number, height: number, left = 0) => ({ top, bottom: top + height, left }) as DOMRect;
15
+
16
+ describe('getCardPosition', () => {
17
+ beforeEach(() => {
18
+ Object.assign(window, { innerHeight: 900, innerWidth: 1400 });
19
+ });
20
+
21
+ it('places the card below an element with room beneath it', () => {
22
+ expect(getCardPosition(rect(100, 20))).toEqual({ top: 120, left: 0 });
23
+ });
24
+
25
+ it('places the card above an element near the bottom of the screen', () => {
26
+ expect(getCardPosition(rect(800, 20))).toEqual({ bottom: 100, left: 0 });
27
+ });
28
+
29
+ it('keeps the card on screen for an element too tall for either', () => {
30
+ // The left nav: from just under the header to the bottom of the screen.
31
+ expect(getCardPosition(rect(48, 852))).toEqual({ top: 52, left: 0 });
32
+ expect(getCardPosition(rect(-200, 1200))).toEqual({ top: 4, left: 0 });
33
+ });
34
+
35
+ it('keeps the card inside the right edge', () => {
36
+ expect(getCardPosition(rect(100, 20, 1300))).toEqual({ top: 120, left: 1080 });
37
+ });
38
+ });
39
+
40
+ describe('TranslationInspector', () => {
41
+ const loginButton: TranslationSighting = {
42
+ namespace: '@openmrs/esm-login-app',
43
+ key: 'loginButton',
44
+ value: 'Log in',
45
+ hasCount: false,
46
+ };
47
+ let underPointer: Element | null = null;
48
+
49
+ beforeEach(() => {
50
+ vi.useFakeTimers();
51
+ vi.mocked(matchTranslations).mockImplementation((text: string) => (text.trim() === 'Log in' ? [loginButton] : []));
52
+ document.elementFromPoint = vi.fn(() => underPointer);
53
+ });
54
+
55
+ afterEach(() => {
56
+ vi.useRealTimers();
57
+ underPointer = null;
58
+ });
59
+
60
+ /** Moves the pointer onto an element, past the inspector's throttle. */
61
+ function hover(element: Element) {
62
+ underPointer = element;
63
+ act(() => vi.advanceTimersByTime(200));
64
+ fireEvent.mouseMove(document, { clientX: 1, clientY: 1 });
65
+ }
66
+
67
+ it('records only while it is mounted', () => {
68
+ const { unmount } = render(<TranslationInspector />);
69
+ expect(enableTranslationInspector).toHaveBeenCalled();
70
+
71
+ unmount();
72
+ expect(disableTranslationInspector).toHaveBeenCalled();
73
+ });
74
+
75
+ it('keeps the card while the pointer is on it, so that its buttons can be used', () => {
76
+ const app = document.createElement('button');
77
+ app.textContent = 'Log in';
78
+ document.body.appendChild(app);
79
+
80
+ render(<TranslationInspector />);
81
+
82
+ hover(app);
83
+ expect(screen.getByText('loginButton')).toBeInTheDocument();
84
+
85
+ // Text the card itself shows is not a translation, so retargeting onto it would close the card.
86
+ hover(screen.getByText('loginButton'));
87
+ const showInTranslations = screen.getByRole('button', { name: /show in translations/i });
88
+
89
+ fireEvent.click(showInTranslations);
90
+
91
+ expect(implementerToolsStore.getState()).toMatchObject({
92
+ isOpen: true,
93
+ openTab: 'translations',
94
+ selectedTranslation: { namespace: '@openmrs/esm-login-app', key: 'loginButton', value: 'Log in' },
95
+ });
96
+ app.remove();
97
+ });
98
+
99
+ it('keeps the card while the pointer crosses from the element onto it', () => {
100
+ const app = document.createElement('button');
101
+ app.textContent = 'Log in';
102
+ document.body.appendChild(app);
103
+ const appRect = { top: 100, bottom: 120, left: 0, right: 100, width: 100, height: 20 } as DOMRect;
104
+ app.getBoundingClientRect = () => appRect;
105
+ const cardTop = getCardPosition(appRect).top as number;
106
+ // Whatever is under each point: the element, then the card below it, with the page in between.
107
+ document.elementFromPoint = vi.fn((_x: number, y: number) =>
108
+ y < appRect.bottom ? app : y >= cardTop ? (screen.queryByText('loginButton') ?? document.body) : document.body,
109
+ );
110
+
111
+ render(<TranslationInspector />);
112
+
113
+ for (let y = 110; y <= cardTop + 5; y++) {
114
+ act(() => vi.advanceTimersByTime(200));
115
+ fireEvent.mouseMove(document, { clientX: 10, clientY: y });
116
+ }
117
+
118
+ expect(screen.getByText('loginButton')).toBeInTheDocument();
119
+ app.remove();
120
+ });
121
+
122
+ it('retargets when content scrolls under a still pointer', () => {
123
+ const app = document.createElement('button');
124
+ app.textContent = 'Log in';
125
+ const scroller = document.createElement('div');
126
+ scroller.appendChild(app);
127
+ document.body.appendChild(scroller);
128
+
129
+ render(<TranslationInspector />);
130
+
131
+ hover(app);
132
+ expect(screen.getByText('loginButton')).toBeInTheDocument();
133
+
134
+ // The button scrolls away inside its container, leaving untranslated content under the pointer.
135
+ underPointer = document.body;
136
+ act(() => vi.advanceTimersByTime(200));
137
+ fireEvent.scroll(scroller);
138
+
139
+ expect(screen.queryByText('loginButton')).not.toBeInTheDocument();
140
+ scroller.remove();
141
+ });
142
+
143
+ it('offers a way out even when nothing is hovered', () => {
144
+ implementerToolsStore.setState({ isTranslationInspectorEnabled: true });
145
+ render(<TranslationInspector />);
146
+
147
+ fireEvent.click(screen.getByRole('button', { name: /exit translation inspector/i }));
148
+
149
+ expect(implementerToolsStore.getState().isTranslationInspectorEnabled).toBe(false);
150
+ });
151
+
152
+ it('does not re-render while the pointer rests on the same text', () => {
153
+ const app = document.createElement('button');
154
+ app.textContent = 'Log in';
155
+ document.body.appendChild(app);
156
+ const onRender = vi.fn();
157
+
158
+ render(
159
+ <Profiler id="inspector" onRender={onRender}>
160
+ <TranslationInspector />
161
+ </Profiler>,
162
+ );
163
+
164
+ // React may render once more before it starts bailing out of an unchanged state.
165
+ hover(app);
166
+ hover(app);
167
+ const renders = onRender.mock.calls.length;
168
+
169
+ for (let sample = 0; sample < 5; sample++) {
170
+ hover(app);
171
+ }
172
+
173
+ expect(onRender).toHaveBeenCalledTimes(renders);
174
+ app.remove();
175
+ });
176
+
177
+ it('follows the element when it scrolls but stays under the pointer', () => {
178
+ const app = document.createElement('button');
179
+ app.textContent = 'Log in';
180
+ document.body.appendChild(app);
181
+ let top = 100;
182
+ app.getBoundingClientRect = () =>
183
+ ({ top, bottom: top + 20, left: 0, right: 100, width: 100, height: 20 }) as DOMRect;
184
+
185
+ const { container } = render(<TranslationInspector />);
186
+ hover(app);
187
+
188
+ top = 90;
189
+ act(() => vi.advanceTimersByTime(200));
190
+ fireEvent.scroll(document);
191
+
192
+ // The highlight is decoration, with no role to query it by.
193
+ // eslint-disable-next-line testing-library/no-container, testing-library/no-node-access
194
+ expect(container.querySelector<HTMLElement>('[style*="height"]')?.style.top).toBe('90px');
195
+ app.remove();
196
+ });
197
+ });
@@ -0,0 +1,210 @@
1
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
2
+ import { useTranslation } from 'react-i18next';
3
+ import { isEqual, throttle } from 'lodash-es';
4
+ import { Button } from '@carbon/react';
5
+ import {
6
+ CloseIcon,
7
+ disableTranslationInspector,
8
+ enableTranslationInspector,
9
+ type TranslationSighting,
10
+ useStoreWithActions,
11
+ } from '@openmrs/esm-framework/src/internal';
12
+ import { type ImplementerToolsStore, implementerToolsStore } from '../store';
13
+ import { findTranslatedText, type InspectionTarget } from './find-translated-text';
14
+ import styles from './translation-inspector.styles.scss';
15
+
16
+ /** How often the pointer position is turned into a lookup. */
17
+ const inspectionIntervalMs = 100;
18
+
19
+ interface Inspection extends InspectionTarget {
20
+ /** Where the element was when inspected. */
21
+ rect: DOMRect;
22
+ }
23
+
24
+ /**
25
+ * Lets the user hover any text in the application and see which translation key produced it.
26
+ *
27
+ * Recording only runs while this component is mounted, and mounting it is gated on the user turning
28
+ * the inspector on in the implementer tools.
29
+ */
30
+ export default function TranslationInspector() {
31
+ const { t } = useTranslation();
32
+ const [target, setTarget] = useState<Inspection | null>(null);
33
+ const cardRef = useRef<HTMLDivElement>(null);
34
+
35
+ useEffect(() => {
36
+ enableTranslationInspector();
37
+ return () => disableTranslationInspector();
38
+ }, []);
39
+
40
+ const inspectAt = useMemo(
41
+ () =>
42
+ throttle((clientX: number, clientY: number) => {
43
+ const element = document.elementFromPoint(clientX, clientY);
44
+
45
+ // Leave the target alone while the pointer is over the inspector's own card, so that the
46
+ // card can be read and its buttons used without it retargeting from under the pointer.
47
+ if (!element || cardRef.current?.contains(element)) {
48
+ return;
49
+ }
50
+
51
+ const found = findTranslatedText(element);
52
+ const next = found && { ...found, rect: found.element.getBoundingClientRect() };
53
+
54
+ // Keeps the current target while nothing about it changed, so that resting the pointer on a
55
+ // label doesn't re-render on every sample.
56
+ setTarget((current) => (isSameInspection(current, next) ? current : next));
57
+ }, inspectionIntervalMs),
58
+ [],
59
+ );
60
+
61
+ useEffect(() => {
62
+ let pointer: { x: number; y: number } | null = null;
63
+ const handleMouseMove = (event: MouseEvent) => {
64
+ pointer = { x: event.clientX, y: event.clientY };
65
+ inspectAt(pointer.x, pointer.y);
66
+ };
67
+ // Scrolling moves content under a still pointer. Captured so that nested containers count too.
68
+ const handleScroll = () => pointer && inspectAt(pointer.x, pointer.y);
69
+
70
+ document.addEventListener('mousemove', handleMouseMove);
71
+ window.addEventListener('scroll', handleScroll, { capture: true, passive: true });
72
+
73
+ return () => {
74
+ document.removeEventListener('mousemove', handleMouseMove);
75
+ window.removeEventListener('scroll', handleScroll, { capture: true });
76
+ inspectAt.cancel();
77
+ };
78
+ }, [inspectAt]);
79
+
80
+ const showInTranslationsTab = useCallback((sighting: TranslationSighting) => {
81
+ implementerToolsStore.setState((state) => ({
82
+ ...state,
83
+ isOpen: true,
84
+ openTab: 'translations',
85
+ selectedTranslation: { namespace: sighting.namespace, key: sighting.key, value: sighting.value },
86
+ }));
87
+ }, []);
88
+
89
+ if (!target) {
90
+ return <ExitButton />;
91
+ }
92
+
93
+ const { rect } = target;
94
+
95
+ return (
96
+ <>
97
+ <ExitButton />
98
+ <div
99
+ className={styles.highlight}
100
+ style={{ top: rect.top, left: rect.left, width: rect.width, height: rect.height }}
101
+ />
102
+ {/* Moving the pointer onto the card stops it retargeting, so its buttons stay reachable. */}
103
+ <div className={styles.card} ref={cardRef} style={getCardPosition(rect)}>
104
+ {target.sightings.map((sighting) => (
105
+ <div className={styles.sighting} key={`${sighting.extensionNamespace ?? sighting.namespace}|${sighting.key}`}>
106
+ <p className={styles.key}>{sighting.key}</p>
107
+ <p className={styles.namespace}>{sighting.namespace}</p>
108
+ {sighting.extensionNamespace ? (
109
+ <p className={styles.note}>
110
+ {t('renderedInExtension', 'Rendered through {{namespace}}', {
111
+ namespace: sighting.extensionNamespace,
112
+ // Namespaces are module names, so they contain slashes, which i18next would
113
+ // otherwise escape to HTML entities that React renders as literal text.
114
+ interpolation: { escapeValue: false },
115
+ })}
116
+ </p>
117
+ ) : null}
118
+ {sighting.hasCount ? (
119
+ <p className={styles.note}>
120
+ {t('pluralKeyNote', 'This is one plural form; other counts render through other forms of the key.')}
121
+ </p>
122
+ ) : null}
123
+ {target.attribute ? (
124
+ <p className={styles.note}>
125
+ {t('renderedInAttribute', 'Rendered as the {{attribute}} attribute', {
126
+ attribute: target.attribute,
127
+ interpolation: { escapeValue: false },
128
+ })}
129
+ </p>
130
+ ) : null}
131
+ <Button kind="ghost" onClick={() => showInTranslationsTab(sighting)} size="sm">
132
+ {t('showInTranslations', 'Show in Translations')}
133
+ </Button>
134
+ </div>
135
+ ))}
136
+ {target.sightings.length > 1 ? (
137
+ <p className={styles.note}>
138
+ {t('multipleKeysNote', 'Several keys render this same text; all of them are listed.')}
139
+ </p>
140
+ ) : null}
141
+ </div>
142
+ </>
143
+ );
144
+ }
145
+
146
+ /** Turns the inspector off, which otherwise stays on across reloads until switched off in the Translations tab. */
147
+ function ExitButton() {
148
+ const { t } = useTranslation();
149
+ const { toggleIsTranslationInspectorEnabled } = useStoreWithActions(implementerToolsStore, actions);
150
+
151
+ return (
152
+ <Button
153
+ className={styles.exitButton}
154
+ hasIconOnly
155
+ iconDescription={t('exitTranslationInspector', 'Exit translation inspector')}
156
+ kind="danger"
157
+ onClick={toggleIsTranslationInspectorEnabled}
158
+ renderIcon={(props) => <CloseIcon {...props} size={16} />}
159
+ size="sm"
160
+ tooltipPosition="left"
161
+ />
162
+ );
163
+ }
164
+
165
+ const actions = {
166
+ toggleIsTranslationInspectorEnabled({ isTranslationInspectorEnabled }: ImplementerToolsStore) {
167
+ return { isTranslationInspectorEnabled: !isTranslationInspectorEnabled };
168
+ },
169
+ };
170
+
171
+ function isSameInspection(current: Inspection | null, next: Inspection | null): boolean {
172
+ if (!current || !next) {
173
+ return current === next;
174
+ }
175
+
176
+ return (
177
+ current.element === next.element &&
178
+ current.attribute === next.attribute &&
179
+ ['top', 'left', 'width', 'height'].every(
180
+ (side) => current.rect[side as keyof DOMRect] === next.rect[side as keyof DOMRect],
181
+ ) &&
182
+ current.sightings.length === next.sightings.length &&
183
+ current.sightings.every((sighting, index) => isEqual(sighting, next.sightings[index]))
184
+ );
185
+ }
186
+
187
+ /** The card's maximum height, from its styles, plus a margin. */
188
+ const cardHeight = 220;
189
+ const cardWidth = 320;
190
+
191
+ /**
192
+ * Places the card just below the inspected element, or above it when there is no room below. An
193
+ * element too tall for either, such as a full-height sidebar, gets the card over its top instead.
194
+ *
195
+ * The card touches the element: any gap between them is background the pointer has to cross on its
196
+ * way to the card, which would retarget and close it.
197
+ */
198
+ export function getCardPosition(rect: DOMRect): React.CSSProperties {
199
+ const left = Math.max(0, Math.min(rect.left, window.innerWidth - cardWidth));
200
+
201
+ if (window.innerHeight - rect.bottom > cardHeight) {
202
+ return { top: rect.bottom, left };
203
+ }
204
+
205
+ if (rect.top > cardHeight) {
206
+ return { bottom: window.innerHeight - rect.top, left };
207
+ }
208
+
209
+ return { top: Math.max(rect.top, 0) + 4, left };
210
+ }
@@ -24,6 +24,7 @@
24
24
  "edit": "Edit",
25
25
  "editValueButtonText": "Edit",
26
26
  "enabled": "Enabled",
27
+ "exitTranslationInspector": "Exit translation inspector",
27
28
  "exitUIEditor": "Exit UI Editor",
28
29
  "extensions": "Extensions",
29
30
  "featureFlag": "Feature flag",
@@ -38,6 +39,7 @@
38
39
  "missing": "Missing",
39
40
  "moduleName": "Module name",
40
41
  "modulesWithMissingDependenciesWarning": "Some modules have unresolved backend dependencies",
42
+ "multipleKeysNote": "Several keys render this same text; all of them are listed.",
41
43
  "namespaceHasNoTranslations": "This module has no translations for this language.",
42
44
  "namespaceNotLoaded": "{{module}} (not loaded)",
43
45
  "noChangesToExport": "No changes have been made to this namespace in this language.",
@@ -52,6 +54,9 @@
52
54
  "overrideResetNotApplied": "The override was removed but could not be applied. Reload the page to see it.",
53
55
  "overrideSavedNotApplied": "The override was saved but could not be applied. Reload the page to see it.",
54
56
  "pickNamespaceToExport": "Pick a namespace to export the changes made to it.",
57
+ "pluralKeyNote": "This is one plural form; other counts render through other forms of the key.",
58
+ "renderedInAttribute": "Rendered as the {{attribute}} attribute",
59
+ "renderedInExtension": "Rendered through {{namespace}}",
55
60
  "requiredVersion": "Required Version",
56
61
  "resetToDefaultValueButtonText": "Reset to default",
57
62
  "searchConceptHelperText": "Search concepts",
@@ -59,6 +64,7 @@
59
64
  "searching": "Searching",
60
65
  "searchPersonAttributeHelperText": "Person attribute type name",
61
66
  "searchTranslations": "Search translations by key or text",
67
+ "showInTranslations": "Show in Translations",
62
68
  "sourceLanguageNotExportable": "English is the source language in Transifex; change it in the app’s en.json instead.",
63
69
  "stringValidationMessage": "Value must be a string",
64
70
  "toggleImplementerTools": "Toggle Implementer Tools",