@vulcantech/forms 0.1.1 → 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.js CHANGED
@@ -612,6 +612,48 @@ function renderNotificationEmail(template, variables) {
612
612
  };
613
613
  }
614
614
 
615
+ // src/utils/resizeImage.ts
616
+ var RESIZABLE_TYPES = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp"]);
617
+ var ENCODE_QUALITY = 0.85;
618
+ var MAX_DECODE_BYTES = 50 * 1024 * 1024;
619
+ function canResize() {
620
+ return typeof createImageBitmap === "function" && typeof document !== "undefined" && typeof document.createElement === "function";
621
+ }
622
+ function canvasToBlob(canvas, type, quality) {
623
+ return new Promise((resolve) => canvas.toBlob(resolve, type, quality));
624
+ }
625
+ function resizeImageFile(file, maxWidth) {
626
+ return __async(this, null, function* () {
627
+ if (!Number.isFinite(maxWidth) || maxWidth <= 0) return file;
628
+ if (!RESIZABLE_TYPES.has(file.type)) return file;
629
+ if (file.size > MAX_DECODE_BYTES) return file;
630
+ if (!canResize()) return file;
631
+ let bitmap;
632
+ try {
633
+ bitmap = yield createImageBitmap(file, { imageOrientation: "from-image" });
634
+ if (bitmap.width <= maxWidth) return file;
635
+ const width = Math.round(maxWidth);
636
+ const height = Math.max(1, Math.round(bitmap.height * width / bitmap.width));
637
+ const canvas = document.createElement("canvas");
638
+ canvas.width = width;
639
+ canvas.height = height;
640
+ const ctx = canvas.getContext("2d");
641
+ if (!ctx) return file;
642
+ ctx.drawImage(bitmap, 0, 0, width, height);
643
+ const blob = yield canvasToBlob(canvas, file.type, ENCODE_QUALITY);
644
+ if (!blob || blob.size >= file.size) return file;
645
+ return new File([blob], file.name, {
646
+ type: file.type,
647
+ lastModified: file.lastModified
648
+ });
649
+ } catch (e) {
650
+ return file;
651
+ } finally {
652
+ bitmap == null ? void 0 : bitmap.close();
653
+ }
654
+ });
655
+ }
656
+
615
657
  // src/crypto/sensitive.ts
616
658
  function bufferToBase64(buf) {
617
659
  const bytes = new Uint8Array(buf);
@@ -1696,6 +1738,10 @@ var SensitiveField = ({ field: fieldDef, disabled }) => {
1696
1738
  hasError && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "mt-[-8px] text-xs", style: styles.errorStyle, children: meta.error })
1697
1739
  ] });
1698
1740
  };
1741
+ var FormFileUploadContext = react.createContext({});
1742
+ var useFormFileUpload = () => react.useContext(FormFileUploadContext);
1743
+ var FormFileUploadProvider = FormFileUploadContext.Provider;
1744
+ var NO_UPLOADER_MESSAGE = "File uploads aren't configured for this form.";
1699
1745
  function formatBytes(bytes) {
1700
1746
  if (bytes < 1024) return `${bytes} B`;
1701
1747
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
@@ -1715,21 +1761,36 @@ function matchesAccept(file, accept) {
1715
1761
  });
1716
1762
  }
1717
1763
  var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1718
- var _a, _b, _c, _d;
1764
+ var _a, _b, _c, _d, _e, _f;
1719
1765
  const [, meta, helpers] = formik.useField(fieldDef.id);
1720
1766
  const { setFieldTouched } = formik.useFormikContext();
1767
+ const { upload: contextUpload, allowObjectUrlFallback } = useFormFileUpload();
1721
1768
  const inputRef = react.useRef(null);
1722
1769
  const [uploading, setUploading] = react.useState(false);
1723
1770
  const [uploadError, setUploadError] = react.useState(null);
1724
1771
  const [files, setFiles] = react.useState([]);
1772
+ const uploader = onUpload != null ? onUpload : contextUpload;
1773
+ const uploadsUnavailable = !uploader && !allowObjectUrlFallback;
1774
+ react.useEffect(() => {
1775
+ if (!uploadsUnavailable) return;
1776
+ console.warn(
1777
+ `[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.`
1778
+ );
1779
+ }, [uploadsUnavailable, fieldDef.id]);
1725
1780
  const config = __spreadValues(__spreadValues({}, DEFAULT_FILE_FIELD_CONFIG), fieldDef.fileConfig);
1726
1781
  const maxSizeBytes = (_a = config.maxSizeBytes) != null ? _a : 10 * 1024 * 1024;
1727
1782
  const multiple = (_b = config.multiple) != null ? _b : false;
1728
1783
  const maxFiles = (_c = config.maxFiles) != null ? _c : 5;
1784
+ const resizeImages = (_d = config.resizeImages) != null ? _d : true;
1785
+ const maxImageWidth = (_e = config.maxImageWidth) != null ? _e : 1600;
1729
1786
  const handleFiles = react.useCallback(
1730
1787
  (fileList) => __async(null, null, function* () {
1731
1788
  var _a2, _b2;
1732
1789
  if (!fileList || fileList.length === 0) return;
1790
+ if (uploadsUnavailable) {
1791
+ setUploadError(NO_UPLOADER_MESSAGE);
1792
+ return;
1793
+ }
1733
1794
  setUploadError(null);
1734
1795
  const toUpload = Array.from(fileList);
1735
1796
  if (multiple && files.length + toUpload.length > maxFiles) {
@@ -1742,24 +1803,20 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1742
1803
  setUploadError(`"${file.name}" is not an accepted file type.`);
1743
1804
  continue;
1744
1805
  }
1745
- if (file.size > maxSizeBytes) {
1746
- setUploadError(
1747
- `"${file.name}" exceeds ${formatBytes(maxSizeBytes)} limit.`
1748
- );
1749
- continue;
1750
- }
1751
1806
  setUploading(true);
1752
1807
  try {
1753
- let result;
1754
- if (onUpload) {
1755
- result = yield onUpload(file, config);
1756
- } else {
1757
- result = {
1758
- url: URL.createObjectURL(file),
1759
- name: file.name,
1760
- size: file.size
1761
- };
1808
+ const prepared = resizeImages ? yield resizeImageFile(file, maxImageWidth) : file;
1809
+ if (prepared.size > maxSizeBytes) {
1810
+ setUploadError(
1811
+ `"${file.name}" exceeds ${formatBytes(maxSizeBytes)} limit.`
1812
+ );
1813
+ continue;
1762
1814
  }
1815
+ const result = uploader ? yield uploader(prepared, config) : {
1816
+ url: URL.createObjectURL(prepared),
1817
+ name: prepared.name,
1818
+ size: prepared.size
1819
+ };
1763
1820
  current = multiple ? [...current, result] : [result];
1764
1821
  } catch (err) {
1765
1822
  setUploadError(`Upload failed: ${err.message}`);
@@ -1778,8 +1835,11 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1778
1835
  multiple,
1779
1836
  maxFiles,
1780
1837
  maxSizeBytes,
1838
+ resizeImages,
1839
+ maxImageWidth,
1781
1840
  config,
1782
- onUpload,
1841
+ uploader,
1842
+ uploadsUnavailable,
1783
1843
  helpers,
1784
1844
  fieldDef.id,
1785
1845
  setFieldTouched
@@ -1794,7 +1854,8 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1794
1854
  [files, multiple, helpers]
1795
1855
  );
1796
1856
  const hasError = meta.touched && meta.error;
1797
- const isRequired = (_d = fieldDef.validation) == null ? void 0 : _d.some((v) => v.type === "required");
1857
+ const isRequired = (_f = fieldDef.validation) == null ? void 0 : _f.some((v) => v.type === "required");
1858
+ const pickerDisabled = disabled || uploadsUnavailable;
1798
1859
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1799
1860
  /* @__PURE__ */ jsxRuntime.jsxs(
1800
1861
  "label",
@@ -1819,12 +1880,14 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1819
1880
  /* @__PURE__ */ jsxRuntime.jsxs(
1820
1881
  "div",
1821
1882
  {
1822
- 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"}`,
1883
+ 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"}`,
1823
1884
  onDragOver: (e) => {
1885
+ if (pickerDisabled) return;
1824
1886
  e.preventDefault();
1825
1887
  e.stopPropagation();
1826
1888
  },
1827
1889
  onDrop: (e) => {
1890
+ if (pickerDisabled) return;
1828
1891
  e.preventDefault();
1829
1892
  e.stopPropagation();
1830
1893
  handleFiles(e.dataTransfer.files);
@@ -1838,7 +1901,7 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1838
1901
  type: "file",
1839
1902
  accept: config.accept,
1840
1903
  multiple,
1841
- disabled,
1904
+ disabled: pickerDisabled,
1842
1905
  onChange: (e) => {
1843
1906
  handleFiles(e.target.files);
1844
1907
  e.target.value = "";
@@ -1849,7 +1912,7 @@ var FileField = ({ field: fieldDef, onUpload, disabled }) => {
1849
1912
  uploading ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
1850
1913
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mx-auto h-1.5 w-32 overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-full w-1/3 animate-pulse rounded-full bg-indigo-500" }) }),
1851
1914
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-gray-500", children: "Uploading\u2026" })
1852
- ] }) : /* @__PURE__ */ jsxRuntime.jsxs(
1915
+ ] }) : uploadsUnavailable ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-gray-500 dark:text-gray-400", children: NO_UPLOADER_MESSAGE }) : /* @__PURE__ */ jsxRuntime.jsxs(
1853
1916
  "button",
1854
1917
  {
1855
1918
  type: "button",
@@ -1960,6 +2023,8 @@ var fieldComponents = {
1960
2023
  datetime: DateTimeField,
1961
2024
  hidden: HiddenField,
1962
2025
  sensitive: SensitiveField,
2026
+ // Its `onUpload`/`projectId` props are optional and normally arrive by
2027
+ // context (see FileUploadContext), so it fits the shared signature.
1963
2028
  file: FileField
1964
2029
  };
1965
2030
  var DynamicFormField = ({ field, mirrored, mirrorBehavior }) => {
@@ -2110,6 +2175,44 @@ function globalTracker() {
2110
2175
  if (typeof window === "undefined") return void 0;
2111
2176
  return window.__vtTrack;
2112
2177
  }
2178
+ function createRouteFileUploader(route, formId) {
2179
+ return (file) => __async(null, null, function* () {
2180
+ const body = new FormData();
2181
+ body.append("file", file);
2182
+ body.append("formId", formId);
2183
+ const res = yield fetch(route, { method: "POST", body });
2184
+ if (!res.ok) {
2185
+ const errBody = yield res.json().catch(() => null);
2186
+ throw new Error((errBody == null ? void 0 : errBody.error) || `Upload failed (${res.status})`);
2187
+ }
2188
+ const data = yield res.json().catch(() => null);
2189
+ if (!data || typeof data.url !== "string" || data.url.length === 0) {
2190
+ throw new Error("Upload route did not return a url");
2191
+ }
2192
+ if (isUnresolvedUploadUrl(data.url)) {
2193
+ throw new Error("Upload route returned a temporary, non-durable url");
2194
+ }
2195
+ return {
2196
+ url: data.url,
2197
+ name: typeof data.name === "string" ? data.name : file.name,
2198
+ size: typeof data.size === "number" ? data.size : file.size
2199
+ };
2200
+ });
2201
+ }
2202
+ function isUnresolvedUploadUrl(value) {
2203
+ return typeof value === "string" && (value.startsWith("blob:") || value.startsWith("data:"));
2204
+ }
2205
+ function findUnresolvedUploads(payload) {
2206
+ const ids = [];
2207
+ for (const [key, value] of Object.entries(payload)) {
2208
+ if (Array.isArray(value)) {
2209
+ if (value.some(isUnresolvedUploadUrl)) ids.push(key);
2210
+ } else if (isUnresolvedUploadUrl(value)) {
2211
+ ids.push(key);
2212
+ }
2213
+ }
2214
+ return ids;
2215
+ }
2113
2216
  function getSensitiveFieldIds(definition) {
2114
2217
  const ids = [];
2115
2218
  for (const section of definition.sections) {
@@ -2309,6 +2412,8 @@ var DynamicForm = ({
2309
2412
  onSuccess,
2310
2413
  onError,
2311
2414
  extraData,
2415
+ onFileUpload,
2416
+ fileUploadRoute,
2312
2417
  className,
2313
2418
  onFormView,
2314
2419
  onFormSubmit: onFormSubmitCallback,
@@ -2360,6 +2465,13 @@ var DynamicForm = ({
2360
2465
  () => [...definition.sections].sort((a, b) => a.order - b.order),
2361
2466
  [definition.sections]
2362
2467
  );
2468
+ const fileUploadValue = react.useMemo(
2469
+ () => ({
2470
+ upload: onFileUpload != null ? onFileUpload : fileUploadRoute ? createRouteFileUploader(fileUploadRoute, definition.id) : void 0,
2471
+ allowObjectUrlFallback: Boolean(previewState)
2472
+ }),
2473
+ [onFileUpload, fileUploadRoute, definition.id, previewState]
2474
+ );
2363
2475
  react.useEffect(() => {
2364
2476
  if (previewTouchAllSignal === void 0 || !formikRef.current) return;
2365
2477
  const touched = {};
@@ -2409,7 +2521,7 @@ var DynamicForm = ({
2409
2521
  }
2410
2522
  ) }) });
2411
2523
  }
2412
- return /* @__PURE__ */ jsxRuntime.jsx(FormStyleProvider, { value: style, children: /* @__PURE__ */ jsxRuntime.jsx(FormPreviewOverridesProvider, { value: previewOverrides, children: /* @__PURE__ */ jsxRuntime.jsx(
2524
+ return /* @__PURE__ */ jsxRuntime.jsx(FormStyleProvider, { value: style, children: /* @__PURE__ */ jsxRuntime.jsx(FormPreviewOverridesProvider, { value: previewOverrides, children: /* @__PURE__ */ jsxRuntime.jsx(FormFileUploadProvider, { value: fileUploadValue, children: /* @__PURE__ */ jsxRuntime.jsx(
2413
2525
  formik.Formik,
2414
2526
  {
2415
2527
  innerRef: formikRef,
@@ -2451,6 +2563,12 @@ var DynamicForm = ({
2451
2563
  for (const toggleKey of getSameAsToggleKeys(definition)) {
2452
2564
  delete payload[toggleKey];
2453
2565
  }
2566
+ const unresolved = findUnresolvedUploads(payload);
2567
+ if (unresolved.length > 0) {
2568
+ throw new Error(
2569
+ `File upload did not complete for: ${unresolved.join(", ")}. Remove the file and add it again.`
2570
+ );
2571
+ }
2454
2572
  const sensitiveIds = getSensitiveFieldIds(definition);
2455
2573
  if (sensitiveIds.length > 0) {
2456
2574
  const transportKey = yield fetchTransportKey(transportKeyEndpoint);
@@ -2609,7 +2727,7 @@ var DynamicForm = ({
2609
2727
  );
2610
2728
  }
2611
2729
  }
2612
- ) }) });
2730
+ ) }) }) });
2613
2731
  };
2614
2732
  function buildQueryString(opts) {
2615
2733
  const params = new URLSearchParams({
@@ -2888,6 +3006,8 @@ exports.DynamicFormSection = DynamicFormSection;
2888
3006
  exports.FORM_CSS_VAR = FORM_CSS_VAR;
2889
3007
  exports.FORM_DEFAULT_COLOR = FORM_DEFAULT_COLOR;
2890
3008
  exports.FORM_VAR = FORM_VAR;
3009
+ exports.FileField = FileField;
3010
+ exports.FormFileUploadProvider = FormFileUploadProvider;
2891
3011
  exports.HONEYPOT_FIELD_NAME = HONEYPOT_FIELD_NAME;
2892
3012
  exports.NEWSLETTER_ALLOWED_FIELD_TYPES = NEWSLETTER_ALLOWED_FIELD_TYPES;
2893
3013
  exports.SAME_AS_TOGGLE_PREFIX = SAME_AS_TOGGLE_PREFIX;
@@ -2910,9 +3030,11 @@ exports.isVisibilityConditionMet = isVisibilityConditionMet;
2910
3030
  exports.parseFormDefinition = parseFormDefinition;
2911
3031
  exports.renderEmailTemplate = renderEmailTemplate;
2912
3032
  exports.renderNotificationEmail = renderNotificationEmail;
3033
+ exports.resizeImageFile = resizeImageFile;
2913
3034
  exports.sameAsToggleKey = sameAsToggleKey;
2914
3035
  exports.useDragReorder = useDragReorder;
2915
3036
  exports.useFormDefinition = useFormDefinition;
3037
+ exports.useFormFileUpload = useFormFileUpload;
2916
3038
  exports.useUndoRedo = useUndoRedo;
2917
3039
  exports.useUndoRedoShortcuts = useUndoRedoShortcuts;
2918
3040
  //# sourceMappingURL=index.js.map