@openmrs/esm-implementer-tools-app 11.0.1-pre.6014 → 11.0.1-pre.6018

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.
Files changed (66) hide show
  1. package/.turbo/turbo-build.log +4 -4
  2. package/dist/1558.css +1 -0
  3. package/dist/{8088.css.map → 1558.css.map} +1 -1
  4. package/dist/1558.js +1 -0
  5. package/dist/1558.js.map +1 -0
  6. package/dist/1944.js +1 -0
  7. package/dist/1944.js.map +1 -0
  8. package/dist/{6479.css.map → 2989.css.map} +1 -1
  9. package/dist/2989.js +1 -0
  10. package/dist/2989.js.map +1 -0
  11. package/dist/4540.js +1 -0
  12. package/dist/4540.js.map +1 -0
  13. package/dist/{4698.js → 4938.js} +1 -1
  14. package/dist/4938.js.map +1 -0
  15. package/dist/5117.js +1 -1
  16. package/dist/5117.js.map +1 -1
  17. package/dist/5822.js +1 -0
  18. package/dist/5822.js.map +1 -0
  19. package/dist/61.css +1 -0
  20. package/dist/61.css.map +1 -0
  21. package/dist/61.js +1 -0
  22. package/dist/61.js.map +1 -0
  23. package/dist/6977.js +15 -0
  24. package/dist/6977.js.map +1 -0
  25. package/dist/7218.js +1 -0
  26. package/dist/7218.js.map +1 -0
  27. package/dist/8978.js +1 -0
  28. package/dist/8978.js.map +1 -0
  29. package/dist/932.js +1 -1
  30. package/dist/932.js.map +1 -1
  31. package/dist/openmrs-esm-implementer-tools-app.js +2 -2
  32. package/dist/openmrs-esm-implementer-tools-app.js.map +1 -1
  33. package/dist/routes.json +1 -1
  34. package/package.json +3 -3
  35. package/src/implementer-tools.component.tsx +3 -1
  36. package/src/implementer-tools.test.tsx +38 -2
  37. package/src/popup/popup.component.tsx +3 -0
  38. package/src/popup/popup.test.tsx +2 -1
  39. package/src/store.ts +30 -1
  40. package/src/translation-inspector/find-translated-text.test.ts +75 -0
  41. package/src/translation-inspector/find-translated-text.ts +87 -0
  42. package/src/translation-inspector/translation-inspector.styles.scss +74 -0
  43. package/src/translation-inspector/translation-inspector.test.tsx +197 -0
  44. package/src/translation-inspector/translation-inspector.tsx +210 -0
  45. package/src/translations/translation-catalog.ts +14 -4
  46. package/src/translations/translations.component.tsx +696 -0
  47. package/src/translations/translations.styles.scss +133 -0
  48. package/src/translations/translations.test.tsx +839 -0
  49. package/translations/en.json +40 -0
  50. package/dist/1492.js +0 -1
  51. package/dist/1492.js.map +0 -1
  52. package/dist/1695.js +0 -1
  53. package/dist/1695.js.map +0 -1
  54. package/dist/195.js +0 -15
  55. package/dist/195.js.map +0 -1
  56. package/dist/2536.js +0 -1
  57. package/dist/2536.js.map +0 -1
  58. package/dist/4698.js.map +0 -1
  59. package/dist/6479.js +0 -1
  60. package/dist/6479.js.map +0 -1
  61. package/dist/8088.css +0 -1
  62. package/dist/8088.js +0 -1
  63. package/dist/8088.js.map +0 -1
  64. package/dist/9270.js +0 -1
  65. package/dist/9270.js.map +0 -1
  66. /package/dist/{6479.css → 2989.css} +0 -0
@@ -0,0 +1,75 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { matchTranslations, type TranslationSighting } from '@openmrs/esm-framework/src/internal';
3
+ import { findTranslatedText } from './find-translated-text';
4
+
5
+ const mockMatchTranslations = vi.mocked(matchTranslations);
6
+
7
+ const loginButtonSighting: TranslationSighting = {
8
+ namespace: '@openmrs/esm-login-app',
9
+ key: 'loginButton',
10
+ value: 'Log in',
11
+ hasCount: false,
12
+ };
13
+
14
+ beforeEach(() => {
15
+ mockMatchTranslations.mockImplementation((text: string) => (text.trim() === 'Log in' ? [loginButtonSighting] : []));
16
+ });
17
+
18
+ function buildDom(html: string): HTMLElement {
19
+ document.body.innerHTML = html;
20
+ return document.body.firstElementChild as HTMLElement;
21
+ }
22
+
23
+ describe('findTranslatedText', () => {
24
+ it('resolves text rendered as an element’s own text node', () => {
25
+ const element = buildDom('<button>Log in</button>');
26
+
27
+ expect(findTranslatedText(element)).toEqual({ element, sightings: [loginButtonSighting], attribute: undefined });
28
+ });
29
+
30
+ it('walks up to the nearest translated ancestor', () => {
31
+ const button = buildDom('<button><span><svg></svg></span>Log in</button>');
32
+ const svg = button.querySelector('svg') as Element;
33
+
34
+ expect(findTranslatedText(svg)?.element).toBe(button);
35
+ });
36
+
37
+ it('resolves text that is only rendered as an attribute', () => {
38
+ const element = buildDom('<button aria-label="Log in"><svg></svg></button>');
39
+
40
+ expect(findTranslatedText(element)).toEqual({
41
+ element,
42
+ sightings: [loginButtonSighting],
43
+ attribute: 'aria-label',
44
+ });
45
+ });
46
+
47
+ it('prefers an element’s own text to its attributes when both are translations', () => {
48
+ const element = buildDom('<button title="Log in">Log in</button>');
49
+
50
+ expect(findTranslatedText(element)?.attribute).toBeUndefined();
51
+ });
52
+
53
+ it('skips a landmark’s aria-label, which is never shown on screen', () => {
54
+ const nav = buildDom('<nav aria-label="Log in"><ul><li>Untranslated item</li></ul></nav>');
55
+ const item = nav.querySelector('li') as Element;
56
+
57
+ expect(findTranslatedText(nav)).toBeNull();
58
+ expect(findTranslatedText(item)).toBeNull();
59
+ });
60
+
61
+ it('does not claim text that merely contains a translation', () => {
62
+ expect(findTranslatedText(buildDom('<h1>Please Log in now</h1>'))).toBeNull();
63
+ });
64
+
65
+ it('reports nothing for text that came from no translation', () => {
66
+ expect(findTranslatedText(buildDom('<p>Kaposi sarcoma</p>'))).toBeNull();
67
+ });
68
+
69
+ it('ignores the implementer tools’ own UI', () => {
70
+ const element = buildDom('<div data-openmrs-implementer-tools><button>Log in</button></div>');
71
+ const button = element.querySelector('button') as Element;
72
+
73
+ expect(findTranslatedText(button)).toBeNull();
74
+ });
75
+ });
@@ -0,0 +1,87 @@
1
+ import { matchTranslations, type TranslationSighting } from '@openmrs/esm-framework/src/internal';
2
+
3
+ /**
4
+ * Attributes whose values are translated and rendered to the user. Inspecting them is what lets the
5
+ * inspector resolve text that never becomes a text node, such as an icon button's `aria-label`. A label
6
+ * referenced through `aria-labelledby`, as Carbon's icon-only buttons use, is not followed.
7
+ */
8
+ const inspectableAttributes = ['aria-label', 'title', 'placeholder', 'alt'];
9
+
10
+ /**
11
+ * The elements whose `aria-label` stands in for a label the user would otherwise see, such as an icon
12
+ * button's. On anything else, a landmark like the left nav for one, it is only ever read out by
13
+ * assistive technology, and matching it would report a key for text that is not on screen.
14
+ */
15
+ const labelledControls = [
16
+ 'a[href]',
17
+ 'button',
18
+ 'input',
19
+ 'select',
20
+ 'textarea',
21
+ 'img',
22
+ 'svg',
23
+ ...['button', 'link', 'menuitem', 'tab', 'checkbox', 'radio', 'switch', 'option', 'combobox', 'img'].map(
24
+ (role) => `[role="${role}"]`,
25
+ ),
26
+ ].join(', ');
27
+
28
+ export interface InspectionTarget {
29
+ /** The element the text was found on. */
30
+ element: Element;
31
+ sightings: Array<TranslationSighting>;
32
+ /** The attribute the text came from, if it was not rendered as a text node. */
33
+ attribute?: string;
34
+ }
35
+
36
+ /**
37
+ * Walks up from the given element to the nearest ancestor whose own text, or whose translated
38
+ * attributes, came from a translation. Walking up is what makes hovering the middle of a button
39
+ * resolve the button's label rather than nothing.
40
+ *
41
+ * Only text that is exactly a translation counts. Text that merely contains one, such as a location
42
+ * named "Outpatient Clinic" containing the translation "Clinic", is at least as likely to be data.
43
+ *
44
+ * Returns `null` for the implementer tools' own UI, which is translated too and would otherwise only
45
+ * ever report itself.
46
+ */
47
+ export function findTranslatedText(element: Element): InspectionTarget | null {
48
+ if (element.closest('[data-openmrs-implementer-tools]')) {
49
+ return null;
50
+ }
51
+
52
+ for (let current: Element | null = element; current; current = current.parentElement) {
53
+ for (const candidate of getInspectableStrings(current)) {
54
+ const sightings = matchTranslations(candidate.text);
55
+
56
+ if (sightings?.length > 0) {
57
+ return { element: current, sightings, attribute: candidate.attribute };
58
+ }
59
+ }
60
+ }
61
+
62
+ return null;
63
+ }
64
+
65
+ function getInspectableStrings(element: Element): Array<{ text: string; attribute?: string }> {
66
+ const strings: Array<{ text: string; attribute?: string }> = [];
67
+
68
+ element.childNodes.forEach((node) => {
69
+ if (node.nodeType === Node.TEXT_NODE && node.textContent?.trim()) {
70
+ strings.push({ text: node.textContent });
71
+ }
72
+ });
73
+
74
+ for (const attribute of inspectableAttributes) {
75
+ if (attribute === 'aria-label' && !element.matches(labelledControls)) {
76
+ continue;
77
+ }
78
+
79
+ const value = element.getAttribute(attribute);
80
+
81
+ if (value?.trim()) {
82
+ strings.push({ text: value, attribute });
83
+ }
84
+ }
85
+
86
+ return strings;
87
+ }
@@ -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
+ }
@@ -192,18 +192,28 @@ export function getLoadedLanguages(): Array<string> {
192
192
  return Object.keys(window.i18next?.store?.data ?? {});
193
193
  }
194
194
 
195
+ /**
196
+ * The namespaces the application has loaded that the language holds no resources for. A language
197
+ * browsed earlier still lacks whatever the application loaded since.
198
+ */
199
+ export function getMissingNamespaces(language: string): Array<string> {
200
+ const loaded = new Set(getLoadedNamespaces(language));
201
+ const running = new Set((window.i18next.languages ?? []).flatMap((candidate) => getLoadedNamespaces(candidate)));
202
+
203
+ return Array.from(running).filter((namespace) => !loaded.has(namespace));
204
+ }
205
+
195
206
  /**
196
207
  * Fetches, for a language the application is not running in, the namespaces the application has
197
- * loaded, which is what lets an implementer browse and override a locale other than their own.
208
+ * loaded that it lacks, which is what lets an implementer browse and override a locale other than
209
+ * their own.
198
210
  *
199
211
  * Not `loadLanguages`: it also requests i18next's default `translation` namespace, which the app
200
212
  * shell refuses, so it always reports a failure; and it adds the language to `preload`, so every
201
213
  * namespace the application loads afterwards is fetched in that language too.
202
214
  */
203
215
  export async function loadTranslationLanguage(language: string): Promise<void> {
204
- const namespaces = new Set((window.i18next.languages ?? []).flatMap((running) => getLoadedNamespaces(running)));
205
-
206
- await Promise.all(Array.from(namespaces, (namespace) => loadTranslationNamespace(namespace, language)));
216
+ await Promise.all(getMissingNamespaces(language).map((namespace) => loadTranslationNamespace(namespace, language)));
207
217
  }
208
218
 
209
219
  export function getLoadedNamespaces(language: string): Array<string> {