@vulcantech/forms 0.2.0 → 0.3.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.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  import * as Yup from 'yup';
2
- import { useFormikContext, Formik, Form, useField } from 'formik';
3
- import { createContext, useEffect, useState, useRef, useMemo, useCallback, useContext } from 'react';
2
+ import { useField, useFormikContext, Formik, Form } from 'formik';
3
+ import { createContext, useContext, useRef, useState, useEffect, useCallback, useMemo } from 'react';
4
4
  import { twMerge } from 'tailwind-merge';
5
5
  import { Checkbox, RadioGroup, Select } from 'radix-ui';
6
6
  import { BsCheck, BsChevronDown } from 'react-icons/bs';
7
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
7
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
8
8
  import DatePicker from 'react-datepicker';
9
9
  import { set, parse, isValid, isWeekend, isSameDay, addDays, format } from 'date-fns';
10
10
  import 'react-datepicker/dist/react-datepicker.css';
@@ -587,6 +587,48 @@ function renderNotificationEmail(template, variables) {
587
587
  };
588
588
  }
589
589
 
590
+ // src/utils/resizeImage.ts
591
+ var RESIZABLE_TYPES = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp"]);
592
+ var ENCODE_QUALITY = 0.85;
593
+ var MAX_DECODE_BYTES = 50 * 1024 * 1024;
594
+ function canResize() {
595
+ return typeof createImageBitmap === "function" && typeof document !== "undefined" && typeof document.createElement === "function";
596
+ }
597
+ function canvasToBlob(canvas, type, quality) {
598
+ return new Promise((resolve) => canvas.toBlob(resolve, type, quality));
599
+ }
600
+ function resizeImageFile(file, maxWidth) {
601
+ return __async(this, null, function* () {
602
+ if (!Number.isFinite(maxWidth) || maxWidth <= 0) return file;
603
+ if (!RESIZABLE_TYPES.has(file.type)) return file;
604
+ if (file.size > MAX_DECODE_BYTES) return file;
605
+ if (!canResize()) return file;
606
+ let bitmap;
607
+ try {
608
+ bitmap = yield createImageBitmap(file, { imageOrientation: "from-image" });
609
+ if (bitmap.width <= maxWidth) return file;
610
+ const width = Math.round(maxWidth);
611
+ const height = Math.max(1, Math.round(bitmap.height * width / bitmap.width));
612
+ const canvas = document.createElement("canvas");
613
+ canvas.width = width;
614
+ canvas.height = height;
615
+ const ctx = canvas.getContext("2d");
616
+ if (!ctx) return file;
617
+ ctx.drawImage(bitmap, 0, 0, width, height);
618
+ const blob = yield canvasToBlob(canvas, file.type, ENCODE_QUALITY);
619
+ if (!blob || blob.size >= file.size) return file;
620
+ return new File([blob], file.name, {
621
+ type: file.type,
622
+ lastModified: file.lastModified
623
+ });
624
+ } catch (e) {
625
+ return file;
626
+ } finally {
627
+ bitmap == null ? void 0 : bitmap.close();
628
+ }
629
+ });
630
+ }
631
+
590
632
  // src/crypto/sensitive.ts
591
633
  function bufferToBase64(buf) {
592
634
  const bytes = new Uint8Array(buf);
@@ -1671,6 +1713,10 @@ var SensitiveField = ({ field: fieldDef, disabled }) => {
1671
1713
  hasError && /* @__PURE__ */ jsx("span", { className: "mt-[-8px] text-xs", style: styles.errorStyle, children: meta.error })
1672
1714
  ] });
1673
1715
  };
1716
+ var FormFileUploadContext = createContext({});
1717
+ var useFormFileUpload = () => useContext(FormFileUploadContext);
1718
+ var FormFileUploadProvider = FormFileUploadContext.Provider;
1719
+ var NO_UPLOADER_MESSAGE = "File uploads aren't configured for this form.";
1674
1720
  function formatBytes(bytes) {
1675
1721
  if (bytes < 1024) return `${bytes} B`;
1676
1722
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
@@ -1690,21 +1736,36 @@ function matchesAccept(file, accept) {
1690
1736
  });
1691
1737
  }
1692
1738
  var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1693
- var _a, _b, _c, _d;
1739
+ var _a, _b, _c, _d, _e, _f;
1694
1740
  const [, meta, helpers] = useField(fieldDef.id);
1695
1741
  const { setFieldTouched } = useFormikContext();
1742
+ const { upload: contextUpload, allowObjectUrlFallback } = useFormFileUpload();
1696
1743
  const inputRef = useRef(null);
1697
1744
  const [uploading, setUploading] = useState(false);
1698
1745
  const [uploadError, setUploadError] = useState(null);
1699
1746
  const [files, setFiles] = useState([]);
1747
+ const uploader = onUpload != null ? onUpload : contextUpload;
1748
+ const uploadsUnavailable = !uploader && !allowObjectUrlFallback;
1749
+ useEffect(() => {
1750
+ if (!uploadsUnavailable) return;
1751
+ console.warn(
1752
+ `[forms] Field "${fieldDef.id}" is a file field but no upload path is configured. Pass onFileUpload or fileUploadRoute to <DynamicForm> (or onUpload to <FileField>) to enable it.`
1753
+ );
1754
+ }, [uploadsUnavailable, fieldDef.id]);
1700
1755
  const config = __spreadValues(__spreadValues({}, DEFAULT_FILE_FIELD_CONFIG), fieldDef.fileConfig);
1701
1756
  const maxSizeBytes = (_a = config.maxSizeBytes) != null ? _a : 10 * 1024 * 1024;
1702
1757
  const multiple = (_b = config.multiple) != null ? _b : false;
1703
1758
  const maxFiles = (_c = config.maxFiles) != null ? _c : 5;
1759
+ const resizeImages = (_d = config.resizeImages) != null ? _d : true;
1760
+ const maxImageWidth = (_e = config.maxImageWidth) != null ? _e : 1600;
1704
1761
  const handleFiles = useCallback(
1705
1762
  (fileList) => __async(null, null, function* () {
1706
1763
  var _a2, _b2;
1707
1764
  if (!fileList || fileList.length === 0) return;
1765
+ if (uploadsUnavailable) {
1766
+ setUploadError(NO_UPLOADER_MESSAGE);
1767
+ return;
1768
+ }
1708
1769
  setUploadError(null);
1709
1770
  const toUpload = Array.from(fileList);
1710
1771
  if (multiple && files.length + toUpload.length > maxFiles) {
@@ -1717,24 +1778,20 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1717
1778
  setUploadError(`"${file.name}" is not an accepted file type.`);
1718
1779
  continue;
1719
1780
  }
1720
- if (file.size > maxSizeBytes) {
1721
- setUploadError(
1722
- `"${file.name}" exceeds ${formatBytes(maxSizeBytes)} limit.`
1723
- );
1724
- continue;
1725
- }
1726
1781
  setUploading(true);
1727
1782
  try {
1728
- let result;
1729
- if (onUpload) {
1730
- result = yield onUpload(file, config);
1731
- } else {
1732
- result = {
1733
- url: URL.createObjectURL(file),
1734
- name: file.name,
1735
- size: file.size
1736
- };
1783
+ const prepared = resizeImages ? yield resizeImageFile(file, maxImageWidth) : file;
1784
+ if (prepared.size > maxSizeBytes) {
1785
+ setUploadError(
1786
+ `"${file.name}" exceeds ${formatBytes(maxSizeBytes)} limit.`
1787
+ );
1788
+ continue;
1737
1789
  }
1790
+ const result = uploader ? yield uploader(prepared, config) : {
1791
+ url: URL.createObjectURL(prepared),
1792
+ name: prepared.name,
1793
+ size: prepared.size
1794
+ };
1738
1795
  current = multiple ? [...current, result] : [result];
1739
1796
  } catch (err) {
1740
1797
  setUploadError(`Upload failed: ${err.message}`);
@@ -1753,8 +1810,11 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1753
1810
  multiple,
1754
1811
  maxFiles,
1755
1812
  maxSizeBytes,
1813
+ resizeImages,
1814
+ maxImageWidth,
1756
1815
  config,
1757
- onUpload,
1816
+ uploader,
1817
+ uploadsUnavailable,
1758
1818
  helpers,
1759
1819
  fieldDef.id,
1760
1820
  setFieldTouched
@@ -1769,7 +1829,8 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1769
1829
  [files, multiple, helpers]
1770
1830
  );
1771
1831
  const hasError = meta.touched && meta.error;
1772
- const isRequired = (_d = fieldDef.validation) == null ? void 0 : _d.some((v) => v.type === "required");
1832
+ const isRequired = (_f = fieldDef.validation) == null ? void 0 : _f.some((v) => v.type === "required");
1833
+ const pickerDisabled = disabled || uploadsUnavailable;
1773
1834
  return /* @__PURE__ */ jsxs("div", { children: [
1774
1835
  /* @__PURE__ */ jsxs(
1775
1836
  "label",
@@ -1794,12 +1855,14 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1794
1855
  /* @__PURE__ */ jsxs(
1795
1856
  "div",
1796
1857
  {
1797
- className: `relative rounded-lg border-2 border-dashed p-6 text-center transition-colors ${hasError ? "border-red-400" : "border-gray-300 hover:border-gray-400 dark:border-gray-600 dark:hover:border-gray-500"}`,
1858
+ className: `relative rounded-lg border-2 border-dashed p-6 text-center transition-colors ${hasError ? "border-red-400" : pickerDisabled ? "border-gray-200 dark:border-gray-700" : "border-gray-300 hover:border-gray-400 dark:border-gray-600 dark:hover:border-gray-500"}`,
1798
1859
  onDragOver: (e) => {
1860
+ if (pickerDisabled) return;
1799
1861
  e.preventDefault();
1800
1862
  e.stopPropagation();
1801
1863
  },
1802
1864
  onDrop: (e) => {
1865
+ if (pickerDisabled) return;
1803
1866
  e.preventDefault();
1804
1867
  e.stopPropagation();
1805
1868
  handleFiles(e.dataTransfer.files);
@@ -1813,7 +1876,7 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1813
1876
  type: "file",
1814
1877
  accept: config.accept,
1815
1878
  multiple,
1816
- disabled,
1879
+ disabled: pickerDisabled,
1817
1880
  onChange: (e) => {
1818
1881
  handleFiles(e.target.files);
1819
1882
  e.target.value = "";
@@ -1824,7 +1887,7 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1824
1887
  uploading ? /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
1825
1888
  /* @__PURE__ */ jsx("div", { className: "mx-auto h-1.5 w-32 overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700", children: /* @__PURE__ */ jsx("div", { className: "h-full w-1/3 animate-pulse rounded-full bg-indigo-500" }) }),
1826
1889
  /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500", children: "Uploading\u2026" })
1827
- ] }) : /* @__PURE__ */ jsxs(
1890
+ ] }) : uploadsUnavailable ? /* @__PURE__ */ jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: NO_UPLOADER_MESSAGE }) : /* @__PURE__ */ jsxs(
1828
1891
  "button",
1829
1892
  {
1830
1893
  type: "button",
@@ -1935,6 +1998,8 @@ var fieldComponents = {
1935
1998
  datetime: DateTimeField,
1936
1999
  hidden: HiddenField,
1937
2000
  sensitive: SensitiveField,
2001
+ // Its `onUpload`/`projectId` props are optional and normally arrive by
2002
+ // context (see FileUploadContext), so it fits the shared signature.
1938
2003
  file: FileField
1939
2004
  };
1940
2005
  var DynamicFormField = ({ field, mirrored, mirrorBehavior }) => {
@@ -2085,6 +2150,44 @@ function globalTracker() {
2085
2150
  if (typeof window === "undefined") return void 0;
2086
2151
  return window.__vtTrack;
2087
2152
  }
2153
+ function createRouteFileUploader(route, formId) {
2154
+ return (file) => __async(null, null, function* () {
2155
+ const body = new FormData();
2156
+ body.append("file", file);
2157
+ body.append("formId", formId);
2158
+ const res = yield fetch(route, { method: "POST", body });
2159
+ if (!res.ok) {
2160
+ const errBody = yield res.json().catch(() => null);
2161
+ throw new Error((errBody == null ? void 0 : errBody.error) || `Upload failed (${res.status})`);
2162
+ }
2163
+ const data = yield res.json().catch(() => null);
2164
+ if (!data || typeof data.url !== "string" || data.url.length === 0) {
2165
+ throw new Error("Upload route did not return a url");
2166
+ }
2167
+ if (isUnresolvedUploadUrl(data.url)) {
2168
+ throw new Error("Upload route returned a temporary, non-durable url");
2169
+ }
2170
+ return {
2171
+ url: data.url,
2172
+ name: typeof data.name === "string" ? data.name : file.name,
2173
+ size: typeof data.size === "number" ? data.size : file.size
2174
+ };
2175
+ });
2176
+ }
2177
+ function isUnresolvedUploadUrl(value) {
2178
+ return typeof value === "string" && (value.startsWith("blob:") || value.startsWith("data:"));
2179
+ }
2180
+ function findUnresolvedUploads(payload) {
2181
+ const ids = [];
2182
+ for (const [key, value] of Object.entries(payload)) {
2183
+ if (Array.isArray(value)) {
2184
+ if (value.some(isUnresolvedUploadUrl)) ids.push(key);
2185
+ } else if (isUnresolvedUploadUrl(value)) {
2186
+ ids.push(key);
2187
+ }
2188
+ }
2189
+ return ids;
2190
+ }
2088
2191
  function getSensitiveFieldIds(definition) {
2089
2192
  const ids = [];
2090
2193
  for (const section of definition.sections) {
@@ -2284,6 +2387,8 @@ var DynamicForm = ({
2284
2387
  onSuccess,
2285
2388
  onError,
2286
2389
  extraData,
2390
+ onFileUpload,
2391
+ fileUploadRoute,
2287
2392
  className,
2288
2393
  onFormView,
2289
2394
  onFormSubmit: onFormSubmitCallback,
@@ -2335,6 +2440,13 @@ var DynamicForm = ({
2335
2440
  () => [...definition.sections].sort((a, b) => a.order - b.order),
2336
2441
  [definition.sections]
2337
2442
  );
2443
+ const fileUploadValue = useMemo(
2444
+ () => ({
2445
+ upload: onFileUpload != null ? onFileUpload : fileUploadRoute ? createRouteFileUploader(fileUploadRoute, definition.id) : void 0,
2446
+ allowObjectUrlFallback: Boolean(previewState)
2447
+ }),
2448
+ [onFileUpload, fileUploadRoute, definition.id, previewState]
2449
+ );
2338
2450
  useEffect(() => {
2339
2451
  if (previewTouchAllSignal === void 0 || !formikRef.current) return;
2340
2452
  const touched = {};
@@ -2384,7 +2496,7 @@ var DynamicForm = ({
2384
2496
  }
2385
2497
  ) }) });
2386
2498
  }
2387
- return /* @__PURE__ */ jsx(FormStyleProvider, { value: style, children: /* @__PURE__ */ jsx(FormPreviewOverridesProvider, { value: previewOverrides, children: /* @__PURE__ */ jsx(
2499
+ return /* @__PURE__ */ jsx(FormStyleProvider, { value: style, children: /* @__PURE__ */ jsx(FormPreviewOverridesProvider, { value: previewOverrides, children: /* @__PURE__ */ jsx(FormFileUploadProvider, { value: fileUploadValue, children: /* @__PURE__ */ jsx(
2388
2500
  Formik,
2389
2501
  {
2390
2502
  innerRef: formikRef,
@@ -2426,6 +2538,12 @@ var DynamicForm = ({
2426
2538
  for (const toggleKey of getSameAsToggleKeys(definition)) {
2427
2539
  delete payload[toggleKey];
2428
2540
  }
2541
+ const unresolved = findUnresolvedUploads(payload);
2542
+ if (unresolved.length > 0) {
2543
+ throw new Error(
2544
+ `File upload did not complete for: ${unresolved.join(", ")}. Remove the file and add it again.`
2545
+ );
2546
+ }
2429
2547
  const sensitiveIds = getSensitiveFieldIds(definition);
2430
2548
  if (sensitiveIds.length > 0) {
2431
2549
  const transportKey = yield fetchTransportKey(transportKeyEndpoint);
@@ -2584,7 +2702,7 @@ var DynamicForm = ({
2584
2702
  );
2585
2703
  }
2586
2704
  }
2587
- ) }) });
2705
+ ) }) }) });
2588
2706
  };
2589
2707
  function buildQueryString(opts) {
2590
2708
  const params = new URLSearchParams({
@@ -2847,6 +2965,6 @@ function useDragReorder({
2847
2965
  });
2848
2966
  }
2849
2967
 
2850
- export { APPLICATION_STATUS_KEYS, CORE_EMAIL_TEMPLATE_VARIABLES, DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES, DEFAULT_FILE_FIELD_CONFIG, DEFAULT_FORM_STYLE, DEFAULT_NOTIFICATION_EMAIL_HTML, DEFAULT_NOTIFICATION_EMAIL_SUBJECT, DEFAULT_NOTIFICATION_EMAIL_TEMPLATE, DEFAULT_SENSITIVE_FIELD_CONFIG, DEFAULT_SPAM_PROTECTION, DynamicForm, DynamicFormField, DynamicFormSection, FORM_CSS_VAR, FORM_DEFAULT_COLOR, FORM_VAR, HONEYPOT_FIELD_NAME, NEWSLETTER_ALLOWED_FIELD_TYPES, SAME_AS_TOGGLE_PREFIX, SAMPLE_EMAIL_TEMPLATE_VARIABLES, applyTextTransform, applyTransform, base64ToBuffer, bufferToBase64, buildEmailTemplateVariables, buildFormCssVars, buildInitialValues, buildYupSchema, deriveLast4, encryptSensitiveValue, formatSsn, formatUsPhone, getFormDefinition, getSafeRedirectUrl, isVisibilityConditionMet, parseFormDefinition, renderEmailTemplate, renderNotificationEmail, sameAsToggleKey, useDragReorder, useFormDefinition, useUndoRedo, useUndoRedoShortcuts };
2968
+ export { APPLICATION_STATUS_KEYS, CORE_EMAIL_TEMPLATE_VARIABLES, DEFAULT_APPLICATION_STATUS_EMAIL_TEMPLATES, DEFAULT_FILE_FIELD_CONFIG, DEFAULT_FORM_STYLE, DEFAULT_NOTIFICATION_EMAIL_HTML, DEFAULT_NOTIFICATION_EMAIL_SUBJECT, DEFAULT_NOTIFICATION_EMAIL_TEMPLATE, DEFAULT_SENSITIVE_FIELD_CONFIG, DEFAULT_SPAM_PROTECTION, DynamicForm, DynamicFormField, DynamicFormSection, FORM_CSS_VAR, FORM_DEFAULT_COLOR, FORM_VAR, FileField, FormFileUploadProvider, HONEYPOT_FIELD_NAME, NEWSLETTER_ALLOWED_FIELD_TYPES, SAME_AS_TOGGLE_PREFIX, SAMPLE_EMAIL_TEMPLATE_VARIABLES, applyTextTransform, applyTransform, base64ToBuffer, bufferToBase64, buildEmailTemplateVariables, buildFormCssVars, buildInitialValues, buildYupSchema, deriveLast4, encryptSensitiveValue, formatSsn, formatUsPhone, getFormDefinition, getSafeRedirectUrl, isVisibilityConditionMet, parseFormDefinition, renderEmailTemplate, renderNotificationEmail, resizeImageFile, sameAsToggleKey, useDragReorder, useFormDefinition, useFormFileUpload, useUndoRedo, useUndoRedoShortcuts };
2851
2969
  //# sourceMappingURL=index.mjs.map
2852
2970
  //# sourceMappingURL=index.mjs.map