@gemina/elements 0.5.4 → 0.7.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.
package/dist/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -22,6 +32,7 @@ var src_exports = {};
22
32
  __export(src_exports, {
23
33
  GeminaChat: () => GeminaChat,
24
34
  GeminaTokenManager: () => GeminaTokenManager,
35
+ GeminaVerification: () => GeminaVerification,
25
36
  VERSION: () => VERSION
26
37
  });
27
38
  module.exports = __toCommonJS(src_exports);
@@ -163,12 +174,7 @@ var GeminaTokenManager = class {
163
174
  var import_react = require("react");
164
175
  var import_sdk = require("@gemina/sdk");
165
176
 
166
- // src/version.ts
167
- var VERSION = "0.5.4";
168
-
169
- // src/chat.tsx
170
- var import_jsx_runtime = require("react/jsx-runtime");
171
- var HEBREW_RE = /[\u0590-\u05FF]/;
177
+ // src/internal/response-like.ts
172
178
  function getResponseLike(error) {
173
179
  if (error !== null && typeof error === "object" && "response" in error) {
174
180
  const response = error.response;
@@ -182,29 +188,16 @@ function httpStatus(error) {
182
188
  const status = getResponseLike(error)?.status;
183
189
  return typeof status === "number" ? status : void 0;
184
190
  }
185
- var ERR_CHAT_QUOTA_EXCEEDED = "CHAT_QUOTA_EXCEEDED";
186
- var ERR_DI_NOT_IN_PLAN = "DOCUMENT_INTELLIGENCE_NOT_IN_PLAN";
187
- var ERR_UNPROCESSABLE = "UNPROCESSABLE_ERROR";
188
- var ERR_BAD_GATEWAY = "BAD_GATEWAY_ERROR";
189
- var ERR_CHAT_SESSION_NOT_FOUND = "CHAT_SESSION_NOT_FOUND";
190
- async function readChatError(error) {
191
+ async function readErrorEnvelope(error) {
191
192
  const response = getResponseLike(error);
192
193
  const info = {
193
194
  status: typeof response?.status === "number" ? response.status : void 0,
194
195
  errorCode: void 0,
195
- description: void 0,
196
- retryAfterSeconds: void 0
196
+ description: void 0
197
197
  };
198
198
  if (response === void 0) {
199
199
  return info;
200
200
  }
201
- const rawRetryAfter = response.headers?.get?.("retry-after");
202
- if (rawRetryAfter !== null && rawRetryAfter !== void 0) {
203
- const seconds = Number(rawRetryAfter);
204
- if (Number.isFinite(seconds) && seconds > 0) {
205
- info.retryAfterSeconds = seconds;
206
- }
207
- }
208
201
  let body;
209
202
  try {
210
203
  const source = typeof response.clone === "function" ? response.clone() : response;
@@ -226,6 +219,30 @@ async function readChatError(error) {
226
219
  }
227
220
  return info;
228
221
  }
222
+
223
+ // src/version.ts
224
+ var VERSION = "0.7.0";
225
+
226
+ // src/chat.tsx
227
+ var import_jsx_runtime = require("react/jsx-runtime");
228
+ var HEBREW_RE = /[\u0590-\u05FF]/;
229
+ var ERR_CHAT_QUOTA_EXCEEDED = "CHAT_QUOTA_EXCEEDED";
230
+ var ERR_DI_NOT_IN_PLAN = "DOCUMENT_INTELLIGENCE_NOT_IN_PLAN";
231
+ var ERR_UNPROCESSABLE = "UNPROCESSABLE_ERROR";
232
+ var ERR_BAD_GATEWAY = "BAD_GATEWAY_ERROR";
233
+ var ERR_CHAT_SESSION_NOT_FOUND = "CHAT_SESSION_NOT_FOUND";
234
+ async function readChatError(error) {
235
+ const envelope = await readErrorEnvelope(error);
236
+ const info = { ...envelope, retryAfterSeconds: void 0 };
237
+ const rawRetryAfter = getResponseLike(error)?.headers?.get?.("retry-after");
238
+ if (rawRetryAfter !== null && rawRetryAfter !== void 0) {
239
+ const seconds = Number(rawRetryAfter);
240
+ if (Number.isFinite(seconds) && seconds > 0) {
241
+ info.retryAfterSeconds = seconds;
242
+ }
243
+ }
244
+ return info;
245
+ }
229
246
  var SESSION_EXPIRED_TEXT = "Session expired \u2014 please reload the page or sign in again.";
230
247
  var CONVERSATION_RESET_TEXT = "This conversation is no longer available \u2014 send your message again to start a new one.";
231
248
  var RATE_LIMIT_TEXT = "You're sending messages too quickly \u2014 try again shortly.";
@@ -851,10 +868,2681 @@ function GeminaChat(props) {
851
868
  ] })
852
869
  ] });
853
870
  }
871
+
872
+ // src/verification/index.tsx
873
+ var import_react4 = require("react");
874
+ var import_sdk2 = require("@gemina/sdk");
875
+
876
+ // src/verification/classify.ts
877
+ var ACRONYMS = /* @__PURE__ */ new Set(["ID", "VAT", "OCR", "PDF", "URL", "API", "HTML", "CSS", "JSON", "XML", "UUID"]);
878
+ function formatLabel(key) {
879
+ const words = key.replace(/([a-z])([A-Z])/g, "$1 $2").replace(/_/g, " ").split(" ").filter(Boolean);
880
+ return words.map((word) => {
881
+ const upper = word.toUpperCase();
882
+ if (ACRONYMS.has(upper)) {
883
+ return upper;
884
+ }
885
+ return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
886
+ }).join(" ");
887
+ }
888
+ function formatValue(value, fieldName) {
889
+ if (value === null || value === void 0) {
890
+ return "-";
891
+ }
892
+ if (typeof value === "boolean") {
893
+ return value ? "Yes" : "No";
894
+ }
895
+ if (typeof value === "number") {
896
+ if (fieldName && /rate|percent/i.test(fieldName)) {
897
+ return `${value}%`;
898
+ }
899
+ if (fieldName && /number|num|id|code|phone|fax|postal|zip/i.test(fieldName)) {
900
+ return String(value);
901
+ }
902
+ return value.toLocaleString();
903
+ }
904
+ if (typeof value === "string") {
905
+ if (/^\d{4}-\d{2}-\d{2}(T|$)/.test(value)) {
906
+ try {
907
+ const date = new Date(value);
908
+ if (!isNaN(date.getTime())) {
909
+ return date.toLocaleDateString();
910
+ }
911
+ } catch {
912
+ }
913
+ }
914
+ return value;
915
+ }
916
+ return String(value);
917
+ }
918
+ function isValueObject(obj) {
919
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
920
+ return false;
921
+ }
922
+ return "value" in obj;
923
+ }
924
+ function isPrimitiveArray(arr) {
925
+ if (arr.length === 0) return false;
926
+ return arr.every((item) => item === null || typeof item !== "object");
927
+ }
928
+ function isSimpleValueArray(arr) {
929
+ if (arr.length === 0) return false;
930
+ return arr.every((item) => isValueObject(item) && Object.keys(item).every((k) => ["value", "coordinates", "confidence", "confidence_reasons"].includes(k)));
931
+ }
932
+ function isTableArray(arr) {
933
+ if (arr.length === 0) return false;
934
+ const first = arr[0];
935
+ if (!first || typeof first !== "object" || Array.isArray(first)) return false;
936
+ const metaFields = /* @__PURE__ */ new Set(["confidence", "confidence_reasons", "coordinates"]);
937
+ const keys = Object.keys(first).filter((k) => !metaFields.has(k));
938
+ if (keys.length > 3) {
939
+ const firstObj = first;
940
+ const nonMetaValues = keys.map((k) => firstObj[k]);
941
+ const allSimple = nonMetaValues.every(
942
+ (v) => v === null || typeof v !== "object" || isValueObject(v)
943
+ );
944
+ return allSimple;
945
+ }
946
+ return false;
947
+ }
948
+ function isEntityArray(arr) {
949
+ if (arr.length === 0) return false;
950
+ if (isPrimitiveArray(arr)) return false;
951
+ if (isSimpleValueArray(arr)) return false;
952
+ if (isTableArray(arr)) return false;
953
+ const first = arr[0];
954
+ if (!first || typeof first !== "object" || Array.isArray(first)) return false;
955
+ return true;
956
+ }
957
+ function extractValue(field) {
958
+ if (isValueObject(field)) {
959
+ return field.value;
960
+ }
961
+ return field;
962
+ }
963
+ function extractCoordinates(field) {
964
+ if (isValueObject(field) && field.coordinates) {
965
+ const coords = field.coordinates;
966
+ if (coords.relative) {
967
+ return { points: coords.relative };
968
+ }
969
+ }
970
+ return null;
971
+ }
972
+ function extractConfidence(field) {
973
+ if (isValueObject(field) && field.confidence) {
974
+ return {
975
+ level: field.confidence,
976
+ reasons: field.confidence_reasons || []
977
+ };
978
+ }
979
+ return null;
980
+ }
981
+ function escapeSegment(segment) {
982
+ return segment.replace(/~/g, "~0").replace(/\//g, "~1");
983
+ }
984
+ var ROW_META_KEY = "_rowMeta";
985
+ function classifyData(data) {
986
+ const result = {
987
+ headers: [],
988
+ simpleLists: [],
989
+ entities: [],
990
+ tables: [],
991
+ fallback: []
992
+ };
993
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
994
+ return result;
995
+ }
996
+ let rootData = data;
997
+ let basePointer = "";
998
+ if ("data" in rootData && typeof rootData.data === "object" && rootData.data !== null && !Array.isArray(rootData.data)) {
999
+ for (const [key, value] of Object.entries(rootData)) {
1000
+ if (key === "data") continue;
1001
+ processField(key, value, result, rootData, "");
1002
+ }
1003
+ rootData = rootData.data;
1004
+ basePointer = "/data";
1005
+ }
1006
+ for (const [key, value] of Object.entries(rootData)) {
1007
+ processField(key, value, result, rootData, basePointer);
1008
+ }
1009
+ return result;
1010
+ }
1011
+ function processField(key, value, result, parentObj, basePointer) {
1012
+ if (["confidence", "confidence_reasons", "coordinates", "overall_confidence"].includes(key)) {
1013
+ return;
1014
+ }
1015
+ const pointer = `${basePointer}/${escapeSegment(key)}`;
1016
+ if (value === null || typeof value !== "object") {
1017
+ result.headers.push({
1018
+ key,
1019
+ pointer,
1020
+ value,
1021
+ coordinates: null,
1022
+ confidence: null
1023
+ });
1024
+ return;
1025
+ }
1026
+ if (isValueObject(value)) {
1027
+ result.headers.push({
1028
+ key,
1029
+ pointer,
1030
+ value: extractValue(value),
1031
+ coordinates: extractCoordinates(value),
1032
+ confidence: extractConfidence(value)
1033
+ });
1034
+ return;
1035
+ }
1036
+ if (Array.isArray(value)) {
1037
+ if (value.length === 0) {
1038
+ result.headers.push({
1039
+ key,
1040
+ pointer,
1041
+ value: null,
1042
+ coordinates: null,
1043
+ confidence: null
1044
+ });
1045
+ return;
1046
+ }
1047
+ if (isPrimitiveArray(value)) {
1048
+ result.simpleLists.push({
1049
+ key,
1050
+ pointer,
1051
+ items: value.map((item, index) => ({
1052
+ pointer: `${pointer}/${index}`,
1053
+ value: item,
1054
+ coordinates: null,
1055
+ confidence: null
1056
+ }))
1057
+ });
1058
+ return;
1059
+ }
1060
+ if (isSimpleValueArray(value)) {
1061
+ result.simpleLists.push({
1062
+ key,
1063
+ pointer,
1064
+ items: value.map((item, index) => ({
1065
+ pointer: `${pointer}/${index}`,
1066
+ value: extractValue(item),
1067
+ coordinates: extractCoordinates(item),
1068
+ confidence: extractConfidence(item)
1069
+ }))
1070
+ });
1071
+ return;
1072
+ }
1073
+ if (isTableArray(value)) {
1074
+ const first = value[0];
1075
+ const metaFields = /* @__PURE__ */ new Set(["confidence", "confidence_reasons", "coordinates"]);
1076
+ const columns = Object.keys(first).filter((k) => !metaFields.has(k));
1077
+ let overallConfidence = null;
1078
+ if (parentObj) {
1079
+ const confidenceKey = `${key}_confidence`;
1080
+ const reasonsKey = `${key}_confidence_reasons`;
1081
+ if (parentObj[confidenceKey]) {
1082
+ overallConfidence = {
1083
+ level: parentObj[confidenceKey],
1084
+ reasons: parentObj[reasonsKey] || []
1085
+ };
1086
+ } else if (parentObj["overall_confidence"]) {
1087
+ overallConfidence = {
1088
+ level: parentObj["overall_confidence"],
1089
+ reasons: parentObj["confidence_reasons"] || []
1090
+ };
1091
+ }
1092
+ }
1093
+ result.tables.push({
1094
+ key,
1095
+ pointer,
1096
+ columns,
1097
+ overallConfidence,
1098
+ rows: value.map((row, rowIndex) => {
1099
+ const rowPointer = `${pointer}/${rowIndex}`;
1100
+ const rowData = {};
1101
+ const rowObj = row ?? {};
1102
+ for (const col of columns) {
1103
+ const cell = rowObj[col];
1104
+ rowData[col] = {
1105
+ pointer: `${rowPointer}/${escapeSegment(col)}`,
1106
+ value: extractValue(cell),
1107
+ coordinates: extractCoordinates(cell),
1108
+ confidence: extractConfidence(cell)
1109
+ };
1110
+ }
1111
+ if (rowObj.confidence || rowObj.confidence_reasons) {
1112
+ rowData[ROW_META_KEY] = {
1113
+ pointer: rowPointer,
1114
+ value: null,
1115
+ coordinates: null,
1116
+ confidence: {
1117
+ level: rowObj.confidence || "",
1118
+ reasons: rowObj.confidence_reasons || []
1119
+ }
1120
+ };
1121
+ }
1122
+ return rowData;
1123
+ })
1124
+ });
1125
+ return;
1126
+ }
1127
+ if (isEntityArray(value)) {
1128
+ result.entities.push({
1129
+ key,
1130
+ pointer,
1131
+ items: value.map((item, index) => {
1132
+ const entity = {};
1133
+ if (item === null || typeof item !== "object" || Array.isArray(item)) {
1134
+ return entity;
1135
+ }
1136
+ for (const [fieldKey, fieldValue] of Object.entries(item)) {
1137
+ if (["confidence", "confidence_reasons", "coordinates"].includes(fieldKey)) {
1138
+ continue;
1139
+ }
1140
+ entity[fieldKey] = {
1141
+ pointer: `${pointer}/${index}/${escapeSegment(fieldKey)}`,
1142
+ value: extractValue(fieldValue),
1143
+ coordinates: extractCoordinates(fieldValue),
1144
+ confidence: extractConfidence(fieldValue)
1145
+ };
1146
+ }
1147
+ return entity;
1148
+ })
1149
+ });
1150
+ return;
1151
+ }
1152
+ result.fallback.push({ key, data: value });
1153
+ return;
1154
+ }
1155
+ const nestedObj = value;
1156
+ const nestedKeys = Object.keys(nestedObj).filter((k) => !["confidence", "confidence_reasons", "coordinates"].includes(k));
1157
+ if (nestedKeys.length > 0 && nestedKeys.length <= 10) {
1158
+ for (const nestedKey of nestedKeys) {
1159
+ const nestedValue = nestedObj[nestedKey];
1160
+ const combinedKey = `${key}.${nestedKey}`;
1161
+ const nestedPointer = `${pointer}/${escapeSegment(nestedKey)}`;
1162
+ if (nestedValue === null || typeof nestedValue !== "object") {
1163
+ result.headers.push({
1164
+ key: combinedKey,
1165
+ pointer: nestedPointer,
1166
+ value: nestedValue,
1167
+ coordinates: null,
1168
+ confidence: null
1169
+ });
1170
+ } else if (isValueObject(nestedValue)) {
1171
+ result.headers.push({
1172
+ key: combinedKey,
1173
+ pointer: nestedPointer,
1174
+ value: extractValue(nestedValue),
1175
+ coordinates: extractCoordinates(nestedValue),
1176
+ confidence: extractConfidence(nestedValue)
1177
+ });
1178
+ } else {
1179
+ result.fallback.push({ key: combinedKey, data: nestedValue });
1180
+ }
1181
+ }
1182
+ return;
1183
+ }
1184
+ result.fallback.push({ key, data: value });
1185
+ }
1186
+
1187
+ // src/verification/pointer.ts
1188
+ var KEY_RE = /^label:([^|]+)\|ptr:(\/.*)$/;
1189
+ function parseSchemaKey(raw) {
1190
+ const match = KEY_RE.exec(raw);
1191
+ if (match === null) {
1192
+ return null;
1193
+ }
1194
+ return { raw, label: match[1], pointer: match[2] };
1195
+ }
1196
+ var NOT_FOUND = /* @__PURE__ */ Symbol("gemina-verification-not-found");
1197
+
1198
+ // src/verification/bindings.ts
1199
+ function unescapeSegment(raw) {
1200
+ return raw.replace(/~1/g, "/").replace(/~0/g, "~");
1201
+ }
1202
+ function escapeSegment2(segment) {
1203
+ return segment.replace(/~/g, "~0").replace(/\//g, "~1");
1204
+ }
1205
+ function snakeToCamel(segment) {
1206
+ return segment.replace(/_([a-zA-Z0-9])/g, (_, ch) => ch.toUpperCase());
1207
+ }
1208
+ function camelizePointer(pointer) {
1209
+ if (!pointer.startsWith("/")) {
1210
+ return pointer;
1211
+ }
1212
+ return "/" + pointer.slice(1).split("/").map((raw) => escapeSegment2(snakeToCamel(unescapeSegment(raw)))).join("/");
1213
+ }
1214
+ function resolveCasingAware(doc, pointer) {
1215
+ const missing = { node: NOT_FOUND, resolvedPointer: camelizePointer(pointer) };
1216
+ if (pointer === "") {
1217
+ return { node: doc, resolvedPointer: "" };
1218
+ }
1219
+ if (!pointer.startsWith("/")) {
1220
+ return missing;
1221
+ }
1222
+ let current = doc;
1223
+ const matched = [];
1224
+ for (const rawSegment of pointer.slice(1).split("/")) {
1225
+ const segment = unescapeSegment(rawSegment);
1226
+ if (Array.isArray(current)) {
1227
+ if (!/^\d+$/.test(segment)) {
1228
+ return missing;
1229
+ }
1230
+ const index = Number(segment);
1231
+ if (index >= current.length) {
1232
+ return missing;
1233
+ }
1234
+ current = current[index];
1235
+ matched.push(rawSegment);
1236
+ } else if (current !== null && typeof current === "object") {
1237
+ let key;
1238
+ if (Object.prototype.hasOwnProperty.call(current, segment)) {
1239
+ key = segment;
1240
+ } else {
1241
+ const camel = snakeToCamel(segment);
1242
+ if (camel === segment || !Object.prototype.hasOwnProperty.call(current, camel)) {
1243
+ return missing;
1244
+ }
1245
+ key = camel;
1246
+ }
1247
+ current = current[key];
1248
+ matched.push(escapeSegment2(key));
1249
+ } else {
1250
+ return missing;
1251
+ }
1252
+ }
1253
+ return { node: current, resolvedPointer: "/" + matched.join("/") };
1254
+ }
1255
+ function stripValueSuffix(pointer) {
1256
+ return pointer.endsWith("/value") ? pointer.slice(0, -"/value".length) : pointer;
1257
+ }
1258
+ function buildBindings(validationSchema, values) {
1259
+ const bindings = [];
1260
+ for (const raw of validationSchema) {
1261
+ const key = parseSchemaKey(raw);
1262
+ if (key === null) {
1263
+ continue;
1264
+ }
1265
+ const { node: serverValue, resolvedPointer } = resolveCasingAware(values, key.pointer);
1266
+ const extracted = serverValue !== NOT_FOUND && isValueObject(serverValue) ? serverValue.value : serverValue;
1267
+ const editable = serverValue === NOT_FOUND || serverValue === null || typeof serverValue !== "object";
1268
+ bindings.push({
1269
+ key,
1270
+ serverValue,
1271
+ extracted,
1272
+ fieldPointer: stripValueSuffix(resolvedPointer),
1273
+ editable
1274
+ });
1275
+ }
1276
+ return bindings;
1277
+ }
1278
+ function indexBindingsByFieldPointer(bindings) {
1279
+ const map = /* @__PURE__ */ new Map();
1280
+ for (const binding of bindings) {
1281
+ map.set(binding.fieldPointer, binding);
1282
+ }
1283
+ return map;
1284
+ }
1285
+ function toInputString(extracted) {
1286
+ if (extracted === NOT_FOUND || extracted === null || extracted === void 0) {
1287
+ return "";
1288
+ }
1289
+ if (typeof extracted === "object") {
1290
+ return JSON.stringify(extracted);
1291
+ }
1292
+ return String(extracted);
1293
+ }
1294
+ function composeSubmission(bindings, edits) {
1295
+ const data = {};
1296
+ const byLabel = {};
1297
+ let confirmed = 0;
1298
+ let corrected = 0;
1299
+ for (const binding of bindings) {
1300
+ const edit = edits.get(binding.key.raw);
1301
+ if (edit !== void 0) {
1302
+ const trimmed = edit.trim();
1303
+ if (trimmed === "" && binding.serverValue === NOT_FOUND) {
1304
+ continue;
1305
+ }
1306
+ const value = trimmed === "" ? null : trimmed;
1307
+ data[binding.key.raw] = value;
1308
+ byLabel[binding.key.label] = value;
1309
+ corrected += 1;
1310
+ } else {
1311
+ if (binding.serverValue === NOT_FOUND) {
1312
+ continue;
1313
+ }
1314
+ data[binding.key.raw] = binding.serverValue;
1315
+ byLabel[binding.key.label] = binding.serverValue;
1316
+ confirmed += 1;
1317
+ }
1318
+ }
1319
+ return { data, byLabel, confirmed, corrected };
1320
+ }
1321
+
1322
+ // src/verification/form.tsx
1323
+ var import_react3 = __toESM(require("react"), 1);
1324
+
1325
+ // src/verification/viewer.tsx
1326
+ var import_react2 = require("react");
1327
+
1328
+ // src/verification/viewer-math.ts
1329
+ function fitScaleFor(natural, container, rotationDeg) {
1330
+ const rot = (rotationDeg % 180 + 180) % 180;
1331
+ const w = rot === 90 ? natural.h : natural.w;
1332
+ const h = rot === 90 ? natural.w : natural.h;
1333
+ const s = Math.min(container.w / w, container.h / h);
1334
+ return isFinite(s) && s > 0 ? s : 1;
1335
+ }
1336
+ function rotatedBox(natural, scale, rotationDeg) {
1337
+ const w0 = natural.w;
1338
+ const h0 = natural.h;
1339
+ const s = scale;
1340
+ const rot = (rotationDeg % 360 + 360) % 360;
1341
+ switch (rot) {
1342
+ case 0:
1343
+ return { W: w0 * s, H: h0 * s, minX: 0, minY: 0 };
1344
+ case 90:
1345
+ return { W: h0 * s, H: w0 * s, minX: -h0 * s, minY: 0 };
1346
+ case 180:
1347
+ return { W: w0 * s, H: h0 * s, minX: -w0 * s, minY: -h0 * s };
1348
+ case 270:
1349
+ return { W: h0 * s, H: w0 * s, minX: 0, minY: -w0 * s };
1350
+ default:
1351
+ return { W: w0 * s, H: h0 * s, minX: 0, minY: 0 };
1352
+ }
1353
+ }
1354
+ function centeredTranslation(natural, container, scale, rotationDeg) {
1355
+ const { W, H, minX, minY } = rotatedBox(natural, scale, rotationDeg);
1356
+ const nx = (container.w - W) / 2 - minX;
1357
+ const ny = (container.h - H) / 2 - minY;
1358
+ return { tx: nx, ty: ny };
1359
+ }
1360
+ function clampScale(s, fitScale, max = 8) {
1361
+ return Math.max(fitScale, Math.min(max, s));
1362
+ }
1363
+ function zoomAtPoint(current, factor, px, py, rotationDeg, fitScale) {
1364
+ const { scale, tx, ty } = current;
1365
+ const newScale = clampScale(scale * factor, fitScale);
1366
+ if (newScale === scale) return current;
1367
+ const rad = rotationDeg * Math.PI / 180;
1368
+ const cosA = Math.cos(rad);
1369
+ const sinA = Math.sin(rad);
1370
+ const dx = px - tx;
1371
+ const dy = py - ty;
1372
+ const cx = (cosA * dx + sinA * dy) / scale;
1373
+ const cy = (-sinA * dx + cosA * dy) / scale;
1374
+ const ntx = px - (cosA * (newScale * cx) - sinA * (newScale * cy));
1375
+ const nty = py - (sinA * (newScale * cx) + cosA * (newScale * cy));
1376
+ return { scale: newScale, tx: ntx, ty: nty };
1377
+ }
1378
+ function flashZoomTarget(rects, natural, container, rotationDeg, fitScale) {
1379
+ let minX = 1, minY = 1, maxX = 0, maxY = 0;
1380
+ for (const rect of rects) {
1381
+ for (const [px, py] of rect.points) {
1382
+ minX = Math.min(minX, px);
1383
+ minY = Math.min(minY, py);
1384
+ maxX = Math.max(maxX, px);
1385
+ maxY = Math.max(maxY, py);
1386
+ }
1387
+ }
1388
+ const centerX = (minX + maxX) / 2 * natural.w;
1389
+ const centerY = (minY + maxY) / 2 * natural.h;
1390
+ const bboxWidth = (maxX - minX) * natural.w;
1391
+ const bboxHeight = (maxY - minY) * natural.h;
1392
+ const rad = rotationDeg * Math.PI / 180;
1393
+ const cosA = Math.cos(rad);
1394
+ const sinA = Math.sin(rad);
1395
+ const TARGET_RENDERED_SIZE = 100;
1396
+ const largerDimension = Math.max(bboxWidth, bboxHeight);
1397
+ const scaleForTargetSize = largerDimension > 0 ? TARGET_RENDERED_SIZE / largerDimension : 1;
1398
+ const targetScale = Math.max(fitScale, Math.min(scaleForTargetSize, 1.8));
1399
+ const newScreenX = cosA * centerX * targetScale - sinA * centerY * targetScale;
1400
+ const newScreenY = sinA * centerX * targetScale + cosA * centerY * targetScale;
1401
+ const targetTx = container.w / 2 - newScreenX;
1402
+ const targetTy = container.h / 2 - newScreenY;
1403
+ return { scale: targetScale, tx: targetTx, ty: targetTy };
1404
+ }
1405
+ var easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
1406
+
1407
+ // src/verification/viewer.tsx
1408
+ var import_jsx_runtime2 = require("react/jsx-runtime");
1409
+ function IconBase({ children }) {
1410
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1411
+ "svg",
1412
+ {
1413
+ width: "16",
1414
+ height: "16",
1415
+ viewBox: "0 0 16 16",
1416
+ fill: "none",
1417
+ stroke: "currentColor",
1418
+ strokeWidth: "1.5",
1419
+ strokeLinecap: "round",
1420
+ strokeLinejoin: "round",
1421
+ "aria-hidden": "true",
1422
+ focusable: "false",
1423
+ children
1424
+ }
1425
+ );
1426
+ }
1427
+ function GlassBody() {
1428
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
1429
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "6.75", cy: "6.75", r: "4.25" }),
1430
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "9.9", y1: "9.9", x2: "13.5", y2: "13.5" })
1431
+ ] });
1432
+ }
1433
+ function IconZoomIn() {
1434
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(IconBase, { children: [
1435
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(GlassBody, {}),
1436
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "4.9", y1: "6.75", x2: "8.6", y2: "6.75" }),
1437
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "6.75", y1: "4.9", x2: "6.75", y2: "8.6" })
1438
+ ] });
1439
+ }
1440
+ function IconZoomOut() {
1441
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(IconBase, { children: [
1442
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(GlassBody, {}),
1443
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "4.9", y1: "6.75", x2: "8.6", y2: "6.75" })
1444
+ ] });
1445
+ }
1446
+ function IconMagnifier() {
1447
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconBase, { children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(GlassBody, {}) });
1448
+ }
1449
+ function IconActualSize() {
1450
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(IconBase, { children: [
1451
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("polyline", { points: "2.8 6.2 4 5 4 11" }),
1452
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("polyline", { points: "10.8 6.2 12 5 12 11" }),
1453
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "8", cy: "6.75", r: "0.8", fill: "currentColor", stroke: "none" }),
1454
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "8", cy: "9.25", r: "0.8", fill: "currentColor", stroke: "none" })
1455
+ ] });
1456
+ }
1457
+ function IconFit() {
1458
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(IconBase, { children: [
1459
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "13.8", y1: "2.2", x2: "9.6", y2: "6.4" }),
1460
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("polyline", { points: "9.6 3.9 9.6 6.4 12.1 6.4" }),
1461
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "2.2", y1: "13.8", x2: "6.4", y2: "9.6" }),
1462
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("polyline", { points: "6.4 12.1 6.4 9.6 3.9 9.6" })
1463
+ ] });
1464
+ }
1465
+ function IconRotate() {
1466
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(IconBase, { children: [
1467
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M11.83 4.79A5 5 0 1 1 8 3" }),
1468
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("polyline", { points: "6 1.7 8 3 6 4.3" })
1469
+ ] });
1470
+ }
1471
+ function IconOverlay() {
1472
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconBase, { children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("rect", { x: "2.75", y: "2.75", width: "10.5", height: "10.5", rx: "1.5", strokeDasharray: "3 2.2" }) });
1473
+ }
1474
+ function IconEye() {
1475
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(IconBase, { children: [
1476
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("path", { d: "M1.5 8s2.4-4.5 6.5-4.5S14.5 8 14.5 8s-2.4 4.5-6.5 4.5S1.5 8 1.5 8z" }),
1477
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "8", cy: "8", r: "2.1" })
1478
+ ] });
1479
+ }
1480
+ function ToolbarButton({
1481
+ label,
1482
+ onClick,
1483
+ disabled,
1484
+ pressed,
1485
+ checked,
1486
+ children
1487
+ }) {
1488
+ const active = (pressed ?? checked) === true;
1489
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1490
+ "button",
1491
+ {
1492
+ type: "button",
1493
+ className: active ? "gemina-verification__toolbar-btn gemina-verification__toolbar-btn--active" : "gemina-verification__toolbar-btn",
1494
+ title: label,
1495
+ "aria-label": label,
1496
+ role: checked === void 0 ? void 0 : "switch",
1497
+ "aria-checked": checked,
1498
+ "aria-pressed": pressed,
1499
+ disabled,
1500
+ onClick,
1501
+ children
1502
+ }
1503
+ );
1504
+ }
1505
+ var ZOOM_STEP = 1.2;
1506
+ var IDENTITY = { scale: 1, tx: 0, ty: 0 };
1507
+ var FLASH_DURATION = 1500;
1508
+ var ZOOM_ANIMATION_DURATION = 350;
1509
+ var REDUCED_MOTION_FLASH_MS = 800;
1510
+ var MIN_SIZE_RATIO = 8e-3;
1511
+ var MAG_RADIUS = 150;
1512
+ var MAG_ZOOM = 2.5;
1513
+ function rectGeometry(rect, natural) {
1514
+ const xs = rect.points.map((point) => point[0]);
1515
+ const ys = rect.points.map((point) => point[1]);
1516
+ const minX = Math.min(...xs);
1517
+ const minY = Math.min(...ys);
1518
+ const rawWidthRatio = Math.max(0, Math.max(...xs) - minX);
1519
+ const rawHeightRatio = Math.max(0, Math.max(...ys) - minY);
1520
+ if (rawWidthRatio <= 0 && rawHeightRatio <= 0) return null;
1521
+ return {
1522
+ left: minX * natural.w,
1523
+ top: minY * natural.h,
1524
+ width: Math.max(rawWidthRatio, MIN_SIZE_RATIO) * natural.w,
1525
+ height: Math.max(rawHeightRatio, MIN_SIZE_RATIO) * natural.h
1526
+ };
1527
+ }
1528
+ function VerificationViewer(props) {
1529
+ const { src, alt, relativeRects, flashRects, onFlashComplete, onImageExpired } = props;
1530
+ const canvasRef = (0, import_react2.useRef)(null);
1531
+ const imgRef = (0, import_react2.useRef)(null);
1532
+ const [natural, setNatural] = (0, import_react2.useState)(null);
1533
+ const [container, setContainer] = (0, import_react2.useState)({ w: 0, h: 0 });
1534
+ const [transform, setTransform] = (0, import_react2.useState)(IDENTITY);
1535
+ const [rotation, setRotation] = (0, import_react2.useState)(0);
1536
+ const [showRects, setShowRects] = (0, import_react2.useState)(false);
1537
+ const [magnifierOn, setMagnifierOn] = (0, import_react2.useState)(false);
1538
+ const [showMag, setShowMag] = (0, import_react2.useState)(false);
1539
+ const [mousePos, setMousePos] = (0, import_react2.useState)({ x: 0, y: 0 });
1540
+ const [isPanning, setIsPanning] = (0, import_react2.useState)(false);
1541
+ const panStart = (0, import_react2.useRef)(null);
1542
+ const [flashOpacity, setFlashOpacity] = (0, import_react2.useState)(0);
1543
+ const [activeFlashRects, setActiveFlashRects] = (0, import_react2.useState)(null);
1544
+ const travelRafRef = (0, import_react2.useRef)(null);
1545
+ const fadeRafRef = (0, import_react2.useRef)(null);
1546
+ const reducedFlashTimeoutRef = (0, import_react2.useRef)(null);
1547
+ const transformRef = (0, import_react2.useRef)(transform);
1548
+ transformRef.current = transform;
1549
+ const onFlashCompleteRef = (0, import_react2.useRef)(onFlashComplete);
1550
+ onFlashCompleteRef.current = onFlashComplete;
1551
+ const hasLoadedRef = (0, import_react2.useRef)(false);
1552
+ (0, import_react2.useLayoutEffect)(() => {
1553
+ const el = canvasRef.current;
1554
+ if (!el) return;
1555
+ if (typeof ResizeObserver === "undefined") {
1556
+ const rect = el.getBoundingClientRect();
1557
+ setContainer({ w: rect.width, h: rect.height });
1558
+ return;
1559
+ }
1560
+ const ro = new ResizeObserver((entries) => {
1561
+ const cr = entries[0]?.contentRect;
1562
+ if (cr) setContainer({ w: cr.width, h: cr.height });
1563
+ });
1564
+ ro.observe(el);
1565
+ return () => ro.disconnect();
1566
+ }, []);
1567
+ const handleImgLoad = (0, import_react2.useCallback)(() => {
1568
+ const img = imgRef.current;
1569
+ if (!img) return;
1570
+ hasLoadedRef.current = true;
1571
+ const w = img.naturalWidth;
1572
+ const h = img.naturalHeight;
1573
+ setNatural((prev) => prev && prev.w === w && prev.h === h ? prev : { w, h });
1574
+ }, []);
1575
+ (0, import_react2.useEffect)(() => {
1576
+ hasLoadedRef.current = false;
1577
+ }, [src]);
1578
+ const handleImgError = (0, import_react2.useCallback)(() => {
1579
+ if (!hasLoadedRef.current) return;
1580
+ hasLoadedRef.current = false;
1581
+ onImageExpired?.();
1582
+ }, [onImageExpired]);
1583
+ const currentFitScale = (0, import_react2.useCallback)(() => {
1584
+ if (!natural || !container.w || !container.h) return 1;
1585
+ return fitScaleFor(natural, container, rotation);
1586
+ }, [natural, container, rotation]);
1587
+ (0, import_react2.useEffect)(() => {
1588
+ if (!natural || !container.w || !container.h) return;
1589
+ const fit = fitScaleFor(natural, container, rotation);
1590
+ const { tx, ty } = centeredTranslation(natural, container, fit, rotation);
1591
+ setTransform(
1592
+ (prev) => Math.abs(prev.scale - fit) < 1e-4 && prev.tx === tx && prev.ty === ty ? prev : { scale: fit, tx, ty }
1593
+ );
1594
+ }, [natural, container, rotation]);
1595
+ const cancelFlashTravel = (0, import_react2.useCallback)(() => {
1596
+ if (travelRafRef.current !== null) {
1597
+ cancelAnimationFrame(travelRafRef.current);
1598
+ travelRafRef.current = null;
1599
+ }
1600
+ }, []);
1601
+ const zoomBy = (0, import_react2.useCallback)(
1602
+ (factor) => {
1603
+ const node = canvasRef.current;
1604
+ if (!node || !natural) return;
1605
+ cancelFlashTravel();
1606
+ const rect = node.getBoundingClientRect();
1607
+ const fit = currentFitScale();
1608
+ setTransform(
1609
+ (prev) => zoomAtPoint(prev, factor, rect.width / 2, rect.height / 2, rotation, fit)
1610
+ );
1611
+ },
1612
+ [natural, rotation, currentFitScale, cancelFlashTravel]
1613
+ );
1614
+ const handleZoomIn = (0, import_react2.useCallback)(() => zoomBy(ZOOM_STEP), [zoomBy]);
1615
+ const handleZoomOut = (0, import_react2.useCallback)(() => zoomBy(1 / ZOOM_STEP), [zoomBy]);
1616
+ const zoomAtClientPoint = (0, import_react2.useCallback)(
1617
+ (factor, clientX, clientY) => {
1618
+ const node = canvasRef.current;
1619
+ if (!node || !natural) return;
1620
+ const rect = node.getBoundingClientRect();
1621
+ const fit = currentFitScale();
1622
+ setTransform(
1623
+ (prev) => zoomAtPoint(prev, factor, clientX - rect.left, clientY - rect.top, rotation, fit)
1624
+ );
1625
+ },
1626
+ [natural, rotation, currentFitScale]
1627
+ );
1628
+ const handleWheel = (0, import_react2.useCallback)(
1629
+ (event) => {
1630
+ event.preventDefault();
1631
+ event.stopPropagation();
1632
+ cancelFlashTravel();
1633
+ const factor = event.deltaY > 0 ? 0.92 : 1.08;
1634
+ zoomAtClientPoint(factor, event.clientX, event.clientY);
1635
+ },
1636
+ [zoomAtClientPoint, cancelFlashTravel]
1637
+ );
1638
+ (0, import_react2.useEffect)(() => {
1639
+ const node = canvasRef.current;
1640
+ if (!node) return;
1641
+ const listener = (event) => handleWheel(event);
1642
+ node.addEventListener("wheel", listener, { passive: false });
1643
+ return () => node.removeEventListener("wheel", listener);
1644
+ }, [handleWheel]);
1645
+ const atFitScale = transform.scale <= currentFitScale() + 1e-3;
1646
+ const handleMouseDown = (0, import_react2.useCallback)(
1647
+ (e) => {
1648
+ cancelFlashTravel();
1649
+ if (e.button !== 0) return;
1650
+ if (atFitScale) return;
1651
+ e.preventDefault();
1652
+ panStart.current = { x: e.clientX, y: e.clientY, tx: transform.tx, ty: transform.ty };
1653
+ setIsPanning(true);
1654
+ },
1655
+ [atFitScale, transform.tx, transform.ty, cancelFlashTravel]
1656
+ );
1657
+ (0, import_react2.useEffect)(() => {
1658
+ if (!isPanning) return;
1659
+ const onMove = (e) => {
1660
+ const start = panStart.current;
1661
+ if (!start) return;
1662
+ const dx = e.clientX - start.x;
1663
+ const dy = e.clientY - start.y;
1664
+ setTransform((prev) => ({ scale: prev.scale, tx: start.tx + dx, ty: start.ty + dy }));
1665
+ };
1666
+ const onUp = () => {
1667
+ panStart.current = null;
1668
+ setIsPanning(false);
1669
+ };
1670
+ document.addEventListener("mousemove", onMove);
1671
+ document.addEventListener("mouseup", onUp);
1672
+ return () => {
1673
+ document.removeEventListener("mousemove", onMove);
1674
+ document.removeEventListener("mouseup", onUp);
1675
+ };
1676
+ }, [isPanning]);
1677
+ const touchState = (0, import_react2.useRef)(null);
1678
+ const handleTouchStart = (0, import_react2.useCallback)(
1679
+ (e) => {
1680
+ cancelFlashTravel();
1681
+ const a = e.touches[0];
1682
+ const b = e.touches[1];
1683
+ if (e.touches.length === 2 && a && b) {
1684
+ touchState.current = {
1685
+ mode: "pinch",
1686
+ dist: Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY)
1687
+ };
1688
+ } else if (e.touches.length === 1 && a && !atFitScale) {
1689
+ touchState.current = { mode: "pan", x: a.clientX, y: a.clientY, tx: transform.tx, ty: transform.ty };
1690
+ } else {
1691
+ touchState.current = null;
1692
+ }
1693
+ },
1694
+ [atFitScale, transform.tx, transform.ty, cancelFlashTravel]
1695
+ );
1696
+ const handleTouchMove = (0, import_react2.useCallback)(
1697
+ (e) => {
1698
+ const state = touchState.current;
1699
+ if (!state) return;
1700
+ if (state.mode === "pinch" && e.touches.length === 2) {
1701
+ const a = e.touches[0];
1702
+ const b = e.touches[1];
1703
+ if (!a || !b) return;
1704
+ const dist = Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY);
1705
+ if (state.dist > 0) {
1706
+ zoomAtClientPoint(dist / state.dist, (a.clientX + b.clientX) / 2, (a.clientY + b.clientY) / 2);
1707
+ }
1708
+ state.dist = dist;
1709
+ } else if (state.mode === "pan" && e.touches.length === 1) {
1710
+ const t = e.touches[0];
1711
+ if (!t) return;
1712
+ setTransform((prev) => ({
1713
+ scale: prev.scale,
1714
+ tx: state.tx + (t.clientX - state.x),
1715
+ ty: state.ty + (t.clientY - state.y)
1716
+ }));
1717
+ }
1718
+ },
1719
+ [zoomAtClientPoint]
1720
+ );
1721
+ const handleTouchEnd = (0, import_react2.useCallback)((e) => {
1722
+ if (e.touches.length === 0) touchState.current = null;
1723
+ }, []);
1724
+ const handleCanvasMouseMove = (0, import_react2.useCallback)((e) => {
1725
+ const rect = canvasRef.current?.getBoundingClientRect();
1726
+ if (!rect) return;
1727
+ setShowMag(true);
1728
+ setMousePos({ x: e.clientX - rect.left, y: e.clientY - rect.top });
1729
+ }, []);
1730
+ const handleCanvasMouseLeave = (0, import_react2.useCallback)(() => {
1731
+ setShowMag(false);
1732
+ }, []);
1733
+ const handleDoubleClick = (0, import_react2.useCallback)(
1734
+ (e) => {
1735
+ cancelFlashTravel();
1736
+ if (!natural) return;
1737
+ const fit = currentFitScale();
1738
+ const nearFit = Math.abs(transform.scale - fit) < 1e-3;
1739
+ if (nearFit) {
1740
+ const target = clampScale(1, fit);
1741
+ zoomAtClientPoint(target / transform.scale, e.clientX, e.clientY);
1742
+ } else {
1743
+ setTransform({ scale: fit, ...centeredTranslation(natural, container, fit, rotation) });
1744
+ }
1745
+ },
1746
+ [natural, container, rotation, transform.scale, currentFitScale, zoomAtClientPoint, cancelFlashTravel]
1747
+ );
1748
+ const handleFit = (0, import_react2.useCallback)(() => {
1749
+ if (!natural) return;
1750
+ cancelFlashTravel();
1751
+ const fit = currentFitScale();
1752
+ setTransform({ scale: fit, ...centeredTranslation(natural, container, fit, rotation) });
1753
+ }, [natural, container, rotation, currentFitScale, cancelFlashTravel]);
1754
+ const handleActualSize = (0, import_react2.useCallback)(() => {
1755
+ if (!natural) return;
1756
+ cancelFlashTravel();
1757
+ const target = clampScale(1, currentFitScale());
1758
+ setTransform({ scale: target, ...centeredTranslation(natural, container, target, rotation) });
1759
+ }, [natural, container, rotation, currentFitScale, cancelFlashTravel]);
1760
+ const handleRotate = (0, import_react2.useCallback)(() => {
1761
+ setRotation((r) => (r + 90) % 360);
1762
+ }, []);
1763
+ const hasRects = relativeRects !== void 0 && relativeRects.length > 0;
1764
+ (0, import_react2.useEffect)(() => {
1765
+ if (!hasRects) setShowRects(false);
1766
+ }, [hasRects]);
1767
+ (0, import_react2.useEffect)(() => {
1768
+ if (!flashRects || flashRects.length === 0 || !natural || !container.w || !container.h) {
1769
+ setActiveFlashRects((prev) => prev === null ? prev : null);
1770
+ setFlashOpacity(0);
1771
+ return;
1772
+ }
1773
+ const fit = fitScaleFor(natural, container, rotation);
1774
+ const target = flashZoomTarget(flashRects, natural, container, rotation, fit);
1775
+ setActiveFlashRects(flashRects);
1776
+ setFlashOpacity(1);
1777
+ const prefersReduced = typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
1778
+ if (prefersReduced) {
1779
+ setTransform(target);
1780
+ reducedFlashTimeoutRef.current = setTimeout(() => {
1781
+ reducedFlashTimeoutRef.current = null;
1782
+ setActiveFlashRects(null);
1783
+ setFlashOpacity(0);
1784
+ onFlashCompleteRef.current?.();
1785
+ }, REDUCED_MOTION_FLASH_MS);
1786
+ return () => {
1787
+ if (reducedFlashTimeoutRef.current !== null) {
1788
+ clearTimeout(reducedFlashTimeoutRef.current);
1789
+ reducedFlashTimeoutRef.current = null;
1790
+ }
1791
+ };
1792
+ }
1793
+ const from = transformRef.current;
1794
+ const zoomStartTime = Date.now();
1795
+ const animateZoom = () => {
1796
+ const progress = Math.min((Date.now() - zoomStartTime) / ZOOM_ANIMATION_DURATION, 1);
1797
+ const eased = easeOutCubic(progress);
1798
+ setTransform({
1799
+ scale: from.scale + (target.scale - from.scale) * eased,
1800
+ tx: from.tx + (target.tx - from.tx) * eased,
1801
+ ty: from.ty + (target.ty - from.ty) * eased
1802
+ });
1803
+ travelRafRef.current = progress < 1 ? requestAnimationFrame(animateZoom) : null;
1804
+ };
1805
+ travelRafRef.current = requestAnimationFrame(animateZoom);
1806
+ const flashStartTime = Date.now();
1807
+ const animateFlash = () => {
1808
+ const progress = Math.min((Date.now() - flashStartTime) / FLASH_DURATION, 1);
1809
+ setFlashOpacity(1 - progress * progress);
1810
+ if (progress < 1) {
1811
+ fadeRafRef.current = requestAnimationFrame(animateFlash);
1812
+ } else {
1813
+ fadeRafRef.current = null;
1814
+ setActiveFlashRects(null);
1815
+ setFlashOpacity(0);
1816
+ onFlashCompleteRef.current?.();
1817
+ }
1818
+ };
1819
+ fadeRafRef.current = requestAnimationFrame(animateFlash);
1820
+ return () => {
1821
+ cancelFlashTravel();
1822
+ if (fadeRafRef.current !== null) {
1823
+ cancelAnimationFrame(fadeRafRef.current);
1824
+ fadeRafRef.current = null;
1825
+ }
1826
+ };
1827
+ }, [flashRects, natural, container.w, container.h, rotation, cancelFlashTravel]);
1828
+ const cursorMode = atFitScale ? "zoom-in" : isPanning ? "grabbing" : "grab";
1829
+ let magnifier = null;
1830
+ if (magnifierOn && showMag && natural && transform.scale > 0) {
1831
+ const rad = rotation * Math.PI / 180;
1832
+ const cosA = Math.cos(rad);
1833
+ const sinA = Math.sin(rad);
1834
+ const dx = mousePos.x - transform.tx;
1835
+ const dy = mousePos.y - transform.ty;
1836
+ const cxRaw = (cosA * dx + sinA * dy) / transform.scale;
1837
+ const cyRaw = (-sinA * dx + cosA * dy) / transform.scale;
1838
+ const clampedX = Math.max(0, Math.min(cxRaw, natural.w));
1839
+ const clampedY = Math.max(0, Math.min(cyRaw, natural.h));
1840
+ const zoomScale = transform.scale * MAG_ZOOM;
1841
+ const px = clampedX * zoomScale;
1842
+ const py = clampedY * zoomScale;
1843
+ const rotatedX = px * cosA - py * sinA;
1844
+ const rotatedY = px * sinA + py * cosA;
1845
+ const translateX = MAG_RADIUS - rotatedX;
1846
+ const translateY = MAG_RADIUS - rotatedY;
1847
+ magnifier = /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1848
+ "div",
1849
+ {
1850
+ className: "gemina-verification__magnifier",
1851
+ style: {
1852
+ width: MAG_RADIUS * 2,
1853
+ height: MAG_RADIUS * 2,
1854
+ top: mousePos.y - MAG_RADIUS,
1855
+ left: mousePos.x - MAG_RADIUS
1856
+ },
1857
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1858
+ "img",
1859
+ {
1860
+ src,
1861
+ alt: "",
1862
+ draggable: false,
1863
+ style: {
1864
+ position: "absolute",
1865
+ width: natural.w,
1866
+ height: natural.h,
1867
+ transformOrigin: "0 0",
1868
+ transform: `translate(${translateX}px, ${translateY}px) rotate(${rotation}deg) scale(${zoomScale})`
1869
+ }
1870
+ }
1871
+ )
1872
+ }
1873
+ );
1874
+ }
1875
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "gemina-verification__viewer", children: [
1876
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "gemina-verification__toolbar", children: [
1877
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ToolbarButton, { label: "Zoom out", onClick: handleZoomOut, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconZoomOut, {}) }),
1878
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ToolbarButton, { label: "Zoom in", onClick: handleZoomIn, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconZoomIn, {}) }),
1879
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ToolbarButton, { label: "Actual size (100%)", onClick: handleActualSize, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconActualSize, {}) }),
1880
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ToolbarButton, { label: "Fit to screen", onClick: handleFit, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconFit, {}) }),
1881
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(ToolbarButton, { label: "Rotate 90 degrees", onClick: handleRotate, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconRotate, {}) }),
1882
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1883
+ ToolbarButton,
1884
+ {
1885
+ label: "Toggle detection overlays",
1886
+ pressed: showRects,
1887
+ disabled: !hasRects,
1888
+ onClick: () => setShowRects((prev) => !prev),
1889
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconOverlay, {})
1890
+ }
1891
+ ),
1892
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1893
+ ToolbarButton,
1894
+ {
1895
+ label: "Magnifier",
1896
+ checked: magnifierOn,
1897
+ onClick: () => setMagnifierOn((prev) => !prev),
1898
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(IconMagnifier, {})
1899
+ }
1900
+ )
1901
+ ] }),
1902
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1903
+ "div",
1904
+ {
1905
+ ref: canvasRef,
1906
+ className: "gemina-verification__canvas",
1907
+ "data-cursor": cursorMode,
1908
+ role: "img",
1909
+ "aria-label": alt ?? "Document image",
1910
+ onDoubleClick: handleDoubleClick,
1911
+ onMouseDown: handleMouseDown,
1912
+ onMouseMove: handleCanvasMouseMove,
1913
+ onMouseLeave: handleCanvasMouseLeave,
1914
+ onTouchStart: handleTouchStart,
1915
+ onTouchMove: handleTouchMove,
1916
+ onTouchEnd: handleTouchEnd,
1917
+ onTouchCancel: handleTouchEnd,
1918
+ children: [
1919
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
1920
+ "div",
1921
+ {
1922
+ style: {
1923
+ position: "absolute",
1924
+ left: transform.tx,
1925
+ top: transform.ty,
1926
+ transform: `rotate(${rotation}deg) scale(${transform.scale})`,
1927
+ transformOrigin: "top left",
1928
+ willChange: "transform,left,top"
1929
+ },
1930
+ children: [
1931
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1932
+ "img",
1933
+ {
1934
+ ref: imgRef,
1935
+ src,
1936
+ alt: alt ?? "Document",
1937
+ draggable: false,
1938
+ onLoad: handleImgLoad,
1939
+ onError: handleImgError
1940
+ }
1941
+ ),
1942
+ showRects && natural && relativeRects?.map((rect, idx) => {
1943
+ const geometry = rectGeometry(rect, natural);
1944
+ if (!geometry) return null;
1945
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1946
+ "div",
1947
+ {
1948
+ className: "gemina-verification__rect",
1949
+ style: geometry,
1950
+ "aria-hidden": "true",
1951
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "gemina-verification__rect-badge", children: [
1952
+ "#",
1953
+ idx + 1
1954
+ ] })
1955
+ },
1956
+ `rect-${idx}`
1957
+ );
1958
+ }),
1959
+ activeFlashRects && natural && activeFlashRects.map((rect, idx) => {
1960
+ const geometry = rectGeometry(rect, natural);
1961
+ if (!geometry) return null;
1962
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1963
+ "div",
1964
+ {
1965
+ className: "gemina-verification__flash-rect",
1966
+ style: { ...geometry, opacity: flashOpacity },
1967
+ "aria-hidden": "true"
1968
+ },
1969
+ `flash-rect-${idx}`
1970
+ );
1971
+ })
1972
+ ]
1973
+ }
1974
+ ),
1975
+ magnifier
1976
+ ]
1977
+ }
1978
+ )
1979
+ ] });
1980
+ }
1981
+
1982
+ // src/verification/form.tsx
1983
+ var import_jsx_runtime3 = require("react/jsx-runtime");
1984
+ function ConfidenceDot(props) {
1985
+ const { confidence } = props;
1986
+ if (!confidence?.level) {
1987
+ return null;
1988
+ }
1989
+ let variant;
1990
+ let label;
1991
+ switch (confidence.level.toLowerCase()) {
1992
+ case "high":
1993
+ variant = "high";
1994
+ label = "High confidence";
1995
+ break;
1996
+ case "medium":
1997
+ variant = "medium";
1998
+ label = "Medium confidence";
1999
+ break;
2000
+ case "low":
2001
+ variant = "low";
2002
+ label = "Low confidence";
2003
+ break;
2004
+ default:
2005
+ variant = "unknown";
2006
+ label = `${confidence.level} confidence`;
2007
+ }
2008
+ const reasons = confidence.reasons.map(formatLabel);
2009
+ const title = [label, ...reasons].join("\n");
2010
+ const ariaLabel = reasons.length > 0 ? `${label}: ${reasons.join(", ")}` : label;
2011
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2012
+ "span",
2013
+ {
2014
+ className: `gemina-verification__dot gemina-verification__dot--${variant}`,
2015
+ role: "img",
2016
+ "aria-label": ariaLabel,
2017
+ title
2018
+ }
2019
+ );
2020
+ }
2021
+ function EyeButton(props) {
2022
+ const { coordinates, onFlash } = props;
2023
+ if (!coordinates) {
2024
+ return null;
2025
+ }
2026
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2027
+ "button",
2028
+ {
2029
+ type: "button",
2030
+ className: "gemina-verification__eye",
2031
+ title: "Show on document",
2032
+ "aria-label": "Show on document",
2033
+ onClick: (event) => {
2034
+ event.stopPropagation();
2035
+ onFlash();
2036
+ },
2037
+ children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(IconEye, {})
2038
+ }
2039
+ );
2040
+ }
2041
+ function FieldInput(props) {
2042
+ const { binding, edit, onEdit, readOnly, ariaLabel } = props;
2043
+ const editedBadgeId = import_react3.default.useId();
2044
+ if (readOnly || !binding.editable) {
2045
+ const display = binding.extracted === NOT_FOUND ? null : binding.extracted;
2046
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: formatValue(display, binding.key.label) });
2047
+ }
2048
+ const dirty = edit !== void 0;
2049
+ const missed = binding.serverValue === NOT_FOUND;
2050
+ const className = [
2051
+ "gemina-verification__input",
2052
+ dirty ? "gemina-verification__input--dirty" : "",
2053
+ missed ? "gemina-verification__input--missed" : ""
2054
+ ].filter(Boolean).join(" ");
2055
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
2056
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2057
+ "input",
2058
+ {
2059
+ type: "text",
2060
+ className,
2061
+ dir: "auto",
2062
+ value: dirty ? edit : toInputString(binding.extracted),
2063
+ onChange: (event) => onEdit(binding.key.raw, event.target.value),
2064
+ placeholder: missed ? "Not detected \u2014 fill in if present" : void 0,
2065
+ "aria-label": ariaLabel,
2066
+ "aria-describedby": dirty ? editedBadgeId : void 0,
2067
+ autoComplete: "off"
2068
+ }
2069
+ ),
2070
+ dirty ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { className: "gemina-verification__edited", id: editedBadgeId, children: "edited" }) : null
2071
+ ] });
2072
+ }
2073
+ function isInteractiveTarget(target) {
2074
+ return target instanceof Element && target.closest("input, button, a, select, textarea") !== null;
2075
+ }
2076
+ function FieldPair(props) {
2077
+ const { label, ariaLabel, cell, shared } = props;
2078
+ const binding = shared.bindingIndex.get(cell.pointer);
2079
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
2080
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("dt", { className: "gemina-verification__dt", children: [
2081
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ConfidenceDot, { confidence: cell.confidence }),
2082
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: label })
2083
+ ] }),
2084
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("dd", { className: "gemina-verification__dd", children: [
2085
+ binding !== void 0 ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2086
+ FieldInput,
2087
+ {
2088
+ binding,
2089
+ edit: shared.edits.get(binding.key.raw),
2090
+ onEdit: shared.onEdit,
2091
+ readOnly: shared.readOnly,
2092
+ ariaLabel
2093
+ }
2094
+ ) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: formatValue(cell.value, label) }),
2095
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2096
+ EyeButton,
2097
+ {
2098
+ coordinates: cell.coordinates,
2099
+ onFlash: () => {
2100
+ if (cell.coordinates) {
2101
+ shared.onFlash([cell.coordinates]);
2102
+ }
2103
+ }
2104
+ }
2105
+ )
2106
+ ] })
2107
+ ] });
2108
+ }
2109
+ function HeaderSection(props) {
2110
+ const { headers, simpleLists, shared } = props;
2111
+ if (headers.length === 0 && simpleLists.length === 0) {
2112
+ return null;
2113
+ }
2114
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "gemina-verification__section", "aria-label": "Details", children: [
2115
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "gemina-verification__section-header", children: "Details" }),
2116
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("dl", { className: "gemina-verification__dl", children: [
2117
+ headers.map((field) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2118
+ FieldPair,
2119
+ {
2120
+ label: formatLabel(field.key),
2121
+ ariaLabel: formatLabel(field.key),
2122
+ cell: field,
2123
+ shared
2124
+ },
2125
+ field.pointer
2126
+ )),
2127
+ simpleLists.map((list) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_react3.default.Fragment, { children: [
2128
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dt", { className: "gemina-verification__dt", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: formatLabel(list.key) }) }),
2129
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dd", { className: "gemina-verification__dd", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("ul", { className: "gemina-verification__list", children: list.items.map((item, index) => {
2130
+ const binding = shared.bindingIndex.get(item.pointer);
2131
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("li", { className: "gemina-verification__cell", children: [
2132
+ binding !== void 0 ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2133
+ FieldInput,
2134
+ {
2135
+ binding,
2136
+ edit: shared.edits.get(binding.key.raw),
2137
+ onEdit: shared.onEdit,
2138
+ readOnly: shared.readOnly,
2139
+ ariaLabel: `${formatLabel(list.key)} item ${index + 1}`
2140
+ }
2141
+ ) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: formatValue(item.value) }),
2142
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ConfidenceDot, { confidence: item.confidence }),
2143
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2144
+ EyeButton,
2145
+ {
2146
+ coordinates: item.coordinates,
2147
+ onFlash: () => {
2148
+ if (item.coordinates) {
2149
+ shared.onFlash([item.coordinates]);
2150
+ }
2151
+ }
2152
+ }
2153
+ )
2154
+ ] }, item.pointer);
2155
+ }) }) })
2156
+ ] }, list.pointer))
2157
+ ] })
2158
+ ] });
2159
+ }
2160
+ function EntitySection(props) {
2161
+ const { entity, shared } = props;
2162
+ const label = formatLabel(entity.key);
2163
+ const singular = label.replace(/s$/, "");
2164
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "gemina-verification__section", "aria-label": label, children: [
2165
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "gemina-verification__section-header", children: [
2166
+ label,
2167
+ " (",
2168
+ entity.items.length,
2169
+ ")"
2170
+ ] }),
2171
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "gemina-verification__section-body", children: entity.items.map((item, itemIndex) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "gemina-verification__card", children: [
2172
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "gemina-verification__card-header", children: [
2173
+ singular,
2174
+ " ",
2175
+ itemIndex + 1
2176
+ ] }),
2177
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dl", { className: "gemina-verification__dl", children: Object.entries(item).map(([fieldKey, cell]) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2178
+ FieldPair,
2179
+ {
2180
+ label: formatLabel(fieldKey),
2181
+ ariaLabel: `${singular} ${itemIndex + 1} \u2014 ${formatLabel(fieldKey)}`,
2182
+ cell,
2183
+ shared
2184
+ },
2185
+ fieldKey
2186
+ )) })
2187
+ ] }, itemIndex)) })
2188
+ ] });
2189
+ }
2190
+ function TableRowView(props) {
2191
+ const { row, rowIndex, columns, tableLabel, hasCoords, hasRowConfidence, shared } = props;
2192
+ const { bindingIndex, edits, onEdit, readOnly, onFlash } = shared;
2193
+ const rects = import_react3.default.useMemo(() => {
2194
+ const collected = [];
2195
+ for (const [key, cell] of Object.entries(row)) {
2196
+ if (key !== ROW_META_KEY && cell.coordinates) {
2197
+ collected.push(cell.coordinates);
2198
+ }
2199
+ }
2200
+ return collected;
2201
+ }, [row]);
2202
+ const handleRowClick = import_react3.default.useCallback(
2203
+ (event) => {
2204
+ if (isInteractiveTarget(event.target)) {
2205
+ return;
2206
+ }
2207
+ if (rects.length > 0) {
2208
+ onFlash(rects);
2209
+ }
2210
+ },
2211
+ [rects, onFlash]
2212
+ );
2213
+ const firstRect = rects.length > 0 ? rects[0] : null;
2214
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("tr", { onClick: handleRowClick, children: [
2215
+ hasCoords ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("td", { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(EyeButton, { coordinates: firstRect, onFlash: () => onFlash(rects) }) }) : null,
2216
+ hasRowConfidence ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("td", { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ConfidenceDot, { confidence: row[ROW_META_KEY]?.confidence ?? null }) }) : null,
2217
+ columns.map((column) => {
2218
+ const cell = row[column];
2219
+ const binding = cell === void 0 ? void 0 : bindingIndex.get(cell.pointer);
2220
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("td", { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "gemina-verification__cell", children: [
2221
+ binding !== void 0 ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2222
+ FieldInput,
2223
+ {
2224
+ binding,
2225
+ edit: edits.get(binding.key.raw),
2226
+ onEdit,
2227
+ readOnly,
2228
+ ariaLabel: `${tableLabel} row ${rowIndex + 1} \u2014 ${formatLabel(column)}`
2229
+ }
2230
+ ) : /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: cell === void 0 ? "-" : formatValue(cell.value, column) }),
2231
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ConfidenceDot, { confidence: cell?.confidence ?? null })
2232
+ ] }) }, column);
2233
+ })
2234
+ ] });
2235
+ }
2236
+ function areRowPropsEqual(prev, next) {
2237
+ if (prev.row !== next.row || prev.rowIndex !== next.rowIndex || prev.columns !== next.columns || prev.tableLabel !== next.tableLabel || prev.hasCoords !== next.hasCoords || prev.hasRowConfidence !== next.hasRowConfidence || prev.shared.bindingIndex !== next.shared.bindingIndex || prev.shared.onEdit !== next.shared.onEdit || prev.shared.onFlash !== next.shared.onFlash || prev.shared.readOnly !== next.shared.readOnly) {
2238
+ return false;
2239
+ }
2240
+ if (prev.shared.edits === next.shared.edits) {
2241
+ return true;
2242
+ }
2243
+ for (const column of next.columns) {
2244
+ const cell = next.row[column];
2245
+ const binding = cell === void 0 ? void 0 : next.shared.bindingIndex.get(cell.pointer);
2246
+ if (binding !== void 0 && prev.shared.edits.get(binding.key.raw) !== next.shared.edits.get(binding.key.raw)) {
2247
+ return false;
2248
+ }
2249
+ }
2250
+ return true;
2251
+ }
2252
+ var TableRow = import_react3.default.memo(TableRowView, areRowPropsEqual);
2253
+ function TableSection(props) {
2254
+ const { table, shared } = props;
2255
+ const label = formatLabel(table.key);
2256
+ const hasCoords = import_react3.default.useMemo(
2257
+ () => table.rows.some(
2258
+ (row) => Object.entries(row).some(([key, cell]) => key !== ROW_META_KEY && cell.coordinates !== null)
2259
+ ),
2260
+ [table]
2261
+ );
2262
+ const hasRowConfidence = import_react3.default.useMemo(
2263
+ () => table.rows.some((row) => Boolean(row[ROW_META_KEY]?.confidence?.level)),
2264
+ [table]
2265
+ );
2266
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "gemina-verification__section", "aria-label": label, children: [
2267
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { className: "gemina-verification__section-header", children: [
2268
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("span", { children: [
2269
+ label,
2270
+ " (",
2271
+ table.rows.length,
2272
+ " rows)"
2273
+ ] }),
2274
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ConfidenceDot, { confidence: table.overallConfidence })
2275
+ ] }),
2276
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "gemina-verification__table-wrap", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("table", { className: "gemina-verification__table", children: [
2277
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("thead", { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("tr", { children: [
2278
+ hasCoords ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("th", { "aria-label": "Show row on document" }) : null,
2279
+ hasRowConfidence ? /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("th", { "aria-label": "Row confidence" }) : null,
2280
+ table.columns.map((column) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("th", { children: formatLabel(column) }, column))
2281
+ ] }) }),
2282
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("tbody", { children: table.rows.map((row, rowIndex) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2283
+ TableRow,
2284
+ {
2285
+ row,
2286
+ rowIndex,
2287
+ columns: table.columns,
2288
+ tableLabel: label,
2289
+ hasCoords,
2290
+ hasRowConfidence,
2291
+ shared
2292
+ },
2293
+ rowIndex
2294
+ )) })
2295
+ ] }) })
2296
+ ] });
2297
+ }
2298
+ var FallbackSection = import_react3.default.memo(function FallbackSection2(props) {
2299
+ const { fallback } = props;
2300
+ if (fallback.length === 0) {
2301
+ return null;
2302
+ }
2303
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "gemina-verification__section", "aria-label": "Additional Data", children: [
2304
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "gemina-verification__section-header", children: "Additional Data" }),
2305
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "gemina-verification__section-body", children: fallback.map((item) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("details", { className: "gemina-verification__fallback", children: [
2306
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("summary", { children: formatLabel(item.key) }),
2307
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("pre", { children: JSON.stringify(item.data, null, 2) })
2308
+ ] }, item.key)) })
2309
+ ] });
2310
+ });
2311
+ function UnmatchedSection(props) {
2312
+ const { unmatched, shared } = props;
2313
+ if (unmatched.length === 0) {
2314
+ return null;
2315
+ }
2316
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { className: "gemina-verification__section", "aria-label": "Not detected", children: [
2317
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { className: "gemina-verification__section-header", children: "Not detected" }),
2318
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dl", { className: "gemina-verification__dl", children: unmatched.map((binding) => /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_react3.default.Fragment, { children: [
2319
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dt", { className: "gemina-verification__dt", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { children: binding.key.label }) }),
2320
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("dd", { className: "gemina-verification__dd", children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
2321
+ FieldInput,
2322
+ {
2323
+ binding,
2324
+ edit: shared.edits.get(binding.key.raw),
2325
+ onEdit: shared.onEdit,
2326
+ readOnly: shared.readOnly,
2327
+ ariaLabel: binding.key.label
2328
+ }
2329
+ ) })
2330
+ ] }, binding.key.raw)) })
2331
+ ] });
2332
+ }
2333
+ function VerificationForm(props) {
2334
+ const { classified, unmatched, bindingIndex, edits, onEdit, readOnly, onFlash } = props;
2335
+ const shared = { bindingIndex, edits, onEdit, readOnly, onFlash };
2336
+ return (
2337
+ // A real, labeled <form> (role "form" landmark): AT users can jump
2338
+ // straight to the editable fields. Submission is owned by the root's
2339
+ // footer button, never by the form element itself — preventDefault stops
2340
+ // implicit submission (Enter in a payload with exactly one input would
2341
+ // otherwise navigate).
2342
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
2343
+ "form",
2344
+ {
2345
+ className: "gemina-verification__form",
2346
+ "aria-label": "Extraction fields",
2347
+ onSubmit: (event) => event.preventDefault(),
2348
+ children: [
2349
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(HeaderSection, { headers: classified.headers, simpleLists: classified.simpleLists, shared }),
2350
+ classified.entities.map((entity) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(EntitySection, { entity, shared }, entity.pointer)),
2351
+ classified.tables.map((table) => /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(TableSection, { table, shared }, table.pointer)),
2352
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(FallbackSection, { fallback: classified.fallback }),
2353
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(UnmatchedSection, { unmatched, shared })
2354
+ ]
2355
+ }
2356
+ )
2357
+ );
2358
+ }
2359
+
2360
+ // src/verification/styles.ts
2361
+ var DARK_VARS2 = `
2362
+ --gemina-verification-bg: #101418;
2363
+ --gemina-verification-fg: #e6e9ee;
2364
+ --gemina-verification-border: #2a323c;
2365
+ --gemina-verification-accent: #4c8dff;
2366
+ --gemina-verification-accent-fg: #ffffff;
2367
+ --gemina-verification-surface: #1c232b;
2368
+ --gemina-verification-muted: #98a2b3;
2369
+ --gemina-verification-error: #f97066;
2370
+ --gemina-verification-input-bg: #12171d;
2371
+ --gemina-verification-input-border: #2a323c;
2372
+ --gemina-verification-dirty: #f7b27a;
2373
+ `;
2374
+ var VERIFICATION_CSS = `
2375
+ .gemina-verification {
2376
+ --gemina-verification-bg: #ffffff;
2377
+ --gemina-verification-fg: #1a1d21;
2378
+ --gemina-verification-border: #d9dce1;
2379
+ --gemina-verification-accent: #2f6fed;
2380
+ --gemina-verification-accent-fg: #ffffff;
2381
+ --gemina-verification-surface: #f2f4f7;
2382
+ --gemina-verification-muted: #667085;
2383
+ --gemina-verification-error: #b42318;
2384
+ --gemina-verification-input-bg: #ffffff;
2385
+ --gemina-verification-input-border: #d0d5e2;
2386
+ --gemina-verification-dirty: #b54708;
2387
+ --gemina-verification-confidence-high: #52c41a;
2388
+ --gemina-verification-confidence-medium: #faad14;
2389
+ --gemina-verification-confidence-low: #ff4d4f;
2390
+ --gemina-verification-confidence-unknown: #d9d9d9;
2391
+ --gemina-verification-overlay-rgb: 24, 144, 255;
2392
+ --gemina-verification-radius: 10px;
2393
+ --gemina-verification-font: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
2394
+
2395
+ box-sizing: border-box;
2396
+ position: relative; /* anchors __confirm; never overflow:hidden here \u2014 it would break the stacked sticky viewer */
2397
+ display: flex;
2398
+ flex-direction: column;
2399
+ gap: 16px;
2400
+ padding: 16px;
2401
+ background: var(--gemina-verification-bg);
2402
+ color: var(--gemina-verification-fg);
2403
+ border: 1px solid var(--gemina-verification-border);
2404
+ border-radius: var(--gemina-verification-radius);
2405
+ font-family: var(--gemina-verification-font);
2406
+ font-size: 14px;
2407
+ line-height: 1.5;
2408
+ }
2409
+ .gemina-verification *, .gemina-verification *::before, .gemina-verification *::after { box-sizing: border-box; }
2410
+ .gemina-verification--dark { ${DARK_VARS2} }
2411
+ @media (prefers-color-scheme: dark) {
2412
+ .gemina-verification--auto { ${DARK_VARS2} }
2413
+ }
2414
+ .gemina-verification--rtl { direction: rtl; }
2415
+
2416
+ /* --- Two-pane layout ------------------------------------------------------ */
2417
+ .gemina-verification__panes {
2418
+ display: grid;
2419
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
2420
+ gap: 16px;
2421
+ }
2422
+ .gemina-verification--stacked .gemina-verification__panes {
2423
+ /* Flex column, NOT a one-column grid: a sticky GRID item is confined to its
2424
+ own grid area \u2014 whose auto row is exactly its own height, leaving zero
2425
+ travel \u2014 while a sticky FLEX child's containing block is the whole panes
2426
+ box, so the viewer genuinely floats over the form as it scrolls. The gap
2427
+ carries over from the base rule. */
2428
+ display: flex;
2429
+ flex-direction: column;
2430
+ }
2431
+ .gemina-verification--stacked .gemina-verification__viewer {
2432
+ position: sticky;
2433
+ top: 0; /* block axis, not inline \u2014 RTL-safe */
2434
+ z-index: 2;
2435
+ /* Cap AND height in one declaration: the canvas is absolutely-positioned
2436
+ geometry with no intrinsic height (it contributes only its min-height),
2437
+ so a max-block-size alone would never bind \u2014 the explicit block-size is
2438
+ what the canvas fills. 48vh keeps the majority of a short viewport for
2439
+ the form the reviewer is working through; 420px stops a tall narrow
2440
+ window from devoting a huge sticky band to the document. The dvh line
2441
+ wins where supported (mobile browser chrome shrinks the visual viewport). */
2442
+ flex: 0 0 auto;
2443
+ block-size: min(48vh, 420px);
2444
+ block-size: min(48dvh, 420px);
2445
+ }
2446
+ .gemina-verification--stacked .gemina-verification__canvas {
2447
+ /* The stacked cap owns the height; the side-by-side 280px floor would
2448
+ overflow it on short viewports (48vh of a 568px screen is ~273px). */
2449
+ min-height: 120px;
2450
+ }
2451
+
2452
+ /* --- Document viewer ------------------------------------------------------ */
2453
+ .gemina-verification__viewer {
2454
+ display: flex;
2455
+ flex-direction: column;
2456
+ min-width: 0;
2457
+ background: var(--gemina-verification-bg);
2458
+ border: 1px solid var(--gemina-verification-border);
2459
+ border-radius: var(--gemina-verification-radius);
2460
+ overflow: hidden;
2461
+ }
2462
+ .gemina-verification__toolbar {
2463
+ display: flex;
2464
+ /* Narrow roots (~<330px) can't fit all 7 buttons on one line: wrap to a
2465
+ second row instead of clipping past the canvas edge. The gap shorthand
2466
+ below already provides the 6px row-gap between wrapped rows. */
2467
+ flex-wrap: wrap;
2468
+ align-items: center;
2469
+ gap: 6px;
2470
+ flex: 0 0 auto;
2471
+ padding: 8px 10px;
2472
+ border-block-end: 1px solid var(--gemina-verification-border);
2473
+ }
2474
+ .gemina-verification__toolbar-btn {
2475
+ font: inherit;
2476
+ font-size: 12px;
2477
+ padding: 4px 10px;
2478
+ border-radius: calc(var(--gemina-verification-radius) - 4px);
2479
+ border: 1px solid var(--gemina-verification-border);
2480
+ background: transparent;
2481
+ color: var(--gemina-verification-fg);
2482
+ cursor: pointer;
2483
+ transition: border-color 120ms ease, background-color 120ms ease, color 120ms ease;
2484
+ }
2485
+ .gemina-verification__toolbar-btn svg { display: block; } /* no inline-baseline slack under the icons */
2486
+ .gemina-verification__toolbar-btn:hover:not(:disabled) { border-color: var(--gemina-verification-accent); }
2487
+ .gemina-verification__toolbar-btn:disabled { opacity: 0.5; cursor: default; }
2488
+ .gemina-verification__toolbar-btn--active {
2489
+ background: var(--gemina-verification-accent);
2490
+ border-color: var(--gemina-verification-accent);
2491
+ color: var(--gemina-verification-accent-fg);
2492
+ }
2493
+ .gemina-verification__canvas {
2494
+ position: relative;
2495
+ flex: 1;
2496
+ min-height: 280px;
2497
+ overflow: hidden;
2498
+ background: var(--gemina-verification-surface);
2499
+ touch-action: none;
2500
+ cursor: zoom-in; /* initial truth: at fit a drag is inert, wheel/dblclick zooms */
2501
+ user-select: none;
2502
+ -webkit-user-select: none;
2503
+ }
2504
+ /* Cursor is the promise of what a drag will do, so it follows viewer state
2505
+ (data-cursor), never :active \u2014 a bare :active rule would claim "grabbing"
2506
+ at fit scale where pan never engages. */
2507
+ .gemina-verification__canvas[data-cursor='zoom-in'] { cursor: zoom-in; }
2508
+ .gemina-verification__canvas[data-cursor='grab'] { cursor: grab; }
2509
+ .gemina-verification__canvas[data-cursor='grabbing'] { cursor: grabbing; }
2510
+ /* The document image is geometry, not layout: a block box at natural size,
2511
+ positioned purely by the JS transform layer above it. */
2512
+ .gemina-verification__canvas img {
2513
+ display: block;
2514
+ max-width: unset;
2515
+ max-height: unset;
2516
+ }
2517
+ /* Overlay geometry (left/top/width/height) is set inline by the viewer from
2518
+ transform math; CSS owns only the appearance. */
2519
+ .gemina-verification__rect {
2520
+ position: absolute;
2521
+ z-index: 2;
2522
+ pointer-events: none;
2523
+ border: 2px solid rgba(var(--gemina-verification-overlay-rgb), 0.85);
2524
+ background: rgba(var(--gemina-verification-overlay-rgb), 0.16);
2525
+ border-radius: 2px;
2526
+ }
2527
+ /* Numbered "#1" chip on each overlay rect. Physical left/top: the badge lives
2528
+ in image coordinate space inside the transform layer (geometry, not layout),
2529
+ so it scales and rotates with the document exactly like the console's.
2530
+ Explicit line-height pins the chip height across host font stacks. */
2531
+ .gemina-verification__rect-badge {
2532
+ position: absolute;
2533
+ top: -18px;
2534
+ left: 0;
2535
+ font-size: 11px;
2536
+ font-weight: 600;
2537
+ line-height: 16px;
2538
+ color: rgb(var(--gemina-verification-overlay-rgb));
2539
+ background: rgba(255, 255, 255, 0.92); /* floats over the document, not the theme surface */
2540
+ padding: 0 6px;
2541
+ border-radius: 12px;
2542
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.16);
2543
+ pointer-events: none;
2544
+ }
2545
+ .gemina-verification__flash-rect {
2546
+ /* Fade is driven by JS via element-level opacity (rAF travel animation);
2547
+ no CSS animation here so the two never fight. Element-level opacity is
2548
+ equivalent to the console's per-channel fade \u2014 border (1\xB7o), background
2549
+ (0.25\xB7o), glow (0.6\xB7o / 0.3\xB7o) \u2014 modulo overlapping-layer compositing:
2550
+ per-channel alphas blend border-over-background where they overlap,
2551
+ element opacity flattens the group first. Indistinguishable in practice. */
2552
+ position: absolute;
2553
+ z-index: 3;
2554
+ pointer-events: none;
2555
+ border: 5px solid rgba(var(--gemina-verification-overlay-rgb), 1);
2556
+ background: rgba(var(--gemina-verification-overlay-rgb), 0.25);
2557
+ box-shadow: 0 0 20px rgba(var(--gemina-verification-overlay-rgb), 0.6),
2558
+ inset 0 0 10px rgba(var(--gemina-verification-overlay-rgb), 0.3);
2559
+ border-radius: 2px;
2560
+ }
2561
+ .gemina-verification__magnifier {
2562
+ position: absolute;
2563
+ z-index: 4;
2564
+ pointer-events: none;
2565
+ overflow: hidden;
2566
+ border-radius: 50%;
2567
+ border: 2px solid rgba(255, 255, 255, 0.85);
2568
+ box-shadow: 0 2px 12px rgba(0, 0, 0, 0.35);
2569
+ background: var(--gemina-verification-surface);
2570
+ }
2571
+
2572
+ /* --- Form pane ------------------------------------------------------------ */
2573
+ /* A real <form> element (labeled AT landmark) \u2014 margin reset guards against
2574
+ host/UA form margins. */
2575
+ .gemina-verification__form {
2576
+ display: flex;
2577
+ flex-direction: column;
2578
+ gap: 12px;
2579
+ min-width: 0;
2580
+ margin: 0;
2581
+ }
2582
+ .gemina-verification__section {
2583
+ background: var(--gemina-verification-bg);
2584
+ border: 1px solid var(--gemina-verification-border);
2585
+ border-radius: var(--gemina-verification-radius);
2586
+ overflow: hidden;
2587
+ }
2588
+ .gemina-verification__section-header {
2589
+ display: flex;
2590
+ align-items: center;
2591
+ gap: 8px;
2592
+ padding: 8px 12px;
2593
+ background: var(--gemina-verification-surface);
2594
+ border-block-end: 1px solid var(--gemina-verification-border);
2595
+ font-size: 13px;
2596
+ font-weight: 600;
2597
+ }
2598
+ .gemina-verification__dl {
2599
+ display: grid;
2600
+ grid-template-columns: minmax(0, 2fr) minmax(0, 3fr);
2601
+ column-gap: 12px;
2602
+ margin: 0;
2603
+ padding: 8px 12px;
2604
+ }
2605
+ .gemina-verification__dt {
2606
+ display: flex;
2607
+ align-items: center;
2608
+ gap: 6px;
2609
+ padding-block: 5px;
2610
+ min-width: 0;
2611
+ font-size: 12px;
2612
+ color: var(--gemina-verification-muted);
2613
+ overflow-wrap: break-word;
2614
+ }
2615
+ .gemina-verification__dd {
2616
+ display: flex;
2617
+ align-items: center;
2618
+ gap: 6px;
2619
+ margin: 0; /* resets the UA's margin-inline-start on <dd> */
2620
+ padding-block: 5px;
2621
+ min-width: 0;
2622
+ font-size: 13px;
2623
+ font-variant-numeric: tabular-nums;
2624
+ overflow-wrap: break-word;
2625
+ }
2626
+ .gemina-verification__input {
2627
+ width: 100%;
2628
+ font: inherit;
2629
+ font-size: 13px;
2630
+ color: var(--gemina-verification-fg);
2631
+ background: var(--gemina-verification-input-bg);
2632
+ border: 1px solid var(--gemina-verification-input-border);
2633
+ border-radius: calc(var(--gemina-verification-radius) - 4px);
2634
+ padding: 5px 8px;
2635
+ }
2636
+ .gemina-verification__input--dirty { border-color: var(--gemina-verification-dirty); }
2637
+ .gemina-verification__input--missed {
2638
+ border-color: var(--gemina-verification-error);
2639
+ box-shadow: 0 0 0 1px var(--gemina-verification-error);
2640
+ }
2641
+ /* Non-color dirty channel: the word itself is the signal (WCAG 1.4.1) \u2014 it
2642
+ stays legible when --missed's error border overrides the dirty border. */
2643
+ .gemina-verification__edited {
2644
+ flex: 0 0 auto;
2645
+ font-size: 10px;
2646
+ font-weight: 600;
2647
+ letter-spacing: 0.06em;
2648
+ text-transform: uppercase;
2649
+ color: var(--gemina-verification-dirty);
2650
+ }
2651
+ .gemina-verification__dot {
2652
+ display: inline-block;
2653
+ flex: 0 0 auto;
2654
+ width: 8px;
2655
+ height: 8px;
2656
+ border-radius: 50%;
2657
+ background: var(--gemina-verification-confidence-unknown);
2658
+ }
2659
+ .gemina-verification__dot--high { background: var(--gemina-verification-confidence-high); }
2660
+ .gemina-verification__dot--medium { background: var(--gemina-verification-confidence-medium); }
2661
+ .gemina-verification__dot--low { background: var(--gemina-verification-confidence-low); }
2662
+ .gemina-verification__dot--unknown { background: var(--gemina-verification-confidence-unknown); }
2663
+ .gemina-verification__eye {
2664
+ display: inline-flex;
2665
+ align-items: center;
2666
+ justify-content: center;
2667
+ flex: 0 0 auto;
2668
+ width: 24px;
2669
+ height: 24px;
2670
+ padding: 0;
2671
+ border: 0;
2672
+ border-radius: calc(var(--gemina-verification-radius) - 4px);
2673
+ background: transparent;
2674
+ color: var(--gemina-verification-muted);
2675
+ cursor: pointer;
2676
+ transition: background-color 120ms ease, color 120ms ease;
2677
+ }
2678
+ .gemina-verification__eye:hover {
2679
+ color: var(--gemina-verification-accent);
2680
+ background: var(--gemina-verification-surface);
2681
+ }
2682
+
2683
+ /* --- Tables and cards ----------------------------------------------------- */
2684
+ /* Section content that is not flush with the section frame (cards, fallback
2685
+ details) sits inside this padded body. */
2686
+ .gemina-verification__section-body { padding: 8px 12px; }
2687
+ /* Flex row for FieldInput's fragment (input + "edited" badge) inside <td>s
2688
+ and list items \u2014 the fragment has no container of its own. */
2689
+ .gemina-verification__cell {
2690
+ display: flex;
2691
+ align-items: center;
2692
+ gap: 6px;
2693
+ min-width: 0;
2694
+ }
2695
+ /* Simple-list items stack inside a __dd; each item row is a __cell. */
2696
+ .gemina-verification__list {
2697
+ display: flex;
2698
+ flex-direction: column;
2699
+ gap: 4px;
2700
+ flex: 1 1 auto;
2701
+ min-width: 0;
2702
+ margin: 0;
2703
+ padding: 0;
2704
+ list-style: none;
2705
+ }
2706
+ .gemina-verification__table-wrap { overflow-x: auto; }
2707
+ .gemina-verification__table {
2708
+ width: 100%;
2709
+ border-collapse: collapse;
2710
+ font-size: 13px;
2711
+ font-variant-numeric: tabular-nums;
2712
+ }
2713
+ .gemina-verification__table th {
2714
+ text-align: start;
2715
+ padding: 6px 10px;
2716
+ font-size: 12px;
2717
+ font-weight: 600;
2718
+ color: var(--gemina-verification-muted);
2719
+ background: var(--gemina-verification-surface);
2720
+ border-block-end: 1px solid var(--gemina-verification-border);
2721
+ }
2722
+ .gemina-verification__table td {
2723
+ padding: 6px 10px;
2724
+ vertical-align: top;
2725
+ border-block-end: 1px solid var(--gemina-verification-border);
2726
+ }
2727
+ .gemina-verification__table tr:last-child td { border-block-end: 0; }
2728
+ /* Wide tables lean on __table-wrap's scroll; the clamp keeps a cell input
2729
+ usable instead of letting the table squeeze it to nothing. */
2730
+ .gemina-verification__table .gemina-verification__input { min-width: 6ch; }
2731
+ .gemina-verification__card {
2732
+ display: flex;
2733
+ flex-direction: column;
2734
+ gap: 6px;
2735
+ padding: 10px 12px;
2736
+ background: var(--gemina-verification-bg);
2737
+ border: 1px solid var(--gemina-verification-border);
2738
+ border-radius: calc(var(--gemina-verification-radius) - 4px);
2739
+ }
2740
+ .gemina-verification__card + .gemina-verification__card { margin-block-start: 8px; }
2741
+ .gemina-verification__card-header {
2742
+ font-size: 12px;
2743
+ font-weight: 600;
2744
+ color: var(--gemina-verification-muted);
2745
+ }
2746
+ /* The card already pads; its inner description list must not double it. */
2747
+ .gemina-verification__card .gemina-verification__dl { padding: 0; }
2748
+ /* Fallback blobs are a native <details>: summary is the toggle, the JSON
2749
+ lives in a <pre> so only the code is monospace/pre-wrapped. */
2750
+ .gemina-verification__fallback {
2751
+ margin: 0;
2752
+ padding: 8px 12px;
2753
+ font-size: 12px;
2754
+ background: var(--gemina-verification-surface);
2755
+ border-radius: calc(var(--gemina-verification-radius) - 4px);
2756
+ }
2757
+ .gemina-verification__fallback + .gemina-verification__fallback { margin-block-start: 8px; }
2758
+ .gemina-verification__fallback summary {
2759
+ cursor: pointer;
2760
+ font-weight: 600;
2761
+ user-select: none;
2762
+ }
2763
+ .gemina-verification__fallback pre {
2764
+ margin: 0;
2765
+ margin-block-start: 8px;
2766
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
2767
+ white-space: pre-wrap;
2768
+ overflow-wrap: break-word;
2769
+ overflow-x: auto;
2770
+ }
2771
+
2772
+ /* --- Messaging, progress, actions ----------------------------------------- */
2773
+ .gemina-verification__banner {
2774
+ padding: 10px 12px;
2775
+ font-size: 13px;
2776
+ background: var(--gemina-verification-surface);
2777
+ border: 1px solid var(--gemina-verification-border);
2778
+ border-radius: var(--gemina-verification-radius);
2779
+ }
2780
+ .gemina-verification__banner--error {
2781
+ background: transparent;
2782
+ border-color: var(--gemina-verification-error);
2783
+ color: var(--gemina-verification-error);
2784
+ }
2785
+ .gemina-verification__progress {
2786
+ font-size: 12px;
2787
+ color: var(--gemina-verification-muted);
2788
+ font-variant-numeric: tabular-nums;
2789
+ /* The counts copy ("N confirmed \xB7 M corrected") is untranslated English
2790
+ chrome; under dir="rtl" the RTL paragraph direction reorders its
2791
+ leading-number run ("confirmed \xB7 0 corrected 7"). plaintext makes the
2792
+ line take its base direction from its own first strong character, so
2793
+ the English copy lays out LTR inside the RTL widget. The done-state
2794
+ recap reuses this same class, so it is covered too. */
2795
+ unicode-bidi: plaintext;
2796
+ }
2797
+ .gemina-verification__footer {
2798
+ display: flex;
2799
+ align-items: center;
2800
+ gap: 10px;
2801
+ padding-block-start: 12px;
2802
+ border-block-start: 1px solid var(--gemina-verification-border);
2803
+ }
2804
+ .gemina-verification__footer .gemina-verification__submit { margin-inline-start: auto; }
2805
+ .gemina-verification__submit {
2806
+ font: inherit;
2807
+ border: none;
2808
+ border-radius: var(--gemina-verification-radius);
2809
+ background: var(--gemina-verification-accent);
2810
+ color: var(--gemina-verification-accent-fg);
2811
+ padding: 8px 16px;
2812
+ cursor: pointer;
2813
+ }
2814
+ .gemina-verification__submit:disabled { opacity: 0.5; cursor: default; }
2815
+ .gemina-verification__retry {
2816
+ font: inherit;
2817
+ font-size: 12px;
2818
+ padding: 2px 10px;
2819
+ border-radius: var(--gemina-verification-radius);
2820
+ border: 1px solid var(--gemina-verification-error);
2821
+ background: transparent;
2822
+ color: var(--gemina-verification-error);
2823
+ cursor: pointer;
2824
+ }
2825
+ .gemina-verification__state {
2826
+ display: flex;
2827
+ flex-direction: column;
2828
+ align-items: center;
2829
+ justify-content: center;
2830
+ gap: 8px;
2831
+ min-height: 220px;
2832
+ padding: 24px;
2833
+ text-align: center;
2834
+ font-size: 13px;
2835
+ color: var(--gemina-verification-muted);
2836
+ }
2837
+ /* Submit-error banner: message + inline Retry on one line. */
2838
+ .gemina-verification__submit-error {
2839
+ display: flex;
2840
+ align-items: center;
2841
+ justify-content: space-between;
2842
+ gap: 10px;
2843
+ }
2844
+ /* Done: the one saturated moment outside the form \u2014 a single accent check. */
2845
+ .gemina-verification__state--done { color: var(--gemina-verification-fg); }
2846
+ /* Programmatic focus landing (tabIndex -1), not an interactive control: no
2847
+ ring \u2014 the accent check IS the visual landing; focus moves here purely so
2848
+ keyboard/AT users don't drop to <body> when the dialog unmounts. */
2849
+ .gemina-verification__state--done:focus,
2850
+ .gemina-verification__state--done:focus-visible { outline: none; }
2851
+ .gemina-verification__done-check {
2852
+ display: flex;
2853
+ align-items: center;
2854
+ justify-content: center;
2855
+ width: 40px;
2856
+ height: 40px;
2857
+ border-radius: 50%;
2858
+ background: var(--gemina-verification-accent);
2859
+ color: var(--gemina-verification-accent-fg);
2860
+ }
2861
+ .gemina-verification__done-title {
2862
+ font-size: 14px;
2863
+ font-weight: 600;
2864
+ }
2865
+ .gemina-verification__state--done .gemina-verification__progress { font-size: 13px; }
2866
+
2867
+ /* --- Confirm dialog ------------------------------------------------------- */
2868
+ .gemina-verification__confirm {
2869
+ position: absolute;
2870
+ inset: 0;
2871
+ z-index: 10;
2872
+ display: flex;
2873
+ /* flex-start + a sticky dialog: the scrim spans the whole component, but the
2874
+ dialog slides with the page so it is in view even when the user is
2875
+ scrolled deep into a long stacked form. Sticky (not fixed) so it survives
2876
+ transformed-ancestor hosts where fixed re-anchors. */
2877
+ align-items: flex-start;
2878
+ justify-content: center;
2879
+ padding: 16px;
2880
+ background: rgba(16, 20, 24, 0.45);
2881
+ border-radius: var(--gemina-verification-radius);
2882
+ }
2883
+ .gemina-verification__confirm-dialog {
2884
+ position: sticky;
2885
+ top: 20vh; /* block axis \u2014 RTL-safe */
2886
+ display: flex;
2887
+ flex-direction: column;
2888
+ gap: 12px;
2889
+ width: 100%;
2890
+ max-width: 380px;
2891
+ padding: 16px;
2892
+ background: var(--gemina-verification-bg);
2893
+ color: var(--gemina-verification-fg);
2894
+ border: 1px solid var(--gemina-verification-border);
2895
+ border-radius: var(--gemina-verification-radius);
2896
+ box-shadow: 0 12px 32px rgba(16, 20, 24, 0.24);
2897
+ }
2898
+ .gemina-verification__confirm-text {
2899
+ margin: 0;
2900
+ font-size: 13px;
2901
+ }
2902
+ .gemina-verification__confirm-actions {
2903
+ display: flex;
2904
+ justify-content: flex-end;
2905
+ gap: 8px;
2906
+ }
2907
+ /* Quiet counterpart to __submit: same geometry, bordered, no fill \u2014 the
2908
+ accent stays on the final action. */
2909
+ .gemina-verification__confirm-cancel {
2910
+ font: inherit;
2911
+ padding: 8px 16px;
2912
+ border: 1px solid var(--gemina-verification-border);
2913
+ border-radius: var(--gemina-verification-radius);
2914
+ background: transparent;
2915
+ color: var(--gemina-verification-fg);
2916
+ cursor: pointer;
2917
+ transition: border-color 120ms ease;
2918
+ }
2919
+ .gemina-verification__confirm-cancel:hover:not(:disabled) {
2920
+ border-color: var(--gemina-verification-accent);
2921
+ }
2922
+ .gemina-verification__confirm-cancel:disabled { opacity: 0.5; cursor: default; }
2923
+
2924
+ /* --- Focus ---------------------------------------------------------------- */
2925
+ .gemina-verification__input:focus-visible {
2926
+ outline: 2px solid var(--gemina-verification-accent);
2927
+ outline-offset: -1px;
2928
+ }
2929
+ .gemina-verification__toolbar-btn:focus-visible,
2930
+ .gemina-verification__eye:focus-visible,
2931
+ .gemina-verification__submit:focus-visible,
2932
+ .gemina-verification__retry:focus-visible,
2933
+ .gemina-verification__confirm-cancel:focus-visible,
2934
+ .gemina-verification__fallback summary:focus-visible {
2935
+ outline: 2px solid var(--gemina-verification-accent);
2936
+ outline-offset: 1px;
2937
+ }
2938
+
2939
+ /* --- Reduced motion -------------------------------------------------------- */
2940
+ /* The viewer also checks this in JS before animating; the CSS block is the
2941
+ backstop that stills the canvas (flash, travel, micro-transitions). */
2942
+ @media (prefers-reduced-motion: reduce) {
2943
+ .gemina-verification__flash-rect,
2944
+ .gemina-verification__rect,
2945
+ .gemina-verification__canvas,
2946
+ .gemina-verification__canvas * {
2947
+ animation: none;
2948
+ transition: none;
2949
+ }
2950
+ }
2951
+ `;
2952
+ var STYLE_ATTR2 = "data-gemina-verification";
2953
+ function ensureVerificationStylesInjected() {
2954
+ if (typeof document === "undefined") {
2955
+ return;
2956
+ }
2957
+ if (document.head.querySelector(`style[${STYLE_ATTR2}]`) !== null) {
2958
+ return;
2959
+ }
2960
+ const style = document.createElement("style");
2961
+ style.setAttribute(STYLE_ATTR2, VERSION);
2962
+ style.textContent = VERIFICATION_CSS;
2963
+ document.head.appendChild(style);
2964
+ }
2965
+
2966
+ // src/verification/index.tsx
2967
+ var import_jsx_runtime4 = require("react/jsx-runtime");
2968
+ var HEBREW_RE2 = /[\u0590-\u05FF]/;
2969
+ var STACKED_BREAKPOINT = 860;
2970
+ var IMAGE_REFRESH_THROTTLE_MS = 6e4;
2971
+ var LOADING_TEXT = "Loading extraction\u2026";
2972
+ var SESSION_EXPIRED_TEXT2 = "Session expired \u2014 please reload the page or sign in again.";
2973
+ var SUBMIT_SESSION_EXPIRED_TEXT = "Session expired \u2014 sign in again in another tab, then press Retry. Your corrections are still here.";
2974
+ var NOT_AVAILABLE_TEXT = "This extraction is not available.";
2975
+ var LOAD_FAILED_TEXT = "Couldn't load the extraction.";
2976
+ var PURGED_TEXT = "Document no longer available (retention policy).";
2977
+ var NOT_COMPLETED_TEXT = "This extraction did not complete, so there is nothing to verify.";
2978
+ var VERIFICATION_UNAVAILABLE_TEXT = "Verification isn't available for this extraction.";
2979
+ var ALREADY_VALIDATED_TEXT = "Already verified \u2014 showing the original extraction.";
2980
+ var CONFIRM_TEXT = "Submit verification? This is final \u2014 feedback can be submitted only once and cannot be changed.";
2981
+ var SUBMITTING_TEXT = "Submitting\u2026";
2982
+ var SUBMIT_FAILED_TEXT = "Submission failed \u2014 your corrections are still here.";
2983
+ var DONE_TITLE_TEXT = "Feedback submitted";
2984
+ var NO_EDITS = /* @__PURE__ */ new Map();
2985
+ var ALERT_REASONS = /* @__PURE__ */ new Set([
2986
+ "session-expired",
2987
+ "not-available",
2988
+ "load-failed"
2989
+ ]);
2990
+ function GeminaVerification(props) {
2991
+ const {
2992
+ extractionId,
2993
+ tokenManager,
2994
+ baseUrl,
2995
+ theme = "auto",
2996
+ dir = "auto",
2997
+ onComplete,
2998
+ onError,
2999
+ className
3000
+ } = props;
3001
+ const [phase, setPhase] = (0, import_react4.useState)({ name: "loading" });
3002
+ const [alreadyValidated, setAlreadyValidated] = (0, import_react4.useState)(false);
3003
+ const [loaded, setLoaded] = (0, import_react4.useState)(null);
3004
+ const [edits, setEdits] = (0, import_react4.useState)(NO_EDITS);
3005
+ const [imageUrl, setImageUrl] = (0, import_react4.useState)(null);
3006
+ const [flashRects, setFlashRects] = (0, import_react4.useState)(null);
3007
+ const [stacked, setStacked] = (0, import_react4.useState)(false);
3008
+ const rootRef = (0, import_react4.useRef)(null);
3009
+ const mountedRef = (0, import_react4.useRef)(false);
3010
+ const loadSeqRef = (0, import_react4.useRef)(0);
3011
+ const lastImageRefreshRef = (0, import_react4.useRef)(0);
3012
+ const onErrorRef = (0, import_react4.useRef)(onError);
3013
+ onErrorRef.current = onError;
3014
+ const onCompleteRef = (0, import_react4.useRef)(onComplete);
3015
+ onCompleteRef.current = onComplete;
3016
+ const completedRef = (0, import_react4.useRef)(false);
3017
+ const submitInFlightRef = (0, import_react4.useRef)(false);
3018
+ const restoreFocusRef = (0, import_react4.useRef)(false);
3019
+ const submitButtonRef = (0, import_react4.useRef)(null);
3020
+ const confirmButtonRef = (0, import_react4.useRef)(null);
3021
+ const cancelButtonRef = (0, import_react4.useRef)(null);
3022
+ const retrySubmitButtonRef = (0, import_react4.useRef)(null);
3023
+ const doneStateRef = (0, import_react4.useRef)(null);
3024
+ const enterUnavailable = (0, import_react4.useCallback)(
3025
+ (reason, message, canRetry, detail) => {
3026
+ setPhase({ name: "unavailable", reason, message, canRetry });
3027
+ onErrorRef.current?.(reason, detail);
3028
+ },
3029
+ []
3030
+ );
3031
+ const fetchOnce = (0, import_react4.useCallback)(async () => {
3032
+ const token = await tokenManager.getToken();
3033
+ return import_sdk2.GeminaClient.withSessionToken(token, baseUrl).documents.getDocumentExtraction({
3034
+ documentExtractionId: extractionId
3035
+ });
3036
+ }, [tokenManager, baseUrl, extractionId]);
3037
+ const fetchWithRetry = (0, import_react4.useCallback)(async () => {
3038
+ try {
3039
+ return await fetchOnce();
3040
+ } catch (error) {
3041
+ if (httpStatus(error) !== 401) {
3042
+ throw error;
3043
+ }
3044
+ tokenManager.invalidate();
3045
+ return await fetchOnce();
3046
+ }
3047
+ }, [fetchOnce, tokenManager]);
3048
+ const load = (0, import_react4.useCallback)(async () => {
3049
+ const seq = ++loadSeqRef.current;
3050
+ const live = () => mountedRef.current && loadSeqRef.current === seq;
3051
+ setPhase({ name: "loading" });
3052
+ completedRef.current = false;
3053
+ setFlashRects(null);
3054
+ lastImageRefreshRef.current = 0;
3055
+ let view;
3056
+ try {
3057
+ view = await fetchWithRetry();
3058
+ } catch (error) {
3059
+ const detail = await readErrorEnvelope(error);
3060
+ if (!live()) {
3061
+ return;
3062
+ }
3063
+ if (detail.status === 401) {
3064
+ enterUnavailable("session-expired", SESSION_EXPIRED_TEXT2, false, detail);
3065
+ } else if (detail.status === 404) {
3066
+ enterUnavailable("not-available", NOT_AVAILABLE_TEXT, false, detail);
3067
+ } else {
3068
+ enterUnavailable("load-failed", LOAD_FAILED_TEXT, true, detail);
3069
+ }
3070
+ return;
3071
+ }
3072
+ if (!live()) {
3073
+ return;
3074
+ }
3075
+ const enterReview = (validated) => {
3076
+ const schema = view.meta.validationFeedback?.validationSchema;
3077
+ setLoaded({
3078
+ values: view.values,
3079
+ schema: Array.isArray(schema) ? schema : []
3080
+ });
3081
+ setEdits(NO_EDITS);
3082
+ const url = view.document.imageUrl;
3083
+ setImageUrl(typeof url === "string" && url.length > 0 ? url : null);
3084
+ setAlreadyValidated(validated);
3085
+ setPhase({ name: "review" });
3086
+ };
3087
+ if (view.meta.purgedAt != null) {
3088
+ enterUnavailable("purged", PURGED_TEXT, false);
3089
+ } else if (view.meta.processingStatus !== "success") {
3090
+ enterUnavailable("not-completed", NOT_COMPLETED_TEXT, false);
3091
+ } else if (view.meta.validated === true) {
3092
+ enterReview(true);
3093
+ } else if (!Array.isArray(view.meta.validationFeedback?.validationSchema) || view.meta.validationFeedback.validationSchema.length === 0) {
3094
+ enterUnavailable("verification-unavailable", VERIFICATION_UNAVAILABLE_TEXT, false);
3095
+ } else {
3096
+ enterReview(false);
3097
+ }
3098
+ }, [fetchWithRetry, enterUnavailable]);
3099
+ (0, import_react4.useEffect)(() => {
3100
+ mountedRef.current = true;
3101
+ ensureVerificationStylesInjected();
3102
+ void load();
3103
+ return () => {
3104
+ mountedRef.current = false;
3105
+ };
3106
+ }, [load]);
3107
+ (0, import_react4.useEffect)(() => {
3108
+ const el = rootRef.current;
3109
+ if (el === null) {
3110
+ return;
3111
+ }
3112
+ const apply = (width) => setStacked(width > 0 && width < STACKED_BREAKPOINT);
3113
+ if (typeof ResizeObserver === "undefined") {
3114
+ apply(el.getBoundingClientRect().width);
3115
+ return;
3116
+ }
3117
+ const observer = new ResizeObserver((entries) => {
3118
+ const entry = entries[0];
3119
+ if (!entry) {
3120
+ return;
3121
+ }
3122
+ const width = entry.borderBoxSize?.[0]?.inlineSize ?? entry.contentRect.width;
3123
+ apply(width);
3124
+ });
3125
+ observer.observe(el);
3126
+ return () => observer.disconnect();
3127
+ }, []);
3128
+ const classified = (0, import_react4.useMemo)(() => classifyData(loaded?.values), [loaded]);
3129
+ const bindings = (0, import_react4.useMemo)(() => buildBindings(loaded?.schema ?? [], loaded?.values), [loaded]);
3130
+ const bindingIndex = (0, import_react4.useMemo)(() => indexBindingsByFieldPointer(bindings), [bindings]);
3131
+ const unmatched = (0, import_react4.useMemo)(() => {
3132
+ const rendered = /* @__PURE__ */ new Set();
3133
+ for (const field of classified.headers) {
3134
+ rendered.add(field.pointer);
3135
+ }
3136
+ for (const list of classified.simpleLists) {
3137
+ for (const item of list.items) {
3138
+ rendered.add(item.pointer);
3139
+ }
3140
+ }
3141
+ for (const entity of classified.entities) {
3142
+ for (const item of entity.items) {
3143
+ for (const cell of Object.values(item)) {
3144
+ rendered.add(cell.pointer);
3145
+ }
3146
+ }
3147
+ }
3148
+ for (const table of classified.tables) {
3149
+ for (const row of table.rows) {
3150
+ for (const [key, cell] of Object.entries(row)) {
3151
+ if (key !== ROW_META_KEY) {
3152
+ rendered.add(cell.pointer);
3153
+ }
3154
+ }
3155
+ }
3156
+ }
3157
+ return bindings.filter((binding) => !rendered.has(binding.fieldPointer));
3158
+ }, [classified, bindings]);
3159
+ const overlayRects = (0, import_react4.useMemo)(() => {
3160
+ const rects = [];
3161
+ for (const field of classified.headers) {
3162
+ if (field.coordinates) {
3163
+ rects.push(field.coordinates);
3164
+ }
3165
+ }
3166
+ for (const list of classified.simpleLists) {
3167
+ for (const item of list.items) {
3168
+ if (item.coordinates) {
3169
+ rects.push(item.coordinates);
3170
+ }
3171
+ }
3172
+ }
3173
+ for (const entity of classified.entities) {
3174
+ for (const item of entity.items) {
3175
+ for (const cell of Object.values(item)) {
3176
+ if (cell.coordinates) {
3177
+ rects.push(cell.coordinates);
3178
+ }
3179
+ }
3180
+ }
3181
+ }
3182
+ for (const table of classified.tables) {
3183
+ for (const row of table.rows) {
3184
+ for (const [key, cell] of Object.entries(row)) {
3185
+ if (key !== ROW_META_KEY && cell.coordinates) {
3186
+ rects.push(cell.coordinates);
3187
+ }
3188
+ }
3189
+ }
3190
+ }
3191
+ return rects.length > 0 ? rects : void 0;
3192
+ }, [classified]);
3193
+ const hasHebrewContent = (0, import_react4.useMemo)(
3194
+ () => bindings.some((binding) => HEBREW_RE2.test(toInputString(binding.extracted))),
3195
+ [bindings]
3196
+ );
3197
+ const effectiveDir = dir === "auto" ? hasHebrewContent ? "rtl" : "ltr" : dir;
3198
+ const bindingsByRawKey = (0, import_react4.useMemo)(() => {
3199
+ const map = /* @__PURE__ */ new Map();
3200
+ for (const binding of bindings) {
3201
+ map.set(binding.key.raw, binding);
3202
+ }
3203
+ return map;
3204
+ }, [bindings]);
3205
+ const bindingsByRawKeyRef = (0, import_react4.useRef)(bindingsByRawKey);
3206
+ bindingsByRawKeyRef.current = bindingsByRawKey;
3207
+ const handleEdit = (0, import_react4.useCallback)((rawKey, value) => {
3208
+ const binding = bindingsByRawKeyRef.current.get(rawKey);
3209
+ const pristine = binding !== void 0 && value === toInputString(binding.extracted);
3210
+ setEdits((prev) => {
3211
+ if (pristine) {
3212
+ if (!prev.has(rawKey)) {
3213
+ return prev;
3214
+ }
3215
+ const next2 = new Map(prev);
3216
+ next2.delete(rawKey);
3217
+ return next2;
3218
+ }
3219
+ if (prev.get(rawKey) === value) {
3220
+ return prev;
3221
+ }
3222
+ const next = new Map(prev);
3223
+ next.set(rawKey, value);
3224
+ return next;
3225
+ });
3226
+ }, []);
3227
+ const submission = (0, import_react4.useMemo)(() => composeSubmission(bindings, edits), [bindings, edits]);
3228
+ const handleFlash = (0, import_react4.useCallback)((rects) => {
3229
+ setFlashRects(rects.map((rect) => ({ points: rect.points })));
3230
+ }, []);
3231
+ const handleFlashComplete = (0, import_react4.useCallback)(() => {
3232
+ setFlashRects(null);
3233
+ }, []);
3234
+ const handleImageExpired = (0, import_react4.useCallback)(() => {
3235
+ const now = Date.now();
3236
+ if (now - lastImageRefreshRef.current < IMAGE_REFRESH_THROTTLE_MS) {
3237
+ return;
3238
+ }
3239
+ lastImageRefreshRef.current = now;
3240
+ const seq = loadSeqRef.current;
3241
+ fetchWithRetry().then((view) => {
3242
+ if (!mountedRef.current || loadSeqRef.current !== seq) {
3243
+ return;
3244
+ }
3245
+ const url = view.document.imageUrl;
3246
+ if (typeof url === "string" && url.length > 0) {
3247
+ setImageUrl(url);
3248
+ }
3249
+ }).catch(() => {
3250
+ });
3251
+ }, [fetchWithRetry]);
3252
+ const handleRetry = (0, import_react4.useCallback)(() => {
3253
+ void load();
3254
+ }, [load]);
3255
+ const doSubmit = (0, import_react4.useCallback)(async () => {
3256
+ if (submitInFlightRef.current) {
3257
+ return;
3258
+ }
3259
+ submitInFlightRef.current = true;
3260
+ const seq = loadSeqRef.current;
3261
+ const live = () => mountedRef.current && loadSeqRef.current === seq;
3262
+ setPhase({ name: "submitting" });
3263
+ const body = submission;
3264
+ const submitOnce = async () => {
3265
+ const token = await tokenManager.getToken();
3266
+ return import_sdk2.GeminaClient.withSessionToken(token, baseUrl).documents.validateDocumentExtraction({
3267
+ targetDocumentExtractionId: extractionId,
3268
+ extractionValidationInDTO: { data: body.data }
3269
+ });
3270
+ };
3271
+ try {
3272
+ let result;
3273
+ try {
3274
+ try {
3275
+ result = await submitOnce();
3276
+ } catch (error) {
3277
+ if (httpStatus(error) !== 401) {
3278
+ throw error;
3279
+ }
3280
+ tokenManager.invalidate();
3281
+ result = await submitOnce();
3282
+ }
3283
+ } catch (error) {
3284
+ const detail = await readErrorEnvelope(error);
3285
+ if (!live()) {
3286
+ return;
3287
+ }
3288
+ if (detail.status === 409) {
3289
+ void load();
3290
+ return;
3291
+ }
3292
+ if (detail.status === 401) {
3293
+ setPhase({ name: "submit-error", message: SUBMIT_SESSION_EXPIRED_TEXT });
3294
+ onErrorRef.current?.("session-expired", detail);
3295
+ return;
3296
+ }
3297
+ setPhase({
3298
+ name: "submit-error",
3299
+ message: detail.description ?? SUBMIT_FAILED_TEXT
3300
+ });
3301
+ onErrorRef.current?.("submit-failed", detail);
3302
+ return;
3303
+ }
3304
+ if (!live()) {
3305
+ return;
3306
+ }
3307
+ setPhase({ name: "done", confirmed: body.confirmed, corrected: body.corrected });
3308
+ if (!completedRef.current) {
3309
+ completedRef.current = true;
3310
+ onCompleteRef.current?.({ correctedValues: body.byLabel, summary: result.data });
3311
+ }
3312
+ } finally {
3313
+ submitInFlightRef.current = false;
3314
+ }
3315
+ }, [submission, tokenManager, baseUrl, extractionId, load]);
3316
+ const handleSubmitClick = (0, import_react4.useCallback)(() => {
3317
+ setPhase({ name: "confirming" });
3318
+ }, []);
3319
+ const handleConfirm = (0, import_react4.useCallback)(() => {
3320
+ void doSubmit();
3321
+ }, [doSubmit]);
3322
+ const handleCancelConfirm = (0, import_react4.useCallback)(() => {
3323
+ restoreFocusRef.current = true;
3324
+ setPhase({ name: "review" });
3325
+ }, []);
3326
+ const handleRetrySubmit = (0, import_react4.useCallback)(() => {
3327
+ void doSubmit();
3328
+ }, [doSubmit]);
3329
+ const handleConfirmKeyDown = (0, import_react4.useCallback)(
3330
+ (event) => {
3331
+ if (phase.name !== "confirming") {
3332
+ return;
3333
+ }
3334
+ if (event.key === "Escape") {
3335
+ event.stopPropagation();
3336
+ handleCancelConfirm();
3337
+ return;
3338
+ }
3339
+ if (event.key === "Tab") {
3340
+ const cancel = cancelButtonRef.current;
3341
+ const confirm = confirmButtonRef.current;
3342
+ if (cancel === null || confirm === null) {
3343
+ return;
3344
+ }
3345
+ const active = document.activeElement;
3346
+ if (event.shiftKey && active === cancel) {
3347
+ event.preventDefault();
3348
+ confirm.focus();
3349
+ } else if (!event.shiftKey && active === confirm) {
3350
+ event.preventDefault();
3351
+ cancel.focus();
3352
+ } else if (active !== cancel && active !== confirm) {
3353
+ event.preventDefault();
3354
+ confirm.focus();
3355
+ }
3356
+ }
3357
+ },
3358
+ [phase.name, handleCancelConfirm]
3359
+ );
3360
+ (0, import_react4.useEffect)(() => {
3361
+ if (phase.name === "confirming") {
3362
+ confirmButtonRef.current?.focus();
3363
+ } else if (phase.name === "review" && restoreFocusRef.current) {
3364
+ restoreFocusRef.current = false;
3365
+ submitButtonRef.current?.focus();
3366
+ } else if (phase.name === "submit-error") {
3367
+ retrySubmitButtonRef.current?.focus();
3368
+ } else if (phase.name === "done") {
3369
+ doneStateRef.current?.focus();
3370
+ }
3371
+ }, [phase.name]);
3372
+ const rootClassName = [
3373
+ "gemina-verification",
3374
+ `gemina-verification--${theme}`,
3375
+ effectiveDir === "rtl" ? "gemina-verification--rtl" : "",
3376
+ stacked ? "gemina-verification--stacked" : "",
3377
+ className ?? ""
3378
+ ].filter((part) => part.length > 0).join(" ");
3379
+ const dialogTextId = (0, import_react4.useId)();
3380
+ const renderReview = (reviewPhase) => {
3381
+ const overlayUp = reviewPhase.name === "confirming" || reviewPhase.name === "submitting";
3382
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(import_jsx_runtime4.Fragment, { children: [
3383
+ alreadyValidated && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "gemina-verification__banner", children: ALREADY_VALIDATED_TEXT }),
3384
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "gemina-verification__panes", children: [
3385
+ imageUrl !== null && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3386
+ VerificationViewer,
3387
+ {
3388
+ src: imageUrl,
3389
+ relativeRects: overlayRects,
3390
+ flashRects,
3391
+ onFlashComplete: handleFlashComplete,
3392
+ onImageExpired: handleImageExpired
3393
+ }
3394
+ ),
3395
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3396
+ VerificationForm,
3397
+ {
3398
+ classified,
3399
+ unmatched,
3400
+ bindingIndex,
3401
+ edits,
3402
+ onEdit: handleEdit,
3403
+ readOnly: alreadyValidated,
3404
+ onFlash: handleFlash
3405
+ }
3406
+ )
3407
+ ] }),
3408
+ reviewPhase.name === "submit-error" && /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
3409
+ "div",
3410
+ {
3411
+ className: "gemina-verification__banner gemina-verification__banner--error gemina-verification__submit-error",
3412
+ role: "alert",
3413
+ children: [
3414
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { children: reviewPhase.message }),
3415
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3416
+ "button",
3417
+ {
3418
+ type: "button",
3419
+ ref: retrySubmitButtonRef,
3420
+ className: "gemina-verification__retry",
3421
+ onClick: handleRetrySubmit,
3422
+ children: "Retry"
3423
+ }
3424
+ )
3425
+ ]
3426
+ }
3427
+ ),
3428
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "gemina-verification__footer", children: [
3429
+ !alreadyValidated && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "gemina-verification__progress", "aria-live": "polite", children: `${submission.confirmed} confirmed \xB7 ${submission.corrected} corrected` }),
3430
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3431
+ "button",
3432
+ {
3433
+ type: "button",
3434
+ ref: submitButtonRef,
3435
+ className: "gemina-verification__submit",
3436
+ disabled: alreadyValidated || reviewPhase.name !== "review",
3437
+ onClick: handleSubmitClick,
3438
+ children: "Submit feedback"
3439
+ }
3440
+ )
3441
+ ] }),
3442
+ overlayUp && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3443
+ "div",
3444
+ {
3445
+ className: "gemina-verification__confirm",
3446
+ onKeyDown: handleConfirmKeyDown,
3447
+ onMouseDown: (event) => {
3448
+ if (!event.target.closest("button")) {
3449
+ event.preventDefault();
3450
+ }
3451
+ },
3452
+ children: /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
3453
+ "div",
3454
+ {
3455
+ className: "gemina-verification__confirm-dialog",
3456
+ role: "dialog",
3457
+ "aria-modal": "true",
3458
+ "aria-labelledby": dialogTextId,
3459
+ children: [
3460
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("p", { id: dialogTextId, className: "gemina-verification__confirm-text", children: reviewPhase.name === "submitting" ? SUBMITTING_TEXT : CONFIRM_TEXT }),
3461
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { className: "gemina-verification__confirm-actions", children: [
3462
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3463
+ "button",
3464
+ {
3465
+ type: "button",
3466
+ ref: cancelButtonRef,
3467
+ className: "gemina-verification__confirm-cancel",
3468
+ onClick: handleCancelConfirm,
3469
+ disabled: reviewPhase.name === "submitting",
3470
+ children: "Cancel"
3471
+ }
3472
+ ),
3473
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3474
+ "button",
3475
+ {
3476
+ type: "button",
3477
+ ref: confirmButtonRef,
3478
+ className: "gemina-verification__submit",
3479
+ onClick: handleConfirm,
3480
+ disabled: reviewPhase.name === "submitting",
3481
+ children: "Confirm submission"
3482
+ }
3483
+ )
3484
+ ] })
3485
+ ]
3486
+ }
3487
+ )
3488
+ }
3489
+ )
3490
+ ] });
3491
+ };
3492
+ const content = (() => {
3493
+ switch (phase.name) {
3494
+ case "loading":
3495
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "gemina-verification__state", role: "status", children: LOADING_TEXT });
3496
+ case "unavailable":
3497
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
3498
+ "div",
3499
+ {
3500
+ className: "gemina-verification__state",
3501
+ role: ALERT_REASONS.has(phase.reason) ? "alert" : "status",
3502
+ children: [
3503
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { children: phase.message }),
3504
+ phase.canRetry && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("button", { type: "button", className: "gemina-verification__retry", onClick: handleRetry, children: "Retry" })
3505
+ ]
3506
+ }
3507
+ );
3508
+ case "review":
3509
+ case "confirming":
3510
+ case "submitting":
3511
+ case "submit-error":
3512
+ return renderReview(phase);
3513
+ case "done":
3514
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(
3515
+ "div",
3516
+ {
3517
+ ref: doneStateRef,
3518
+ tabIndex: -1,
3519
+ className: "gemina-verification__state gemina-verification__state--done",
3520
+ role: "status",
3521
+ children: [
3522
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("span", { className: "gemina-verification__done-check", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("svg", { width: "20", height: "20", viewBox: "0 0 20 20", fill: "none", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(
3523
+ "path",
3524
+ {
3525
+ d: "M4 10.5l4 4 8-9",
3526
+ stroke: "currentColor",
3527
+ strokeWidth: "2.4",
3528
+ strokeLinecap: "round",
3529
+ strokeLinejoin: "round"
3530
+ }
3531
+ ) }) }),
3532
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "gemina-verification__done-title", children: DONE_TITLE_TEXT }),
3533
+ /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { className: "gemina-verification__progress", children: `${phase.confirmed} confirmed \xB7 ${phase.corrected} corrected` })
3534
+ ]
3535
+ }
3536
+ );
3537
+ }
3538
+ })();
3539
+ return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { ref: rootRef, className: rootClassName, dir: effectiveDir, children: content });
3540
+ }
854
3541
  // Annotate the CommonJS export names for ESM import in node:
855
3542
  0 && (module.exports = {
856
3543
  GeminaChat,
857
3544
  GeminaTokenManager,
3545
+ GeminaVerification,
858
3546
  VERSION
859
3547
  });
860
3548
  //# sourceMappingURL=index.cjs.map