@olenbetong/synergi-react 5.0.0 → 5.1.0

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 (141) hide show
  1. package/es/components/Checkbox/index.js +1 -9
  2. package/es/components/CodeEditor/CodeEditor.css +6 -6
  3. package/es/components/FilePond.js +3 -12
  4. package/es/components/ImageEditor/plugins/redactPlugin/useRedactTool.js +18 -14
  5. package/es/components/ImageEditor/useImageHistory.js +13 -1
  6. package/es/components/MergeProgressDialog/MergeProgressDialogDs.js +1 -1
  7. package/es/components/MergeProgressDialog/useMergeJob.js +5 -4
  8. package/es/components/Portal/index.js +20 -20
  9. package/es/components/SplitContainer/index.js +3 -1
  10. package/es/components/Toolbar/Toolbar.css +137 -137
  11. package/es/components/Toolbar/index.js +6 -1
  12. package/es/elements/ElementLookupDialog/BarcodeScanner/decoders/zxing.js +8 -0
  13. package/es/elements/ElementLookupDialog/HIDScanner/useHIDScanner.js +3 -1
  14. package/es/elements-ds/DescriptionInput.d.ts +16 -0
  15. package/es/elements-ds/DescriptionInput.js +41 -0
  16. package/es/elements-ds/DuplicateElementDamage.d.ts +40 -0
  17. package/es/elements-ds/DuplicateElementDamage.js +57 -0
  18. package/es/elements-ds/ElementLookup.d.ts +23 -0
  19. package/es/elements-ds/ElementLookup.js +35 -0
  20. package/es/elements-ds/ElementLookupDialog.d.ts +7 -0
  21. package/es/elements-ds/ElementLookupDialog.js +84 -0
  22. package/es/elements-ds/FormFields.d.ts +43 -0
  23. package/es/elements-ds/FormFields.js +67 -0
  24. package/es/elements-ds/HIDScanner.d.ts +7 -0
  25. package/es/elements-ds/HIDScanner.js +36 -0
  26. package/es/elements-ds/ManualForm.d.ts +7 -0
  27. package/es/elements-ds/ManualForm.js +70 -0
  28. package/es/elements-ds/ProjectSelect.d.ts +28 -0
  29. package/es/elements-ds/ProjectSelect.js +45 -0
  30. package/es/elements-ds/elements-ds.css +157 -0
  31. package/es/elements-ds/index.d.ts +12 -0
  32. package/es/elements-ds/index.js +14 -0
  33. package/es/useTranslation/index.js +5 -3
  34. package/package.json +15 -3
  35. package/src/chrome/AppShell/AppShell.test.tsx +48 -0
  36. package/src/chrome/AppShell/index.tsx +29 -29
  37. package/src/chrome/openReport.test.ts +50 -0
  38. package/src/chrome/openReport.ts +34 -34
  39. package/src/colorScheme.test.ts +188 -0
  40. package/src/colorScheme.ts +125 -125
  41. package/src/components/Checkbox/Checkbox.browser.test.tsx +116 -0
  42. package/src/components/Checkbox/index.tsx +1 -10
  43. package/src/components/CodeEditor/CodeEditor.css +6 -6
  44. package/src/components/CodeEditor/CodeEditor.tsx +173 -173
  45. package/src/components/CodeEditor/index.ts +1 -1
  46. package/src/components/ColorCard/ColorCard.test.tsx +34 -0
  47. package/src/components/DateNavigator/DateNavigator.test.tsx +175 -0
  48. package/src/components/DateNavigator/index.tsx +186 -186
  49. package/src/components/FilePond.browser.test.tsx +389 -0
  50. package/src/components/FilePond.tsx +303 -312
  51. package/src/components/ImageEditor/ImageEditor.browser.test.tsx +286 -0
  52. package/src/components/ImageEditor/ImageEditor.test.tsx +299 -0
  53. package/src/components/ImageEditor/ImageEditor.tsx +348 -348
  54. package/src/components/ImageEditor/index.ts +9 -9
  55. package/src/components/ImageEditor/plugins/cropPlugin/CropOverlay.tsx +165 -165
  56. package/src/components/ImageEditor/plugins/cropPlugin/CropToolbar.tsx +48 -48
  57. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.test.ts +225 -0
  58. package/src/components/ImageEditor/plugins/cropPlugin/useCropTool.ts +405 -405
  59. package/src/components/ImageEditor/plugins/plugins.browser.test.ts +252 -0
  60. package/src/components/ImageEditor/plugins/redactPlugin/RedactToolbar.tsx +47 -47
  61. package/src/components/ImageEditor/plugins/redactPlugin/useRedactTool.test.ts +89 -0
  62. package/src/components/ImageEditor/plugins/redactPlugin/useRedactTool.ts +16 -13
  63. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomContext.tsx +23 -23
  64. package/src/components/ImageEditor/plugins/zoomPlugin/ZoomControls.tsx +40 -40
  65. package/src/components/ImageEditor/plugins/zoomPlugin/useZoomPan.test.ts +154 -0
  66. package/src/components/ImageEditor/useActiveTool.ts +21 -21
  67. package/src/components/ImageEditor/useEdgeDetection.test.ts +96 -0
  68. package/src/components/ImageEditor/useEdgeDetection.ts +319 -319
  69. package/src/components/ImageEditor/useImageHistory.test.ts +409 -0
  70. package/src/components/ImageEditor/useImageHistory.ts +206 -197
  71. package/src/components/ImageEditor/useOpenCV.test.ts +208 -0
  72. package/src/components/ImageEditor/useOpenCV.ts +184 -184
  73. package/src/components/LinkedCardList/index.scss +95 -95
  74. package/src/components/MergeProgressDialog/MergeProgressDialogDs.browser.test.tsx +156 -0
  75. package/src/components/MergeProgressDialog/MergeProgressDialogDs.tsx +1 -0
  76. package/src/components/MergeProgressDialog/useMergeJob.test.ts +326 -0
  77. package/src/components/MergeProgressDialog/useMergeJob.ts +4 -3
  78. package/src/components/PageBanner/index.tsx +80 -80
  79. package/src/components/PdfViewer/PdfViewer.browser.test.tsx +78 -0
  80. package/src/components/PdfViewer/PdfViewer.tsx +158 -158
  81. package/src/components/Portal/Portal.test.tsx +106 -0
  82. package/src/components/Portal/index.tsx +22 -25
  83. package/src/components/Sidebar/Sidebar.browser.test.tsx +57 -0
  84. package/src/components/Sidebar/Sidebar.test.tsx +123 -0
  85. package/src/components/SplitContainer/SplitContainer.browser.test.tsx +304 -0
  86. package/src/components/SplitContainer/index.tsx +335 -333
  87. package/src/components/Toolbar/Toolbar.css +137 -137
  88. package/src/components/Toolbar/Toolbar.test.tsx +216 -0
  89. package/src/components/Toolbar/ToolbarBreadcrumbs.browser.test.tsx +137 -0
  90. package/src/components/Toolbar/index.tsx +270 -265
  91. package/src/components/ValueToggleGroup/ValueToggleGroup.test.tsx +112 -0
  92. package/src/designsystemet-web-types.d.ts +24 -24
  93. package/src/elements/ElementDamage/DamageFormButtons.tsx +35 -35
  94. package/src/elements/ElementDamage/DescriptionInput.tsx +120 -120
  95. package/src/elements/ElementDamage/DuplicateDamage/DesktopView.tsx +82 -82
  96. package/src/elements/ElementDamage/DuplicateDamage/DublicateElementDamageDialog.tsx +67 -67
  97. package/src/elements/ElementDamage/DuplicateDamage/PhoneView.tsx +45 -45
  98. package/src/elements/ElementDamage/ElementNumberTextField.tsx +41 -41
  99. package/src/elements/ElementDamage/RegisterFix.tsx +100 -100
  100. package/src/elements/ElementDamage/SubmitButtons.tsx +40 -40
  101. package/src/elements/ElementDamage/TransportElementSelect.tsx +52 -52
  102. package/src/elements/ElementLookup.tsx +123 -123
  103. package/src/elements/ElementLookupDialog/BarcodeScanner/BarcodeScanner.browser.test.tsx +175 -0
  104. package/src/elements/ElementLookupDialog/BarcodeScanner/decoders/zxing.ts +8 -0
  105. package/src/elements/ElementLookupDialog/BarcodeScanner/engines.browser.test.ts +225 -0
  106. package/src/elements/ElementLookupDialog/HIDScanner/index.tsx +67 -67
  107. package/src/elements/ElementLookupDialog/HIDScanner/useHIDScanner.test.ts +124 -0
  108. package/src/elements/ElementLookupDialog/HIDScanner/useHIDScanner.ts +2 -1
  109. package/src/elements/ElementLookupDialog/Manual/ManualForm.tsx +141 -141
  110. package/src/elements/ElementLookupDialog/getElement.test.ts +133 -0
  111. package/src/elements/ElementLookupDialog/index.tsx +226 -226
  112. package/src/elements/ElementLookupDialog/utils/Giai.test.ts +53 -0
  113. package/src/elements/ElementLookupDialog/utils/Giai.ts +209 -209
  114. package/src/elements/ProjectSelect.tsx +130 -130
  115. package/src/elements/index.ts +15 -15
  116. package/src/elements-ds/DamageForm.browser.test.tsx +530 -0
  117. package/src/elements-ds/DescriptionInput.tsx +114 -0
  118. package/src/elements-ds/DuplicateElementDamage.tsx +185 -0
  119. package/src/elements-ds/ElementLookup.tsx +114 -0
  120. package/src/elements-ds/ElementLookupDialog.browser.test.tsx +207 -0
  121. package/src/elements-ds/ElementLookupDialog.tsx +196 -0
  122. package/src/elements-ds/FormFields.tsx +176 -0
  123. package/src/elements-ds/HIDScanner.tsx +53 -0
  124. package/src/elements-ds/ManualForm.tsx +129 -0
  125. package/src/elements-ds/ProjectSelect.tsx +120 -0
  126. package/src/elements-ds/elements-ds.css +157 -0
  127. package/src/elements-ds/index.ts +16 -0
  128. package/src/filter/index.ts +34 -34
  129. package/src/i18n.test.ts +31 -0
  130. package/src/i18n.ts +13 -13
  131. package/src/mui/MuiThemeProvider.tsx +135 -135
  132. package/src/test/fakeCamera.ts +98 -0
  133. package/src/test/fakeDataApi.ts +90 -0
  134. package/src/test/setup.browser.ts +21 -0
  135. package/src/test/setup.ts +23 -23
  136. package/src/useTranslation/index.ts +5 -3
  137. package/src/useTranslation/useTranslation.test.ts +128 -0
  138. package/es/elements/ElementLookupDialog/BarcodeScanner/decoders.test.d.ts +0 -1
  139. package/es/elements/ElementLookupDialog/BarcodeScanner/decoders.test.js +0 -103
  140. package/es/test/setup.d.ts +0 -6
  141. package/es/test/setup.js +0 -6
@@ -1,123 +1,123 @@
1
- import SearchIcon from "@mui/icons-material/Search";
2
- import { IconButton, TextField } from "@mui/material";
3
- import { type ReactNode, type RefObject, useEffect, useImperativeHandle, useRef, useState } from "react";
4
- import { type AddElement, ElementLookupDialog } from "./ElementLookupDialog";
5
- import type { DecoderFactory } from "./ElementLookupDialog/BarcodeScanner";
6
- import { getLocalizedString } from "../i18n.js";
7
-
8
- export type Element = {
9
- Domain: string;
10
- PrimKey: string;
11
- ProjectID: string;
12
- ProjectName: string;
13
- ElementID: string | null;
14
- };
15
-
16
- export type ElementLookupHandle = {
17
- openDialog: () => void;
18
- closeDialog: () => void;
19
- };
20
-
21
- export type ElementLookupProps = {
22
- value?: Element | null;
23
- defaultValue?: Element | null;
24
- ref?: RefObject<ElementLookupHandle | null>;
25
- elementIDRequired?: boolean;
26
- openLookupDialogIcon?: boolean;
27
- onChange?: (value: Element | null) => void;
28
- onDialogChange?: (open: boolean) => void;
29
- /** Engine for the camera tab of the lookup dialog. Defaults to zxing-wasm. */
30
- decoder?: DecoderFactory;
31
- /** Extra controls in the camera tab footer, e.g. an engine picker. */
32
- scannerActions?: ReactNode;
33
- };
34
-
35
- export function ElementLookup({
36
- value,
37
- defaultValue,
38
- ref,
39
- elementIDRequired = false,
40
- openLookupDialogIcon,
41
- onChange,
42
- onDialogChange,
43
- decoder,
44
- scannerActions,
45
- }: ElementLookupProps) {
46
- let initializedRef = useRef<boolean>(false);
47
-
48
- let [openElementLookupDialog, setOpenElementLookupDialog] = useState<boolean>(false);
49
- let [element, setElement] = useState<Element | null>(defaultValue ?? null);
50
- let elementValue = value === undefined ? element : value;
51
-
52
- useEffect(() => {
53
- if (initializedRef.current) {
54
- return;
55
- }
56
-
57
- if (value === undefined && defaultValue) {
58
- setElement(defaultValue);
59
- initializedRef.current = true;
60
- }
61
- }, [defaultValue]); // oxlint-disable-line react-hooks/exhaustive-deps (intentionally skipping "value" dependency as this shouldn't run when "value" changes)
62
-
63
- useImperativeHandle(ref, () => ({
64
- openDialog: () => setOpenElementLookupDialog(true),
65
- closeDialog: () => setOpenElementLookupDialog(false),
66
- }));
67
-
68
- async function handleAddElement(addElement: AddElement) {
69
- onChange?.(addElement.element);
70
- setElement(addElement.element);
71
- }
72
-
73
- useEffect(() => {
74
- onDialogChange?.(openElementLookupDialog);
75
- }, [openElementLookupDialog]); // oxlint-disable-line react-hooks/exhaustive-deps (only run when openElementLookupDialog changes)
76
-
77
- return (
78
- <>
79
- <ElementLookupDialog
80
- open={openElementLookupDialog}
81
- mode="single"
82
- onClose={() => setOpenElementLookupDialog(false)}
83
- onAdd={handleAddElement}
84
- allowEmptyElement={!elementIDRequired}
85
- decoder={decoder}
86
- scannerActions={scannerActions}
87
- />
88
-
89
- <input type="hidden" name="ProjectID" value={elementValue?.ProjectID ?? ""} />
90
- <input type="hidden" name="ElementRef" value={elementValue?.PrimKey ?? ""} />
91
-
92
- <TextField
93
- id="NewElementDamge_Project"
94
- value={elementValue ? `${elementValue.ProjectID}: ${elementValue.ProjectName}` : ""}
95
- label={getLocalizedString("Project")}
96
- fullWidth
97
- required
98
- autoComplete="off"
99
- slotProps={{ htmlInput: { readOnly: true } }}
100
- />
101
- <TextField
102
- name="ElementID"
103
- id="NewElementDamage_ElementID"
104
- value={elementValue ? elementValue.ElementID : ""}
105
- label={getLocalizedString("Element ID")}
106
- fullWidth
107
- required={elementIDRequired}
108
- autoComplete="off"
109
- slotProps={{
110
- htmlInput: { readOnly: true },
111
- input: {
112
- endAdornment: openLookupDialogIcon ? (
113
- <IconButton onClick={() => setOpenElementLookupDialog(true)}>
114
- <SearchIcon />
115
- </IconButton>
116
- ) : undefined,
117
- },
118
- inputLabel: { shrink: !!elementValue?.ElementID },
119
- }}
120
- />
121
- </>
122
- );
123
- }
1
+ import SearchIcon from "@mui/icons-material/Search";
2
+ import { IconButton, TextField } from "@mui/material";
3
+ import { type ReactNode, type RefObject, useEffect, useImperativeHandle, useRef, useState } from "react";
4
+ import { type AddElement, ElementLookupDialog } from "./ElementLookupDialog";
5
+ import type { DecoderFactory } from "./ElementLookupDialog/BarcodeScanner";
6
+ import { getLocalizedString } from "../i18n.js";
7
+
8
+ export type Element = {
9
+ Domain: string;
10
+ PrimKey: string;
11
+ ProjectID: string;
12
+ ProjectName: string;
13
+ ElementID: string | null;
14
+ };
15
+
16
+ export type ElementLookupHandle = {
17
+ openDialog: () => void;
18
+ closeDialog: () => void;
19
+ };
20
+
21
+ export type ElementLookupProps = {
22
+ value?: Element | null;
23
+ defaultValue?: Element | null;
24
+ ref?: RefObject<ElementLookupHandle | null>;
25
+ elementIDRequired?: boolean;
26
+ openLookupDialogIcon?: boolean;
27
+ onChange?: (value: Element | null) => void;
28
+ onDialogChange?: (open: boolean) => void;
29
+ /** Engine for the camera tab of the lookup dialog. Defaults to zxing-wasm. */
30
+ decoder?: DecoderFactory;
31
+ /** Extra controls in the camera tab footer, e.g. an engine picker. */
32
+ scannerActions?: ReactNode;
33
+ };
34
+
35
+ export function ElementLookup({
36
+ value,
37
+ defaultValue,
38
+ ref,
39
+ elementIDRequired = false,
40
+ openLookupDialogIcon,
41
+ onChange,
42
+ onDialogChange,
43
+ decoder,
44
+ scannerActions,
45
+ }: ElementLookupProps) {
46
+ let initializedRef = useRef<boolean>(false);
47
+
48
+ let [openElementLookupDialog, setOpenElementLookupDialog] = useState<boolean>(false);
49
+ let [element, setElement] = useState<Element | null>(defaultValue ?? null);
50
+ let elementValue = value === undefined ? element : value;
51
+
52
+ useEffect(() => {
53
+ if (initializedRef.current) {
54
+ return;
55
+ }
56
+
57
+ if (value === undefined && defaultValue) {
58
+ setElement(defaultValue);
59
+ initializedRef.current = true;
60
+ }
61
+ }, [defaultValue]); // oxlint-disable-line react-hooks/exhaustive-deps (intentionally skipping "value" dependency as this shouldn't run when "value" changes)
62
+
63
+ useImperativeHandle(ref, () => ({
64
+ openDialog: () => setOpenElementLookupDialog(true),
65
+ closeDialog: () => setOpenElementLookupDialog(false),
66
+ }));
67
+
68
+ async function handleAddElement(addElement: AddElement) {
69
+ onChange?.(addElement.element);
70
+ setElement(addElement.element);
71
+ }
72
+
73
+ useEffect(() => {
74
+ onDialogChange?.(openElementLookupDialog);
75
+ }, [openElementLookupDialog]); // oxlint-disable-line react-hooks/exhaustive-deps (only run when openElementLookupDialog changes)
76
+
77
+ return (
78
+ <>
79
+ <ElementLookupDialog
80
+ open={openElementLookupDialog}
81
+ mode="single"
82
+ onClose={() => setOpenElementLookupDialog(false)}
83
+ onAdd={handleAddElement}
84
+ allowEmptyElement={!elementIDRequired}
85
+ decoder={decoder}
86
+ scannerActions={scannerActions}
87
+ />
88
+
89
+ <input type="hidden" name="ProjectID" value={elementValue?.ProjectID ?? ""} />
90
+ <input type="hidden" name="ElementRef" value={elementValue?.PrimKey ?? ""} />
91
+
92
+ <TextField
93
+ id="NewElementDamge_Project"
94
+ value={elementValue ? `${elementValue.ProjectID}: ${elementValue.ProjectName}` : ""}
95
+ label={getLocalizedString("Project")}
96
+ fullWidth
97
+ required
98
+ autoComplete="off"
99
+ slotProps={{ htmlInput: { readOnly: true } }}
100
+ />
101
+ <TextField
102
+ name="ElementID"
103
+ id="NewElementDamage_ElementID"
104
+ value={elementValue ? elementValue.ElementID : ""}
105
+ label={getLocalizedString("Element ID")}
106
+ fullWidth
107
+ required={elementIDRequired}
108
+ autoComplete="off"
109
+ slotProps={{
110
+ htmlInput: { readOnly: true },
111
+ input: {
112
+ endAdornment: openLookupDialogIcon ? (
113
+ <IconButton onClick={() => setOpenElementLookupDialog(true)}>
114
+ <SearchIcon />
115
+ </IconButton>
116
+ ) : undefined,
117
+ },
118
+ inputLabel: { shrink: !!elementValue?.ElementID },
119
+ }}
120
+ />
121
+ </>
122
+ );
123
+ }
@@ -0,0 +1,175 @@
1
+ import { render, screen } from "@testing-library/react";
2
+ import readerWasmUrl from "zxing-wasm/reader/zxing_reader.wasm?url";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+
5
+ import { createGs1Label, createSeparatedLabel, type FakeCamera, GS, installFakeCamera } from "../../../test/fakeCamera";
6
+ import Giai from "../utils/Giai";
7
+ import type { DecoderFactory } from "./decoder";
8
+ import { BarcodeScanner, createZxingDecoder } from "./index";
9
+
10
+ // The real zxing engine, with its WebAssembly served locally instead of from the CDN.
11
+ const zxing = createZxingDecoder({ wasmUrl: readerWasmUrl });
12
+
13
+ /** What the scanner reports for each label, and the element identity both resolve to. */
14
+ const ELEMENT = "8004704321012345";
15
+ const OTHER_ELEMENT = "8004704321067890";
16
+ const ELEMENT_URI = "urn:epc:id:giai:7043210.12345";
17
+
18
+ let camera: FakeCamera;
19
+
20
+ beforeEach(() => {
21
+ camera = installFakeCamera();
22
+ });
23
+
24
+ afterEach(() => {
25
+ camera.restore();
26
+ });
27
+
28
+ describe("BarcodeScanner with the zxing engine", () => {
29
+ it("reads a GS1 element label held in front of the camera", async () => {
30
+ let onRead = vi.fn();
31
+ camera.show(await createGs1Label("7043210", "12345"));
32
+
33
+ render(<BarcodeScanner decoder={zxing} onRead={onRead} />);
34
+
35
+ await vi.waitFor(() => expect(onRead).toHaveBeenCalledWith(ELEMENT), { timeout: 5000 });
36
+ expect(await screen.findByTestId("barcode-engine")).toHaveTextContent("zxing");
37
+ expect(Giai.fromString(onRead.mock.calls[0][0]).toEpcPureIdentityUri()).toBe(ELEMENT_URI);
38
+ });
39
+
40
+ it("reads a label that separates prefix and reference with GS", async () => {
41
+ let onRead = vi.fn();
42
+ camera.show(await createSeparatedLabel("7043210", "12345"));
43
+
44
+ render(<BarcodeScanner decoder={zxing} onRead={onRead} />);
45
+
46
+ await vi.waitFor(() => expect(onRead).toHaveBeenCalledWith(`80047043210${GS}12345`), { timeout: 5000 });
47
+ expect(Giai.fromString(onRead.mock.calls[0][0]).toEpcPureIdentityUri()).toBe(ELEMENT_URI);
48
+ });
49
+
50
+ it("asks for the rear camera", async () => {
51
+ render(<BarcodeScanner decoder={zxing} onRead={() => {}} />);
52
+
53
+ await vi.waitFor(() => expect(camera.getUserMedia).toHaveBeenCalled());
54
+ expect(camera.getUserMedia.mock.calls[0][0]).toMatchObject({
55
+ audio: false,
56
+ video: { facingMode: { ideal: "environment" } },
57
+ });
58
+ });
59
+
60
+ it("reads a label that is small and off-centre in the picture", async () => {
61
+ let onRead = vi.fn();
62
+ camera.show(await createGs1Label("7043210", "12345"), { x: 420, y: 300, size: 130 });
63
+
64
+ render(<BarcodeScanner decoder={zxing} onRead={onRead} />);
65
+
66
+ await vi.waitFor(() => expect(onRead).toHaveBeenCalledWith(ELEMENT), { timeout: 5000 });
67
+ });
68
+
69
+ it("reads two labels in view at the same time", async () => {
70
+ let onRead = vi.fn();
71
+ camera.show(await createGs1Label("7043210", "12345"), { x: 30, y: 180, size: 260 });
72
+ camera.show(await createGs1Label("7043210", "67890"), { x: 350, y: 180, size: 260 });
73
+
74
+ render(<BarcodeScanner decoder={zxing} onRead={onRead} />);
75
+
76
+ await vi.waitFor(
77
+ () => {
78
+ expect(onRead).toHaveBeenCalledWith(ELEMENT);
79
+ expect(onRead).toHaveBeenCalledWith(OTHER_ELEMENT);
80
+ },
81
+ { timeout: 5000 },
82
+ );
83
+ });
84
+
85
+ it("reports a label that stays in view once, and again after it has been away", async () => {
86
+ let onRead = vi.fn();
87
+ let label = await createGs1Label("7043210", "12345");
88
+ camera.show(label);
89
+
90
+ render(<BarcodeScanner decoder={zxing} onRead={onRead} />);
91
+ await vi.waitFor(() => expect(onRead).toHaveBeenCalledOnce(), { timeout: 5000 });
92
+
93
+ // Many frames later, still in view: no second read.
94
+ await new Promise((resolve) => setTimeout(resolve, 1500));
95
+ expect(onRead).toHaveBeenCalledOnce();
96
+
97
+ // Out of view for more than a second, then back.
98
+ camera.clear();
99
+ await new Promise((resolve) => setTimeout(resolve, 1300));
100
+ camera.show(label);
101
+
102
+ await vi.waitFor(() => expect(onRead).toHaveBeenCalledTimes(2), { timeout: 5000 });
103
+ });
104
+
105
+ it("reads nothing from an empty picture", async () => {
106
+ let onRead = vi.fn();
107
+
108
+ render(<BarcodeScanner decoder={zxing} onRead={onRead} />);
109
+ await screen.findByTestId("barcode-engine");
110
+ await new Promise((resolve) => setTimeout(resolve, 1000));
111
+
112
+ expect(onRead).not.toHaveBeenCalled();
113
+ });
114
+ });
115
+
116
+ describe("BarcodeScanner failures", () => {
117
+ it("says so when there is no camera", async () => {
118
+ camera.getUserMedia.mockRejectedValue(new DOMException("Requested device not found", "NotFoundError"));
119
+
120
+ render(<BarcodeScanner decoder={zxing} onRead={() => {}} />);
121
+
122
+ expect(await screen.findByText("No camera available")).toBeInTheDocument();
123
+ });
124
+
125
+ it("says so when camera access is refused", async () => {
126
+ camera.getUserMedia.mockRejectedValue(new DOMException("Permission denied", "NotAllowedError"));
127
+
128
+ render(<BarcodeScanner decoder={zxing} onRead={() => {}} />);
129
+
130
+ expect(await screen.findByText("No camera available")).toBeInTheDocument();
131
+ });
132
+
133
+ it("says so when the browser cannot run the engine", async () => {
134
+ let unsupported: DecoderFactory = async () => {
135
+ throw new Error("WebAssembly is not supported");
136
+ };
137
+
138
+ render(<BarcodeScanner decoder={unsupported} onRead={() => {}} />);
139
+
140
+ expect(await screen.findByText(/A browser that supports WebAssembly is required/)).toBeInTheDocument();
141
+ });
142
+
143
+ it("keeps scanning when one frame fails to decode", async () => {
144
+ let onRead = vi.fn();
145
+ let calls = 0;
146
+ let flaky: DecoderFactory = async () => ({
147
+ name: "flaky",
148
+ async decodeFrame() {
149
+ calls++;
150
+ if (calls === 1) throw new Error("decode failed");
151
+ return [
152
+ {
153
+ text: ELEMENT,
154
+ corners: [
155
+ { x: 0, y: 0 },
156
+ { x: 1, y: 0 },
157
+ { x: 1, y: 1 },
158
+ { x: 0, y: 1 },
159
+ ],
160
+ },
161
+ ];
162
+ },
163
+ async decodeImage() {
164
+ return [];
165
+ },
166
+ });
167
+ let warn = vi.spyOn(console, "warn").mockImplementation(() => {});
168
+
169
+ render(<BarcodeScanner decoder={flaky} onRead={onRead} />);
170
+
171
+ await vi.waitFor(() => expect(onRead).toHaveBeenCalledWith(ELEMENT), { timeout: 5000 });
172
+ expect(warn).toHaveBeenCalled();
173
+ warn.mockRestore();
174
+ });
175
+ });
@@ -13,8 +13,15 @@ export type ZxingDecoderOptions = {
13
13
  imageOptions?: ReaderOptions;
14
14
  };
15
15
 
16
+ /*
17
+ * `textMode: "Plain"` returns the symbol's content as encoded, with GS1 separators as U+001D -
18
+ * what `Giai.fromString` parses and the other engines return. zxing's own default ("HRI") gives
19
+ * the human-readable form instead: `(8004)7043210...` for a GS1 label and `<GS>` for a separator,
20
+ * neither of which resolves to an element.
21
+ */
16
22
  const defaultFrameOptions: ReaderOptions = {
17
23
  formats: ["DataMatrix"],
24
+ textMode: "Plain",
18
25
  tryHarder: false,
19
26
  tryRotate: true,
20
27
  tryInvert: false,
@@ -24,6 +31,7 @@ const defaultFrameOptions: ReaderOptions = {
24
31
 
25
32
  const defaultImageOptions: ReaderOptions = {
26
33
  formats: ["DataMatrix"],
34
+ textMode: "Plain",
27
35
  tryHarder: true,
28
36
  tryRotate: true,
29
37
  tryInvert: true,
@@ -0,0 +1,225 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+
3
+ import { createDbrDecoder } from "./decoders/dbr";
4
+ import { createNativeDecoder, isNativeDecoderAvailable } from "./decoders/native";
5
+
6
+ const GS1_LABEL = "8004704321012345";
7
+
8
+ let globals = window as unknown as Record<string, unknown>;
9
+
10
+ /*
11
+ * A stand-in for the Dynamsoft Barcode Reader 6 SDK, served as a real script so the loader's
12
+ * script-tag path runs. It records what the decoder configures and decodes one GS1 label.
13
+ */
14
+ function fakeDbrScript() {
15
+ let source = `
16
+ window.__dbr = { created: 0, deleted: 0, settings: null };
17
+ window.BarcodeReader = {
18
+ licenseKey: null,
19
+ EnumBarcodeFormat: { DATAMATRIX: 134217728, ALL: -1 },
20
+ async createInstance() {
21
+ window.__dbr.created++;
22
+ let settings = { mBarcodeFormatIds: -1, mAntiDamageLevel: 0, mDeblurLevel: 9 };
23
+ return {
24
+ getRuntimeSettings: () => ({ ...settings }),
25
+ async updateRuntimeSettings(next) { window.__dbr.settings = next; },
26
+ async decode() {
27
+ return [{
28
+ BarcodeText: "${GS1_LABEL}",
29
+ BarcodeFormat: 134217728,
30
+ LocalizationResult: { X1: 1, Y1: 2, X2: 3, Y2: 4, X3: 5, Y3: 6, X4: 7, Y4: 8 },
31
+ }];
32
+ },
33
+ deleteInstance() { window.__dbr.deleted++; },
34
+ };
35
+ },
36
+ };
37
+ `;
38
+ return URL.createObjectURL(new Blob([source], { type: "text/javascript" }));
39
+ }
40
+
41
+ function scriptsFor(url: string) {
42
+ return document.head.querySelectorAll(`script[src="${url}"]`).length;
43
+ }
44
+
45
+ afterEach(() => {
46
+ delete globals.BarcodeReader;
47
+ delete globals.__dbr;
48
+ delete globals.BarcodeDetector;
49
+ });
50
+
51
+ /*
52
+ * The DBR loader remembers a successful load for the page's lifetime, so the failure cases run
53
+ * before the ones that load the SDK.
54
+ */
55
+ describe("Dynamsoft engine (dbr)", () => {
56
+ it("reports a script that cannot be loaded, and tries again next time", async () => {
57
+ let missing = `${location.origin}/no-such-dbr-${Date.now()}.js`;
58
+
59
+ await expect(createDbrDecoder({ scriptUrl: missing, licenseKey: "key" })()).rejects.toThrow(
60
+ `Failed to load ${missing}`,
61
+ );
62
+ expect(scriptsFor(missing)).toBe(0);
63
+
64
+ let url = fakeDbrScript();
65
+ let decoder = await createDbrDecoder({ scriptUrl: url, licenseKey: "key" })();
66
+ expect(decoder.name).toBe("dbr");
67
+ });
68
+
69
+ it("uses an SDK the page has already loaded instead of loading another", async () => {
70
+ let url = fakeDbrScript();
71
+ // Load it the way an article used to: a script tag in the page.
72
+ await new Promise<void>((resolve) => {
73
+ let script = document.createElement("script");
74
+ script.src = url;
75
+ script.onload = () => resolve();
76
+ document.head.append(script);
77
+ });
78
+
79
+ await createDbrDecoder({ scriptUrl: "/lib/dbr/should-not-load.js", licenseKey: "key" })();
80
+
81
+ expect(scriptsFor("/lib/dbr/should-not-load.js")).toBe(0);
82
+ });
83
+
84
+ it("sets the licence, reads DataMatrix only and maps what it finds", async () => {
85
+ let url = fakeDbrScript();
86
+ await new Promise<void>((resolve) => {
87
+ let script = document.createElement("script");
88
+ script.src = url;
89
+ script.onload = () => resolve();
90
+ document.head.append(script);
91
+ });
92
+
93
+ let decoder = await createDbrDecoder({ scriptUrl: url, licenseKey: "license-123" })();
94
+ let results = await decoder.decodeFrame(document.createElement("canvas"));
95
+
96
+ let sdk = globals.BarcodeReader as { licenseKey: string };
97
+ let recorded = globals.__dbr as { settings: Record<string, number>; deleted: number };
98
+ expect(sdk.licenseKey).toBe("license-123");
99
+ expect(recorded.settings).toMatchObject({ mBarcodeFormatIds: 134217728, mAntiDamageLevel: 3, mDeblurLevel: 0 });
100
+ expect(results).toEqual([
101
+ {
102
+ text: GS1_LABEL,
103
+ format: "134217728",
104
+ corners: [
105
+ { x: 1, y: 2 },
106
+ { x: 3, y: 4 },
107
+ { x: 5, y: 6 },
108
+ { x: 7, y: 8 },
109
+ ],
110
+ },
111
+ ]);
112
+
113
+ decoder.dispose?.();
114
+ expect(recorded.deleted).toBe(1);
115
+ });
116
+ });
117
+
118
+ /** A stand-in for the Barcode Detection API as Chrome on Android exposes it. */
119
+ function installBarcodeDetector(formats: string[], detected: unknown[] = []) {
120
+ let constructed: unknown[] = [];
121
+ class FakeBarcodeDetector {
122
+ static getSupportedFormats = vi.fn(async () => formats);
123
+ constructor(options: unknown) {
124
+ constructed.push(options);
125
+ }
126
+ detect = vi.fn(async () => detected);
127
+ }
128
+ globals.BarcodeDetector = FakeBarcodeDetector;
129
+ return { constructed };
130
+ }
131
+
132
+ describe("native engine (Barcode Detection API)", () => {
133
+ it("is unavailable where the browser has no BarcodeDetector", async () => {
134
+ expect(await isNativeDecoderAvailable()).toBe(false);
135
+ await expect(createNativeDecoder()()).rejects.toThrow("This browser cannot detect barcodes natively");
136
+ });
137
+
138
+ it("is unavailable where BarcodeDetector cannot read DataMatrix, as on desktop Chrome", async () => {
139
+ installBarcodeDetector(["qr_code"]);
140
+
141
+ expect(await isNativeDecoderAvailable()).toBe(false);
142
+ });
143
+
144
+ it("is unavailable when asking for the formats fails", async () => {
145
+ installBarcodeDetector([]);
146
+ (globals.BarcodeDetector as { getSupportedFormats: () => Promise<string[]> }).getSupportedFormats = async () => {
147
+ throw new Error("not allowed");
148
+ };
149
+
150
+ expect(await isNativeDecoderAvailable()).toBe(false);
151
+ });
152
+
153
+ it("reads DataMatrix only, and maps the corners it reports", async () => {
154
+ let { constructed } = installBarcodeDetector(
155
+ ["qr_code", "data_matrix"],
156
+ [
157
+ {
158
+ rawValue: GS1_LABEL,
159
+ format: "data_matrix",
160
+ boundingBox: { left: 0, top: 0, right: 10, bottom: 10 },
161
+ cornerPoints: [
162
+ { x: 1, y: 2 },
163
+ { x: 3, y: 4 },
164
+ { x: 5, y: 6 },
165
+ { x: 7, y: 8 },
166
+ ],
167
+ },
168
+ ],
169
+ );
170
+
171
+ let decoder = await createNativeDecoder()();
172
+ let results = await decoder.decodeFrame(document.createElement("canvas"));
173
+
174
+ expect(decoder.name).toBe("native");
175
+ expect(constructed).toEqual([{ formats: ["data_matrix"] }]);
176
+ expect(results[0]).toMatchObject({ text: GS1_LABEL, format: "data_matrix" });
177
+ expect(results[0]!.corners[2]).toEqual({ x: 5, y: 6 });
178
+ });
179
+
180
+ it("falls back to the bounding box when the corners are missing", async () => {
181
+ installBarcodeDetector(
182
+ ["data_matrix"],
183
+ [
184
+ {
185
+ rawValue: GS1_LABEL,
186
+ format: "data_matrix",
187
+ boundingBox: { left: 10, top: 20, right: 110, bottom: 120 },
188
+ cornerPoints: [],
189
+ },
190
+ ],
191
+ );
192
+
193
+ let decoder = await createNativeDecoder()();
194
+ let [result] = await decoder.decodeFrame(document.createElement("canvas"));
195
+
196
+ expect(result!.corners).toEqual([
197
+ { x: 10, y: 20 },
198
+ { x: 110, y: 20 },
199
+ { x: 110, y: 120 },
200
+ { x: 10, y: 120 },
201
+ ]);
202
+ });
203
+
204
+ it("decodes a photo as well as camera frames", async () => {
205
+ installBarcodeDetector(
206
+ ["data_matrix"],
207
+ [
208
+ {
209
+ rawValue: GS1_LABEL,
210
+ format: "data_matrix",
211
+ boundingBox: { left: 0, top: 0, right: 1, bottom: 1 },
212
+ cornerPoints: [],
213
+ },
214
+ ],
215
+ );
216
+ let canvas = new OffscreenCanvas(8, 8);
217
+ canvas.getContext("2d")!.fillRect(0, 0, 8, 8);
218
+ let photo = await canvas.convertToBlob({ type: "image/png" });
219
+
220
+ let decoder = await createNativeDecoder()();
221
+ let results = await decoder.decodeImage(photo);
222
+
223
+ expect(results.map((r) => r.text)).toEqual([GS1_LABEL]);
224
+ });
225
+ });