@form-engine-ts/react 4.4.0 → 4.6.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.js CHANGED
@@ -102,7 +102,7 @@ import {
102
102
  DEFAULT_FIELD_TYPE_DEFINITIONS,
103
103
  populateSchemaTranslations
104
104
  } from "@form-engine-ts/core";
105
- import { Children, createContext, isValidElement, useContext, useState } from "react";
105
+ import { Children, createContext, isValidElement, useContext, useState as useState2 } from "react";
106
106
 
107
107
  // src/hooks/useFormBuilder.ts
108
108
  import {
@@ -110,7 +110,7 @@ import {
110
110
  transformFieldType,
111
111
  validateFormSchema
112
112
  } from "@form-engine-ts/core";
113
- import { useCallback, useMemo } from "react";
113
+ import { useCallback, useMemo, useState } from "react";
114
114
  var DEFAULT_PREFIXES = { field: "q", option: "opt", page: "page" };
115
115
  var CHOICE_TYPES = ["select", "radio", "multi-select"];
116
116
  function defaultIdFactory(kind, existingIds) {
@@ -197,8 +197,20 @@ function move(items, sourceIndex, targetIndex) {
197
197
  result.splice(targetIndex, 0, item);
198
198
  return result;
199
199
  }
200
+ function displayRuleSourceIds(field) {
201
+ if (field.displayRule === void 0) return [];
202
+ const ids = [];
203
+ const visit = (group) => {
204
+ for (const condition of group.conditions) {
205
+ if ("logic" in condition) visit(condition);
206
+ else ids.push(condition.fieldId);
207
+ }
208
+ };
209
+ visit(field.displayRule.condition);
210
+ return ids;
211
+ }
200
212
  function withoutDisplayCondition(field) {
201
- const { displayCondition: _displayCondition, ...rest } = field;
213
+ const { displayCondition: _displayCondition, displayRule: _displayRule, ...rest } = field;
202
214
  return rest;
203
215
  }
204
216
  function removeLocalizedProperty(translations, locale, property) {
@@ -221,8 +233,23 @@ function useFormBuilder({
221
233
  onChange,
222
234
  policy,
223
235
  idFactory = defaultIdFactory,
224
- factories = {}
236
+ factories = {},
237
+ fieldEditorMode = "all",
238
+ activeFieldId: controlledActiveFieldId,
239
+ defaultActiveFieldId,
240
+ onActiveFieldChange
225
241
  }) {
242
+ const [internalActiveFieldId, setInternalActiveFieldId] = useState(
243
+ defaultActiveFieldId ?? (fieldEditorMode === "single" ? schema.fields[0]?.id : void 0)
244
+ );
245
+ const activeFieldId = controlledActiveFieldId ?? internalActiveFieldId;
246
+ const setActiveFieldId = useCallback(
247
+ (fieldId) => {
248
+ if (controlledActiveFieldId === void 0) setInternalActiveFieldId(fieldId);
249
+ onActiveFieldChange?.(fieldId);
250
+ },
251
+ [controlledActiveFieldId, onActiveFieldChange]
252
+ );
226
253
  const createId = useCallback(
227
254
  (kind, existingIds) => {
228
255
  const rawId = idFactory(kind, existingIds);
@@ -335,9 +362,10 @@ function useFormBuilder({
335
362
  questionIds: page.id === pageId || pageId === void 0 && index === (schema.pages?.length ?? 0) - 1 ? [...page.questionIds, field.id] : page.questionIds
336
363
  }));
337
364
  onChange({ ...schema, fields: [...schema.fields, field], ...pages === void 0 ? {} : { pages } });
365
+ setActiveFieldId(field.id);
338
366
  return { success: true };
339
367
  },
340
- [createId, factories, onChange, policy, schema]
368
+ [createId, factories, onChange, policy, schema, setActiveFieldId]
341
369
  );
342
370
  const removeField = useCallback(
343
371
  (fieldId) => {
@@ -345,15 +373,19 @@ function useFormBuilder({
345
373
  return { success: false, error: { type: "node_not_found", kind: "field", id: fieldId } };
346
374
  if (schema.fields.length <= 1)
347
375
  return { success: false, error: { type: "invalid_operation", message: "A form must contain one field." } };
348
- const fields = schema.fields.filter((field) => field.id !== fieldId).map((field) => field.displayCondition?.questionId === fieldId ? withoutDisplayCondition(field) : field);
376
+ const removedIndex = schema.fields.findIndex((field) => field.id === fieldId);
377
+ const fields = schema.fields.filter((field) => field.id !== fieldId).map(
378
+ (field) => field.displayCondition?.questionId === fieldId || displayRuleSourceIds(field).includes(fieldId) ? withoutDisplayCondition(field) : field
379
+ );
349
380
  const pages = schema.pages?.map((page) => ({ ...page, questionIds: page.questionIds.filter((id) => id !== fieldId) })).filter((page) => page.questionIds.length > 0);
350
381
  if (schema.pages !== void 0 && pages?.length === 0) {
351
382
  const { pages: _pages, ...single } = schema;
352
383
  onChange({ ...single, fields });
353
384
  } else onChange({ ...schema, fields, ...pages === void 0 ? {} : { pages } });
385
+ if (activeFieldId === fieldId) setActiveFieldId(fields[removedIndex]?.id ?? fields.at(-1)?.id);
354
386
  return { success: true };
355
387
  },
356
- [onChange, schema]
388
+ [activeFieldId, onChange, schema, setActiveFieldId]
357
389
  );
358
390
  const moveField = useCallback(
359
391
  (fieldId, targetIndex) => {
@@ -366,8 +398,8 @@ function useFormBuilder({
366
398
  onChange({
367
399
  ...schema,
368
400
  fields: fields.map((field, index) => {
369
- const source = field.displayCondition?.questionId;
370
- return source === void 0 || (indexById.get(source) ?? index) < index ? field : withoutDisplayCondition(field);
401
+ const sources = field.displayCondition?.questionId === void 0 ? displayRuleSourceIds(field) : [field.displayCondition.questionId];
402
+ return sources.every((source) => (indexById.get(source) ?? index) < index) ? field : withoutDisplayCondition(field);
371
403
  })
372
404
  });
373
405
  return { success: true };
@@ -791,6 +823,14 @@ function useFormBuilder({
791
823
  const result = validateFormSchema(schema, policy === void 0 ? {} : { policy });
792
824
  return result.valid ? [] : result.issues;
793
825
  }, [policy, schema]);
826
+ const getFieldEditorProps = useCallback(
827
+ (fieldId) => ({
828
+ isActive: activeFieldId === fieldId,
829
+ isVisible: fieldEditorMode === "all" || activeFieldId === fieldId,
830
+ onSelect: () => setActiveFieldId(fieldId)
831
+ }),
832
+ [activeFieldId, fieldEditorMode, setActiveFieldId]
833
+ );
794
834
  return {
795
835
  schema,
796
836
  addField,
@@ -812,7 +852,10 @@ function useFormBuilder({
812
852
  setLocaleTranslation,
813
853
  addLocale,
814
854
  setDefaultLocale,
815
- validationIssues
855
+ validationIssues,
856
+ ...activeFieldId === void 0 ? {} : { activeFieldId },
857
+ setActiveFieldId,
858
+ getFieldEditorProps
816
859
  };
817
860
  }
818
861
 
@@ -1465,7 +1508,10 @@ var BUILDER_DEFAULTS = {
1465
1508
  "builder.operator.equals": "equals",
1466
1509
  "builder.operator.not_equals": "does not equal",
1467
1510
  "builder.operator.contains": "contains",
1468
- "builder.operator.not_empty": "is not empty"
1511
+ "builder.operator.not_empty": "is not empty",
1512
+ "builder.submissionSettings": "Submission settings",
1513
+ "builder.showConfirmationBeforeSubmit": "Show confirmation before submit",
1514
+ "builder.confirmationRenderMode": "Confirmation display mode"
1469
1515
  };
1470
1516
  function BuilderSectionGroup({ children }) {
1471
1517
  return children;
@@ -1642,7 +1688,12 @@ function FormBuilder({
1642
1688
  slots,
1643
1689
  sectionOrder,
1644
1690
  disableDefaultStyles = false,
1645
- unstyled = false
1691
+ unstyled = false,
1692
+ fieldEditorMode = "all",
1693
+ activeFieldId,
1694
+ defaultActiveFieldId,
1695
+ onActiveFieldChange,
1696
+ submissionSettingsOptions
1646
1697
  }) {
1647
1698
  const resolvedComponents = { ...DEFAULT_COMPONENTS, ...componentOverrides };
1648
1699
  const components = {
@@ -1665,14 +1716,18 @@ function FormBuilder({
1665
1716
  onChange,
1666
1717
  ...policy === void 0 ? {} : { policy },
1667
1718
  ...idFactory === void 0 ? {} : { idFactory },
1668
- ...factories === void 0 ? {} : { factories }
1719
+ ...factories === void 0 ? {} : { factories },
1720
+ fieldEditorMode,
1721
+ ...activeFieldId === void 0 ? {} : { activeFieldId },
1722
+ ...defaultActiveFieldId === void 0 ? {} : { defaultActiveFieldId },
1723
+ ...onActiveFieldChange === void 0 ? {} : { onActiveFieldChange }
1669
1724
  });
1670
- const [newPageQuestionId, setNewPageQuestionId] = useState("");
1671
- const [newLocale, setNewLocale] = useState("");
1672
- const [editingLocale, setEditingLocale] = useState("");
1673
- const [isTranslating, setIsTranslating] = useState(false);
1674
- const [translationError, setTranslationError] = useState(null);
1675
- const [translationReport, setTranslationReport] = useState();
1725
+ const [newPageQuestionId, setNewPageQuestionId] = useState2("");
1726
+ const [newLocale, setNewLocale] = useState2("");
1727
+ const [editingLocale, setEditingLocale] = useState2("");
1728
+ const [isTranslating, setIsTranslating] = useState2(false);
1729
+ const [translationError, setTranslationError] = useState2(null);
1730
+ const [translationReport, setTranslationReport] = useState2();
1676
1731
  const translate = (key, params = {}) => resolveTranslation(
1677
1732
  key,
1678
1733
  BUILDER_TRANSLATION_ALIASES[key] === void 0 ? [] : [BUILDER_TRANSLATION_ALIASES[key]],
@@ -2005,6 +2060,47 @@ function FormBuilder({
2005
2060
  ] })
2006
2061
  }
2007
2062
  ) }),
2063
+ /* @__PURE__ */ jsx(BuilderSectionGroup, { name: "submissionSettings", children: submissionSettingsOptions?.enabled ? /* @__PURE__ */ jsxs(
2064
+ Section,
2065
+ {
2066
+ className: builderClass("form-engine-builder__submission-settings"),
2067
+ title: translate("builder.submissionSettings"),
2068
+ children: [
2069
+ /* @__PURE__ */ jsx(
2070
+ Checkbox,
2071
+ {
2072
+ id: "builder-show-confirmation",
2073
+ label: translate("builder.showConfirmationBeforeSubmit"),
2074
+ checked: schema.submissionSettings?.showConfirmationBeforeSubmit === true,
2075
+ onChange: (checked) => onChange({
2076
+ ...schema,
2077
+ submissionSettings: { ...schema.submissionSettings, showConfirmationBeforeSubmit: checked }
2078
+ })
2079
+ }
2080
+ ),
2081
+ /* @__PURE__ */ jsx(
2082
+ Select,
2083
+ {
2084
+ id: "builder-confirmation-render-mode",
2085
+ label: translate("builder.confirmationRenderMode"),
2086
+ value: schema.submissionSettings?.confirmationRenderMode ?? "inline",
2087
+ options: [
2088
+ { value: "dialog", label: "Dialog" },
2089
+ { value: "inline", label: "Inline" },
2090
+ { value: "replace", label: "Replace" }
2091
+ ],
2092
+ onChange: (value) => {
2093
+ if (value !== "dialog" && value !== "inline" && value !== "replace") return;
2094
+ onChange({
2095
+ ...schema,
2096
+ submissionSettings: { ...schema.submissionSettings, confirmationRenderMode: value }
2097
+ });
2098
+ }
2099
+ }
2100
+ )
2101
+ ]
2102
+ }
2103
+ ) : null }),
2008
2104
  resolvedSectionOrder === void 0 ? null : /* @__PURE__ */ jsx(BuilderSectionGroup, { name: "completionMessage", children: /* @__PURE__ */ jsx(Section, { headingId: "builder-completion-message-heading", title: translate("builder.completionMessage"), children: /* @__PURE__ */ jsx(
2009
2105
  TextInput,
2010
2106
  {
@@ -2403,9 +2499,25 @@ function FormBuilder({
2403
2499
  ) : null }),
2404
2500
  /* @__PURE__ */ jsx(BuilderSectionGroup, { name: "questions", children: /* @__PURE__ */ jsx("div", { className: builderClass("form-engine-builder__list"), children: schema.fields.map((field, index) => {
2405
2501
  const controls = resolveFieldEditorControls(fieldEditorControls);
2502
+ const editorState = headless.getFieldEditorProps?.(field.id) ?? {
2503
+ isActive: true,
2504
+ isVisible: true,
2505
+ onSelect: () => void 0
2506
+ };
2406
2507
  const condition = field.displayCondition;
2407
2508
  const source = condition === void 0 ? void 0 : schema.fields.find((item) => item.id === condition.questionId);
2408
2509
  const availableSources = schema.fields.slice(0, index);
2510
+ if (!editorState.isVisible) {
2511
+ return /* @__PURE__ */ jsx(
2512
+ "div",
2513
+ {
2514
+ className: builderClass("form-engine-builder__question-preview"),
2515
+ "data-field-id": field.id,
2516
+ children: /* @__PURE__ */ jsx("button", { type: "button", onClick: editorState.onSelect, children: field.title })
2517
+ },
2518
+ field.id
2519
+ );
2520
+ }
2409
2521
  if (FieldEditorSlot !== void 0) {
2410
2522
  return /* @__PURE__ */ jsx(
2411
2523
  FieldEditorSlot,
@@ -2901,7 +3013,7 @@ import {
2901
3013
  validateAnswers,
2902
3014
  validatePageAnswers
2903
3015
  } from "@form-engine-ts/core";
2904
- import { createContext as createContext2, useCallback as useCallback2, useContext as useContext2, useEffect, useMemo as useMemo2, useRef, useState as useState2 } from "react";
3016
+ import { createContext as createContext2, useCallback as useCallback2, useContext as useContext2, useEffect, useMemo as useMemo2, useRef, useState as useState3 } from "react";
2905
3017
 
2906
3018
  // src/types.ts
2907
3019
  var FormSubmissionError = class extends Error {
@@ -2948,11 +3060,11 @@ function FormProvider({
2948
3060
  assertValidFormSchema(localized);
2949
3061
  return localized;
2950
3062
  }, [locale, schema]);
2951
- const [values, setValues] = useState2(() => ({ ...initialValues }));
2952
- const [errors, setErrors] = useState2({});
2953
- const [submitStatus, setSubmitStatus] = useState2("idle");
2954
- const [submitError, setSubmitError] = useState2(null);
2955
- const [validationPageIndex, setValidationPageIndex] = useState2(null);
3063
+ const [values, setValues] = useState3(() => ({ ...initialValues }));
3064
+ const [errors, setErrors] = useState3({});
3065
+ const [submitStatus, setSubmitStatus] = useState3("idle");
3066
+ const [submitError, setSubmitError] = useState3(null);
3067
+ const [validationPageIndex, setValidationPageIndex] = useState3(null);
2956
3068
  const submissionInFlight = useRef(false);
2957
3069
  const visibility = useMemo2(() => calculateFieldVisibility(validSchema, values), [validSchema, values]);
2958
3070
  const pageVisibility = useMemo2(() => calculatePageVisibility(validSchema, values), [validSchema, values]);
@@ -3121,8 +3233,300 @@ function useField(fieldId) {
3121
3233
  return { field, value: form.values[fieldId], error: form.errors[fieldId], setValue };
3122
3234
  }
3123
3235
 
3236
+ // src/hooks/useTranslationWorkspace.ts
3237
+ import {
3238
+ collectSchemaLocales as collectSchemaLocales2,
3239
+ collectTranslationSlots,
3240
+ computeSourceTextHash,
3241
+ populateSchemaTranslations as populateSchemaTranslations2,
3242
+ removeLocaleFromSchema
3243
+ } from "@form-engine-ts/core";
3244
+ import { useCallback as useCallback3, useMemo as useMemo3, useState as useState4 } from "react";
3245
+ function updateTranslationMap(translations, locale, property, text) {
3246
+ if (property === "label") return translations ?? {};
3247
+ const current = translations?.[locale];
3248
+ const next = { ...current, [property]: text };
3249
+ return { ...translations, [locale]: next };
3250
+ }
3251
+ function asAsyncAdapter(adapter) {
3252
+ if ("translateBatch" in adapter) return adapter;
3253
+ return {
3254
+ translateText: async (text, locale, sourceLocale) => adapter.translate(text, locale, sourceLocale === void 0 ? void 0 : { sourceLocale }) ?? text,
3255
+ translateBatch: async (texts, locale, sourceLocale) => texts.map(
3256
+ (text) => adapter.translate(text, locale, sourceLocale === void 0 ? void 0 : { sourceLocale }) ?? text
3257
+ )
3258
+ };
3259
+ }
3260
+ function validateLocaleByPolicy(locale, currentLocales, policy) {
3261
+ if (locale.length === 0) {
3262
+ return {
3263
+ valid: false,
3264
+ error: { type: "invalid_locale_format", message: "Locale must not be empty." }
3265
+ };
3266
+ }
3267
+ try {
3268
+ Intl.getCanonicalLocales(locale);
3269
+ } catch {
3270
+ return {
3271
+ valid: false,
3272
+ error: { type: "invalid_locale_format", message: `Locale "${locale}" is not a valid BCP 47 locale.` }
3273
+ };
3274
+ }
3275
+ if (policy?.allowedLocales !== void 0 && !policy.allowedLocales.includes(locale)) {
3276
+ return {
3277
+ valid: false,
3278
+ error: { type: "locale_not_allowed", message: `Locale "${locale}" is not allowed by the form policy.` }
3279
+ };
3280
+ }
3281
+ if (policy?.maxLocales !== void 0 && !currentLocales.includes(locale) && currentLocales.length >= policy.maxLocales) {
3282
+ return {
3283
+ valid: false,
3284
+ error: {
3285
+ type: "max_locales_exceeded",
3286
+ message: `At most ${policy.maxLocales} locales are allowed by the form policy.`
3287
+ }
3288
+ };
3289
+ }
3290
+ return { valid: true };
3291
+ }
3292
+ function manualMetadata(sourceText, sourceLocale) {
3293
+ return {
3294
+ sourceLocale,
3295
+ sourceTextHash: computeSourceTextHash(sourceText),
3296
+ translationSource: "manual",
3297
+ editedAt: (/* @__PURE__ */ new Date()).toISOString()
3298
+ };
3299
+ }
3300
+ function setNodeMetadata(node, slot, text, sourceLocale) {
3301
+ const localeMetadata = node.translationMetadata?.[slot.locale];
3302
+ const nextMetadata = text.trim().length === 0 ? Object.fromEntries(Object.entries(localeMetadata ?? {}).filter(([key]) => key !== slot.property)) : { ...localeMetadata, [slot.property]: manualMetadata(slot.sourceText, sourceLocale) };
3303
+ return { ...node, translationMetadata: { ...node.translationMetadata, [slot.locale]: nextMetadata } };
3304
+ }
3305
+ function updateSchemaTranslation(schema, slot, text, sourceLocale) {
3306
+ if (slot.kind === "form") {
3307
+ return setNodeMetadata(
3308
+ { ...schema, translations: updateTranslationMap(schema.translations, slot.locale, slot.property, text) },
3309
+ slot,
3310
+ text,
3311
+ sourceLocale
3312
+ );
3313
+ }
3314
+ if (slot.kind === "field") {
3315
+ return {
3316
+ ...schema,
3317
+ fields: schema.fields.map((field) => {
3318
+ if (field.id !== slot.nodeId) return field;
3319
+ const translations = updateTranslationMap(field.translations, slot.locale, slot.property, text);
3320
+ return setNodeMetadata({ ...field, translations }, slot, text, sourceLocale);
3321
+ })
3322
+ };
3323
+ }
3324
+ if (slot.kind === "option") {
3325
+ return {
3326
+ ...schema,
3327
+ fields: schema.fields.map((field) => {
3328
+ if (!("options" in field)) return field;
3329
+ return {
3330
+ ...field,
3331
+ options: field.options.map((option) => {
3332
+ if (option.id !== slot.nodeId) return option;
3333
+ const translations = text.trim().length === 0 ? Object.fromEntries(
3334
+ Object.entries(option.translations ?? {}).filter(([locale]) => locale !== slot.locale)
3335
+ ) : { ...option.translations, [slot.locale]: text };
3336
+ return setNodeMetadata({ ...option, translations }, slot, text, sourceLocale);
3337
+ })
3338
+ };
3339
+ })
3340
+ };
3341
+ }
3342
+ return {
3343
+ ...schema,
3344
+ ...schema.pages === void 0 ? {} : {
3345
+ pages: schema.pages.map((page) => {
3346
+ if (page.id !== slot.nodeId) return page;
3347
+ const translations = updateTranslationMap(page.translations, slot.locale, slot.property, text);
3348
+ return setNodeMetadata({ ...page, translations }, slot, text, sourceLocale);
3349
+ })
3350
+ }
3351
+ };
3352
+ }
3353
+ function useTranslationWorkspace({
3354
+ schema,
3355
+ onChange,
3356
+ sourceLocale = schema.defaultLocale ?? "en",
3357
+ targetLocale,
3358
+ translationAdapter,
3359
+ readOnly = false,
3360
+ policy,
3361
+ validateLocale
3362
+ }) {
3363
+ const [draftSchema, setDraftSchema] = useState4(schema);
3364
+ const [selectedLocale, setSelectedLocale] = useState4(targetLocale ?? "");
3365
+ const [isTranslating, setIsTranslating] = useState4(false);
3366
+ const [error, setError] = useState4();
3367
+ const currentSchema = onChange === void 0 ? draftSchema : schema;
3368
+ const targetLocales = useMemo3(() => {
3369
+ const locales = collectSchemaLocales2(currentSchema).allUniqueLocales;
3370
+ return [.../* @__PURE__ */ new Set([...currentSchema.supportedLocales ?? [], ...locales])].filter(
3371
+ (locale) => locale !== sourceLocale
3372
+ );
3373
+ }, [currentSchema, sourceLocale]);
3374
+ const activeLocale = selectedLocale.length > 0 ? selectedLocale : targetLocales[0] ?? "";
3375
+ const slots = useMemo3(
3376
+ () => activeLocale.length === 0 ? [] : collectTranslationSlots(currentSchema, activeLocale),
3377
+ [activeLocale, currentSchema]
3378
+ );
3379
+ const summary = useMemo3(() => {
3380
+ const counts = {
3381
+ missing: 0,
3382
+ translated: 0,
3383
+ stale: 0,
3384
+ manual: 0,
3385
+ "manual-stale": 0
3386
+ };
3387
+ for (const slot of slots) counts[slot.status ?? "missing"] += 1;
3388
+ const complete = counts.translated + counts.manual;
3389
+ return {
3390
+ totalSlots: slots.length,
3391
+ translatedCount: complete,
3392
+ missingCount: counts.missing,
3393
+ staleCount: counts.stale + counts["manual-stale"],
3394
+ manualCount: counts.manual + counts["manual-stale"],
3395
+ completionPercentage: slots.length === 0 ? 100 : Math.round(complete / slots.length * 100)
3396
+ };
3397
+ }, [slots]);
3398
+ const commit = useCallback3(
3399
+ (next) => {
3400
+ setDraftSchema(next);
3401
+ onChange?.(next);
3402
+ },
3403
+ [onChange]
3404
+ );
3405
+ const setTranslation = useCallback3(
3406
+ (slot, text) => {
3407
+ if (readOnly) return;
3408
+ commit(updateSchemaTranslation(currentSchema, slot, text, sourceLocale));
3409
+ },
3410
+ [commit, currentSchema, readOnly, sourceLocale]
3411
+ );
3412
+ const addLocale = useCallback3(
3413
+ (locale) => {
3414
+ if (readOnly) return { success: false, error: "Workspace is read-only." };
3415
+ const normalized = locale.trim();
3416
+ const currentLocales = [
3417
+ .../* @__PURE__ */ new Set([
3418
+ ...currentSchema.defaultLocale === void 0 ? [] : [currentSchema.defaultLocale],
3419
+ sourceLocale,
3420
+ ...collectSchemaLocales2(currentSchema).allUniqueLocales
3421
+ ])
3422
+ ];
3423
+ const validation = validateLocale?.(normalized, currentLocales) ?? validateLocaleByPolicy(normalized, currentLocales, policy);
3424
+ if (!validation.valid) return { success: false, error: validation.error?.message ?? "Locale is not valid." };
3425
+ const alreadyRegistered = normalized === sourceLocale || normalized === currentSchema.defaultLocale || (currentSchema.supportedLocales ?? []).includes(normalized);
3426
+ if (alreadyRegistered) {
3427
+ setSelectedLocale(normalized);
3428
+ return { success: true };
3429
+ }
3430
+ commit({
3431
+ ...currentSchema,
3432
+ supportedLocales: [.../* @__PURE__ */ new Set([...currentSchema.supportedLocales ?? [], normalized])]
3433
+ });
3434
+ setSelectedLocale(normalized);
3435
+ return { success: true };
3436
+ },
3437
+ [commit, currentSchema, policy, readOnly, sourceLocale, validateLocale]
3438
+ );
3439
+ const isAddLocaleAllowed = useCallback3(
3440
+ (locale) => {
3441
+ if (readOnly) return false;
3442
+ const normalized = locale.trim();
3443
+ const currentLocales = [
3444
+ .../* @__PURE__ */ new Set([
3445
+ ...currentSchema.defaultLocale === void 0 ? [] : [currentSchema.defaultLocale],
3446
+ sourceLocale,
3447
+ ...collectSchemaLocales2(currentSchema).allUniqueLocales
3448
+ ])
3449
+ ];
3450
+ return (validateLocale?.(normalized, currentLocales) ?? validateLocaleByPolicy(normalized, currentLocales, policy)).valid;
3451
+ },
3452
+ [currentSchema, policy, readOnly, sourceLocale, validateLocale]
3453
+ );
3454
+ const removeLocale = useCallback3(
3455
+ (locale) => {
3456
+ if (readOnly || locale === sourceLocale || locale === currentSchema.defaultLocale) return;
3457
+ commit(removeLocaleFromSchema(currentSchema, locale));
3458
+ if (activeLocale === locale) setSelectedLocale("");
3459
+ },
3460
+ [activeLocale, commit, currentSchema, readOnly, sourceLocale]
3461
+ );
3462
+ const translateAll = useCallback3(
3463
+ async (options = {}) => {
3464
+ if (translationAdapter === void 0) throw new Error("A translation adapter is required.");
3465
+ if (activeLocale.length === 0) throw new Error("A target locale is required.");
3466
+ setIsTranslating(true);
3467
+ setError(void 0);
3468
+ try {
3469
+ const populated = await populateSchemaTranslations2(
3470
+ currentSchema,
3471
+ [activeLocale],
3472
+ asAsyncAdapter(translationAdapter),
3473
+ {
3474
+ overwrite: "stale-and-missing",
3475
+ preserveManualTranslations: true,
3476
+ ...options
3477
+ }
3478
+ );
3479
+ commit(populated.schema);
3480
+ return populated.report;
3481
+ } catch (cause) {
3482
+ const message = cause instanceof Error ? cause.message : String(cause);
3483
+ setError(message);
3484
+ throw cause;
3485
+ } finally {
3486
+ setIsTranslating(false);
3487
+ }
3488
+ },
3489
+ [activeLocale, commit, currentSchema, translationAdapter]
3490
+ );
3491
+ const translateSlot = useCallback3(
3492
+ async (slot) => {
3493
+ if (translationAdapter === void 0) throw new Error("A translation adapter is required.");
3494
+ if (readOnly) return;
3495
+ setIsTranslating(true);
3496
+ setError(void 0);
3497
+ try {
3498
+ const text = await asAsyncAdapter(translationAdapter).translateText(slot.sourceText, slot.locale, sourceLocale);
3499
+ commit(updateSchemaTranslation(currentSchema, slot, text, sourceLocale));
3500
+ } catch (cause) {
3501
+ const message = cause instanceof Error ? cause.message : String(cause);
3502
+ setError(message);
3503
+ throw cause;
3504
+ } finally {
3505
+ setIsTranslating(false);
3506
+ }
3507
+ },
3508
+ [commit, currentSchema, readOnly, sourceLocale, translationAdapter]
3509
+ );
3510
+ return {
3511
+ sourceLocale,
3512
+ targetLocale: activeLocale,
3513
+ targetLocales,
3514
+ setTargetLocale: setSelectedLocale,
3515
+ slots,
3516
+ summary,
3517
+ addLocale,
3518
+ isAddLocaleAllowed,
3519
+ removeLocale,
3520
+ setTranslation,
3521
+ translateAll,
3522
+ translateSlot,
3523
+ isTranslating,
3524
+ ...error === void 0 ? {} : { error }
3525
+ };
3526
+ }
3527
+
3124
3528
  // src/receipt.ts
3125
- import { useEffect as useEffect2, useMemo as useMemo3, useState as useState3 } from "react";
3529
+ import { useEffect as useEffect2, useMemo as useMemo4, useState as useState5 } from "react";
3126
3530
  function submissionReceiptQueryKey(formId, formVersion) {
3127
3531
  return `${formId}:v${formVersion}`;
3128
3532
  }
@@ -3193,14 +3597,14 @@ function createLocalStorageSubmissionReceiptStore(options = {}) {
3193
3597
  }
3194
3598
  function useSubmissionReceipts(store, queries) {
3195
3599
  const querySignature = JSON.stringify(queries.map(({ formId, formVersion }) => [formId, formVersion]));
3196
- const stableQueries = useMemo3(() => {
3600
+ const stableQueries = useMemo4(() => {
3197
3601
  const parsed = JSON.parse(querySignature);
3198
3602
  if (!Array.isArray(parsed)) return [];
3199
3603
  return parsed.flatMap(
3200
3604
  (entry) => Array.isArray(entry) && typeof entry[0] === "string" && typeof entry[1] === "number" && Number.isSafeInteger(entry[1]) ? [{ formId: entry[0], formVersion: entry[1] }] : []
3201
3605
  );
3202
3606
  }, [querySignature]);
3203
- const [state, setState] = useState3({
3607
+ const [state, setState] = useState5({
3204
3608
  receipts: /* @__PURE__ */ new Map(),
3205
3609
  isLoading: stableQueries.length > 0,
3206
3610
  error: null
@@ -3245,12 +3649,12 @@ import {
3245
3649
  } from "@form-engine-ts/core";
3246
3650
  import {
3247
3651
  Fragment as Fragment2,
3248
- useCallback as useCallback3,
3652
+ useCallback as useCallback4,
3249
3653
  useEffect as useEffect3,
3250
3654
  useId,
3251
- useMemo as useMemo4,
3655
+ useMemo as useMemo5,
3252
3656
  useRef as useRef2,
3253
- useState as useState4
3657
+ useState as useState6
3254
3658
  } from "react";
3255
3659
  import { Fragment as Fragment3, jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
3256
3660
  var isChoiceFieldType = (type) => type === "radio" || type === "checkbox" || type === "multi-select" || type === "select";
@@ -3765,38 +4169,38 @@ function ContextFormRenderer({
3765
4169
  const prefix = useId().replace(/:/g, "");
3766
4170
  const formRef = useRef2(null);
3767
4171
  const loadedDraftKey = useRef2(null);
3768
- const [draftRestored, setDraftRestored] = useState4(false);
3769
- const [currentPageIndex, setCurrentPageIndex] = useState4(0);
3770
- const [focusFieldId, setFocusFieldId] = useState4(null);
3771
- const [confirmation, setConfirmation] = useState4(null);
3772
- const [guardMessage, setGuardMessage] = useState4(null);
3773
- const [guardsPending, setGuardsPending] = useState4(false);
3774
- const [receipt, setReceipt] = useState4(null);
3775
- const [completionData, setCompletionData] = useState4(null);
3776
- const [receiptLoaded, setReceiptLoaded] = useState4(receiptStore === void 0);
4172
+ const [draftRestored, setDraftRestored] = useState6(false);
4173
+ const [currentPageIndex, setCurrentPageIndex] = useState6(0);
4174
+ const [focusFieldId, setFocusFieldId] = useState6(null);
4175
+ const [confirmation, setConfirmation] = useState6(null);
4176
+ const [guardMessage, setGuardMessage] = useState6(null);
4177
+ const [guardsPending, setGuardsPending] = useState6(false);
4178
+ const [receipt, setReceipt] = useState6(null);
4179
+ const [completionData, setCompletionData] = useState6(null);
4180
+ const [receiptLoaded, setReceiptLoaded] = useState6(receiptStore === void 0);
3777
4181
  const rendererSubmissionInFlight = useRef2(false);
3778
4182
  const fallbackAttemptId = useRef2(null);
3779
4183
  const completionRef = useRef2(null);
3780
4184
  const confirmationRef = useRef2(null);
3781
4185
  const pages = form.schema.pages;
3782
- const visiblePageIndexes = useMemo4(
4186
+ const visiblePageIndexes = useMemo5(
3783
4187
  () => pages === void 0 ? [] : pages.flatMap((page, index) => form.pageVisibility[page.id] === true ? [index] : []),
3784
4188
  [form.pageVisibility, pages]
3785
4189
  );
3786
4190
  const activePage = pages?.[currentPageIndex];
3787
4191
  const activeVisibleIndex = visiblePageIndexes.indexOf(currentPageIndex);
3788
4192
  const fieldIds = activePage === void 0 ? void 0 : new Set(activePage.questionIds);
3789
- const visibleValues = useMemo4(() => selectVisibleAnswers2(form.schema, form.values), [form.schema, form.values]);
3790
- const visibleItems = useMemo4(
4193
+ const visibleValues = useMemo5(() => selectVisibleAnswers2(form.schema, form.values), [form.schema, form.values]);
4194
+ const visibleItems = useMemo5(
3791
4195
  () => buildSubmittedItems(form.schema, form.values, form.visibility, (key) => form.translate(key), false),
3792
4196
  [form.schema, form.translate, form.values, form.visibility]
3793
4197
  );
3794
- const confirmationRenderMode = submissionConfirmation?.renderMode ?? submissionConfirmationRenderMode ?? "inline";
3795
- const confirmationEnabled = submissionConfirmation?.enabled === true;
4198
+ const confirmationRenderMode = submissionConfirmation?.renderMode ?? submissionConfirmationRenderMode ?? form.schema.submissionSettings?.confirmationRenderMode ?? "inline";
4199
+ const confirmationEnabled = submissionConfirmation?.enabled ?? form.schema.submissionSettings?.showConfirmationBeforeSubmit ?? false;
3796
4200
  const submitState = confirmation === null && !guardsPending ? form.submitStatus : "confirming";
3797
4201
  const interactionLocked = submitState === "confirming" || submitState === "submitting";
3798
4202
  const isReplaceMode = successRenderMode === "replace" || hideFormOnSuccess;
3799
- const resolveMessage = useCallback3(
4203
+ const resolveMessage = useCallback4(
3800
4204
  (key, fallback) => {
3801
4205
  const defaultText = fallback ?? DEFAULT_RENDERER_MESSAGES[form.locale.toLowerCase().startsWith("ja") ? "ja" : "en"][key] ?? key;
3802
4206
  const configured = messages[key];
@@ -3804,11 +4208,11 @@ function ContextFormRenderer({
3804
4208
  },
3805
4209
  [form.locale, messageResolver, messages]
3806
4210
  );
3807
- const fieldTranslate = useCallback3(
4211
+ const fieldTranslate = useCallback4(
3808
4212
  (key, params) => key === "validation.required" && (messages.requiredField !== void 0 || messageResolver !== void 0) ? resolveMessage("requiredField") : form.translate(key, params),
3809
4213
  [form.translate, messageResolver, messages.requiredField, resolveMessage]
3810
4214
  );
3811
- const focusSubmitButton = useCallback3(() => {
4215
+ const focusSubmitButton = useCallback4(() => {
3812
4216
  const button = formRef.current?.querySelector(".fe-submit, button[type='submit'], button");
3813
4217
  button?.focus();
3814
4218
  }, []);
@@ -4427,5 +4831,6 @@ export {
4427
4831
  useField,
4428
4832
  useForm,
4429
4833
  useFormBuilder,
4430
- useSubmissionReceipts
4834
+ useSubmissionReceipts,
4835
+ useTranslationWorkspace
4431
4836
  };