Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(mes): an inspection lot can be rejected at any time (#2061)

Brad Barbin24b4ca406387
diff --git a/.claude/rules/mes-job-operation-ui.md b/.claude/rules/mes-job-operation-ui.md
index 3af5e7bede..357454e652 100644
--- a/.claude/rules/mes-job-operation-ui.md
+++ b/.claude/rules/mes-job-operation-ui.md
@@ -3,6 +3,7 @@ paths:
- "apps/mes/app/components/JobOperation/**"
- "apps/mes/app/routes/x+/operation.$operationId.tsx"
- "apps/mes/app/routes/x+/batch.$batchId.tsx"
+ - "packages/react/src/hooks/useKeyboardWedge.ts"
---
# MES Job Operation UI
@@ -237,6 +238,35 @@ In batch mode `JobOperation` derives `isBatched = !!batch`,
disabled (`active: !!kanban?.id && !isBatched`) — it completes a single op,
never a batched member.
+## Barcode scans (keyboard wedge)
+
+`useKeyboardWedge` (`@carbon/react`) registers a handler with ONE capture-phase
+`keydown` listener on `window`, shared by every wedge on the page, so a
+component that stops a key (Combobox, Dock) cannot hide a scan from it.
+`ScanReader` splits the keys into bursts at any gap over 80 ms. A stray key is
+therefore dropped rather than kept in front of the next scan, and two
+scanner-speed bursts are joined (a Bluetooth pause). From the fourth
+scanner-speed key on, the keys are kept from the page, so a scan never hits
+Space (Start/Pause) or clicks the focused button with its Enter. A scan with no
+Enter or Tab ends after 700 ms of quiet. Ending sooner acted on the first half
+of a paused URL, which is itself a valid link.
+
+- The MES layout opens MES/ERP links; `JobOperation` and `AssemblyView`
+ complete the kanban (`isKanbanCompleteScan`, `~/utils/kanban`). That check
+ compares the label's PATH, because a label holds the origin it was printed
+ from. It accepts the completed barcode override and the printed label.
+- All three set `inTextFields`: a matching scan is taken even while a field
+ has focus, and the field is set back to its value from before the scan.
+ A scan no handler takes stays in the field.
+- A scan outside a field that no handler takes is kept from the page, and
+ the layout's `onUnrecognized` shows a toast.
+- A callback that returns a promise (`navigate`, `fetcher.load`, or the
+ cross-origin `location.assign` that the default callback waits on) keeps
+ the scan pending. `useScanPending` drives `ScanPendingOverlay` in the
+ layout, and every other scan is ignored until the promise settles (at most
+ 20 s). A kanban start label loads the ERP and then the MES, so without
+ this state operators scanned it twice.
+
## Components
- **`JobOperation/JobOperation.tsx`** — large root component (~1700 lines). Holds the
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 01ee048775..d34c4582a5 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1296,7 +1296,7 @@
{"name":"sales_createReplacementSalesOrder","classification":"WRITE","schema":"3fdcd215dc22","response":"3797626bd17e","permission":"sales:create","paginates":false},
{"name":"sales_createReturnOrderLine","classification":"WRITE","schema":"f0f787b6d728","response":"f9d1513a44f3","permission":"sales:create","paginates":false},
{"name":"sales_createReturnReason","classification":"WRITE","schema":"5607534c1255","response":"3797626bd17e","permission":"sales:create","paginates":false},
- {"name":"sales_createSalesOrderLine","classification":"WRITE","schema":"1e749569c4c8","response":"8f061af39e95","permission":"sales:create","paginates":false},
+ {"name":"sales_createSalesOrderLine","classification":"WRITE","schema":"afd4977d9445","response":"8f061af39e95","permission":"sales:create","paginates":false},
{"name":"sales_createSalesReturnOrderCredit","classification":"WRITE","schema":"a752775acc57","response":"00404e686415","permission":"invoicing:create","paginates":false},
{"name":"sales_createSalesRfq","classification":"WRITE","schema":"80ed1c7536b4","response":"0c1a1b93cca3","permission":"sales:create","paginates":false},
{"name":"sales_createSalesRFQ","classification":"WRITE","schema":"bd0f125f410c","response":"2e56e1180d37","permission":"sales:create","paginates":false},
@@ -1494,7 +1494,7 @@
{"name":"sales_updateReturnReason","classification":"WRITE","schema":"03734363977f","response":"3797626bd17e","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesOrderDetails","classification":"WRITE","schema":"cdfda47dd459","response":"d160a49d6787","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","schema":"222e5249c015","response":"bcde375ebd4c","permission":"sales:update","paginates":false},
- {"name":"sales_updateSalesOrderLine","classification":"WRITE","schema":"aa4e634c9f14","response":"8f061af39e95","permission":"sales:create","paginates":false},
+ {"name":"sales_updateSalesOrderLine","classification":"WRITE","schema":"113ef3408dd2","response":"8f061af39e95","permission":"sales:create","paginates":false},
{"name":"sales_updateSalesOrderLineOrder","classification":"WRITE","schema":"bc4baf1732ad","response":"none","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesRFQ","classification":"WRITE","schema":"2cb421dde994","response":"2e56e1180d37","permission":"sales:update","paginates":false},
{"name":"sales_updateSalesRFQLine","classification":"WRITE","schema":"827ecf864e53","response":"3797626bd17e","permission":"sales:update","paginates":false},
diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsx
index 42312a4add..ab9b7971ed 100644
--- a/apps/mes/app/components/AssemblyView.tsx
+++ b/apps/mes/app/components/AssemblyView.tsx
@@ -116,6 +116,7 @@ import type {
OperationWithDetails,
ProductionEvent as ProductionEventType
} from "~/services/types";
+import { isKanbanCompleteScan } from "~/utils/kanban";
import { ORIGIN_PARAM, readOrigin, useOrigin } from "~/utils/origin";
import { getPrivateUrl, path } from "~/utils/path";
import { deriveUnits } from "~/utils/units";
@@ -595,17 +596,13 @@ export function AssemblyView({
useRealtime("jobOperation", `id=eq.${operationId}`);
// Kanban barcode scan → complete the operation (matches the operation view).
- // The returned buffer is non-empty while a scan burst is in flight — the
- // keyboard-shortcut effect below yields Enter to the wedge during that window.
+ // The wedge takes a scan's Enter in the capture phase, so the Enter/Space
+ // shortcut below never sees it.
const completeFetcher = useFetcher();
- const wedgeBuffer = useKeyboardWedge({
- test: (input) =>
- kanban?.completedBarcodeOverride
- ? input === kanban.completedBarcodeOverride
- : kanban?.id
- ? input === path.to.kanbanComplete(kanban.id)
- : false,
+ useKeyboardWedge({
+ test: (input) => !!kanban && isKanbanCompleteScan(input, kanban),
callback: () => completeFetcher.load(path.to.endOperation(operationId)),
+ inTextFields: true,
active: !!kanban?.id
});
@@ -1342,9 +1339,6 @@ export function AssemblyView({
// Any open dialog (RecordModal, issue/scan modals, zoom) keeps native
// key semantics — the armed-clicker swallow below is the one exception.
!hasOpenDialog() &&
- // A barcode wedge scan terminates with Enter — yield it to
- // useKeyboardWedge while a scan burst is buffered.
- !(event.key === "Enter" && wedgeBuffer !== "") &&
// No primary action (step done, gated, or submitting) → leave the
// action keys native, so a keyboard user who focused Skip can still
// activate it with Space/Enter.
diff --git a/apps/mes/app/components/Inspection/InspectionView.tsx b/apps/mes/app/components/Inspection/InspectionView.tsx
index e1f1848142..f51f17dc31 100644
--- a/apps/mes/app/components/Inspection/InspectionView.tsx
+++ b/apps/mes/app/components/Inspection/InspectionView.tsx
@@ -505,11 +505,12 @@ export function InspectionView({
? Math.max(1, ...liveFeatures.map((f) => f.sampleSize))
: inspection.sampleSize;
- // Gating mirrors the server-side disposition guards: feature-driven lots
- // gate per feature; lots without features gate at the lot level on
- // the "Overall result" pass/fail counts.
+ // Accept gating: feature-driven lots gate per feature; lots without
+ // features gate at the lot level on the "Overall result" pass/fail counts.
+ // Reject is open at any time — an inspector can condemn a lot for reasons
+ // no characteristic captures (damage, wrong part, contamination).
let canAccept: boolean;
- let canReject: boolean;
+ let failedStatistically: boolean;
if (hasFeatures) {
const allFeaturesSatisfied = liveFeatures.every((feature) => {
const counts = featureCounts.get(feature.inspectionFeatureId) ?? {
@@ -526,14 +527,15 @@ export function InspectionView({
return counts != null && counts.failed >= feature.rejectionNumber;
});
canAccept = !isLocked && allFeaturesSatisfied;
- canReject = !isLocked && (anyFeatureRejectable || fails > 0);
+ failedStatistically = anyFeatureRejectable || fails > 0;
} else {
canAccept =
!isLocked &&
inspected >= inspection.sampleSize &&
fails <= inspection.acceptanceNumber;
- canReject = !isLocked && fails > inspection.acceptanceNumber;
+ failedStatistically = fails > inspection.acceptanceNumber;
}
+ const canReject = !isLocked;
const failedFeatureSummary = useMemo<FailedFeatureSummary[]>(() => {
if (!hasFeatures) return [];
@@ -1067,7 +1069,11 @@ export function InspectionView({
maxAllocatable={opRemaining}
completions={0}
issueTypes={issueTypes}
- summary={t`Statistical acceptance failed, so the entire lot of ${inspection.lotSize} is considered non-conforming (ISO 9001:2015 §8.7) — ${passes} sampled pass(es) and ${fails} failure(s). Route the units below to scrap or rework, or record the verdict only.`}
+ summary={
+ failedStatistically
+ ? t`Statistical acceptance failed, so the entire lot of ${inspection.lotSize} is considered non-conforming (ISO 9001:2015 §8.7) — ${passes} sampled pass(es) and ${fails} failure(s). Route the units below to scrap or rework, or record the verdict only.`
+ : t`The entire lot of ${inspection.lotSize} will be rejected as non-conforming — ${passes} sampled pass(es) and ${fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only.`
+ }
failedFeatureSummary={failedFeatureSummary}
eventIds={eventIds}
onCancel={rejectDisclosure.onClose}
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index fe54ac79bc..4b2bea05b8 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -143,6 +143,7 @@ import type {
} from "~/services/types";
import { useItems } from "~/stores";
import { makeDurations } from "~/utils/durations";
+import { isKanbanCompleteScan } from "~/utils/kanban";
import { useOrigin } from "~/utils/origin";
import { path } from "~/utils/path";
import ItemThumbnail from "../ItemThumbnail";
@@ -682,17 +683,9 @@ export const JobOperation = ({
const completeFetcher = useFetcher<Result>();
useKeyboardWedge({
- test: (input) => {
- if (kanban?.completedBarcodeOverride) {
- return input === kanban.completedBarcodeOverride;
- } else if (kanban?.id) {
- return input === path.to.kanbanComplete(kanban.id);
- }
- return false;
- },
- callback: () => {
- completeFetcher.load(path.to.endOperation(operation.id));
- },
+ test: (input) => !!kanban && isKanbanCompleteScan(input, kanban),
+ callback: () => completeFetcher.load(path.to.endOperation(operation.id)),
+ inTextFields: true,
// The wedge completes this single op via endOperation — never for a batched
// member; the batch completes as a whole.
active: !!kanban?.id && !isBatched && !abilityBlocked
diff --git a/apps/mes/app/components/ScanPendingOverlay.tsx b/apps/mes/app/components/ScanPendingOverlay.tsx
new file mode 100644
index 0000000000..319ee3e019
--- /dev/null
+++ b/apps/mes/app/components/ScanPendingOverlay.tsx
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { CarbonPulse } from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+
+/**
+ * Shown from the moment a scan is accepted until its page or action finishes.
+ * A kanban start label loads the ERP and then the MES, and without this the
+ * screen does not change for seconds: operators scanned it again.
+ */
+export function ScanPendingOverlay() {
+ const { t } = useLingui();
+ return (
+ <div className="fixed inset-0 z-50 flex flex-col items-center justify-center gap-3 bg-card">
+ <CarbonPulse label={t`Scan received`} />
+ <p className="text-lg font-medium" aria-hidden>
+ <Trans>Scan received</Trans>
+ </p>
+ <p className="text-sm text-muted-foreground">
+ <Trans>Loading. There's no need to scan again.</Trans>
+ </p>
+ </div>
+ );
+}
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index e2b4235d6f..a5a9156fce 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -39,8 +39,10 @@ import {
ItarUserCertification,
SidebarProvider,
TooltipProvider,
+ toast,
useKeyboardWedge,
useNProgress,
+ useScanPending,
VStack
} from "@carbon/react";
import { HalloweenLayer } from "@carbon/react/Halloween";
@@ -76,6 +78,7 @@ import { ConsolePill } from "~/components/ConsolePill";
import { isTabBarPath, MesTabBar } from "~/components/MesTabBar";
import { PinInOverlay } from "~/components/PinInOverlay";
import RealtimeDataProvider from "~/components/RealtimeDataProvider";
+import { ScanPendingOverlay } from "~/components/ScanPendingOverlay";
import SessionLockOverlay from "~/components/SessionLockOverlay";
import ShortcutHelp from "~/components/ShortcutHelp";
import { TimeCardWarning } from "~/components/TimeCardWarning";
@@ -391,14 +394,17 @@ export default function AuthenticatedRoute() {
}, [consoleIsIdle]);
useNProgress();
+
+ const userId = user?.id;
+ const { t } = useLingui();
useKeyboardWedge({
test: (input) =>
(input.startsWith(MES_URL) || input.startsWith(ERP_URL)) &&
- !input.includes("/kanban/complete/") // we handle this more gracefully in JobOperation
+ !input.includes("/kanban/complete/"), // we handle this more gracefully in JobOperation
+ inTextFields: true,
+ onUnrecognized: () => toast.error(t`Nothing on this page uses that barcode`)
});
-
- const userId = user?.id;
- const { t } = useLingui();
+ const scanPending = useScanPending();
const systemStatus = useLoaderQuery<typeof systemStatusLoader>(
path.to.api.systemStatus
);
@@ -603,6 +609,7 @@ export default function AuthenticatedRoute() {
</Await>
</Suspense>
)}
+ {scanPending && <ScanPendingOverlay />}
{consoleMode && !pinnedInUser && (
<PinInOverlay
companyId={company.companyId!}
diff --git a/apps/mes/app/utils/kanban.test.ts b/apps/mes/app/utils/kanban.test.ts
new file mode 100644
index 0000000000..54be5d6569
--- /dev/null
+++ b/apps/mes/app/utils/kanban.test.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import { isKanbanCompleteScan } from "./kanban";
+
+const kanban = { id: "kbn_8f3k2m1q", completedBarcodeOverride: null };
+
+describe("isKanbanCompleteScan", () => {
+ it("accepts the label whatever host it was printed from", () => {
+ expect(
+ isKanbanCompleteScan(
+ "https://erp.try.carbon.ms/api/kanban/complete/kbn_8f3k2m1q",
+ kanban
+ )
+ ).toBe(true);
+ });
+
+ it("refuses another kanban's label", () => {
+ expect(
+ isKanbanCompleteScan(
+ "https://erp.carbon.ms/api/kanban/complete/kbn_other01",
+ kanban
+ )
+ ).toBe(false);
+ });
+
+ it("accepts the override and, beside it, the printed label", () => {
+ const withOverride = {
+ ...kanban,
+ completedBarcodeOverride: "KB 0042/DONE#1"
+ };
+ expect(isKanbanCompleteScan("KB 0042/DONE#1", withOverride)).toBe(true);
+ expect(
+ isKanbanCompleteScan(
+ "https://erp.carbon.ms/api/kanban/complete/kbn_8f3k2m1q",
+ withOverride
+ )
+ ).toBe(true);
+ });
+
+ it("refuses text that is not a URL", () => {
+ expect(isKanbanCompleteScan("kbn_8f3k2m1q", kanban)).toBe(false);
+ });
+});
diff --git a/apps/mes/app/utils/kanban.ts b/apps/mes/app/utils/kanban.ts
new file mode 100644
index 0000000000..52dd61538d
--- /dev/null
+++ b/apps/mes/app/utils/kanban.ts
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+/**
+ * Whether a scan completes this kanban: its completed barcode override, or its
+ * printed complete label. The label holds the origin it was printed from,
+ * which need not be this deployment's ERP_URL, so only the path is compared.
+ */
+export function isKanbanCompleteScan(
+ input: string,
+ kanban: { id?: string; completedBarcodeOverride?: string | null }
+): boolean {
+ if (
+ kanban.completedBarcodeOverride &&
+ input === kanban.completedBarcodeOverride
+ ) {
+ return true;
+ }
+ let url: URL;
+ try {
+ url = new URL(input);
+ } catch {
+ return false;
+ }
+ return !!kanban.id && url.pathname === `/api/kanban/complete/${kanban.id}`;
+}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 2d2098753e..53bcb844f9 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -170,7 +170,6 @@ export const path = {
jobMakeMethodDetail: (jobId: string, makeMethodId: string) =>
`${getAppUrl()}${x}/job/${jobId}/make/${makeMethodId}`,
jobs: `${x}/jobs`,
- kanbanComplete: (id: string) => `${ERP_URL}/api/kanban/complete/${id}`,
location: `${x}/location`,
login: "/login",
logout: "/logout",
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 19d42842af..1a8349ac87 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -107809,6 +107809,51 @@ export default {
tags: ["(rpc) get_foreign_key_map"]
}
},
+ "/rpc/sync_delete_unlinked_contact": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_new: {
+ format: "jsonb"
+ },
+ p_old: {
+ format: "jsonb"
+ },
+ p_operation: {
+ format: "text",
+ type: "string"
+ },
+ p_table: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_table", "p_operation", "p_new", "p_old"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) sync_delete_unlinked_contact"]
+ }
+ },
"/rpc/get_ar_aging": {
post: {
parameters: [
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index be1f2e5246..058b134e47 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -94932,6 +94932,10 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ sync_delete_unlinked_contact: {
+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
+ Returns: undefined
+ }
sync_delete_user_identity_group: {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index 92a39ba094..f02956d93d 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -993,6 +993,9 @@ msgstr "Beladen: {loadedLabel}"
msgid "Loading item details..."
msgstr "Artikeldetails werden geladen..."
+msgid "Loading. There's no need to scan again."
+msgstr "Wird geladen. Sie müssen nicht erneut scannen."
+
msgid "Loading..."
msgstr "Wird geladen..."
@@ -1289,6 +1292,9 @@ msgstr "Keine"
msgid "Notes"
msgstr "Notizen"
+msgid "Nothing on this page uses that barcode"
+msgstr "Nichts auf dieser Seite verwendet diesen Barcode"
+
msgid "Nothing running"
msgstr "Nichts läuft"
@@ -1703,6 +1709,9 @@ msgstr "Seriennummer scannen oder suchen..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "Scannen oder wählen Sie eine Verfolgte Einheit aus dieser Charge, um sie als Probenspalte hinzuzufügen, dann erfassen Sie das Ergebnis in der Tabelle."
+msgid "Scan received"
+msgstr "Scan empfangen"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "Scannen Sie diesen QR-Code mit Ihrer Authentifizierungs-App (z. B. Google Authenticator oder 1Password), und geben Sie dann den 6-stelligen Code ein, den sie anzeigt."
@@ -2014,6 +2023,10 @@ msgstr "Die in Carbon verwendete Akzentfarbe."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "Die abgeschlossene Menge für diesen Arbeitsgang ist geringer als die erforderliche Menge von {targetQuantity}."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "Die Fertigungsaufträge und Teile, die diesen Durchlauf ausmachen."
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index bccae4b286..54fe16c43a 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -993,6 +993,9 @@ msgstr "Loaded: {loadedLabel}"
msgid "Loading item details..."
msgstr "Loading item details..."
+msgid "Loading. There's no need to scan again."
+msgstr "Loading. There's no need to scan again."
+
msgid "Loading..."
msgstr "Loading..."
@@ -1289,6 +1292,9 @@ msgstr "None"
msgid "Notes"
msgstr "Notes"
+msgid "Nothing on this page uses that barcode"
+msgstr "Nothing on this page uses that barcode"
+
msgid "Nothing running"
msgstr "Nothing running"
@@ -1703,6 +1709,9 @@ msgstr "Scan or search serial number..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
+msgid "Scan received"
+msgstr "Scan received"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
@@ -2014,6 +2023,10 @@ msgstr "The accent color used across Carbon."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+
msgid "The jobs and parts that make up this run."
msgstr "The jobs and parts that make up this run."
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index d08ba23d21..0b0327a3c1 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -993,6 +993,9 @@ msgstr "Cargado: {loadedLabel}"
msgid "Loading item details..."
msgstr "Cargando detalles del artículo..."
+msgid "Loading. There's no need to scan again."
+msgstr "Cargando. No es necesario escanear de nuevo."
+
msgid "Loading..."
msgstr "Cargando..."
@@ -1289,6 +1292,9 @@ msgstr "Ninguno"
msgid "Notes"
msgstr "Notas"
+msgid "Nothing on this page uses that barcode"
+msgstr "Nada en esta página usa ese código de barras"
+
msgid "Nothing running"
msgstr "Nada en ejecución"
@@ -1703,6 +1709,9 @@ msgstr "Escanear o buscar número de serie..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "Escanee o seleccione una entidad rastreada de este lote para agregarla como columna de muestra, luego registre su resultado en la cuadrícula."
+msgid "Scan received"
+msgstr "Escaneo recibido"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "Escanea este código QR con tu aplicación autenticadora (p. ej. Google Authenticator o 1Password), luego ingresa el código de 6 dígitos que muestra."
@@ -2014,6 +2023,10 @@ msgstr "El color de acento utilizado en toda Carbon."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "La cantidad completada para esta operación es menor que la cantidad requerida de {targetQuantity}."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "Las órdenes de trabajo y piezas que componen esta ejecución."
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index 467627e0a5..32ab082eb1 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -993,6 +993,9 @@ msgstr "Chargée : {loadedLabel}"
msgid "Loading item details..."
msgstr "Chargement des détails de l'article..."
+msgid "Loading. There's no need to scan again."
+msgstr "Chargement. Inutile de scanner à nouveau."
+
msgid "Loading..."
msgstr "Chargement..."
@@ -1289,6 +1292,9 @@ msgstr "Aucun"
msgid "Notes"
msgstr "Notes"
+msgid "Nothing on this page uses that barcode"
+msgstr "Rien sur cette page n'utilise ce code-barres"
+
msgid "Nothing running"
msgstr "Rien en cours"
@@ -1703,6 +1709,9 @@ msgstr "Scannez ou recherchez un numéro de série..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "Scannez ou sélectionnez une entité suivie de ce lot pour l'ajouter en tant que colonne d'échantillon, puis enregistrez son résultat dans la grille."
+msgid "Scan received"
+msgstr "Scan reçu"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "Scanner ce code QR avec votre application d'authentification (p. ex. Google Authenticator ou 1Password), puis entrez le code à 6 chiffres qu'il affiche."
@@ -2014,6 +2023,10 @@ msgstr "Couleur d'accent utilisée dans Carbon."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "La quantité produite pour cette opération est inférieure à la quantité requise de {targetQuantity}."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "Les ordres de fabrication et les pièces qui composent cette série."
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index fe019b8d65..7997ecd4da 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -993,6 +993,9 @@ msgstr "लोड किया गया: {loadedLabel}"
msgid "Loading item details..."
msgstr "आइटम विवरण लोड हो रहे हैं..."
+msgid "Loading. There's no need to scan again."
+msgstr "लोड हो रहा है। दोबारा स्कैन करने की ज़रूरत नहीं है।"
+
msgid "Loading..."
msgstr "लोड हो रहा है..."
@@ -1289,6 +1292,9 @@ msgstr "कोई नहीं"
msgid "Notes"
msgstr "नोट्स"
+msgid "Nothing on this page uses that barcode"
+msgstr "इस पेज पर कुछ भी उस बारकोड का उपयोग नहीं करता"
+
msgid "Nothing running"
msgstr "कुछ नहीं चल रहा"
@@ -1703,6 +1709,9 @@ msgstr "सीरियल नंबर स्कैन करें या ख
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "इस लॉट से एक ट्रैक की गई इकाई को स्कैन या चुनें, इसे नमूना कॉलम के रूप में जोड़ें, और फिर ग्रिड में इसका परिणाम रिकॉर्ड करें।"
+msgid "Scan received"
+msgstr "स्कैन प्राप्त हुआ"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "इस QR कोड को अपने प्रमाणकर्ता ऐप्लिकेशन (जैसे Google Authenticator या 1Password) के साथ स्कैन करें, फिर इसके द्वारा दिया गया 6-अंकीय कोड दर्ज करें।"
@@ -2014,6 +2023,10 @@ msgstr "Carbon में उपयोग किया जाने वाला
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "इस ऑपरेशन के लिए पूर्ण मात्रा आवश्यक मात्रा {targetQuantity} से कम है।"
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "जॉब्स और पार्ट्स जो इस रन को बनाते हैं।"
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index 0d37839df9..3101e5e3ee 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -993,6 +993,9 @@ msgstr "Caricato: {loadedLabel}"
msgid "Loading item details..."
msgstr "Caricamento dettagli articolo..."
+msgid "Loading. There's no need to scan again."
+msgstr "Caricamento in corso. Non è necessario scansionare di nuovo."
+
msgid "Loading..."
msgstr "Caricamento..."
@@ -1289,6 +1292,9 @@ msgstr "Nessuno"
msgid "Notes"
msgstr "Note"
+msgid "Nothing on this page uses that barcode"
+msgstr "Nessun elemento di questa pagina usa quel codice a barre"
+
msgid "Nothing running"
msgstr "Niente in esecuzione"
@@ -1703,6 +1709,9 @@ msgstr "Scansiona o cerca numero di serie..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "Scansiona o seleziona un'entità tracciata da questo lotto per aggiungerla come colonna campione, quindi registra il suo risultato nella griglia."
+msgid "Scan received"
+msgstr "Scansione ricevuta"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "Scansiona questo codice QR con la tua app autenticatore (ad esempio Google Authenticator o 1Password), quindi inserisci il codice a 6 cifre che mostra."
@@ -2014,6 +2023,10 @@ msgstr "Il colore di accento utilizzato in Carbon."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "La quantità completata per questa operazione è inferiore alla quantità richiesta di {targetQuantity}."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "Gli ordini di produzione e i componenti che compongono questa esecuzione."
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index b45135a0e5..45ad35d0d1 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -993,6 +993,9 @@ msgstr "ロード済み: {loadedLabel}"
msgid "Loading item details..."
msgstr "品目詳細を読み込み中..."
+msgid "Loading. There's no need to scan again."
+msgstr "読み込み中です。もう一度スキャンする必要はありません。"
+
msgid "Loading..."
msgstr "読み込み中..."
@@ -1289,6 +1292,9 @@ msgstr "なし"
msgid "Notes"
msgstr "メモ"
+msgid "Nothing on this page uses that barcode"
+msgstr "このページにはそのバーコードを使うものがありません"
+
msgid "Nothing running"
msgstr "稼働中の作業はありません"
@@ -1703,6 +1709,9 @@ msgstr "シリアル番号をスキャンまたは検索..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "このロットから追跡対象をスキャンまたは選択してサンプル列として追加し、グリッドに結果を記録します。"
+msgid "Scan received"
+msgstr "スキャンを受け付けました"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "このQRコードをスキャンしてください(例:Google AuthenticatorまたはOnePassword)、その後に表示される6桁のコードを入力してください。"
@@ -2014,6 +2023,10 @@ msgstr "Carbon全体で使用されるアクセントカラー。"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "この工程の完了数量が必要数量 {targetQuantity} を下回っています。"
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "このランを構成する製造指図と部品"
diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.po
index f783bb9f31..549adaa4ee 100644
--- a/packages/locale/locales/ko/mes.po
+++ b/packages/locale/locales/ko/mes.po
@@ -993,6 +993,9 @@ msgstr "로드됨: {loadedLabel}"
msgid "Loading item details..."
msgstr "품목 세부정보를 불러오는 중..."
+msgid "Loading. There's no need to scan again."
+msgstr "로드 중입니다. 다시 스캔할 필요가 없습니다."
+
msgid "Loading..."
msgstr "불러오는 중..."
@@ -1289,6 +1292,9 @@ msgstr "없음"
msgid "Notes"
msgstr "메모"
+msgid "Nothing on this page uses that barcode"
+msgstr "이 페이지에서 해당 바코드를 사용하는 항목이 없습니다"
+
msgid "Nothing running"
msgstr "실행 중인 것 없음"
@@ -1703,6 +1709,9 @@ msgstr "시리얼 번호를 스캔하거나 검색하세요..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "이 로트에서 추적 대상을 스캔하거나 선택하여 샘플 열로 추가한 다음 그리드에 결과를 기록하세요."
+msgid "Scan received"
+msgstr "스캔을 받았습니다"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "인증 앱(예: Google Authenticator 또는 1Password)으로 이 QR 코드를 스캔한 후 표시되는 6자리 코드를 입력하십시오."
@@ -2014,6 +2023,10 @@ msgstr "Carbon 전체에서 사용되는 강조 색상입니다."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "이 공정작업의 완료 수량이 필요 수량 {targetQuantity}보다 적습니다."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "이 실행을 구성하는 작업 지시와 부품입니다."
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index 7628d92f77..e00570226b 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -993,6 +993,9 @@ msgstr "Załadowany: {loadedLabel}"
msgid "Loading item details..."
msgstr "Ładowanie szczegółów pozycji..."
+msgid "Loading. There's no need to scan again."
+msgstr "Ładowanie. Nie trzeba skanować ponownie."
+
msgid "Loading..."
msgstr "Ładowanie..."
@@ -1289,6 +1292,9 @@ msgstr "Brak"
msgid "Notes"
msgstr "Notatki"
+msgid "Nothing on this page uses that barcode"
+msgstr "Nic na tej stronie nie używa tego kodu kreskowego"
+
msgid "Nothing running"
msgstr "Nic nie działa"
@@ -1703,6 +1709,9 @@ msgstr "Skanuj lub wyszukaj numer seryjny..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "Skanuj lub wybierz jednostkę śledzoną z tej partii, aby dodać ją jako kolumnę próby, a następnie zapisz jej wynik w siatce."
+msgid "Scan received"
+msgstr "Skan odebrany"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "Skanuj ten kod QR aplikacją uwierzytelniającą (np. Google Authenticator lub 1Password), a następnie wprowadź 6-cyfrowy kod, który wyświetla."
@@ -2014,6 +2023,10 @@ msgstr "Kolor akcentu używany w Carbon."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "Ukończona ilość dla tej operacji jest mniejsza niż wymagana ilość {targetQuantity}."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "Zlecenia produkcyjne i części, które składają się na ten przebieg."
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index 110d235391..0b27b00c70 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -993,6 +993,9 @@ msgstr "Carregado: {loadedLabel}"
msgid "Loading item details..."
msgstr "Carregando detalhes do item..."
+msgid "Loading. There's no need to scan again."
+msgstr "Carregando. Não é necessário escanear novamente."
+
msgid "Loading..."
msgstr "Carregando..."
@@ -1289,6 +1292,9 @@ msgstr "Nenhum"
msgid "Notes"
msgstr "Observações"
+msgid "Nothing on this page uses that barcode"
+msgstr "Nada nesta página usa esse código de barras"
+
msgid "Nothing running"
msgstr "Nada em execução"
@@ -1703,6 +1709,9 @@ msgstr "Escanear ou pesquisar número de série..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "Escanear ou selecionar uma entidade rastreada deste lote para adicioná-la como coluna de amostra, depois registrar seu resultado na grade."
+msgid "Scan received"
+msgstr "Escaneamento recebido"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "Escaneie este código QR com seu aplicativo autenticador (por exemplo, Google Authenticator ou 1Password) e digite o código de 6 dígitos que ele exibe."
@@ -2014,6 +2023,10 @@ msgstr "A cor de destaque usada em todo o Carbon."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "A quantidade concluída para esta operação é menor que a quantidade requerida de {targetQuantity}."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "As ordens de produção e peças que compõem esta execução."
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index cf58960d62..4f461198df 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -993,6 +993,9 @@ msgstr "Загружена: {loadedLabel}"
msgid "Loading item details..."
msgstr "Загрузка данных номенклатуры..."
+msgid "Loading. There's no need to scan again."
+msgstr "Загрузка. Повторно сканировать не нужно."
+
msgid "Loading..."
msgstr "Загрузка..."
@@ -1289,6 +1292,9 @@ msgstr "Нет"
msgid "Notes"
msgstr "Примечания"
+msgid "Nothing on this page uses that barcode"
+msgstr "На этой странице ничто не использует этот штрихкод"
+
msgid "Nothing running"
msgstr "Ничего не работает"
@@ -1703,6 +1709,9 @@ msgstr "Сканировать или найти серийный номер..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "Сканировать или выбрать отслеживаемый объект из этой партии, чтобы добавить его как столбец образца, затем записать его результат в таблицу."
+msgid "Scan received"
+msgstr "Скан получен"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "Отсканируйте этот QR код с помощью приложения аутентификации (например, Google Authenticator или 1Password), затем введите 6-значный код, который оно покажет."
@@ -2014,6 +2023,10 @@ msgstr "Цвет акцента, используемый во всём Carbon."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "Количество готовой продукции по этой операции меньше требуемого количества {targetQuantity}."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "Производственные заказы и детали, которые составляют этот запуск."
diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.po
index 480c76444d..c8eef15b89 100644
--- a/packages/locale/locales/tr/mes.po
+++ b/packages/locale/locales/tr/mes.po
@@ -993,6 +993,9 @@ msgstr "Yüklendi: {loadedLabel}"
msgid "Loading item details..."
msgstr "Ürün detayları yükleniyor..."
+msgid "Loading. There's no need to scan again."
+msgstr "Yükleniyor. Tekrar taramanıza gerek yok."
+
msgid "Loading..."
msgstr "Yükleniyor..."
@@ -1289,6 +1292,9 @@ msgstr "Hiçbiri"
msgid "Notes"
msgstr "Notlar"
+msgid "Nothing on this page uses that barcode"
+msgstr "Bu sayfada hiçbir şey bu barkodu kullanmıyor"
+
msgid "Nothing running"
msgstr "Hiçbir şey çalışmıyor"
@@ -1703,6 +1709,9 @@ msgstr "Seri numaras tarayın veya arayın..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "Bu lottan izlenen bir varlığı tarayın veya seçin, onu bir örnek sütunu olarak ekleyin ve sonucunu ızgarada kaydedin."
+msgid "Scan received"
+msgstr "Tarama alındı"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "Bu QR kodunu kimlik doğrulayıcı uygulamanızla tarayın (örn. Google Authenticator veya 1Password), ardından gösterdiği 6 haneli kodu girin."
@@ -2014,6 +2023,10 @@ msgstr "Carbon'da kullanılan vurgu rengi."
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "Bu işlem için tamamlanan miktar, gerekli miktar olan {targetQuantity}'dan azdır."
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "Bu çalıştırmayı oluşturan iş emirleri ve parçalar."
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index dfed46f4ed..63a3dd213e 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -993,6 +993,9 @@ msgstr "已加载: {loadedLabel}"
msgid "Loading item details..."
msgstr "正在加载物料详情..."
+msgid "Loading. There's no need to scan again."
+msgstr "正在加载,无需再次扫码。"
+
msgid "Loading..."
msgstr "加载中..."
@@ -1289,6 +1292,9 @@ msgstr "无"
msgid "Notes"
msgstr "备注"
+msgid "Nothing on this page uses that barcode"
+msgstr "此页面上没有使用该条码的内容"
+
msgid "Nothing running"
msgstr "没有运行"
@@ -1703,6 +1709,9 @@ msgstr "扫码或搜索序列号..."
msgid "Scan or select a tracked entity from this lot to add it as a sample column, then record its result in the grid."
msgstr "从此批次中扫码或选择追踪实体并将其添加为样本列,然后在网格中记录其结果。"
+msgid "Scan received"
+msgstr "已收到扫码"
+
msgid "Scan this QR code with your authenticator app (e.g. Google Authenticator or 1Password), then enter the 6-digit code it shows."
msgstr "使用身份验证应用(如 Google Authenticator 或 1Password)扫码此 QR 代码,然后输入它显示的6位数代码。"
@@ -2014,6 +2023,10 @@ msgstr "整个 Carbon 中使用的强调色。"
msgid "The completed quantity for this operation is less than the required quantity of {targetQuantity}."
msgstr "此工序的完成数量小于所需数量 {targetQuantity}。"
+#. placeholder {0}: inspection.lotSize
+msgid "The entire lot of {0} will be rejected as non-conforming — {passes} sampled pass(es) and {fails} failure(s) so far. Route the units below to scrap or rework, or record the verdict only."
+msgstr ""
+
msgid "The jobs and parts that make up this run."
msgstr "组成此次运行的工单和零件。"
diff --git a/packages/react/src/__tests__/useKeyboardWedge.test.ts b/packages/react/src/__tests__/useKeyboardWedge.test.ts
index d1c16a3aa8..8f5cf1ab4a 100644
--- a/packages/react/src/__tests__/useKeyboardWedge.test.ts
+++ b/packages/react/src/__tests__/useKeyboardWedge.test.ts
@@ -3,7 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { describe, expect, it } from "vitest";
-import { typedByScanner } from "../hooks/useKeyboardWedge";
+import { ScanReader, typedByScanner } from "../hooks/useKeyboardWedge";
// A kanban URL is 70 characters: 69 gaps between its first and last key.
describe("typedByScanner", () => {
@@ -28,3 +28,65 @@ describe("typedByScanner", () => {
expect(typedByScanner(100, 100, 1)).toBe(false);
});
});
+
+const URL_TEXT = "https://erp.carbon.ms/api/kanban/complete/kbn_8f3k2m1q";
+
+/** Types `text` into `reader` from `start` at `gap` ms per key; returns the last key's time. */
+function type(reader: ScanReader, text: string, start: number, gap: number) {
+ let at = start;
+ for (const char of text) {
+ reader.key(char, at);
+ at += gap;
+ }
+ return at - gap;
+}
+
+describe("ScanReader", () => {
+ it("reads a scan at scanner speed", () => {
+ const reader = new ScanReader();
+ type(reader, URL_TEXT, 0, 8);
+ expect(reader.isScan()).toBe(true);
+ expect(reader.candidates()[0]).toBe(URL_TEXT);
+ });
+
+ it("drops a stray key pressed a second before the scan", () => {
+ const reader = new ScanReader();
+ reader.key("a", 0);
+ type(reader, URL_TEXT, 1000, 8);
+ expect(reader.candidates()[0]).toBe(URL_TEXT);
+ });
+
+ it("joins a scan the scanner paused for 400 ms part-way through", () => {
+ const reader = new ScanReader();
+ const last = type(reader, URL_TEXT.slice(0, 30), 0, 8);
+ type(reader, URL_TEXT.slice(30), last + 400, 8);
+ expect(reader.candidates()[0]).toBe(URL_TEXT);
+ });
+
+ it("keeps every printable character, including % # + and spaces", () => {
+ const reader = new ScanReader();
+ const text = "https://erp.carbon.ms/x/items?search=M6%20bolt+nut#top KB 1";
+ type(reader, text, 0, 8);
+ expect(reader.candidates()[0]).toBe(text);
+ });
+
+ it("holds keys back from the page only from the fourth scanner-speed key", () => {
+ const reader = new ScanReader();
+ const holds = [..."http"].map((char, i) => reader.key(char, i * 8).hold);
+ expect(holds).toEqual([false, false, false, true]);
+ });
+
+ it("never treats a person typing as a scan", () => {
+ const reader = new ScanReader();
+ type(reader, "hello", 0, 150);
+ expect(reader.isScan()).toBe(false);
+ expect(reader.typedByScanner()).toBe(false);
+ expect(reader.candidates()).toEqual(["o"]);
+ });
+
+ it("does not count two keys pressed together as a scan", () => {
+ const reader = new ScanReader();
+ type(reader, "gs", 0, 20);
+ expect(reader.isScan()).toBe(false);
+ });
+});
diff --git a/packages/react/src/__tests__/useKeyboardWedgeDom.test.tsx b/packages/react/src/__tests__/useKeyboardWedgeDom.test.tsx
new file mode 100644
index 0000000000..daa3c0b484
--- /dev/null
+++ b/packages/react/src/__tests__/useKeyboardWedgeDom.test.tsx
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// @vitest-environment jsdom
+
+import { act } from "react";
+import type { Root } from "react-dom/client";
+import { createRoot } from "react-dom/client";
+import { createMemoryRouter, RouterProvider } from "react-router";
+import {
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi
+} from "vitest";
+import { useKeyboardWedge, useScanPending } from "../hooks/useKeyboardWedge";
+
+const LABEL = "https://erp.carbon.ms/api/kanban/complete/kbn_8f3k2m1q";
+
+type Options = Parameters<typeof useKeyboardWedge>[0];
+
+let root: Root | undefined;
+let container: HTMLDivElement | undefined;
+let pending = false;
+
+function Harness({ options }: { options: Options }) {
+ useKeyboardWedge(options);
+ pending = useScanPending();
+ return <input aria-label="search" />;
+}
+
+function mount(options: Options) {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ const router = createMemoryRouter([
+ { path: "/", element: <Harness options={options} /> }
+ ]);
+ root = createRoot(container);
+ act(() => root!.render(<RouterProvider router={router} />));
+ return container.querySelector("input")!;
+}
+
+/** Dispatches one keydown and does what the browser would when nobody prevented it. */
+function press(key: string, target: EventTarget = document.body) {
+ const event = new KeyboardEvent("keydown", {
+ key,
+ bubbles: true,
+ cancelable: true
+ });
+ const notPrevented = target.dispatchEvent(event);
+ if (notPrevented && key.length === 1 && target instanceof HTMLInputElement) {
+ target.value += key;
+ }
+ return event;
+}
+
+/** Types `text` at scanner speed, then `suffix`; returns the suffix's event. */
+function scan(
+ text: string,
+ target: EventTarget = document.body,
+ suffix = "Enter"
+) {
+ for (const char of text) {
+ press(char, target);
+ vi.advanceTimersByTime(8);
+ }
+ return suffix ? press(suffix, target) : null;
+}
+
+beforeAll(() => {
+ (
+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
+ ).IS_REACT_ACT_ENVIRONMENT = true;
+});
+
+beforeEach(() => {
+ // jsdom stamps every event with Date.now(): faking it sets the key timing.
+ vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
+});
+
+afterEach(() => {
+ act(() => root?.unmount());
+ container?.remove();
+ root = undefined;
+ container = undefined;
+ vi.useRealTimers();
+});
+
+describe("useKeyboardWedge", () => {
+ it("acts on a scan, and keeps its keys and Enter from the page", () => {
+ const callback = vi.fn();
+ mount({ test: (input) => input === LABEL, callback });
+ const reachedPage = vi.fn();
+ document.addEventListener("keydown", reachedPage);
+
+ const enter = scan(LABEL);
+
+ document.removeEventListener("keydown", reachedPage);
+ expect(callback).toHaveBeenCalledWith(LABEL);
+ expect(enter?.defaultPrevented).toBe(true);
+ // The first three keys can't be told from a person yet; the rest are held.
+ expect(reachedPage).toHaveBeenCalledTimes(3);
+ });
+
+ it("ignores a stray key pressed a second before the scan", () => {
+ const callback = vi.fn();
+ mount({ test: (input) => input === LABEL, callback });
+ press("a");
+ vi.advanceTimersByTime(1000);
+ scan(LABEL);
+ expect(callback).toHaveBeenCalledWith(LABEL);
+ });
+
+ it("still sees the Enter when a component stops it", () => {
+ const callback = vi.fn();
+ mount({ test: (input) => input === LABEL, callback });
+ const combobox = document.createElement("div");
+ combobox.addEventListener("keydown", (event) => event.stopPropagation());
+ document.body.appendChild(combobox);
+
+ scan(LABEL, combobox);
+
+ combobox.remove();
+ expect(callback).toHaveBeenCalledWith(LABEL);
+ });
+
+ it("takes a scan out of a text field when it opted in", () => {
+ const callback = vi.fn();
+ const field = mount({
+ test: (input) => input === LABEL,
+ callback,
+ inTextFields: true
+ });
+ field.value = "bolt";
+ field.focus();
+
+ scan(LABEL, field);
+
+ expect(callback).toHaveBeenCalledWith(LABEL);
+ expect(field.value).toBe("bolt");
+ });
+
+ it("leaves a scan in a text field to the field when it did not opt in", () => {
+ const callback = vi.fn();
+ const field = mount({ test: (input) => input === LABEL, callback });
+ field.focus();
+
+ const enter = scan(LABEL, field);
+
+ expect(callback).not.toHaveBeenCalled();
+ expect(field.value).toBe(LABEL);
+ expect(enter?.defaultPrevented).toBe(false);
+ });
+
+ it("reports a scan nothing accepted, and keeps its Enter from the page", () => {
+ const onUnrecognized = vi.fn();
+ mount({ test: () => false, callback: vi.fn(), onUnrecognized });
+
+ const enter = scan("LOT-2026-0042");
+
+ expect(onUnrecognized).toHaveBeenCalledWith("LOT-2026-0042");
+ expect(enter?.defaultPrevented).toBe(true);
+ });
+
+ it("leaves an unrecognized scan in a text field alone", () => {
+ const onUnrecognized = vi.fn();
+ const field = mount({
+ test: () => false,
+ callback: vi.fn(),
+ inTextFields: true,
+ onUnrecognized
+ });
+ field.focus();
+
+ const enter = scan("LOT-2026-0042", field);
+
+ expect(onUnrecognized).not.toHaveBeenCalled();
+ expect(enter?.defaultPrevented).toBe(false);
+ expect(field.value).toBe("LOT-2026-0042");
+ });
+
+ it("waits out a pause before acting on a scan with no Enter", () => {
+ const callback = vi.fn();
+ // The first half of the label is a valid link on its own.
+ mount({ test: (input) => input.startsWith("https://"), callback });
+
+ scan(LABEL.slice(0, 30), document.body, "");
+ vi.advanceTimersByTime(400);
+ scan(LABEL.slice(30), document.body, "");
+ // `scan` already waited 8 ms after the last key: 699 ms of quiet so far.
+ vi.advanceTimersByTime(691);
+ expect(callback).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(1);
+ expect(callback).toHaveBeenCalledWith(LABEL);
+ });
+
+ it("stays pending until the action settles, and ignores a second scan meanwhile", async () => {
+ let settle: () => void = () => undefined;
+ const callback = vi.fn(
+ () => new Promise<void>((resolve) => (settle = resolve))
+ );
+ mount({ test: (input) => input === LABEL, callback });
+
+ act(() => void scan(LABEL));
+ expect(pending).toBe(true);
+
+ vi.advanceTimersByTime(1000);
+ const second = scan(LABEL);
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(second?.defaultPrevented).toBe(true);
+
+ await act(async () => settle());
+ expect(pending).toBe(false);
+ });
+});
diff --git a/packages/react/src/hooks/index.ts b/packages/react/src/hooks/index.ts
index cdca31a058..6599b5b90a 100644
--- a/packages/react/src/hooks/index.ts
+++ b/packages/react/src/hooks/index.ts
@@ -12,7 +12,7 @@ import { useIdle } from "./useIdle";
import useInitialDimensions from "./useInitialDimenions";
import { useInterval } from "./useInterval";
import { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect";
-import { useKeyboardWedge } from "./useKeyboardWedge";
+import { useKeyboardWedge, useScanPending } from "./useKeyboardWedge";
import useLocalStorage from "./useLocalStorage";
import {
getSystemMode,
@@ -59,6 +59,7 @@ export {
usePlan,
useRevalidator,
useRouteData,
+ useScanPending,
useShortcutKeyMap,
useShortcutKeys,
useShortcutSequence,
diff --git a/packages/react/src/hooks/useKeyboardWedge.ts b/packages/react/src/hooks/useKeyboardWedge.ts
index 42223ac483..07913a6515 100644
--- a/packages/react/src/hooks/useKeyboardWedge.ts
+++ b/packages/react/src/hooks/useKeyboardWedge.ts
@@ -2,21 +2,44 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useRef, useSyncExternalStore } from "react";
import { useNavigate } from "react-router";
+import { isTextEntryTarget } from "../utils/keyboard";
interface UseKeyboardWedgeOptions {
test: (input: string) => boolean;
- callback?: (input: string) => void;
+ /**
+ * Runs for an accepted scan. Return a promise (a navigation, a fetcher) and
+ * the scan stays pending until it settles: `useScanPending` reports it, and
+ * every other scan is ignored meanwhile, so a second scan of the same label
+ * does nothing.
+ */
+ callback?: (input: string) => unknown;
active?: boolean;
+ /**
+ * Also take scans made while a text field has focus. A matched scan is
+ * removed from the field; an unmatched one stays in it.
+ */
+ inTextFields?: boolean;
+ /** A scan no wedge on the page accepted, made outside a text field. */
+ onUnrecognized?: (input: string) => void;
}
/** A scanner types faster than this per key on average; a person never does. */
const SCANNER_KEY_GAP_MS = 50;
-/** A scan with no Enter suffix is over once no key arrives for this long. */
-const SCAN_END_MS = 200;
-/** A buffer nobody submitted is dropped after this long without a key. */
-const BUFFER_RESET_MS = 3000;
+/** A gap longer than this between two keys starts a new burst. */
+const NEW_BURST_GAP_MS = 80;
+/**
+ * A scan with no Enter or Tab suffix ends once no key arrives for this long.
+ * The wait also joins a scan a Bluetooth scanner paused part-way through: the
+ * first half of a URL is often a valid URL itself, so ending sooner would act
+ * on half a scan.
+ */
+const QUIET_END_MS = 700;
+/** Scanner-speed keys before they are kept from the page; below this, two keys pressed together would count. */
+const MIN_SCAN_LENGTH = 4;
+/** A pending scan whose callback never settles (a navigation that failed to load) stops blocking after this. */
+const PENDING_TIMEOUT_MS = 20_000;
/**
* Whether `length` keys typed between `firstKeyAt` and `lastKeyAt` came from
@@ -33,8 +56,234 @@ export function typedByScanner(
return (lastKeyAt - firstKeyAt) / (length - 1) < SCANNER_KEY_GAP_MS;
}
+type Burst = { text: string; firstAt: number; lastAt: number };
+
+/**
+ * Splits the keystream into bursts at every gap longer than
+ * `NEW_BURST_GAP_MS`. A burst at scanner speed is (part of) a scan; anything
+ * else is a person, and is dropped when the next burst starts — so a stray
+ * key can never sit in front of the next scan. Scanner bursts separated by a
+ * pause are kept (`held`) and joined.
+ */
+export class ScanReader {
+ private burst: Burst | null = null;
+ private held = "";
+
+ /**
+ * One printable key at `at` ms. `startsScan` is true for the first key of
+ * what may become a scan; `hold` is true once the key is part of a scan and
+ * should be kept from the page.
+ */
+ key(char: string, at: number): { startsScan: boolean; hold: boolean } {
+ let startsScan = false;
+ if (this.burst && at - this.burst.lastAt > NEW_BURST_GAP_MS) {
+ if (this.isScannerBurst(this.burst)) this.held += this.burst.text;
+ this.burst = null;
+ }
+ if (!this.burst) {
+ this.burst = { text: "", firstAt: at, lastAt: at };
+ startsScan = this.held === "";
+ }
+ this.burst.text += char;
+ this.burst.lastAt = at;
+ return { startsScan, hold: this.isScan() };
+ }
+
+ /** What the scan so far could be, most likely first. */
+ candidates(): string[] {
+ if (!this.burst) return this.held ? [this.held] : [];
+ const joinable =
+ this.held &&
+ (this.isScannerBurst(this.burst) || this.burst.text.length <= 2);
+ return joinable
+ ? [this.held + this.burst.text, this.burst.text]
+ : [this.burst.text];
+ }
+
+ /** Long enough, and fast enough, to be a scan rather than a person. */
+ isScan(): boolean {
+ const length = this.held.length + (this.burst?.text.length ?? 0);
+ return (
+ length >= MIN_SCAN_LENGTH &&
+ (this.held !== "" || this.isScannerBurst(this.burst))
+ );
+ }
+
+ /** Typed by a scanner at all, however short (a scan with no Enter suffix ends on this). */
+ typedByScanner(): boolean {
+ return this.held !== "" || this.isScannerBurst(this.burst);
+ }
+
+ reset() {
+ this.burst = null;
+ this.held = "";
+ }
+
+ private isScannerBurst(burst: Burst | null): boolean {
+ return (
+ !!burst && typedByScanner(burst.firstAt, burst.lastAt, burst.text.length)
+ );
+ }
+}
+
+type Handler = Required<
+ Pick<UseKeyboardWedgeOptions, "test" | "inTextFields">
+> & {
+ callback: (input: string) => unknown;
+ onUnrecognized?: (input: string) => void;
+};
+
+// One reader for the page, however many wedges are mounted: the layout's and a
+// screen's own see the same scan, and only one of them acts on it.
+const handlers = new Set<{ current: Handler }>();
+const reader = new ScanReader();
+let origin: {
+ inField: boolean;
+ field: TextField | null;
+ value: string;
+} | null = null;
+let quietTimer: ReturnType<typeof setTimeout> | undefined;
+
+let pending = false;
+const pendingListeners = new Set<() => void>();
+function setPending(next: boolean) {
+ if (pending === next) return;
+ pending = next;
+ for (const listener of pendingListeners) listener();
+}
+
+type TextField = HTMLInputElement | HTMLTextAreaElement;
+function textField(target: EventTarget | null): TextField | null {
+ return target instanceof HTMLInputElement ||
+ target instanceof HTMLTextAreaElement
+ ? target
+ : null;
+}
+
+// Through the native setter, so a controlled input's onChange sees it.
+function restoreField(field: TextField, value: string) {
+ const prototype =
+ field instanceof HTMLTextAreaElement
+ ? HTMLTextAreaElement.prototype
+ : HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(prototype, "value")?.set?.call(field, value);
+ field.dispatchEvent(new Event("input", { bubbles: true }));
+}
+
+function swallow(event: KeyboardEvent | null) {
+ event?.preventDefault();
+ event?.stopImmediatePropagation();
+}
+
+function run(handler: Handler, input: string) {
+ const result = handler.callback(input);
+ if (!(result instanceof Promise)) return;
+ setPending(true);
+ const timeout = setTimeout(() => setPending(false), PENDING_TIMEOUT_MS);
+ const settle = () => {
+ clearTimeout(timeout);
+ setPending(false);
+ };
+ result.then(settle, settle);
+}
+
+/** Ends the scan in progress: on Enter or Tab (`event`), or when it went quiet (`null`). */
+function finish(event: KeyboardEvent | null) {
+ clearTimeout(quietTimer);
+ const candidates = reader.candidates();
+ const isScan = reader.isScan();
+ const byScanner = reader.typedByScanner();
+ const from = origin;
+ reader.reset();
+ origin = null;
+ if (!candidates.length || (!event && !byScanner)) return;
+
+ if (pending) {
+ // A scan is already being handled: this is the second scan of the label.
+ if (isScan && !from?.inField) swallow(event);
+ return;
+ }
+
+ const eligible = [...handlers]
+ .map((handler) => handler.current)
+ .filter((handler) => !from?.inField || handler.inTextFields);
+ for (const input of candidates) {
+ const handler = eligible.find((h) => h.test(input));
+ if (!handler) continue;
+ swallow(event);
+ if (from?.field) restoreField(from.field, from.value);
+ run(handler, input);
+ return;
+ }
+
+ // An unrecognized scan never clicks the focused button. In a text field it
+ // is the field's: someone scanned a lot number into it.
+ if (!isScan || from?.inField) return;
+ swallow(event);
+ const [input] = candidates;
+ if (input) eligible.find((h) => h.onUnrecognized)?.onUnrecognized?.(input);
+}
+
+function handleKeyDown(event: KeyboardEvent) {
+ if (event.ctrlKey || event.metaKey || event.altKey) return;
+
+ if (event.key.length === 1) {
+ const { startsScan, hold } = reader.key(event.key, event.timeStamp);
+ if (startsScan) {
+ const field = textField(event.target);
+ origin = {
+ inField: isTextEntryTarget(event.target),
+ field,
+ value: field?.value ?? ""
+ };
+ }
+ // Held keys never reach the page's shortcuts (Space is Start/Pause). In a
+ // text field they type as usual until the scan is matched.
+ if (hold && !origin?.inField) swallow(event);
+ clearTimeout(quietTimer);
+ quietTimer = setTimeout(() => finish(null), QUIET_END_MS);
+ } else if (
+ event.key === "Enter" ||
+ (event.key === "Tab" && reader.isScan())
+ ) {
+ finish(event);
+ } else if (event.key === "Escape") {
+ clearTimeout(quietTimer);
+ reader.reset();
+ origin = null;
+ }
+}
+
+function register(handler: { current: Handler }) {
+ handlers.add(handler);
+ // Capture on window: runs before any component can stop the key.
+ if (handlers.size === 1) {
+ window.addEventListener("keydown", handleKeyDown, true);
+ }
+ return () => {
+ handlers.delete(handler);
+ if (handlers.size === 0) {
+ window.removeEventListener("keydown", handleKeyDown, true);
+ clearTimeout(quietTimer);
+ reader.reset();
+ origin = null;
+ }
+ };
+}
+
+/** True while an accepted scan's action is still running. */
+export function useScanPending() {
+ return useSyncExternalStore(
+ (listener) => {
+ pendingListeners.add(listener);
+ return () => pendingListeners.delete(listener);
+ },
+ () => pending,
+ () => false
+ );
+}
+
export function useKeyboardWedge(options?: UseKeyboardWedgeOptions) {
- const [inputBuffer, setInputBuffer] = useState("");
const navigate = useNavigate();
// Default test and callback for backward compatibility
@@ -44,97 +293,35 @@ export function useKeyboardWedge(options?: UseKeyboardWedgeOptions) {
try {
url = new URL(input);
} catch {
- navigate(input);
- return;
+ return navigate(input);
}
// A link into the other app (an ERP kanban scanned in the MES) has a
- // different origin, and its path does not exist here: load it there.
+ // different origin, and its path does not exist here: load it there. The
+ // page unloads when it arrives, so the scan stays pending until then.
if (url.origin !== window.location.origin) {
window.location.assign(url.href);
- return;
+ return new Promise<void>((resolve) => {
+ // Back from the bfcache: the page never unloaded.
+ window.addEventListener("pageshow", () => resolve(), { once: true });
+ });
}
- navigate(url.pathname + url.search);
+ return navigate(url.pathname + url.search);
};
- const test = options?.test ?? defaultTest;
- const callback = options?.callback ?? defaultCallback;
const active = options?.active ?? true;
- // Callers pass inline functions; the listener reads the latest ones so it
- // never re-subscribes (and loses the buffer) mid-scan.
- const handlers = useRef({ test, callback });
- handlers.current = { test, callback };
+ // Callers pass inline functions; the reader calls the latest ones, so the
+ // wedge never re-registers mid-scan.
+ const handler = useRef<Handler>(null!);
+ handler.current = {
+ test: options?.test ?? defaultTest,
+ callback: options?.callback ?? defaultCallback,
+ inTextFields: options?.inTextFields ?? false,
+ onUnrecognized: options?.onUnrecognized
+ };
useEffect(() => {
if (!active) return;
-
- // The buffer lives here, not in state: the Enter that ends a scan must
- // see every key before it, whether or not React has re-rendered since.
- let buffer = "";
- let firstKeyAt = 0;
- let lastKeyAt = 0;
- let scanEndTimer: ReturnType<typeof setTimeout> | undefined;
- let resetTimer: ReturnType<typeof setTimeout> | undefined;
-
- const clear = () => {
- buffer = "";
- clearTimeout(scanEndTimer);
- clearTimeout(resetTimer);
- setInputBuffer("");
- };
-
- // A scanner with no Enter suffix: submit once the burst goes quiet.
- const endScan = () => {
- if (
- typedByScanner(firstKeyAt, lastKeyAt, buffer.length) &&
- handlers.current.test(buffer)
- ) {
- const input = buffer;
- clear();
- handlers.current.callback(input);
- }
- };
-
- const handleKeyDown = (event: KeyboardEvent) => {
- // Check if the active element is an input or textarea
- const activeElement = document.activeElement;
- if (
- activeElement &&
- (activeElement.tagName === "INPUT" ||
- activeElement.tagName === "TEXTAREA")
- ) {
- return;
- }
-
- if (/^[a-zA-Z0-9\-./:?=&_]$/.test(event.key)) {
- const now = Date.now();
- if (buffer === "") firstKeyAt = now;
- lastKeyAt = now;
- buffer += event.key;
- setInputBuffer(buffer);
- clearTimeout(scanEndTimer);
- clearTimeout(resetTimer);
- scanEndTimer = setTimeout(endScan, SCAN_END_MS);
- resetTimer = setTimeout(clear, BUFFER_RESET_MS);
- } else if (event.key === "Enter") {
- const input = buffer;
- clear();
- if (handlers.current.test(input)) {
- event.preventDefault();
- handlers.current.callback(input);
- }
- } else if (event.key === "Escape") {
- clear();
- }
- };
-
- document.addEventListener("keydown", handleKeyDown);
-
- return () => {
- document.removeEventListener("keydown", handleKeyDown);
- clear();
- };
+ return register(handler);
}, [active]);
-
- return inputBuffer;
}