@ttt-productions/file-input 0.11.8 → 0.11.10

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.
@@ -20,11 +20,22 @@ export interface ValidateUploadFileOptions {
20
20
  fileSize: number;
21
21
  fileType: string;
22
22
  }) => void;
23
+ /**
24
+ * FAIL-OPEN for indeterminate picker metadata: when the file's kind cannot
25
+ * be determined from browser MIME/extension, pass it through with the
26
+ * NEUTRAL `application/octet-stream` type (never a fabricated media type)
27
+ * instead of throwing, so the server's canonical byte inspector — the only
28
+ * classification authority — decides. The kind-mismatch check still throws
29
+ * when the client metadata IS determinate. Requires the upload path to opt
30
+ * into `allowNeutralContentType`.
31
+ */
32
+ allowIndeterminate?: boolean;
23
33
  }
24
34
  /**
25
35
  * Validates and normalizes a file for upload.
26
36
  *
27
- * - Throws a user-friendly Error if the file's kind cannot be determined.
37
+ * - Throws a user-friendly Error if the file's kind cannot be determined
38
+ * (unless `allowIndeterminate` fails open to the neutral content type).
28
39
  * - Throws a user-friendly Error if `expectedKind` is not 'any' and doesn't
29
40
  * match the detected kind.
30
41
  * - Otherwise returns a File with a guaranteed valid media contentType.
@@ -1 +1 @@
1
- {"version":3,"file":"validate-upload-kind.d.ts","sourceRoot":"","sources":["../../src/lib/validate-upload-kind.ts"],"names":[],"mappings":"AAGA,KAAK,UAAU,GAAG,OAAO,GAAG,OAAO,GAAG,OAAO,CAAC;AAC9C,MAAM,MAAM,YAAY,GAAG,UAAU,GAAG,KAAK,GAAG,SAAS,UAAU,EAAE,CAAC;AAEtE;;;GAGG;AACH,MAAM,MAAM,2BAA2B,GACnC,2BAA2B,GAC3B,sBAAsB,CAAC;AAE3B,MAAM,WAAW,yBAAyB;IACxC;;;;;OAKG;IACH,OAAO,CAAC,EAAE,CAAC,IAAI,EAAE,2BAA2B,EAAE,KAAK,EAAE;QACnD,UAAU,EAAE,MAAM,CAAC;QACnB,YAAY,EAAE,MAAM,CAAC;QACrB,YAAY,C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@@ function matchesExpected(detected, expected) {
17
17
  /**
18
18
  * Validates and normalizes a file for upload.
19
19
  *
20
- * - Throws a user-friendly Error if the file's kind cannot be determined.
20
+ * - Throws a user-friendly Error if the file's kind cannot be determined
21
+ * (unless `allowIndeterminate` fails open to the neutral content type).
21
22
  * - Throws a user-friendly Error if `expectedKind` is not 'any' and doesn't
22
23
  * match the detected kind.
23
24
  * - Otherwise returns a File with a guaranteed valid media contentType.
@@ -31,6 +32,11 @@ function matchesExpected(detected, expected) {
31
32
  export function validateAndNormalizeUploadFile(file, fileOrigin, expectedKind, options) {
32
33
  const detected = getSimplifiedMediaType(file);
33
34
  if (detected === 'other') {
35
+ if (options?.allowIndeterminate === true) {
36
+ // No fallback kind: inferContentType resolves an unknown file to the
37
+ // NEUTRAL type, never a fabricated media fact.
38
+ return ensureFileWithContentType(file);
39
+ }
34
40
  options?.onError?.('upload_kind_indeterminate', {
35
41
  fileOrigin,
36
42
  expectedKind: describeExpected(expectedKind),
@@ -1 +1 @@
1
- {"version":3,"file":"validate-upload-kind.js","sourceRoot":"","sources":["../../src/lib/validate-upload-kind.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AA8BpE,SAAS,gBAAgB,CAAC,QAAsB;IAC9C,IAAI,QAAQ,KAAK,KAAK;QAAE,OAAO,wBAAwB,CAAC;IACxD,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1D,OAAO,QAAkB,CAAC;AAC5B,CAAC;AAED,SAAS,eAAe,CAAC,QAAoB,EAAE,QAAsB;IACnE,IAAI,QAAQ,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IACpC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAQ,QAAkC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC3F,OAAO,QAAQ,KAAK,QAAQ,CAAC;AAC/B,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,8BAA8B,CAC5C,IAAU,EACV,UAAkB,EAClB,YAA0B,EAC1B,OAAmC;IAEnC,MAAM,QAAQ,GAAG,sBAAsB,CAAC,IAAI,CAAC,CAAC;IAE9C,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;QACzB,OAAO,EAAE,OAAO,EAAE,CAAC,2BAA2B,EAAE;YAC9C,UAAU;YACV,YAAY,EAAE,gBAAgB,CAAC,YAAY,CAAC;YAC5C,YAAY,EAAE,QAAQ;YACtB,QAAQ,EAAE,IAAI,CAAC,IAAI;YACnB,QAAQ,EAAE,IAAI,CAAC,IAAI;YACnB,QAAQ,EAAE,IAAI,CAAC,IAAI;SACpB,CAAC,CAAC;QACH,MAAM,IAAI,KAAK,CACb,oGAAoG,CACrG,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,YAAY,CAAC,EAAE,CAAC;QAC7C,OAAO,EAAE,OAAO,EAAE,CAAC,sBAAsB,EAAE;YACzC,UAAU;YACV,YAAY,EAAE,gBAAgB,CAAC,YAAY,CAAC;YAC5C,YAAY,EAAE,QAAQ;YACtB,QAAQ,EAAE,IAAI,CAAC,IAAI;YACnB,QAAQ,EAAE,IAAI,CAAC,IAAI;YACnB,QAAQ,EAAE,IAAI,CAAC,IAAI;SACpB,CAAC,CAAC;QACH,MAAM,IAAI,KAAK,CACb,0BAA0B,gBAAgB,CAAC,YAAY,CAAC,gCAAgC,QAAQ,GAAG,CACpG,CAAC;IACJ,CAAC;IAED,OAAO,yBAAyB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import { getSimplifiedMediaType } from '@ttt-productions/media-schemas';\nimport { ensureFileWithContentType } from './infer-content-type.js';\n\ntype SingleKind = 'image' | 'video' | 'audio';\nexport type ExpectedKind = SingleKind | 'any' | readonly SingleKind[];\n\n/**\n * Diagnostic codes emitted by validateAndNormalizeUploadFile when validation\n * fails. Consumers can route these to monitoring/Sentry via the onError option.\n */\nexport type ValidateUploadFileErrorCode =\n | 'upload_kind_indeterminate'\n | 'upload_kind_mismatch';\n\nexport interface ValidateUploadFileOptions {\n /**\n * Optional diagnostic callback fired before the function throws.\n * Useful for routing to Sentry / monitoring-core. The thrown Error\n * carries the user-facing message; this callback gets the machine\n * code + structured extras.\n */\n onError?: (code: ValidateUploadFileErrorCode, extra: {\n fileOrigin: string;\n expectedKind: string;\n detectedKind?: SingleKind | 'other';\n fileName: string;\n fileSize: number;\n fileType: string;\n }) => void;\n}\n\nfunction describeExpected(expected: ExpectedKind): string {\n if (expected === 'any') return 'image, video, or audio';\n if (Array.isArray(expected)) return expected.join(' or ');\n return expected as string;\n}\n\nfunction matchesExpected(detected: SingleKind, expected: ExpectedKind): boolean {\n if (expected === 'any') return true;\n if (Array.isArray(expected)) return (expected as readonly SingleKind[]).includes(detected);\n return detected === expected;\n}\n\n/**\n * Validates and normalizes a file for upload.\n *\n * - Throws a user-friendly Error if the file's kind cannot be determined.\n * - Throws a user-friendly Error if `expectedKind` is not 'any' and doesn't\n * match the detected kind.\n * - Otherwise returns a File with a guaranteed valid media contentType.\n *\n * Optional `onError` callback fires with a machine-readable code + structured\n * extras before the throw, so consumers can route to monitoring without this\n * package depending on any monitoring library.\n *\n * Use this at the top of every upload mutation, before uploadFileResumable.\n */\nexport function validateAndNormalizeUploadFile(\n file: File,\n fileOrigin: string,\n expectedKind: ExpectedKind,\n options?: ValidateUploadFileOptions,\n): File {\n const detected = getSimplifiedMediaType(file);\n\n if (detected === 'other') {\n options?.onError?.('upload_kind_indeterminate', {\n fileOrigin,\n expectedKind: describeExpected(expectedKind),\n detectedKind: detected,\n fileName: file.name,\n fileSize: file.size,\n fileType: file.type,\n });\n throw new Error(\n 'Could not determine the file type. Please try a different file or re-export it in a common format.'\n );\n }\n\n if (!matchesExpected(detected, expectedKind)) {\n options?.onError?.('upload_kind_mismatch', {\n fileOrigin,\n expectedKind: describeExpected(expectedKind),\n detectedKind: detected,\n fileName: file.name,\n fileSize: file.size,\n fileType: file.type,\n });\n throw new Error(\n `This slot only accepts ${describeExpected(expectedKind)} files. The selected file is ${detected}.`\n );\n }\n\n return ensureFileWithContentType(file, detected);\n}\n"]}
1
+ {"version":3,"file":"validate-upload-kind.js","sourceRoot":"","sources":["../../src/lib/validate-upload-kind.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAwCpE,SAAS,gBAAgB,CAAC,QAAsB;IAC9C,IAAI,QAAQ,KAAK,KAAK;QAAE,OAAO,wBAAwB,CAAC;IACxD,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAO,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC1D,OAAO,QAAkB,CAAC;AAC5B,CAAC;AAED,SAAS,eAAe,CAAC,QAAoB,EAAE,QAAsB;IACnE,IAAI,QAAQ,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IACpC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAAE,OAAQ,QAAkC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;IAC3F,OAAO,QAAQ,KAAK,QAAQ,CAAC;AAC/B,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,8BAA8B,CAC5C,IAAU,EACV,UAAkB,EAClB,YAA0B,EAC1B,OAAmC;IAEnC,MAAM,QAAQ,GAAG,sBAAsB,CAAC,IAAI,CAAC,CAAC;IAE9C,IAAI,QAAQ,KAAK,OAAO,EAAE,CAAC;QACzB,IAAI,OAAO,EAAE,kBAAkB,KAAK,IAAI,EAAE,CAAC;YACzC,qEAAqE;YACrE,+CAA+C;YAC/C,OAAO,yBAAyB,CAAC,IAAI,CAAC,CAAC;QACzC,CAAC;QACD,OAAO,EAAE,OAAO,EAAE,CAAC,2BAA2B,EAAE;YAC9C,UAAU;YACV,YAAY,EAAE,gBAAgB,CAAC,YAAY,CAAC;YAC5C,YAAY,EAAE,QAAQ;YACtB,QAAQ,EAAE,IAAI,CAAC,IAAI;YACnB,QAAQ,EAAE,IAAI,CAAC,IAAI;YACnB,QAAQ,EAAE,IAAI,CAAC,IAAI;SACpB,CAAC,CAAC;QACH,MAAM,IAAI,KAAK,CACb,oGAAoG,CACrG,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE,YAAY,CAAC,EAAE,CAAC;QAC7C,OAAO,EAAE,OAAO,EAAE,CAAC,sBAAsB,EAAE;YACzC,UAAU;YACV,YAAY,EAAE,gBAAgB,CAAC,YAAY,CAAC;YAC5C,YAAY,EAAE,QAAQ;YACtB,QAAQ,EAAE,IAAI,CAAC,IAAI;YACnB,QAAQ,EAAE,IAAI,CAAC,IAAI;YACnB,QAAQ,EAAE,IAAI,CAAC,IAAI;SACpB,CAAC,CAAC;QACH,MAAM,IAAI,KAAK,CACb,0BAA0B,gBAAgB,CAAC,YAAY,CAAC,gCAAgC,QAAQ,GAAG,CACpG,CAAC;IACJ,CAAC;IAED,OAAO,yBAAyB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AACnD,CAAC","sourcesContent":["import { getSimplifiedMediaType } from '@ttt-productions/media-schemas';\nimport { ensureFileWithContentType } from './infer-content-type.js';\n\ntype SingleKind = 'image' | 'video' | 'audio';\nexport type ExpectedKind = SingleKind | 'any' | readonly SingleKind[];\n\n/**\n * Diagnostic codes emitted by validateAndNormalizeUploadFile when validation\n * fails. Consumers can route these to monitoring/Sentry via the onError option.\n */\nexport type ValidateUploadFileErrorCode =\n | 'upload_kind_indeterminate'\n | 'upload_kind_mismatch';\n\nexport interface ValidateUploadFileOptions {\n /**\n * Optional diagnostic callback fired before the function throws.\n * Useful for routing to Sentry / monitoring-core. The thrown Error\n * carries the user-facing message; this callback gets the machine\n * code + structured extras.\n */\n onError?: (code: ValidateUploadFileErrorCode, extra: {\n fileOrigin: string;\n expectedKind: string;\n detectedKind?: SingleKind | 'other';\n fileName: string;\n fileSize: number;\n fileType: string;\n }) => void;\n /**\n * FAIL-OPEN for indeterminate picker metadata: when the file's kind cannot\n * be determined from browser MIME/extension, pass it through with the\n * NEUTRAL `application/octet-stream` type (never a fabricated media type)\n * instead of throwing, so the server's canonical byte inspector — the only\n * classification authority — decides. The kind-mismatch check still throws\n * when the client metadata IS determinate. Requires the upload path to opt\n * into `allowNeutralContentType`.\n */\n allowIndeterminate?: boolean;\n}\n\nfunction describeExpected(expected: ExpectedKind): string {\n if (expected === 'any') return 'image, video, or audio';\n if (Array.isArray(expected)) return expected.join(' or ');\n return expected as string;\n}\n\nfunction matchesExpected(detected: SingleKind, expected: ExpectedKind): boolean {\n if (expected === 'any') return true;\n if (Array.isArray(expected)) return (expected as readonly SingleKind[]).includes(detected);\n return detected === expected;\n}\n\n/**\n * Validates and normalizes a file for upload.\n *\n * - Throws a user-friendly Error if the file's kind cannot be determined\n * (unless `allowIndeterminate` fails open to the neutral content type).\n * - Throws a user-friendly Error if `expectedKind` is not 'any' and doesn't\n * match the detected kind.\n * - Otherwise returns a File with a guaranteed valid media contentType.\n *\n * Optional `onError` callback fires with a machine-readable code + structured\n * extras before the throw, so consumers can route to monitoring without this\n * package depending on any monitoring library.\n *\n * Use this at the top of every upload mutation, before uploadFileResumable.\n */\nexport function validateAndNormalizeUploadFile(\n file: File,\n fileOrigin: string,\n expectedKind: ExpectedKind,\n options?: ValidateUploadFileOptions,\n): File {\n const detected = getSimplifiedMediaType(file);\n\n if (detected === 'other') {\n if (options?.allowIndeterminate === true) {\n // No fallback kind: inferContentType resolves an unknown file to the\n // NEUTRAL type, never a fabricated media fact.\n return ensureFileWithContentType(file);\n }\n options?.onError?.('upload_kind_indeterminate', {\n fileOrigin,\n expectedKind: describeExpected(expectedKind),\n detectedKind: detected,\n fileName: file.name,\n fileSize: file.size,\n fileType: file.type,\n });\n throw new Error(\n 'Could not determine the file type. Please try a different file or re-export it in a common format.'\n );\n }\n\n if (!matchesExpected(detected, expectedKind)) {\n options?.onError?.('upload_kind_mismatch', {\n fileOrigin,\n expectedKind: describeExpected(expectedKind),\n detectedKind: detected,\n fileName: file.name,\n fileSize: file.size,\n fileType: file.type,\n });\n throw new Error(\n `This slot only accepts ${describeExpected(expectedKind)} files. The selected file is ${detected}.`\n );\n }\n\n return ensureFileWithContentType(file, detected);\n}\n"]}
@@ -2,9 +2,9 @@
2
2
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
3
  import { useCallback, useEffect, useMemo, useRef, useState, useId } from "react";
4
4
  import { getSimplifiedMediaType } from "@ttt-productions/media-schemas";
5
- import { Alert, AlertDescription, Button, Card, Input, Progress } from "@ttt-productions/ui-core/react";
5
+ import { Alert, AlertDescription, Button, Card, Input, Progress, Spinner } from "@ttt-productions/ui-core/react";
6
6
  import { cn } from "@ttt-productions/ui-core";
7
- import { Info, X, Upload, Film, Music, Paperclip, AlertTriangle, Loader2 } from "lucide-react";
7
+ import { Info, X, Upload, Film, Music, Paperclip, AlertTriangle } from "lucide-react";
8
8
  import { validateMediaDuration } from "../../lib/validate-media-duration.js";
9
9
  import { ImageCropperModal } from "./image-cropper-modal.js";
10
10
  const MIME_MAP = {
@@ -167,7 +167,7 @@ export function FileInput(props) {
167
167
  });
168
168
  };
169
169
  const isUploading = typeof uploadProgress === "number" && isLoading;
170
- return (_jsxs("div", { className: cn("relative w-full", className), children: [localError && (_jsxs(Alert, { variant: "destructive", className: "mb-2", children: [_jsx(AlertTriangle, { className: "icon-xs" }), _jsx(AlertDescription, { children: localError.message })] })), _jsx(Input, { id: inputId, type: "file", accept: acceptString, onChange: handleFileChange, className: "hidden", disabled: disabled || isLoading, ref: fileInputRef }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("label", { htmlFor: inputId, className: "w-full flex-grow", children: _jsx(Button, { asChild: true, disabled: disabled || isLoading, variant: variant, size: size, className: cn("w-full relative overflow-hidden cursor-pointer", { "icon-xl p-0": size === "icon" }), children: _jsxs("span", { className: "relative w-full h-full center-row", children: [isUploading && (_jsx(Progress, { value: uploadProgress ?? 0, className: "absolute left-0 top-0 h-full w-full z-0 bg-accent" })), _jsx("span", { className: "z-10 center-row w-full", children: isLoading ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "mr-2 spinner-xs" }), " ", isUploading ? `${(uploadProgress ?? 0).toFixed(0)}%` : "Processing..."] })) : fileValue ? (_jsxs("span", { className: "flex items-center justify-between w-full", children: [_jsx("span", { className: "truncate pr-2", children: getSelectedFileLabel(fileValue) }), _jsx(Button, { variant: "ghost", size: "icon", className: "icon-sm hover:bg-destructive/20 shrink-0", onClick: handleClear, children: _jsx(X, { className: "icon-xs" }) })] })) : (_jsx(_Fragment, { children: buttonLabel === "Attach"
170
+ return (_jsxs("div", { className: cn("relative w-full", className), children: [localError && (_jsxs(Alert, { variant: "destructive", className: "mb-2", children: [_jsx(AlertTriangle, { className: "icon-xs" }), _jsx(AlertDescription, { children: localError.message })] })), _jsx(Input, { id: inputId, type: "file", accept: acceptString, onChange: handleFileChange, className: "hidden", disabled: disabled || isLoading, ref: fileInputRef }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("label", { htmlFor: inputId, className: "w-full flex-grow", children: _jsx(Button, { asChild: true, disabled: disabled || isLoading, variant: variant, size: size, className: cn("w-full relative overflow-hidden cursor-pointer", { "icon-xl p-0": size === "icon" }), children: _jsxs("span", { className: "relative w-full h-full center-row", children: [isUploading && (_jsx(Progress, { value: uploadProgress ?? 0, className: "absolute left-0 top-0 h-full w-full z-0 bg-accent" })), _jsx("span", { className: "z-10 center-row w-full", children: isLoading ? (_jsxs(_Fragment, { children: [_jsx(Spinner, { size: "xs", className: "mr-2" }), " ", isUploading ? `${(uploadProgress ?? 0).toFixed(0)}%` : "Processing..."] })) : fileValue ? (_jsxs("span", { className: "flex items-center justify-between w-full", children: [_jsx("span", { className: "truncate pr-2", children: getSelectedFileLabel(fileValue) }), _jsx(Button, { variant: "ghost", size: "icon", className: "icon-sm hover:bg-destructive/20 shrink-0", onClick: handleClear, children: _jsx(X, { className: "icon-xs" }) })] })) : (_jsx(_Fragment, { children: buttonLabel === "Attach"
171
171
  ? _jsxs(_Fragment, { children: [_jsx(Paperclip, { className: "mr-2 icon-xs" }), " ", buttonLabel] })
172
172
  : _jsxs(_Fragment, { children: [getUploadIcon(), " ", buttonLabel] }) })) })] }) }) }), detailsDescriptionParts.length > 0 && size !== "icon" && (_jsx(Button, { type: "button", variant: "default", size: "icon", onClick: () => setShowDetails((p) => !p), "aria-label": "Show file processing details", className: "flex-shrink-0 icon-xl", children: _jsx(Info, { className: "icon-sm" }) }))] }), showDetails && detailsDescriptionParts.length > 0 && size !== "icon" && (_jsx(Card, { className: "page-card w-full mt-2", children: _jsx("div", { className: "text-center p-2 space-y-0.5", children: detailsDescriptionParts.map((part, i) => (_jsx("p", { className: "text-small font-bold", children: part }, i))) }) })), cropConfig && imageToCrop && (_jsx(ImageCropperModal, { isOpen: isCropperOpen, onClose: () => {
173
173
  setIsCropperOpen(false);
@@ -1 +1 @@
1
- {"version":3,"file":"file-input.js","sourceRoot":"","sources":["../../../src/react/components/file-input.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AACjF,OAAO,EAAE,sBAAsB,EAA4B,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AACxG,OAAO,EAAE,EAAE,EAAE,MAAM,0BAA0B,CAAC;AAC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,IACG,CACP,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState, useId } from \"react\";\nimport { getSimplifiedMediaType, type SimplifiedMediaType } from \"@ttt-productions/media-schemas\";\nimport { Alert, AlertDescription, Button, Card, Input, Progress } from \"@ttt-productions/ui-core/react\";\nimport { cn } from \"@ttt-productions/ui-core\";\nimport { Info, X, Upload, Film, Music, Paperclip, AlertTriangle, Loader2 } from \"lucide-react\";\n\nimport type { FileInputError, FileInputProps } from \"../../types.js\";\nimport { validateMediaDuration } from \"../../lib/validate-media-duration.js\";\nimport { ImageCropperModal } from \"./image-cropper-modal.js\";\n\nconst MIME_MAP: Record<SimplifiedMediaType, string> = {\n image: \"image/jpeg, image/png, image/gif, image/webp, image/svg+xml, image/bmp, image/avif\",\n video: \"video/*, .mkv\",\n audio: \"audio/*\",\n other: \".pdf, .doc, .docx\"\n};\n\nfunction err(code: FileInputError[\"code\"], message: string, details?: Record<string, unknown>): FileInputError {\n return { code, message, details };\n}\n\nfunction getSelectedFileLabel(file: File): string {\n switch (getSimplifiedMediaType(file)) {\n case \"image\": return \"Image selected\";\n case \"video\": return \"Video selected\";\n case \"audio\": return \"Audio selected\";\n default: return \"File selected\";\n }\n}\n\nexport function FileInput(props: FileInputProps) {\n const {\n acceptTypes,\n maxSizeMB,\n selectedFile,\n onChange,\n onError,\n isLoading = false,\n disabled = false,\n buttonLabel = \"Upload File\",\n className,\n uploadProgress = null,\n variant = \"default\",\n size = \"default\",\n cropConfig,\n videoMaxDurationSec,\n audioMaxDurationSec,\n defaultShowDetails = false,\n } = props;\n\n const fileInputRef = useRef<HTMLInputElement>(null);\n const lastPreviewUrlRef = useRef<string | null>(null);\n\n const revokeLastPreviewUrl = useCallback(() => {\n if (!lastPreviewUrlRef.current) return;\n try {\n URL.revokeObjectURL(lastPreviewUrlRef.current);\n } catch {}\n lastPreviewUrlRef.current = null;\n }, []);\n\n const makePreviewUrl = useCallback((blob: Blob) => {\n revokeLastPreviewUrl();\n const url = URL.createObjectURL(blob);\n lastPreviewUrlRef.current = url;\n return url;\n }, [revokeLastPreviewUrl]);\n\n useEffect(() => {\n return () => revokeLastPreviewUrl();\n }, [revokeLastPreviewUrl]);\n const uniqueId = useId();\n const inputId = `file-input-${uniqueId}`;\n\n const [internalSelected, setInternalSelected] = useState<File | null>(null);\n const fileValue = selectedFile !== undefined ? selectedFile : internalSelected;\n\n const [localError, setLocalError] = useState<FileInputError | null>(null);\n\n const [isCropperOpen, setIsCropperOpen] = useState(false);\n const [imageToCrop, setImageToCrop] = useState<string | null>(null);\n\n const [showDetails, setShowDetails] = useState(defaultShowDetails);\n\n const acceptString = useMemo(\n () => (acceptTypes.length ? acceptTypes.map((t) => MIME_MAP[t]).join(\", \") : undefined),\n [acceptTypes]\n );\n\n const detailsDescriptionParts = useMemo(() => {\n const parts: string[] = [];\n\n if (cropConfig) {\n const ratioDisplay = cropConfig.aspectRatioDisplay || `${cropConfig.aspectRatio.toFixed(2)}:1`;\n parts.push(`Image will be cropped to a ${ratioDisplay} rect (${cropConfig.outputWidth}x${cropConfig.outputHeight}px).`);\n }\n\n const sizeParts = acceptTypes\n .map((t) => (maxSizeMB[t] ? `${t.charAt(0).toUpperCase() + t.slice(1)} (${maxSizeMB[t]}MB)` : null))\n .filter(Boolean) as string[];\n\n if (sizeParts.length) parts.push(`Max sizes: ${sizeParts.join(\", \")}.`);\n\n if (videoMaxDurationSec) parts.push(`Max video duration: ${videoMaxDurationSec}s.`);\n if (audioMaxDurationSec) parts.push(`Max audio duration: ${audioMaxDurationSec}s.`);\n\n return parts;\n }, [acceptTypes, maxSizeMB, cropConfig, videoMaxDurationSec, audioMaxDurationSec]);\n\n const getUploadIcon = () => {\n if (acceptTypes.includes(\"image\")) return <Upload className=\"mr-2 icon-xs\" />;\n if (acceptTypes.includes(\"video\")) return <Film className=\"mr-2 icon-xs\" />;\n if (acceptTypes.includes(\"audio\")) return <Music className=\"mr-2 icon-xs\" />;\n return <Upload className=\"mr-2 icon-xs\" />;\n };\n\n const clearNative = () => {\n if (fileInputRef.current) fileInputRef.current.value = \"\";\n };\n\n const emitError = useCallback((e: FileInputError, type: SimplifiedMediaType = \"other\") => {\n setLocalError(e);\n onError?.(e);\n onChange({ type, error: e });\n }, [onError, onChange]);\n\n const handleClear = (e: React.MouseEvent<HTMLButtonElement>) => {\n e.stopPropagation();\n e.preventDefault();\n setLocalError(null);\n setInternalSelected(null);\n clearNative();\n onChange({ type: \"other\" });\n };\n\n const handleFileChange = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {\n const file = event.target.files?.[0];\n clearNative();\n setLocalError(null);\n\n if (!file) {\n setInternalSelected(null);\n onChange({ type: \"other\" });\n return;\n }\n\n const fileType = getSimplifiedMediaType(file);\n if (acceptTypes.length && !acceptTypes.includes(fileType)) {\n emitError(err(\"invalid_type\", `Invalid file type. Allowed: ${acceptTypes.join(\", \")}.`), fileType);\n return;\n }\n\n const maxBytes = (maxSizeMB[fileType] ?? Infinity) * 1024 * 1024;\n if (file.size > maxBytes) {\n emitError(err(\"too_large\", `File too large. Max ${maxSizeMB[fileType]}MB for ${fileType}.`, { size: file.size, maxBytes }), fileType);\n return;\n }\n\n if (fileType === \"video\" && videoMaxDurationSec) {\n const ok = await validateMediaDuration(file, videoMaxDurationSec);\n if (!ok) {\n emitError(err(\"too_long\", `Video too long. Max ${videoMaxDurationSec} seconds.`), fileType);\n return;\n }\n }\n\n if (fileType === \"audio\" && audioMaxDurationSec) {\n const ok = await validateMediaDuration(file, audioMaxDurationSec);\n if (!ok) {\n emitError(err(\"too_long\", `Audio too long. Max ${audioMaxDurationSec} seconds.`), fileType);\n return;\n }\n }\n\n // cropping path\n if (cropConfig && fileType === \"image\") {\n const reader = new FileReader();\n reader.onload = () => {\n setImageToCrop(reader.result as string);\n setIsCropperOpen(true);\n };\n reader.onerror = () => {\n emitError(err(\"read_failed\", \"Failed to read image for cropping.\"));\n };\n reader.readAsDataURL(file);\n setInternalSelected(file);\n return;\n }\n\n // normal selection\n setInternalSelected(file);\n const previewUrl = makePreviewUrl(file);\n onChange({ type: fileType, file, previewUrl, revokePreviewUrl: revokeLastPreviewUrl });\n }, [acceptTypes, maxSizeMB, cropConfig, videoMaxDurationSec, audioMaxDurationSec, emitError, makePreviewUrl, onChange, revokeLastPreviewUrl]);\n\n const handleCropComplete = (blob: Blob | null) => {\n setIsCropperOpen(false);\n\n const original = internalSelected;\n setImageToCrop(null);\n\n if (!blob) {\n emitError(err(\"crop_failed\", \"Cropping failed.\"), \"image\");\n return;\n }\n\n onChange({\n type: \"image\",\n file: original ?? undefined,\n blob,\n previewUrl: makePreviewUrl(blob),\n revokePreviewUrl: revokeLastPreviewUrl,\n });\n };\n\n const isUploading = typeof uploadProgress === \"number\" && isLoading;\n\n return (\n <div className={cn(\"relative w-full\", className)}>\n {localError && (\n <Alert variant=\"destructive\" className=\"mb-2\">\n <AlertTriangle className=\"icon-xs\" />\n <AlertDescription>{localError.message}</AlertDescription>\n </Alert>\n )}\n\n <Input\n id={inputId}\n type=\"file\"\n accept={acceptString}\n onChange={handleFileChange}\n className=\"hidden\"\n disabled={disabled || isLoading}\n ref={fileInputRef}\n />\n\n <div className=\"flex items-center gap-2\">\n <label htmlFor={inputId} className=\"w-full flex-grow\">\n <Button\n asChild\n disabled={disabled || isLoading}\n variant={variant}\n size={size}\n className={cn(\"w-full relative overflow-hidden cursor-pointer\", { \"icon-xl p-0\": size === \"icon\" })}\n >\n <span className=\"relative w-full h-full center-row\">\n {isUploading && (\n <Progress value={uploadProgress ?? 0} className=\"absolute left-0 top-0 h-full w-full z-0 bg-accent\" />\n )}\n\n <span className=\"z-10 center-row w-full\">\n {isLoading ? (\n <><Loader2 className=\"mr-2 spinner-xs\" /> {isUploading ? `${(uploadProgress ?? 0).toFixed(0)}%` : \"Processing...\"}</>\n ) : fileValue ? (\n <span className=\"flex items-center justify-between w-full\">\n <span className=\"truncate pr-2\">{getSelectedFileLabel(fileValue)}</span>\n <Button variant=\"ghost\" size=\"icon\" className=\"icon-sm hover:bg-destructive/20 shrink-0\" onClick={handleClear}>\n <X className=\"icon-xs\" />\n </Button>\n </span>\n ) : (\n <>\n {buttonLabel === \"Attach\"\n ? <><Paperclip className=\"mr-2 icon-xs\" /> {buttonLabel}</>\n : <>{getUploadIcon()} {buttonLabel}</>}\n </>\n )}\n </span>\n </span>\n </Button>\n </label>\n\n {detailsDescriptionParts.length > 0 && size !== \"icon\" && (\n <Button\n type=\"button\"\n variant=\"default\"\n size=\"icon\"\n onClick={() => setShowDetails((p) => !p)}\n aria-label=\"Show file processing details\"\n className=\"flex-shrink-0 icon-xl\"\n >\n <Info className=\"icon-sm\" />\n </Button>\n )}\n </div>\n\n {showDetails && detailsDescriptionParts.length > 0 && size !== \"icon\" && (\n <Card className=\"page-card w-full mt-2\">\n <div className=\"text-center p-2 space-y-0.5\">\n {detailsDescriptionParts.map((part, i) => (\n <p key={i} className=\"text-small font-bold\">{part}</p>\n ))}\n </div>\n </Card>\n )}\n\n {cropConfig && imageToCrop && (\n <ImageCropperModal\n isOpen={isCropperOpen}\n onClose={() => {\n setIsCropperOpen(false);\n setImageToCrop(null);\n }}\n imageSrc={imageToCrop}\n aspectRatio={cropConfig.aspectRatio}\n shape={cropConfig.shape}\n outputWidth={cropConfig.outputWidth}\n outputHeight={cropConfig.outputHeight}\n onCropComplete={handleCropComplete}\n />\n )}\n </div>\n );\n}\n"]}
1
+ {"version":3,"file":"file-input.js","sourceRoot":"","sources":["../../../src/react/components/file-input.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AACjF,OAAO,EAAE,sBAAsB,EAA4B,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAE,MAAM,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAA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W,EAAE,UAAU,CAAC,WAAW,EACnC,YAAY,EAAE,UAAU,CAAC,YAAY,EACrC,cAAc,EAAE,kBAAkB,GAClC,CACH,IACG,CACP,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState, useId } from \"react\";\nimport { getSimplifiedMediaType, type SimplifiedMediaType } from \"@ttt-productions/media-schemas\";\nimport { Alert, AlertDescription, Button, Card, Input, Progress, Spinner } from \"@ttt-productions/ui-core/react\";\nimport { cn } from \"@ttt-productions/ui-core\";\nimport { Info, X, Upload, Film, Music, Paperclip, AlertTriangle } from \"lucide-react\";\n\nimport type { FileInputError, FileInputProps } from \"../../types.js\";\nimport { validateMediaDuration } from \"../../lib/validate-media-duration.js\";\nimport { ImageCropperModal } from \"./image-cropper-modal.js\";\n\nconst MIME_MAP: Record<SimplifiedMediaType, string> = {\n image: \"image/jpeg, image/png, image/gif, image/webp, image/svg+xml, image/bmp, image/avif\",\n video: \"video/*, .mkv\",\n audio: \"audio/*\",\n other: \".pdf, .doc, .docx\"\n};\n\nfunction err(code: FileInputError[\"code\"], message: string, details?: Record<string, unknown>): FileInputError {\n return { code, message, details };\n}\n\nfunction getSelectedFileLabel(file: File): string {\n switch (getSimplifiedMediaType(file)) {\n case \"image\": return \"Image selected\";\n case \"video\": return \"Video selected\";\n case \"audio\": return \"Audio selected\";\n default: return \"File selected\";\n }\n}\n\nexport function FileInput(props: FileInputProps) {\n const {\n acceptTypes,\n maxSizeMB,\n selectedFile,\n onChange,\n onError,\n isLoading = false,\n disabled = false,\n buttonLabel = \"Upload File\",\n className,\n uploadProgress = null,\n variant = \"default\",\n size = \"default\",\n cropConfig,\n videoMaxDurationSec,\n audioMaxDurationSec,\n defaultShowDetails = false,\n } = props;\n\n const fileInputRef = useRef<HTMLInputElement>(null);\n const lastPreviewUrlRef = useRef<string | null>(null);\n\n const revokeLastPreviewUrl = useCallback(() => {\n if (!lastPreviewUrlRef.current) return;\n try {\n URL.revokeObjectURL(lastPreviewUrlRef.current);\n } catch {}\n lastPreviewUrlRef.current = null;\n }, []);\n\n const makePreviewUrl = useCallback((blob: Blob) => {\n revokeLastPreviewUrl();\n const url = URL.createObjectURL(blob);\n lastPreviewUrlRef.current = url;\n return url;\n }, [revokeLastPreviewUrl]);\n\n useEffect(() => {\n return () => revokeLastPreviewUrl();\n }, [revokeLastPreviewUrl]);\n const uniqueId = useId();\n const inputId = `file-input-${uniqueId}`;\n\n const [internalSelected, setInternalSelected] = useState<File | null>(null);\n const fileValue = selectedFile !== undefined ? selectedFile : internalSelected;\n\n const [localError, setLocalError] = useState<FileInputError | null>(null);\n\n const [isCropperOpen, setIsCropperOpen] = useState(false);\n const [imageToCrop, setImageToCrop] = useState<string | null>(null);\n\n const [showDetails, setShowDetails] = useState(defaultShowDetails);\n\n const acceptString = useMemo(\n () => (acceptTypes.length ? acceptTypes.map((t) => MIME_MAP[t]).join(\", \") : undefined),\n [acceptTypes]\n );\n\n const detailsDescriptionParts = useMemo(() => {\n const parts: string[] = [];\n\n if (cropConfig) {\n const ratioDisplay = cropConfig.aspectRatioDisplay || `${cropConfig.aspectRatio.toFixed(2)}:1`;\n parts.push(`Image will be cropped to a ${ratioDisplay} rect (${cropConfig.outputWidth}x${cropConfig.outputHeight}px).`);\n }\n\n const sizeParts = acceptTypes\n .map((t) => (maxSizeMB[t] ? `${t.charAt(0).toUpperCase() + t.slice(1)} (${maxSizeMB[t]}MB)` : null))\n .filter(Boolean) as string[];\n\n if (sizeParts.length) parts.push(`Max sizes: ${sizeParts.join(\", \")}.`);\n\n if (videoMaxDurationSec) parts.push(`Max video duration: ${videoMaxDurationSec}s.`);\n if (audioMaxDurationSec) parts.push(`Max audio duration: ${audioMaxDurationSec}s.`);\n\n return parts;\n }, [acceptTypes, maxSizeMB, cropConfig, videoMaxDurationSec, audioMaxDurationSec]);\n\n const getUploadIcon = () => {\n if (acceptTypes.includes(\"image\")) return <Upload className=\"mr-2 icon-xs\" />;\n if (acceptTypes.includes(\"video\")) return <Film className=\"mr-2 icon-xs\" />;\n if (acceptTypes.includes(\"audio\")) return <Music className=\"mr-2 icon-xs\" />;\n return <Upload className=\"mr-2 icon-xs\" />;\n };\n\n const clearNative = () => {\n if (fileInputRef.current) fileInputRef.current.value = \"\";\n };\n\n const emitError = useCallback((e: FileInputError, type: SimplifiedMediaType = \"other\") => {\n setLocalError(e);\n onError?.(e);\n onChange({ type, error: e });\n }, [onError, onChange]);\n\n const handleClear = (e: React.MouseEvent<HTMLButtonElement>) => {\n e.stopPropagation();\n e.preventDefault();\n setLocalError(null);\n setInternalSelected(null);\n clearNative();\n onChange({ type: \"other\" });\n };\n\n const handleFileChange = useCallback(async (event: React.ChangeEvent<HTMLInputElement>) => {\n const file = event.target.files?.[0];\n clearNative();\n setLocalError(null);\n\n if (!file) {\n setInternalSelected(null);\n onChange({ type: \"other\" });\n return;\n }\n\n const fileType = getSimplifiedMediaType(file);\n if (acceptTypes.length && !acceptTypes.includes(fileType)) {\n emitError(err(\"invalid_type\", `Invalid file type. Allowed: ${acceptTypes.join(\", \")}.`), fileType);\n return;\n }\n\n const maxBytes = (maxSizeMB[fileType] ?? Infinity) * 1024 * 1024;\n if (file.size > maxBytes) {\n emitError(err(\"too_large\", `File too large. Max ${maxSizeMB[fileType]}MB for ${fileType}.`, { size: file.size, maxBytes }), fileType);\n return;\n }\n\n if (fileType === \"video\" && videoMaxDurationSec) {\n const ok = await validateMediaDuration(file, videoMaxDurationSec);\n if (!ok) {\n emitError(err(\"too_long\", `Video too long. Max ${videoMaxDurationSec} seconds.`), fileType);\n return;\n }\n }\n\n if (fileType === \"audio\" && audioMaxDurationSec) {\n const ok = await validateMediaDuration(file, audioMaxDurationSec);\n if (!ok) {\n emitError(err(\"too_long\", `Audio too long. Max ${audioMaxDurationSec} seconds.`), fileType);\n return;\n }\n }\n\n // cropping path\n if (cropConfig && fileType === \"image\") {\n const reader = new FileReader();\n reader.onload = () => {\n setImageToCrop(reader.result as string);\n setIsCropperOpen(true);\n };\n reader.onerror = () => {\n emitError(err(\"read_failed\", \"Failed to read image for cropping.\"));\n };\n reader.readAsDataURL(file);\n setInternalSelected(file);\n return;\n }\n\n // normal selection\n setInternalSelected(file);\n const previewUrl = makePreviewUrl(file);\n onChange({ type: fileType, file, previewUrl, revokePreviewUrl: revokeLastPreviewUrl });\n }, [acceptTypes, maxSizeMB, cropConfig, videoMaxDurationSec, audioMaxDurationSec, emitError, makePreviewUrl, onChange, revokeLastPreviewUrl]);\n\n const handleCropComplete = (blob: Blob | null) => {\n setIsCropperOpen(false);\n\n const original = internalSelected;\n setImageToCrop(null);\n\n if (!blob) {\n emitError(err(\"crop_failed\", \"Cropping failed.\"), \"image\");\n return;\n }\n\n onChange({\n type: \"image\",\n file: original ?? undefined,\n blob,\n previewUrl: makePreviewUrl(blob),\n revokePreviewUrl: revokeLastPreviewUrl,\n });\n };\n\n const isUploading = typeof uploadProgress === \"number\" && isLoading;\n\n return (\n <div className={cn(\"relative w-full\", className)}>\n {localError && (\n <Alert variant=\"destructive\" className=\"mb-2\">\n <AlertTriangle className=\"icon-xs\" />\n <AlertDescription>{localError.message}</AlertDescription>\n </Alert>\n )}\n\n <Input\n id={inputId}\n type=\"file\"\n accept={acceptString}\n onChange={handleFileChange}\n className=\"hidden\"\n disabled={disabled || isLoading}\n ref={fileInputRef}\n />\n\n <div className=\"flex items-center gap-2\">\n <label htmlFor={inputId} className=\"w-full flex-grow\">\n <Button\n asChild\n disabled={disabled || isLoading}\n variant={variant}\n size={size}\n className={cn(\"w-full relative overflow-hidden cursor-pointer\", { \"icon-xl p-0\": size === \"icon\" })}\n >\n <span className=\"relative w-full h-full center-row\">\n {isUploading && (\n <Progress value={uploadProgress ?? 0} className=\"absolute left-0 top-0 h-full w-full z-0 bg-accent\" />\n )}\n\n <span className=\"z-10 center-row w-full\">\n {isLoading ? (\n <><Spinner size=\"xs\" className=\"mr-2\" /> {isUploading ? `${(uploadProgress ?? 0).toFixed(0)}%` : \"Processing...\"}</>\n ) : fileValue ? (\n <span className=\"flex items-center justify-between w-full\">\n <span className=\"truncate pr-2\">{getSelectedFileLabel(fileValue)}</span>\n <Button variant=\"ghost\" size=\"icon\" className=\"icon-sm hover:bg-destructive/20 shrink-0\" onClick={handleClear}>\n <X className=\"icon-xs\" />\n </Button>\n </span>\n ) : (\n <>\n {buttonLabel === \"Attach\"\n ? <><Paperclip className=\"mr-2 icon-xs\" /> {buttonLabel}</>\n : <>{getUploadIcon()} {buttonLabel}</>}\n </>\n )}\n </span>\n </span>\n </Button>\n </label>\n\n {detailsDescriptionParts.length > 0 && size !== \"icon\" && (\n <Button\n type=\"button\"\n variant=\"default\"\n size=\"icon\"\n onClick={() => setShowDetails((p) => !p)}\n aria-label=\"Show file processing details\"\n className=\"flex-shrink-0 icon-xl\"\n >\n <Info className=\"icon-sm\" />\n </Button>\n )}\n </div>\n\n {showDetails && detailsDescriptionParts.length > 0 && size !== \"icon\" && (\n <Card className=\"page-card w-full mt-2\">\n <div className=\"text-center p-2 space-y-0.5\">\n {detailsDescriptionParts.map((part, i) => (\n <p key={i} className=\"text-small font-bold\">{part}</p>\n ))}\n </div>\n </Card>\n )}\n\n {cropConfig && imageToCrop && (\n <ImageCropperModal\n isOpen={isCropperOpen}\n onClose={() => {\n setIsCropperOpen(false);\n setImageToCrop(null);\n }}\n imageSrc={imageToCrop}\n aspectRatio={cropConfig.aspectRatio}\n shape={cropConfig.shape}\n outputWidth={cropConfig.outputWidth}\n outputHeight={cropConfig.outputHeight}\n onCropComplete={handleCropComplete}\n />\n )}\n </div>\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"image-cropper-modal.d.ts","sourceRoot":"","sources":["../../../src/react/components/image-cropper-modal.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAgC,MAAM,OAAO,CAAC;AAOrD,MAAM,WAAW,sBAAsB;IACrC,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,CAAC,WAAW,EAAE,IAAI,GAAG,IAAI,KAAK,IAAI,CAAC;CACpD;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,sBAAsB,4BA0D9D"}
1
+ {"version":3,"file":"image-cropper-modal.d.ts","sourceRoot":"","sources":["../../../src/react/components/image-cropper-modal.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAgC,MAAM,OAAO,CAAC;AAOrD,MAAM,WAAW,sBAAsB;IACrC,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,CAAC,WAAW,EAAE,IAAI,GAAG,IAAI,KAAK,IAAI,CAAC;CACpD;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,sBAAsB,4BA2D9D"}
@@ -3,7 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { useState, useCallback } from "react";
4
4
  import Cropper from "react-easy-crop";
5
5
  const CropperComponent = Cropper;
6
- import { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription, Slider } from "@ttt-productions/ui-core/react";
6
+ import { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription, Slider, useAsyncAction } from "@ttt-productions/ui-core/react";
7
7
  import { getCroppedImg } from "../../lib/image-utils.js";
8
8
  export function ImageCropperModal(props) {
9
9
  const { isOpen, onClose, imageSrc, aspectRatio, shape, outputWidth, outputHeight, onCropComplete } = props;
@@ -13,20 +13,17 @@ export function ImageCropperModal(props) {
13
13
  const handleCropComplete = useCallback((_a, pixels) => {
14
14
  setCroppedAreaPixels(pixels);
15
15
  }, []);
16
- const handleConfirm = useCallback(async () => {
16
+ // Confirm renders the crop, then emits it. It is pending for that whole window and
17
+ // ignores a repeat click, so a double click can never emit (and upload) twice.
18
+ const confirm = useAsyncAction(async () => {
17
19
  if (!imageSrc || !croppedAreaPixels)
18
20
  return;
19
- try {
20
- const blob = await getCroppedImg(imageSrc, croppedAreaPixels, 0, { horizontal: false, vertical: false }, outputWidth, outputHeight);
21
- onCropComplete(blob);
22
- onClose();
23
- }
24
- catch {
25
- onCropComplete(null);
26
- }
27
- }, [imageSrc, croppedAreaPixels, onCropComplete, onClose, outputWidth, outputHeight]);
21
+ const blob = await getCroppedImg(imageSrc, croppedAreaPixels, 0, { horizontal: false, vertical: false }, outputWidth, outputHeight);
22
+ onCropComplete(blob);
23
+ onClose();
24
+ }, { onError: () => onCropComplete(null) });
28
25
  if (!imageSrc)
29
26
  return null;
30
- return (_jsx(Dialog, { open: isOpen, onOpenChange: (open) => !open && onClose(), children: _jsxs(DialogContent, { className: "max-w-md", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Crop Image" }), _jsx(DialogDescription, { children: "Adjust the crop area and zoom level to select the desired portion of your image." })] }), _jsx("div", { className: "relative h-64 w-full bg-muted", children: _jsx(CropperComponent, { image: imageSrc, crop: crop, zoom: zoom, aspect: aspectRatio, cropShape: shape, showGrid: false, onCropChange: setCrop, onZoomChange: setZoom, onCropComplete: handleCropComplete }) }), _jsxs("div", { className: "stack-2", children: [_jsx("label", { htmlFor: "zoom", className: "text-small", children: "Zoom" }), _jsx(Slider, { id: "zoom", min: 1, max: 3, step: 0.1, value: [zoom], onValueChange: (v) => setZoom(v[0]) })] }), _jsxs(DialogFooter, { className: "flex-row justify-end gap-2", children: [_jsx(Button, { variant: "destructive", onClick: onClose, children: "Cancel" }), _jsx(Button, { variant: "default", onClick: handleConfirm, children: "Confirm" })] })] }) }));
27
+ return (_jsx(Dialog, { open: isOpen, onOpenChange: (open) => !open && !confirm.pending && onClose(), children: _jsxs(DialogContent, { className: "max-w-md", children: [_jsxs(DialogHeader, { children: [_jsx(DialogTitle, { children: "Crop Image" }), _jsx(DialogDescription, { children: "Adjust the crop area and zoom level to select the desired portion of your image." })] }), _jsx("div", { className: "relative h-64 w-full bg-muted", children: _jsx(CropperComponent, { image: imageSrc, crop: crop, zoom: zoom, aspect: aspectRatio, cropShape: shape, showGrid: false, onCropChange: setCrop, onZoomChange: setZoom, onCropComplete: handleCropComplete }) }), _jsxs("div", { className: "stack-2", children: [_jsx("label", { htmlFor: "zoom", className: "text-small", children: "Zoom" }), _jsx(Slider, { id: "zoom", min: 1, max: 3, step: 0.1, value: [zoom], onValueChange: (v) => setZoom(v[0]) })] }), _jsxs(DialogFooter, { className: "flex-row justify-end gap-2", children: [_jsx(Button, { variant: "destructive", onClick: onClose, disabled: confirm.pending, children: "Cancel" }), _jsx(Button, { variant: "default", onClick: () => void confirm.run(), pending: confirm.pending, children: "Confirm" })] })] }) }));
31
28
  }
32
29
  //# sourceMappingURL=image-cropper-modal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"image-cropper-modal.js","sourceRoot":"","sources":["../../../src/react/components/image-cropper-modal.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAc,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACrD,OAAO,OAAsB,MAAM,iBAAiB,CAAC;AAErD,MAAM,gBAAgB,GAAG,OAA8C,CAAC;AACxE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AACnJ,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAazD,MAAM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AC,MAAM,IAAC,IAAI,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,IAAI,OAAO,EAAE,YAC9D,MAAC,aAAa,IAAC,SAAS,EAAC,UAAU,aACjC,MAAC,YAAY,eACX,KAAC,WAAW,6BAAyB,EACrC,KAAC,iBAAiB,mGAAqG,IAC1G,EAEf,cAAK,SAAS,EAAC,+BAA+B,YAC5C,KAAC,gBAAgB,IACf,KAAK,EAAE,QAAQ,EACf,IAAI,EAAE,IAAI,EACV,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,WAAW,EACnB,SAAS,EAAE,KAAK,EAChB,QAAQ,EAAE,KAAK,EACf,YAAY,EAAE,OAAO,EACrB,YAAY,EAAE,OAAO,EACrB,cAAc,EAAE,kBAAkB,GAClC,GACE,EAEN,eAAK,SAAS,EAAC,SAAS,aACtB,gBAAO,OAAO,EAAC,MAAM,EAAC,SAAS,EAAC,YAAY,qBAAa,EACzD,KAAC,MAAM,IAAC,EAAE,EAAC,MAAM,EAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,IAAI,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAI,IAC/F,EAEN,MAAC,YAAY,IAAC,SAAS,EAAC,4BAA4B,aAClD,KAAC,MAAM,IAAC,OAAO,EAAC,aAAa,EAAC,OAAO,EAAE,OAAO,uBAAiB,EAC/D,KAAC,MAAM,IAAC,OAAO,EAAC,SAAS,EAAC,OAAO,EAAE,aAAa,wBAAkB,IACrD,IACD,GACT,CACV,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport React, { useState, useCallback } from \"react\";\nimport Cropper, { type Area } from \"react-easy-crop\";\n \nconst CropperComponent = Cropper as unknown as React.ComponentType<any>;\nimport { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription, Slider } from \"@ttt-productions/ui-core/react\";\nimport { getCroppedImg } from \"../../lib/image-utils.js\";\n\nexport interface ImageCropperModalProps {\n isOpen: boolean;\n onClose: () => void;\n imageSrc: string | null;\n aspectRatio: number;\n shape: \"rect\" | \"round\";\n outputWidth: number;\n outputHeight: number;\n onCropComplete: (croppedBlob: Blob | null) => void;\n}\n\nexport function ImageCropperModal(props: ImageCropperModalProps) {\n const { isOpen, onClose, imageSrc, aspectRatio, shape, outputWidth, outputHeight, onCropComplete } = props;\n\n const [crop, setCrop] = useState({ x: 0, y: 0 });\n const [zoom, setZoom] = useState(1);\n const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);\n\n const handleCropComplete = useCallback((_a: Area, pixels: Area) => {\n setCroppedAreaPixels(pixels);\n }, []);\n\n const handleConfirm = useCallback(async () => {\n if (!imageSrc || !croppedAreaPixels) return;\n try {\n const blob = await getCroppedImg(imageSrc, croppedAreaPixels, 0, { horizontal: false, vertical: false }, outputWidth, outputHeight);\n onCropComplete(blob);\n onClose();\n } catch {\n onCropComplete(null);\n }\n }, [imageSrc, croppedAreaPixels, onCropComplete, onClose, outputWidth, outputHeight]);\n\n if (!imageSrc) return null;\n\n return (\n <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>\n <DialogContent className=\"max-w-md\">\n <DialogHeader>\n <DialogTitle>Crop Image</DialogTitle>\n <DialogDescription>Adjust the crop area and zoom level to select the desired portion of your image.</DialogDescription>\n </DialogHeader>\n\n <div className=\"relative h-64 w-full bg-muted\">\n <CropperComponent\n image={imageSrc}\n crop={crop}\n zoom={zoom}\n aspect={aspectRatio}\n cropShape={shape}\n showGrid={false}\n onCropChange={setCrop}\n onZoomChange={setZoom}\n onCropComplete={handleCropComplete}\n />\n </div>\n\n <div className=\"stack-2\">\n <label htmlFor=\"zoom\" className=\"text-small\">Zoom</label>\n <Slider id=\"zoom\" min={1} max={3} step={0.1} value={[zoom]} onValueChange={(v) => setZoom(v[0])} />\n </div>\n\n <DialogFooter className=\"flex-row justify-end gap-2\">\n <Button variant=\"destructive\" onClick={onClose}>Cancel</Button>\n <Button variant=\"default\" onClick={handleConfirm}>Confirm</Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n"]}
1
+ {"version":3,"file":"image-cropper-modal.js","sourceRoot":"","sources":["../../../src/react/components/image-cropper-modal.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAc,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACrD,OAAO,OAAsB,MAAM,iBAAiB,CAAC;AAErD,MAAM,gBAAgB,GAAG,OAA8C,CAAC;AACxE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACnK,OAAO,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAazD,MAAM,UAAU,iBAAiB,CAAC,KAA6B;IAC7D,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,cAAc,EAAE,GAAG,KAAK,CAAC;IAE3G,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IACjD,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IACpC,MAAM,CAAC,iBAAiB,EAAE,oBAAoB,CAAC,GAAG,QAAQ,CAAc,IAAI,CAAC,CAAC;IAE9E,MAAM,kBAAkB,GAAG,WAAW,CAAC,CAAC,EAAQ,EAAE,MAAY,EAAE,EAAE;QAChE,oBAAoB,CAAC,MAAM,CAAC,CAAC;IAC/B,CAAC,EA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AC,MAAM,EAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,IAAI,CAAC,EAAE,aAAa,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAI,IAC/F,EAEN,MAAC,YAAY,IAAC,SAAS,EAAC,4BAA4B,aAClD,KAAC,MAAM,IAAC,OAAO,EAAC,aAAa,EAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,OAAO,uBAAiB,EAC1F,KAAC,MAAM,IAAC,OAAO,EAAC,SAAS,EAAC,OAAO,EAAE,GAAG,EAAE,CAAC,KAAK,OAAO,CAAC,GAAG,EAAE,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,wBAAkB,IAC1F,IACD,GACT,CACV,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport React, { useState, useCallback } from \"react\";\nimport Cropper, { type Area } from \"react-easy-crop\";\n \nconst CropperComponent = Cropper as unknown as React.ComponentType<any>;\nimport { Button, Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription, Slider, useAsyncAction } from \"@ttt-productions/ui-core/react\";\nimport { getCroppedImg } from \"../../lib/image-utils.js\";\n\nexport interface ImageCropperModalProps {\n isOpen: boolean;\n onClose: () => void;\n imageSrc: string | null;\n aspectRatio: number;\n shape: \"rect\" | \"round\";\n outputWidth: number;\n outputHeight: number;\n onCropComplete: (croppedBlob: Blob | null) => void;\n}\n\nexport function ImageCropperModal(props: ImageCropperModalProps) {\n const { isOpen, onClose, imageSrc, aspectRatio, shape, outputWidth, outputHeight, onCropComplete } = props;\n\n const [crop, setCrop] = useState({ x: 0, y: 0 });\n const [zoom, setZoom] = useState(1);\n const [croppedAreaPixels, setCroppedAreaPixels] = useState<Area | null>(null);\n\n const handleCropComplete = useCallback((_a: Area, pixels: Area) => {\n setCroppedAreaPixels(pixels);\n }, []);\n\n // Confirm renders the crop, then emits it. It is pending for that whole window and\n // ignores a repeat click, so a double click can never emit (and upload) twice.\n const confirm = useAsyncAction(\n async () => {\n if (!imageSrc || !croppedAreaPixels) return;\n const blob = await getCroppedImg(imageSrc, croppedAreaPixels, 0, { horizontal: false, vertical: false }, outputWidth, outputHeight);\n onCropComplete(blob);\n onClose();\n },\n { onError: () => onCropComplete(null) },\n );\n\n if (!imageSrc) return null;\n\n return (\n <Dialog open={isOpen} onOpenChange={(open) => !open && !confirm.pending && onClose()}>\n <DialogContent className=\"max-w-md\">\n <DialogHeader>\n <DialogTitle>Crop Image</DialogTitle>\n <DialogDescription>Adjust the crop area and zoom level to select the desired portion of your image.</DialogDescription>\n </DialogHeader>\n\n <div className=\"relative h-64 w-full bg-muted\">\n <CropperComponent\n image={imageSrc}\n crop={crop}\n zoom={zoom}\n aspect={aspectRatio}\n cropShape={shape}\n showGrid={false}\n onCropChange={setCrop}\n onZoomChange={setZoom}\n onCropComplete={handleCropComplete}\n />\n </div>\n\n <div className=\"stack-2\">\n <label htmlFor=\"zoom\" className=\"text-small\">Zoom</label>\n <Slider id=\"zoom\" min={1} max={3} step={0.1} value={[zoom]} onValueChange={(v) => setZoom(v[0])} />\n </div>\n\n <DialogFooter className=\"flex-row justify-end gap-2\">\n <Button variant=\"destructive\" onClick={onClose} disabled={confirm.pending}>Cancel</Button>\n <Button variant=\"default\" onClick={() => void confirm.run()} pending={confirm.pending}>Confirm</Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"media-input.d.ts","sourceRoot":"","sources":["../../../src/react/components/media-input.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAoG,MAAM,OAAO,CAAC;AAoBzH,OAAO,KAAK,EAAkB,gBAAgB,EAAE,eAAe,EAAqB,MAAM,gBAAgB,CAAC;AAoH3G,eAAO,MAAM,UAAU,0FAsnBrB,CAAC"}
1
+ {"version":3,"file":"media-input.d.ts","sourceRoot":"","sources":["../../../src/react/components/media-input.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAoG,MAAM,OAAO,CAAC;AAqBzH,OAAO,KAAK,EAAkB,gBAAgB,EAAE,eAAe,EAAqB,MAAM,gBAAgB,CAAC;AAoH3G,eAAO,MAAM,UAAU,0FA0oBrB,CAAC"}
@@ -2,8 +2,8 @@
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from "react";
4
4
  import { getSimplifiedMediaType } from "@ttt-productions/media-schemas";
5
- import { Info, Camera, Mic, Video, Upload, X, Loader2, Plus } from "lucide-react";
6
- import { Alert, AlertDescription, Button, Card, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, Input, Progress, } from "@ttt-productions/ui-core/react";
5
+ import { Info, Camera, Mic, Video, Upload, X, Plus } from "lucide-react";
6
+ import { Alert, AlertDescription, Button, Card, DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, Input, Progress, Spinner, } from "@ttt-productions/ui-core/react";
7
7
  import { cn } from "@ttt-productions/ui-core";
8
8
  import { MediaPreview } from "@ttt-productions/media-viewer/react";
9
9
  import { DEFAULT_PROGRESS_BAR_MIN_BYTES } from "../../index.js";
@@ -139,6 +139,8 @@ export const MediaInput = forwardRef(function MediaInput(props, ref) {
139
139
  // via the trigger button; the imperative `openSelection()` handle opens it when
140
140
  // more than one action is enabled.
141
141
  const [menuOpen, setMenuOpen] = useState(false);
142
+ const [validating, setValidating] = useState(false);
143
+ const [emittedSize, setEmittedSize] = useState(null);
142
144
  // Prevent memory leaks from object URLs
143
145
  const lastObjectUrlRef = useRef(null);
144
146
  const revokeLastObjectUrl = useCallback(() => {
@@ -200,13 +202,15 @@ export const MediaInput = forwardRef(function MediaInput(props, ref) {
200
202
  const rawKind = payload.meta?.kind;
201
203
  const mediaKind = rawKind === "image" || rawKind === "video" || rawKind === "audio" ? rawKind : "image";
202
204
  const resolvedSpec = resolveActiveSpec(spec, mediaKind);
205
+ if (payload.file)
206
+ setEmittedSize(payload.file.size);
203
207
  onChange({ spec: resolvedSpec, ...payload });
204
208
  }, [onChange, spec]);
205
209
  const fail = useCallback((e) => {
206
210
  setLocalError(e);
207
211
  emit({ error: e });
208
212
  }, [emit]);
209
- const handleSelected = useCallback(async (file, previewUrl, action = undefined) => {
213
+ const validateAndEmit = useCallback(async (file, previewUrl, action = undefined) => {
210
214
  setLocalError(null);
211
215
  // Defense-in-depth: normalize the content type before any downstream
212
216
  // handling. Recorder/capture files carry their declared kind; a picker
@@ -311,6 +315,18 @@ export const MediaInput = forwardRef(function MediaInput(props, ref) {
311
315
  }
312
316
  emit({ file: safeFile, previewUrl, meta, claim });
313
317
  }, [spec, cropSpec, emit, fail]);
318
+ // A picked, captured, or recorded file is validated (type, meta, duration,
319
+ // dimensions, crop) before it is emitted. The trigger shows pending for that
320
+ // whole window, so a second pick cannot race the first.
321
+ const handleSelected = useCallback(async (file, previewUrl, action = undefined) => {
322
+ setValidating(true);
323
+ try {
324
+ await validateAndEmit(file, previewUrl, action);
325
+ }
326
+ finally {
327
+ setValidating(false);
328
+ }
329
+ }, [validateAndEmit]);
314
330
  const onPick = useCallback(async (e) => {
315
331
  const file = e.target.files?.[0];
316
332
  e.target.value = "";
@@ -355,10 +371,13 @@ export const MediaInput = forwardRef(function MediaInput(props, ref) {
355
371
  const isPreparing = phase === 'preparing' && isLoading;
356
372
  const isFinalizing = phase === 'finalizing' && isLoading;
357
373
  const sizeThreshold = progressBarMinBytes ?? DEFAULT_PROGRESS_BAR_MIN_BYTES;
374
+ // Consumers usually pass selectedFile={null} once the file is handed off, so
375
+ // the bar judges the size of the file this input emitted.
376
+ const trackedSize = selectedFile?.size ?? emittedSize;
358
377
  const showRealBar = isUploading &&
359
378
  typeof percent === 'number' &&
360
- !!selectedFile &&
361
- selectedFile.size >= sizeThreshold;
379
+ trackedSize !== null &&
380
+ trackedSize >= sizeThreshold;
362
381
  const canPick = spec.client?.allowPick ?? true;
363
382
  const canPhoto = spec.client?.allowCapturePhoto ?? true;
364
383
  const canRecVideo = spec.client?.allowRecordVideo ?? true;
@@ -408,13 +427,13 @@ export const MediaInput = forwardRef(function MediaInput(props, ref) {
408
427
  const actions = useMemo(() => {
409
428
  const list = [];
410
429
  if (canPick)
411
- list.push({ kind: "pick", label: "Choose file", icon: _jsx(Upload, { className: "mr-2 icon-xs" }) });
430
+ list.push({ kind: "pick", label: "Choose file", icon: _jsx(Upload, { className: "icon-xs" }) });
412
431
  if (canPhoto)
413
- list.push({ kind: "photo", label: "Take photo", icon: _jsx(Camera, { className: "mr-2 icon-xs" }) });
432
+ list.push({ kind: "photo", label: "Take photo", icon: _jsx(Camera, { className: "icon-xs" }) });
414
433
  if (canRecVideo)
415
- list.push({ kind: "recordVideo", label: "Record video", icon: _jsx(Video, { className: "mr-2 icon-xs" }) });
434
+ list.push({ kind: "recordVideo", label: "Record video", icon: _jsx(Video, { className: "icon-xs" }) });
416
435
  if (canRecAudio)
417
- list.push({ kind: "recordAudio", label: "Record audio", icon: _jsx(Mic, { className: "mr-2 icon-xs" }) });
436
+ list.push({ kind: "recordAudio", label: "Record audio", icon: _jsx(Mic, { className: "icon-xs" }) });
418
437
  return list;
419
438
  }, [canPick, canPhoto, canRecVideo, canRecAudio]);
420
439
  /** Label & icon for the single trigger button. */
@@ -422,8 +441,8 @@ export const MediaInput = forwardRef(function MediaInput(props, ref) {
422
441
  if (actions.length === 1)
423
442
  return actions[0].icon;
424
443
  if (buttonLabel !== "Add media")
425
- return _jsx(Upload, { className: "mr-2 icon-xs" });
426
- return _jsx(Plus, { className: "mr-2 icon-xs" });
444
+ return _jsx(Upload, { className: "icon-xs" });
445
+ return _jsx(Plus, { className: "icon-xs" });
427
446
  }, [actions, buttonLabel]);
428
447
  const triggerLabel = useMemo(() => {
429
448
  // If the consumer explicitly set a custom buttonLabel, always respect it.
@@ -449,16 +468,16 @@ export const MediaInput = forwardRef(function MediaInput(props, ref) {
449
468
  * Never touches the hidden input directly, so none of the gates are bypassed.
450
469
  */
451
470
  const openSelection = useCallback(() => {
452
- if (disabled || isLoading || actions.length === 0)
471
+ if (disabled || isLoading || validating || actions.length === 0)
453
472
  return;
454
473
  if (actions.length === 1) {
455
474
  void runAction(actions[0].kind);
456
475
  return;
457
476
  }
458
477
  setMenuOpen(true);
459
- }, [disabled, isLoading, actions, runAction]);
478
+ }, [disabled, isLoading, validating, actions, runAction]);
460
479
  useImperativeHandle(ref, () => ({ openSelection }), [openSelection]);
461
- return (_jsxs(Card, { className: cn("p-3", className), children: [_jsx(Input, { id: `media-pick-${id}`, ref: pickerRef, type: "file", accept: acceptAttr, className: "hidden", onChange: onPick, disabled: disabled || isLoading }), selectedFile && !isLoading ? (_jsxs("div", { className: "mb-2 space-y-2", children: [previewKind === "image" || previewKind === "video" || previewKind === "audio" ? (_jsx("div", { className: cn("relative w-full rounded-md bg-muted", previewKind === "audio" ? "p-2" : "h-48 overflow-hidden"), children: _jsx(MediaPreview, { url: selectedFile, type: previewKind, mime: selectedFile.type, controls: true, className: previewKind === "audio" ? "w-full" : "h-full w-full" }) })) : null, _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "text-sm truncate flex-1", children: selectedFileLabel }), onClear && (_jsx(Button, { variant: "ghost", size: "icon", className: "icon-sm hover:bg-destructive/20 shrink-0", onClick: onClear, children: _jsx(X, { className: "icon-xs" }) }))] })] })) : null, isLoading ? (_jsxs("div", { className: "flex items-center gap-2 mb-2", children: [_jsx(Loader2, { className: "icon-xs spinner-xs" }), _jsx("span", { className: "text-sm text-muted-foreground", children: isPreparing
480
+ return (_jsxs(Card, { className: cn("p-3", className), children: [_jsx(Input, { id: `media-pick-${id}`, ref: pickerRef, type: "file", accept: acceptAttr, className: "hidden", onChange: onPick, disabled: disabled || isLoading || validating }), selectedFile && !isLoading ? (_jsxs("div", { className: "mb-2 space-y-2", children: [previewKind === "image" || previewKind === "video" || previewKind === "audio" ? (_jsx("div", { className: cn("relative w-full rounded-md bg-muted", previewKind === "audio" ? "p-2" : "h-48 overflow-hidden"), children: _jsx(MediaPreview, { url: selectedFile, type: previewKind, mime: selectedFile.type, controls: true, className: previewKind === "audio" ? "w-full" : "h-full w-full" }) })) : null, _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "text-sm truncate flex-1", children: selectedFileLabel }), onClear && (_jsx(Button, { variant: "ghost", size: "icon", className: "icon-sm hover:bg-destructive/20 shrink-0", onClick: onClear, children: _jsx(X, { className: "icon-xs" }) }))] })] })) : null, isLoading ? (_jsxs("div", { className: "flex items-center gap-2 mb-2", children: [_jsx(Spinner, { size: "xs" }), _jsx("span", { className: "text-sm text-muted-foreground", children: isPreparing
462
481
  ? "Preparing..."
463
482
  : isUploading && showRealBar
464
483
  ? `Uploading ${Math.round(percent ?? 0)}%...`
@@ -468,9 +487,9 @@ export const MediaInput = forwardRef(function MediaInput(props, ref) {
468
487
  ? "Finalizing..."
469
488
  : "Finalizing..." }), (isPreparing || isUploading) && onCancel ? (_jsx(Button, { type: "button", variant: "ghost", size: "icon", className: "icon-sm hover:bg-destructive/20 shrink-0 ml-auto", onClick: onCancel, "aria-label": "Cancel upload", children: _jsx(X, { className: "icon-xs" }) })) : null] })) : null, showRealBar ? _jsx(Progress, { value: percent ?? 0, className: "mb-2 h-1.5" }) : null, _jsxs("div", { className: "flex flex-wrap gap-2", children: [actions.length <= 1 ? (
470
489
  /* Single action (or none): plain button, no dropdown */
471
- _jsxs(Button, { variant: "default", onClick: handleTriggerClick, disabled: disabled || isLoading || actions.length === 0, children: [triggerIcon, triggerLabel] })) : (
490
+ _jsx(Button, { variant: "default", onClick: handleTriggerClick, disabled: disabled || isLoading || actions.length === 0, pending: validating, icon: triggerIcon, children: triggerLabel })) : (
472
491
  /* Multiple actions: dropdown menu */
473
- _jsxs(DropdownMenu, { open: menuOpen, onOpenChange: setMenuOpen, children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsxs(Button, { variant: "default", disabled: disabled || isLoading, children: [triggerIcon, triggerLabel] }) }), _jsx(DropdownMenuContent, { align: "start", children: actions.map((a) => (_jsxs(DropdownMenuItem, { onClick: () => void runAction(a.kind), children: [a.icon, a.label] }, a.kind))) })] })), showInfoToggle ? (_jsxs(Button, { variant: "outline", onClick: () => setShowInfo((v) => !v), disabled: disabled || isLoading, children: [_jsx(Info, { className: "mr-2 icon-xs" }), showInfo ? "Hide info" : "Info"] })) : null] }), showInfo && showInfoToggle ? (_jsxs("div", { className: "mt-3 space-y-2", children: [infoNotes.length > 0 ? (_jsx("ul", { className: "text-xs text-muted-foreground list-disc pl-4 space-y-1", children: infoNotes.map((n, i) => (_jsx("li", { children: n }, i))) })) : null, specHasConstraints ? _jsx(MediaConstraintsHint, { spec: spec }) : null] })) : null, localError && (_jsx(Alert, { variant: "destructive", className: "mt-3", children: _jsx(AlertDescription, { children: localError.message }) })), cropSpec && (_jsx(ImageCropperModal, { isOpen: cropOpen, onClose: () => {
492
+ _jsxs(DropdownMenu, { open: menuOpen, onOpenChange: setMenuOpen, children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsx(Button, { variant: "default", disabled: disabled || isLoading, pending: validating, icon: triggerIcon, children: triggerLabel }) }), _jsx(DropdownMenuContent, { align: "start", children: actions.map((a) => (_jsx(DropdownMenuItem, { onClick: () => void runAction(a.kind), icon: a.icon, children: a.label }, a.kind))) })] })), showInfoToggle ? (_jsxs(Button, { variant: "outline", onClick: () => setShowInfo((v) => !v), disabled: disabled || isLoading, children: [_jsx(Info, { className: "mr-2 icon-xs" }), showInfo ? "Hide info" : "Info"] })) : null] }), showInfo && showInfoToggle ? (_jsxs("div", { className: "mt-3 space-y-2", children: [infoNotes.length > 0 ? (_jsx("ul", { className: "text-xs text-muted-foreground list-disc pl-4 space-y-1", children: infoNotes.map((n, i) => (_jsx("li", { children: n }, i))) })) : null, specHasConstraints ? _jsx(MediaConstraintsHint, { spec: spec }) : null] })) : null, localError && (_jsx(Alert, { variant: "destructive", className: "mt-3", children: _jsx(AlertDescription, { children: localError.message }) })), cropSpec && (_jsx(ImageCropperModal, { isOpen: cropOpen, onClose: () => {
474
493
  setCropOpen(false);
475
494
  setCropSrc(null);
476
495
  }, imageSrc: cropSrc, aspectRatio: cropSpec.aspectRatio, shape: cropSpec.shape ?? "rect", outputWidth: cropSpec.outputWidth, outputHeight: cropSpec.outputHeight, onCropComplete: onCropComplete })), _jsx(PhotoCaptureModal, { open: photoOpen, facingMode: spec.client?.cameraFacingMode ?? "user", onCapture: onPhotoCapture, onClose: () => setPhotoOpen(false) }), _jsx(RecordDialog, { open: recordOpen, onOpenChange: setRecordOpen, initialKind: recordKind, canPhoto: canPhoto, canRecVideo: canRecVideo, canRecAudio: canRecAudio, cameraFacingMode: spec.client?.cameraFacingMode, maxRecordDurationSec: spec.client?.maxRecordDurationSec, disabled: disabled, isLoading: isLoading, onRecorded: async (file, url, recordedKind) => {