@umodeapporg/ui 0.35.0 → 0.36.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/components/Form/ControlledViewToggle.d.ts +2 -1
- package/dist/components/Form/ControlledViewToggle.js +9 -1
- package/dist/components/Form/ControlledViewToggle.js.map +1 -1
- package/dist/components/Upload/UploaderComponent.d.ts +19 -0
- package/dist/components/Upload/UploaderComponent.js +61 -32
- package/dist/components/Upload/UploaderComponent.js.map +1 -1
- package/dist/locales/en/ui.json.d.ts +4 -1
- package/dist/locales/en/ui.json.js +1 -1
- package/dist/locales/index.d.ts +6 -0
- package/dist/locales/pt/ui.json.d.ts +4 -1
- package/dist/locales/pt/ui.json.js +1 -1
- package/package.json +1 -1
|
@@ -6,7 +6,8 @@ export interface IControlledViewToggleOption<V extends string = string> {
|
|
|
6
6
|
icon?: SymbolCodepoints;
|
|
7
7
|
/**
|
|
8
8
|
* Option name. Rendered as visible text when the option has no icon or when
|
|
9
|
-
* `showLabels` is on; otherwise shown as the option's tooltip
|
|
9
|
+
* `showLabels` is on; otherwise shown as the option's tooltip and kept as
|
|
10
|
+
* screen-reader-only text, so the button is still named.
|
|
10
11
|
*/
|
|
11
12
|
label: string;
|
|
12
13
|
/**
|
|
@@ -141,7 +141,15 @@ const ControlledViewToggle = (props) => {
|
|
|
141
141
|
),
|
|
142
142
|
children: [
|
|
143
143
|
option.icon && /* @__PURE__ */ jsx(MaterialSymbol, { icon: option.icon, size: styles.icon }),
|
|
144
|
-
|
|
144
|
+
/* @__PURE__ */ jsx(
|
|
145
|
+
"span",
|
|
146
|
+
{
|
|
147
|
+
className: classNames(
|
|
148
|
+
showText ? ["whitespace-nowrap font-medium", styles.textClass] : "sr-only"
|
|
149
|
+
),
|
|
150
|
+
children: option.label
|
|
151
|
+
}
|
|
152
|
+
),
|
|
145
153
|
renderOptionCounter(option, isActive)
|
|
146
154
|
]
|
|
147
155
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ControlledViewToggle.js","sources":["../../../src/components/Form/ControlledViewToggle.tsx"],"sourcesContent":["import { Fragment, useEffect, useMemo, useRef } from 'react';\nimport classNames from 'classnames';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport { useUiNavigation } from '@/components/Navigation/UiNavigationContext';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport LoadingSpinner from '@/components/UI/LoadingSpinner';\nimport { MaterialSymbol, SymbolCodepoints } from '@/components/UI/MaterialSymbol';\nimport { formatNumber } from '@/helpers/formatHelpers';\nimport { uiLogger } from '@/helpers/uiLogger';\nimport {\n claimUrlParam,\n ownsUrlParam,\n queueUrlParamUpdate,\n releaseUrlParam,\n TABS_URL_PARAM,\n URL_PARAM_PRIORITY,\n} from '@/helpers/urlParamSync';\n\nexport type TControlledViewToggleSize = 'sm' | 'md';\n\nexport interface IControlledViewToggleOption<V extends string = string> {\n value: V;\n /** Optional icon; options without one render their label as text instead. */\n icon?: SymbolCodepoints;\n /**\n * Option name. Rendered as visible text when the option has no icon or when\n * `showLabels` is on; otherwise shown as the option's tooltip.\n */\n label: string;\n /**\n * Replaces the label in the tooltip when the option needs to explain itself, not just be named.\n * The label stays the accessible name, so it must remain short.\n */\n tooltip?: string;\n /** Counter badge next to the label, as in ControlledTabs. Hidden when null/undefined. */\n count?: number | null;\n /** Replaces the counter badge with a spinner while this option's data loads. */\n loading?: boolean;\n}\n\ninterface IControlledViewToggleBaseProps<V extends string = string> {\n options: Array<IControlledViewToggleOption<V>>;\n /** Renders every option's label as visible text next to its icon. */\n showLabels?: boolean;\n /** `md` (default) pairs with page-level controls; `sm` matches compact filter bars. */\n size?: TControlledViewToggleSize;\n /** Disables every option, keeping the current selection visible. */\n disabled?: boolean;\n /**\n * Mirrors the selection in the URL, on by default like `ControlledTabs`. Turn it off for toggles\n * that hold form state (a weekday picker, an AND/OR combinator) or that live inside a drawer,\n * where the selection is not page state and should not reach the URL.\n */\n syncWithUrl?: boolean;\n /**\n * Query param used when `syncWithUrl` is on, defaults to `view`. A page holding more than one\n * synced toggle must give each a unique key: the first one mounted keeps the param and the others\n * stop writing (with a warning in development) instead of overwriting each other.\n *\n * Lifecycle mirrors `ControlledTabs`: on mount an existing valid param wins over `value` and is\n * pushed to the host through `onChange`; with no param (or an invalid one) the current value is\n * stamped into the URL right away. From there on the host selection is the authority and every\n * change rewrites the param, always preserving the other params and replacing the history entry.\n * In `multiple` mode values are comma separated and an empty selection removes the param.\n */\n urlParamKey?: string;\n className?: string;\n}\n\ninterface IControlledViewToggleSingleProps<V extends string = string> extends IControlledViewToggleBaseProps<V> {\n multiple?: false;\n value: V;\n onChange: (value: V) => void;\n}\n\ninterface IControlledViewToggleMultipleProps<V extends string = string> extends IControlledViewToggleBaseProps<V> {\n multiple: true;\n value: Array<V>;\n /** Receives the whole next selection, which may be empty. */\n onChange: (values: Array<V>) => void;\n}\n\nexport type TControlledViewToggleProps<V extends string = string> =\n IControlledViewToggleSingleProps<V> | IControlledViewToggleMultipleProps<V>;\n\nconst DEFAULT_URL_PARAM_KEY = 'view';\n\nconst SIZE_STYLES: Record<\n TControlledViewToggleSize,\n { container: string; button: string; textClass: string; inactive: string; icon: number }\n> = {\n sm: {\n // Inner radius mirrors the container radius minus its padding, so the active\n // segment stays concentric with the outer border.\n container: 'h-9 gap-1 rounded-xl',\n button: 'h-7 rounded-lg px-2.5',\n textClass: 'text-xs',\n // One step darker than md so the segments match the neighbouring controls\n // in the compact filter bars this size is used by.\n inactive: 'text-foreground-muted hover:bg-muted-hover hover:text-foreground',\n icon: 16,\n },\n // leading-[18px] matches the icon height so icon-only, text-only and\n // icon + text options all keep the same button height.\n md: {\n container: 'gap-1 rounded-lg shadow-sm',\n button: 'rounded-md px-2.5 py-1.5',\n textClass: 'text-sm leading-[18px]',\n inactive: 'text-foreground-subtle hover:bg-muted-hover hover:text-foreground-muted',\n icon: 18,\n },\n};\n\n/**\n * Segmented toggle for switching between visualization modes (e.g. cards /\n * list / grouped). Options can be icon-only, text-only or icon + text, and the\n * component is generic over the option value union so hosts keep their own mode\n * types. Clicking the already-active option fires `onChange` again, letting\n * hosts react to re-selection (e.g. reopening a configuration dialog).\n *\n * With `multiple`, it becomes a segmented multi-select: `value` is the selected\n * array, clicking an option adds or removes it, and `onChange` receives the\n * whole next selection, which may be empty.\n */\nconst ControlledViewToggle = <V extends string = string>(props: TControlledViewToggleProps<V>) => {\n const {\n options,\n showLabels = false,\n size = 'md',\n disabled = false,\n syncWithUrl = true,\n urlParamKey = DEFAULT_URL_PARAM_KEY,\n className,\n } = props;\n const styles = SIZE_STYLES[size];\n const { searchParams, setSearchParams } = useUiNavigation();\n\n const safeOptions = useMemo(() => (Array.isArray(options) ? options : []), [options]);\n const selectedValues = props.multiple ? (Array.isArray(props.value) ? props.value : []) : [props.value];\n const serializedValue = selectedValues.join(',');\n\n const hasReadUrlSelectionRef = useRef(false);\n const pendingUrlSelectionRef = useRef<string | null>(null);\n const ownerIdRef = useRef<object>({});\n\n const isUrlParamReserved = urlParamKey === TABS_URL_PARAM;\n const isUrlSyncEnabled = syncWithUrl && !isUrlParamReserved;\n\n useEffect(() => {\n if (!syncWithUrl) return;\n\n if (isUrlParamReserved) {\n uiLogger.warn(\n `[ControlledViewToggle] \"${TABS_URL_PARAM}\" belongs to ControlledTabs. ` +\n 'Give this toggle its own urlParamKey: it will not write to the URL.',\n );\n return;\n }\n\n const ownerId = ownerIdRef.current;\n\n if (!claimUrlParam(urlParamKey, ownerId, URL_PARAM_PRIORITY.viewToggle)) {\n uiLogger.warn(\n `[ControlledViewToggle] More than one control syncs \"${urlParamKey}\". ` +\n 'Give each one a unique urlParamKey: this instance will not write to the URL.',\n );\n }\n\n return () => releaseUrlParam(urlParamKey, ownerId);\n }, [syncWithUrl, isUrlParamReserved, urlParamKey]);\n\n // Um efeito só, em duas fases. Na montagem o parâmetro manda: existindo um valor válido ele é\n // aplicado no host, e a escrita fica suspensa até o host adotá-lo (senão o valor padrão seria\n // gravado por cima do que veio na URL). Não existindo, o valor atual é carimbado na hora. Depois\n // disso a seleção do host é a autoridade e a URL apenas a reflete.\n useEffect(() => {\n if (!isUrlSyncEnabled || !ownsUrlParam(urlParamKey, ownerIdRef.current)) return;\n\n const rawParam = searchParams.get(urlParamKey) ?? '';\n\n if (pendingUrlSelectionRef.current !== null) {\n if (serializedValue === pendingUrlSelectionRef.current) pendingUrlSelectionRef.current = null;\n return;\n }\n\n if (!hasReadUrlSelectionRef.current) {\n hasReadUrlSelectionRef.current = true;\n\n const optionValues = new Set(safeOptions.map((option) => option.value));\n const urlValues = rawParam\n .split(',')\n .map((rawValue) => rawValue.trim())\n .filter((rawValue): rawValue is V => optionValues.has(rawValue as V));\n\n if (urlValues.length) {\n const urlSelection = urlValues.join(',');\n if (urlSelection !== serializedValue) {\n pendingUrlSelectionRef.current = urlSelection;\n if (props.multiple) props.onChange(urlValues);\n else props.onChange(urlValues[0]);\n }\n return;\n }\n }\n\n if (rawParam === serializedValue) return;\n\n queueUrlParamUpdate(urlParamKey, serializedValue, setSearchParams);\n }, [isUrlSyncEnabled, urlParamKey, searchParams, safeOptions, serializedValue, setSearchParams, props]);\n\n const handleSelectOption = (optionValue: V) => {\n if (!props.multiple) {\n props.onChange(optionValue);\n return;\n }\n\n const currentValues = Array.isArray(props.value) ? props.value : [];\n props.onChange(\n currentValues.includes(optionValue)\n ? currentValues.filter((selectedValue) => selectedValue !== optionValue)\n : [...currentValues, optionValue],\n );\n };\n\n const renderOptionCounter = (option: IControlledViewToggleOption<V>, isActive: boolean) => {\n if (option.loading) return <LoadingSpinner size={3} />;\n if (option.count === undefined || option.count === null) return null;\n\n return (\n <span\n className={classNames(\n 'inline-flex min-w-[18px] items-center justify-center rounded-full px-1.5 py-px text-[11px] font-medium leading-none',\n isActive ? 'bg-glass/25 text-white' : 'bg-muted-hover text-foreground-subtle',\n )}\n >\n {formatNumber(option.count)}\n </span>\n );\n };\n\n return (\n <div\n className={classNames(\n 'inline-flex shrink-0 items-center border border-border bg-surface p-1',\n styles.container,\n className,\n )}\n >\n {safeOptions.map((option) => {\n const isActive = selectedValues.includes(option.value);\n const showText = showLabels || !option.icon;\n\n const button = (\n <ControlledButton\n defaultHtmlButton\n aria-pressed={isActive}\n disabled={disabled}\n onClick={() => handleSelectOption(option.value)}\n className={classNames(\n 'flex items-center justify-center gap-1.5 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-brand-border disabled:cursor-not-allowed',\n styles.button,\n isActive ? 'bg-brand text-brand-fg shadow-sm' : styles.inactive,\n )}\n >\n {option.icon && <MaterialSymbol icon={option.icon} size={styles.icon} />}\n {showText && (\n <span className={classNames('whitespace-nowrap font-medium', styles.textClass)}>{option.label}</span>\n )}\n {renderOptionCounter(option, isActive)}\n </ControlledButton>\n );\n\n // The tooltip only adds value when the label is not already visible.\n return showText ? (\n <Fragment key={option.value}>{button}</Fragment>\n ) : (\n <ControlledTooltip key={option.value} content={option.tooltip ?? option.label}>\n {button}\n </ControlledTooltip>\n );\n })}\n </div>\n );\n};\n\nexport default ControlledViewToggle;\n"],"names":[],"mappings":";;;;;;;;;;;AAsFA,MAAM,wBAAwB;AAE9B,MAAM,cAGF;AAAA,EACF,IAAI;AAAA;AAAA;AAAA,IAGF,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,WAAW;AAAA;AAAA;AAAA,IAGX,UAAU;AAAA,IACV,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA,EAIR,IAAI;AAAA,IACF,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,UAAU;AAAA,IACV,MAAM;AAAA,EAAA;AAEV;AAaA,MAAM,uBAAuB,CAA4B,UAAyC;AAChG,QAAM;AAAA,IACJ;AAAA,IACA,aAAa;AAAA,IACb,OAAO;AAAA,IACP,WAAW;AAAA,IACX,cAAc;AAAA,IACd,cAAc;AAAA,IACd;AAAA,EAAA,IACE;AACJ,QAAM,SAAS,YAAY,IAAI;AAC/B,QAAM,EAAE,cAAc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Ae,SAAS,OAAO,KAAK;AACrD,cAAM,WAAW,cAAc,CAAC,OAAO;AAEvC,cAAM,SACJ;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,mBAAiB;AAAA,YACjB,gBAAc;AAAA,YACd;AAAA,YACA,SAAS,MAAM,mBAAmB,OAAO,KAAK;AAAA,YAC9C,WAAW;AAAA,cACT;AAAA,cACA,OAAO;AAAA,cACP,WAAW,qCAAqC,OAAO;AAAA,YAAA;AAAA,YAGxD,UAAA;AAAA,cAAA,OAAO,4BAAS,gBAAA,EAAe,MAAM,OAAO,MAAM,MAAM,OAAO,KAAA,CAAM;AAAA,cACrE,YACC,oBAAC,QAAA,EAAK,WAAW,WAAW,iCAAiC,OAAO,SAAS,GAAI,UAAA,OAAO,MAAA,CAAM;AAAA,cAE/F,oBAAoB,QAAQ,QAAQ;AAAA,YAAA;AAAA,UAAA;AAAA,QAAA;AAKzC,eAAO,WACL,oBAAC,UAAA,EAA6B,UAAA,UAAf,OAAO,KAAe,IAErC,oBAAC,mBAAA,EAAqC,SAAS,OAAO,WAAW,OAAO,OACrE,UAAA,OAAA,GADqB,OAAO,KAE/B;AAAA,MAEJ,CAAC;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
1
|
+
{"version":3,"file":"ControlledViewToggle.js","sources":["../../../src/components/Form/ControlledViewToggle.tsx"],"sourcesContent":["import { Fragment, useEffect, useMemo, useRef } from 'react';\nimport classNames from 'classnames';\n\nimport ControlledButton from '@/components/Form/ControlledButton';\nimport { useUiNavigation } from '@/components/Navigation/UiNavigationContext';\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\nimport LoadingSpinner from '@/components/UI/LoadingSpinner';\nimport { MaterialSymbol, SymbolCodepoints } from '@/components/UI/MaterialSymbol';\nimport { formatNumber } from '@/helpers/formatHelpers';\nimport { uiLogger } from '@/helpers/uiLogger';\nimport {\n claimUrlParam,\n ownsUrlParam,\n queueUrlParamUpdate,\n releaseUrlParam,\n TABS_URL_PARAM,\n URL_PARAM_PRIORITY,\n} from '@/helpers/urlParamSync';\n\nexport type TControlledViewToggleSize = 'sm' | 'md';\n\nexport interface IControlledViewToggleOption<V extends string = string> {\n value: V;\n /** Optional icon; options without one render their label as text instead. */\n icon?: SymbolCodepoints;\n /**\n * Option name. Rendered as visible text when the option has no icon or when\n * `showLabels` is on; otherwise shown as the option's tooltip and kept as\n * screen-reader-only text, so the button is still named.\n */\n label: string;\n /**\n * Replaces the label in the tooltip when the option needs to explain itself, not just be named.\n * The label stays the accessible name, so it must remain short.\n */\n tooltip?: string;\n /** Counter badge next to the label, as in ControlledTabs. Hidden when null/undefined. */\n count?: number | null;\n /** Replaces the counter badge with a spinner while this option's data loads. */\n loading?: boolean;\n}\n\ninterface IControlledViewToggleBaseProps<V extends string = string> {\n options: Array<IControlledViewToggleOption<V>>;\n /** Renders every option's label as visible text next to its icon. */\n showLabels?: boolean;\n /** `md` (default) pairs with page-level controls; `sm` matches compact filter bars. */\n size?: TControlledViewToggleSize;\n /** Disables every option, keeping the current selection visible. */\n disabled?: boolean;\n /**\n * Mirrors the selection in the URL, on by default like `ControlledTabs`. Turn it off for toggles\n * that hold form state (a weekday picker, an AND/OR combinator) or that live inside a drawer,\n * where the selection is not page state and should not reach the URL.\n */\n syncWithUrl?: boolean;\n /**\n * Query param used when `syncWithUrl` is on, defaults to `view`. A page holding more than one\n * synced toggle must give each a unique key: the first one mounted keeps the param and the others\n * stop writing (with a warning in development) instead of overwriting each other.\n *\n * Lifecycle mirrors `ControlledTabs`: on mount an existing valid param wins over `value` and is\n * pushed to the host through `onChange`; with no param (or an invalid one) the current value is\n * stamped into the URL right away. From there on the host selection is the authority and every\n * change rewrites the param, always preserving the other params and replacing the history entry.\n * In `multiple` mode values are comma separated and an empty selection removes the param.\n */\n urlParamKey?: string;\n className?: string;\n}\n\ninterface IControlledViewToggleSingleProps<V extends string = string> extends IControlledViewToggleBaseProps<V> {\n multiple?: false;\n value: V;\n onChange: (value: V) => void;\n}\n\ninterface IControlledViewToggleMultipleProps<V extends string = string> extends IControlledViewToggleBaseProps<V> {\n multiple: true;\n value: Array<V>;\n /** Receives the whole next selection, which may be empty. */\n onChange: (values: Array<V>) => void;\n}\n\nexport type TControlledViewToggleProps<V extends string = string> =\n IControlledViewToggleSingleProps<V> | IControlledViewToggleMultipleProps<V>;\n\nconst DEFAULT_URL_PARAM_KEY = 'view';\n\nconst SIZE_STYLES: Record<\n TControlledViewToggleSize,\n { container: string; button: string; textClass: string; inactive: string; icon: number }\n> = {\n sm: {\n // Inner radius mirrors the container radius minus its padding, so the active\n // segment stays concentric with the outer border.\n container: 'h-9 gap-1 rounded-xl',\n button: 'h-7 rounded-lg px-2.5',\n textClass: 'text-xs',\n // One step darker than md so the segments match the neighbouring controls\n // in the compact filter bars this size is used by.\n inactive: 'text-foreground-muted hover:bg-muted-hover hover:text-foreground',\n icon: 16,\n },\n // leading-[18px] matches the icon height so icon-only, text-only and\n // icon + text options all keep the same button height.\n md: {\n container: 'gap-1 rounded-lg shadow-sm',\n button: 'rounded-md px-2.5 py-1.5',\n textClass: 'text-sm leading-[18px]',\n inactive: 'text-foreground-subtle hover:bg-muted-hover hover:text-foreground-muted',\n icon: 18,\n },\n};\n\n/**\n * Segmented toggle for switching between visualization modes (e.g. cards /\n * list / grouped). Options can be icon-only, text-only or icon + text, and the\n * component is generic over the option value union so hosts keep their own mode\n * types. Clicking the already-active option fires `onChange` again, letting\n * hosts react to re-selection (e.g. reopening a configuration dialog).\n *\n * With `multiple`, it becomes a segmented multi-select: `value` is the selected\n * array, clicking an option adds or removes it, and `onChange` receives the\n * whole next selection, which may be empty.\n */\nconst ControlledViewToggle = <V extends string = string>(props: TControlledViewToggleProps<V>) => {\n const {\n options,\n showLabels = false,\n size = 'md',\n disabled = false,\n syncWithUrl = true,\n urlParamKey = DEFAULT_URL_PARAM_KEY,\n className,\n } = props;\n const styles = SIZE_STYLES[size];\n const { searchParams, setSearchParams } = useUiNavigation();\n\n const safeOptions = useMemo(() => (Array.isArray(options) ? options : []), [options]);\n const selectedValues = props.multiple ? (Array.isArray(props.value) ? props.value : []) : [props.value];\n const serializedValue = selectedValues.join(',');\n\n const hasReadUrlSelectionRef = useRef(false);\n const pendingUrlSelectionRef = useRef<string | null>(null);\n const ownerIdRef = useRef<object>({});\n\n const isUrlParamReserved = urlParamKey === TABS_URL_PARAM;\n const isUrlSyncEnabled = syncWithUrl && !isUrlParamReserved;\n\n useEffect(() => {\n if (!syncWithUrl) return;\n\n if (isUrlParamReserved) {\n uiLogger.warn(\n `[ControlledViewToggle] \"${TABS_URL_PARAM}\" belongs to ControlledTabs. ` +\n 'Give this toggle its own urlParamKey: it will not write to the URL.',\n );\n return;\n }\n\n const ownerId = ownerIdRef.current;\n\n if (!claimUrlParam(urlParamKey, ownerId, URL_PARAM_PRIORITY.viewToggle)) {\n uiLogger.warn(\n `[ControlledViewToggle] More than one control syncs \"${urlParamKey}\". ` +\n 'Give each one a unique urlParamKey: this instance will not write to the URL.',\n );\n }\n\n return () => releaseUrlParam(urlParamKey, ownerId);\n }, [syncWithUrl, isUrlParamReserved, urlParamKey]);\n\n // Um efeito só, em duas fases. Na montagem o parâmetro manda: existindo um valor válido ele é\n // aplicado no host, e a escrita fica suspensa até o host adotá-lo (senão o valor padrão seria\n // gravado por cima do que veio na URL). Não existindo, o valor atual é carimbado na hora. Depois\n // disso a seleção do host é a autoridade e a URL apenas a reflete.\n useEffect(() => {\n if (!isUrlSyncEnabled || !ownsUrlParam(urlParamKey, ownerIdRef.current)) return;\n\n const rawParam = searchParams.get(urlParamKey) ?? '';\n\n if (pendingUrlSelectionRef.current !== null) {\n if (serializedValue === pendingUrlSelectionRef.current) pendingUrlSelectionRef.current = null;\n return;\n }\n\n if (!hasReadUrlSelectionRef.current) {\n hasReadUrlSelectionRef.current = true;\n\n const optionValues = new Set(safeOptions.map((option) => option.value));\n const urlValues = rawParam\n .split(',')\n .map((rawValue) => rawValue.trim())\n .filter((rawValue): rawValue is V => optionValues.has(rawValue as V));\n\n if (urlValues.length) {\n const urlSelection = urlValues.join(',');\n if (urlSelection !== serializedValue) {\n pendingUrlSelectionRef.current = urlSelection;\n if (props.multiple) props.onChange(urlValues);\n else props.onChange(urlValues[0]);\n }\n return;\n }\n }\n\n if (rawParam === serializedValue) return;\n\n queueUrlParamUpdate(urlParamKey, serializedValue, setSearchParams);\n }, [isUrlSyncEnabled, urlParamKey, searchParams, safeOptions, serializedValue, setSearchParams, props]);\n\n const handleSelectOption = (optionValue: V) => {\n if (!props.multiple) {\n props.onChange(optionValue);\n return;\n }\n\n const currentValues = Array.isArray(props.value) ? props.value : [];\n props.onChange(\n currentValues.includes(optionValue)\n ? currentValues.filter((selectedValue) => selectedValue !== optionValue)\n : [...currentValues, optionValue],\n );\n };\n\n const renderOptionCounter = (option: IControlledViewToggleOption<V>, isActive: boolean) => {\n if (option.loading) return <LoadingSpinner size={3} />;\n if (option.count === undefined || option.count === null) return null;\n\n return (\n <span\n className={classNames(\n 'inline-flex min-w-[18px] items-center justify-center rounded-full px-1.5 py-px text-[11px] font-medium leading-none',\n isActive ? 'bg-glass/25 text-white' : 'bg-muted-hover text-foreground-subtle',\n )}\n >\n {formatNumber(option.count)}\n </span>\n );\n };\n\n return (\n <div\n className={classNames(\n 'inline-flex shrink-0 items-center border border-border bg-surface p-1',\n styles.container,\n className,\n )}\n >\n {safeOptions.map((option) => {\n const isActive = selectedValues.includes(option.value);\n const showText = showLabels || !option.icon;\n\n const button = (\n <ControlledButton\n defaultHtmlButton\n aria-pressed={isActive}\n disabled={disabled}\n onClick={() => handleSelectOption(option.value)}\n className={classNames(\n 'flex items-center justify-center gap-1.5 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-brand-border disabled:cursor-not-allowed',\n styles.button,\n isActive ? 'bg-brand text-brand-fg shadow-sm' : styles.inactive,\n )}\n >\n {option.icon && <MaterialSymbol icon={option.icon} size={styles.icon} />}\n {/* Icon only: the label stays the button's name for assistive tech (the icon is decorative). */}\n <span\n className={classNames(\n showText ? ['whitespace-nowrap font-medium', styles.textClass] : 'sr-only',\n )}\n >\n {option.label}\n </span>\n {renderOptionCounter(option, isActive)}\n </ControlledButton>\n );\n\n // The tooltip only adds value when the label is not already visible.\n return showText ? (\n <Fragment key={option.value}>{button}</Fragment>\n ) : (\n <ControlledTooltip key={option.value} content={option.tooltip ?? option.label}>\n {button}\n </ControlledTooltip>\n );\n })}\n </div>\n );\n};\n\nexport default ControlledViewToggle;\n"],"names":[],"mappings":";;;;;;;;;;;AAuFA,MAAM,wBAAwB;AAE9B,MAAM,cAGF;AAAA,EACF,IAAI;AAAA;AAAA;AAAA,IAGF,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,WAAW;AAAA;AAAA;AAAA,IAGX,UAAU;AAAA,IACV,MAAM;AAAA,EAAA;AAAA;AAAA;AAAA,EAIR,IAAI;AAAA,IACF,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,WAAW;AAAA,IACX,UAAU;AAAA,IACV,MAAM;AAAA,EAAA;AAEV;AAaA,MAAM,uBAAuB,CAA4B,UAAyC;AAChG,QAAM;AAAA,IACJ;AAAA,IACA,aAAa;AAAA,IACb,OAAO;AAAA,IACP,WAAW;AAAA,IACX,cAAc;AAAA,IACd,cAAc;AAAA,IACd;AAAA,EAAA,IACE;AACJ,QAAM,SAAS,YAAY,IAAI;AAC/B,QAAM,EAAE,cAAc,gBAAA,IAAoB,gBAAA;AAE1C,QAAM,cAAc,QAAQ,MAAO,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAA,GAAK,CAAC,OAAO,CAAC;AACpF,QAAM,iBAAiB,MAAM,WAAY,MAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,QAAQ,CAAA,IAAM,CAAC,MAAM,KAAK;AACtG,QAAM,kBAAkB,eAAe,KAAK,GAAG;AAE/C,QAAM,yBAAyB,OAAO,KAAK;AAC3C,QAAM,yBAAyB,OAAsB,IAAI;AACzD,QAAM,aAAa,OAAe,EAAE;AAEpC,QAAM,qBAAqB,gBAAg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,cAEtE;AAAA,gBAAC;AAAA,gBAAA;AAAA,kBACC,WAAW;AAAA,oBACT,WAAW,CAAC,iCAAiC,OAAO,SAAS,IAAI;AAAA,kBAAA;AAAA,kBAGlE,UAAA,OAAO;AAAA,gBAAA;AAAA,cAAA;AAAA,cAET,oBAAoB,QAAQ,QAAQ;AAAA,YAAA;AAAA,UAAA;AAAA,QAAA;AAKzC,eAAO,WACL,oBAAC,UAAA,EAA6B,UAAA,UAAf,OAAO,KAAe,IAErC,oBAAC,mBAAA,EAAqC,SAAS,OAAO,WAAW,OAAO,OACrE,UAAA,OAAA,GADqB,OAAO,KAE/B;AAAA,MAEJ,CAAC;AAAA,IAAA;AAAA,EAAA;AAGP;"}
|
|
@@ -1,6 +1,17 @@
|
|
|
1
1
|
import * as React from 'react';
|
|
2
2
|
interface IUploaderComponentProps {
|
|
3
|
+
/**
|
|
4
|
+
* MIME types (`image/png`) or extensions (`.pdf`) the uploader accepts. An EMPTY list accepts
|
|
5
|
+
* any type, minus `blockedExtensions`, and stops filtering the system file picker.
|
|
6
|
+
*/
|
|
3
7
|
allowedTypes: Array<string>;
|
|
8
|
+
/** Extensions (`.exe`) refused on every path (picker, drop and paste), whatever `allowedTypes` says. */
|
|
9
|
+
blockedExtensions?: Array<string>;
|
|
10
|
+
/**
|
|
11
|
+
* Replaces the generated "allowed formats ... up to N MB" line, for a policy that a list of
|
|
12
|
+
* extensions cannot say well. The host composes it from `t()`.
|
|
13
|
+
*/
|
|
14
|
+
formatsHint?: string;
|
|
4
15
|
handleFilesSelected: (files: Array<File>) => void;
|
|
5
16
|
multiple?: boolean;
|
|
6
17
|
className?: string;
|
|
@@ -24,6 +35,14 @@ interface IUploaderComponentProps {
|
|
|
24
35
|
* a larger area and should be the single drop target, avoiding duplicated uploads.
|
|
25
36
|
*/
|
|
26
37
|
disableDragDrop?: boolean;
|
|
38
|
+
/**
|
|
39
|
+
* When true, every chosen file reaches `handleFilesSelected` unchecked (type, size and
|
|
40
|
+
* `blockedExtensions` are ignored) and the component raises no toast. Use when the host already
|
|
41
|
+
* validates the same files from other entry points and must report local refusals and server
|
|
42
|
+
* failures in ONE message: only one toast is on screen at a time, so two validators erase each
|
|
43
|
+
* other's reasons.
|
|
44
|
+
*/
|
|
45
|
+
disableFileValidation?: boolean;
|
|
27
46
|
}
|
|
28
47
|
declare const UploaderComponent: React.FC<IUploaderComponentProps>;
|
|
29
48
|
export default UploaderComponent;
|
|
@@ -6,8 +6,20 @@ import ControlledTooltip from "../UI/ControlledTooltip.js";
|
|
|
6
6
|
import { useNotification } from "../../hooks/useNotification.js";
|
|
7
7
|
import ControlledButton from "../Form/ControlledButton.js";
|
|
8
8
|
import { MaterialSymbol } from "../UI/MaterialSymbol/index.js";
|
|
9
|
+
const normalizeExtension = (extension) => {
|
|
10
|
+
const lowered = extension.trim().toLowerCase();
|
|
11
|
+
return lowered.startsWith(".") ? lowered : `.${lowered}`;
|
|
12
|
+
};
|
|
13
|
+
const extensionOfFileName = (fileName) => {
|
|
14
|
+
const cleanName = fileName.trim().replace(/[.\s]+$/, "");
|
|
15
|
+
const dotIndex = cleanName.lastIndexOf(".");
|
|
16
|
+
return dotIndex > 0 ? cleanName.slice(dotIndex).toLowerCase() : "";
|
|
17
|
+
};
|
|
18
|
+
const fileNamesOf = (files) => files.map((file) => file.name).join(", ");
|
|
9
19
|
const UploaderComponent = ({
|
|
10
20
|
allowedTypes,
|
|
21
|
+
blockedExtensions,
|
|
22
|
+
formatsHint,
|
|
11
23
|
handleFilesSelected,
|
|
12
24
|
multiple = false,
|
|
13
25
|
className,
|
|
@@ -15,7 +27,8 @@ const UploaderComponent = ({
|
|
|
15
27
|
maxSizeMB = 1,
|
|
16
28
|
autoUpload = false,
|
|
17
29
|
variant = "default",
|
|
18
|
-
disableDragDrop = false
|
|
30
|
+
disableDragDrop = false,
|
|
31
|
+
disableFileValidation = false
|
|
19
32
|
}) => {
|
|
20
33
|
const { t } = useTranslation("ui");
|
|
21
34
|
const { notify } = useNotification();
|
|
@@ -25,10 +38,39 @@ const UploaderComponent = ({
|
|
|
25
38
|
const [files, setFiles] = useState([]);
|
|
26
39
|
const [isDragging, setIsDragging] = useState(false);
|
|
27
40
|
const inputId = useId();
|
|
41
|
+
const acceptedTypes = Array.isArray(allowedTypes) ? allowedTypes : [];
|
|
42
|
+
const acceptsAnyType = acceptedTypes.length === 0;
|
|
43
|
+
const pickerAccept = acceptsAnyType ? void 0 : acceptedTypes.join(", ");
|
|
44
|
+
const blockedExtensionSet = new Set((blockedExtensions ?? []).map(normalizeExtension));
|
|
28
45
|
const matchesAllowedType = (file) => {
|
|
29
|
-
if (
|
|
46
|
+
if (acceptsAnyType) return true;
|
|
47
|
+
if (acceptedTypes.includes(file.type)) return true;
|
|
30
48
|
const extension = "." + (file.name.split(".").pop() ?? "").toLowerCase();
|
|
31
|
-
return
|
|
49
|
+
return acceptedTypes.some((type) => type.toLowerCase() === extension);
|
|
50
|
+
};
|
|
51
|
+
const isBlockedFile = (file) => blockedExtensionSet.has(extensionOfFileName(file.name));
|
|
52
|
+
const partitionCandidates = (candidates, { checkType }) => {
|
|
53
|
+
const partition = {
|
|
54
|
+
validFiles: [],
|
|
55
|
+
blockedFiles: [],
|
|
56
|
+
oversizedFiles: [],
|
|
57
|
+
wrongTypeFiles: []
|
|
58
|
+
};
|
|
59
|
+
candidates.forEach((file) => {
|
|
60
|
+
if (isBlockedFile(file)) partition.blockedFiles.push(file);
|
|
61
|
+
else if (checkType && !matchesAllowedType(file)) partition.wrongTypeFiles.push(file);
|
|
62
|
+
else if (file.size > MAX_FILE_SIZE_BYTES) partition.oversizedFiles.push(file);
|
|
63
|
+
else partition.validFiles.push(file);
|
|
64
|
+
});
|
|
65
|
+
return partition;
|
|
66
|
+
};
|
|
67
|
+
const notifyRejections = ({ blockedFiles, oversizedFiles, wrongTypeFiles }) => {
|
|
68
|
+
const reasons = [
|
|
69
|
+
blockedFiles.length > 0 ? t("uploader.filesBlocked", { files: fileNamesOf(blockedFiles) }) : null,
|
|
70
|
+
wrongTypeFiles.length > 0 ? t("uploader.invalidFormat") : null,
|
|
71
|
+
oversizedFiles.length > 0 ? t("uploader.filesOverMaxSize", { size: MAX_FILE_SIZE_MB, files: fileNamesOf(oversizedFiles) }) : null
|
|
72
|
+
].filter((reason) => Boolean(reason));
|
|
73
|
+
if (reasons.length > 0) notify({ message: reasons.join(" "), type: "error" });
|
|
32
74
|
};
|
|
33
75
|
const handleFiles = (newFiles) => {
|
|
34
76
|
if (autoUpload) {
|
|
@@ -40,17 +82,14 @@ const UploaderComponent = ({
|
|
|
40
82
|
handleFilesSelected(newFiles);
|
|
41
83
|
}
|
|
42
84
|
};
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
notify({ message: t("uploader.filesIgnoredMaxSize", { size: MAX_FILE_SIZE_MB }), type: "error" });
|
|
48
|
-
}
|
|
49
|
-
if (validFiles.length > 0) {
|
|
50
|
-
handleFiles(validFiles);
|
|
51
|
-
} else {
|
|
52
|
-
notify({ message: t("uploader.invalidFormat"), type: "error" });
|
|
85
|
+
const acceptCandidates = (candidates, { checkType }) => {
|
|
86
|
+
if (disableFileValidation) {
|
|
87
|
+
handleFiles(candidates);
|
|
88
|
+
return;
|
|
53
89
|
}
|
|
90
|
+
const partition = partitionCandidates(candidates, { checkType });
|
|
91
|
+
notifyRejections(partition);
|
|
92
|
+
if (partition.validFiles.length > 0) handleFiles(partition.validFiles);
|
|
54
93
|
};
|
|
55
94
|
const clipboardFiles = (clipboardData) => {
|
|
56
95
|
const fromFiles = Array.from(clipboardData?.files ?? []);
|
|
@@ -61,7 +100,7 @@ const UploaderComponent = ({
|
|
|
61
100
|
const pasted = clipboardFiles(event.clipboardData);
|
|
62
101
|
if (pasted.length === 0) return;
|
|
63
102
|
event.preventDefault();
|
|
64
|
-
|
|
103
|
+
acceptCandidates(pasted, { checkType: true });
|
|
65
104
|
};
|
|
66
105
|
const handleDragEnterOrOver = (event) => {
|
|
67
106
|
event.preventDefault();
|
|
@@ -72,24 +111,14 @@ const UploaderComponent = ({
|
|
|
72
111
|
setIsDragging(false);
|
|
73
112
|
};
|
|
74
113
|
const handleFileChange = (event) => {
|
|
75
|
-
const selectedFiles = event.target.files;
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
if (newFiles.length < selectedFiles.length) {
|
|
79
|
-
notify({
|
|
80
|
-
message: t("uploader.filesIgnoredMaxSize", { size: MAX_FILE_SIZE_MB }),
|
|
81
|
-
type: "error"
|
|
82
|
-
});
|
|
83
|
-
}
|
|
84
|
-
if (newFiles.length > 0) {
|
|
85
|
-
handleFiles(newFiles);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
114
|
+
const selectedFiles = Array.from(event.target.files ?? []);
|
|
115
|
+
event.target.value = "";
|
|
116
|
+
if (selectedFiles.length > 0) acceptCandidates(selectedFiles, { checkType: false });
|
|
88
117
|
};
|
|
89
118
|
const handleDrop = (event) => {
|
|
90
119
|
event.preventDefault();
|
|
91
120
|
setIsDragging(false);
|
|
92
|
-
|
|
121
|
+
acceptCandidates(Array.from(event.dataTransfer.files), { checkType: true });
|
|
93
122
|
};
|
|
94
123
|
const handleRemoveFile = (index) => {
|
|
95
124
|
setFiles((prevFiles) => {
|
|
@@ -122,7 +151,7 @@ const UploaderComponent = ({
|
|
|
122
151
|
type: "file",
|
|
123
152
|
id: inputId,
|
|
124
153
|
onChange: handleFileChange,
|
|
125
|
-
accept:
|
|
154
|
+
accept: pickerAccept,
|
|
126
155
|
multiple,
|
|
127
156
|
className: "hidden"
|
|
128
157
|
}
|
|
@@ -172,7 +201,7 @@ const UploaderComponent = ({
|
|
|
172
201
|
type: "file",
|
|
173
202
|
id: inputId,
|
|
174
203
|
onChange: handleFileChange,
|
|
175
|
-
accept:
|
|
204
|
+
accept: pickerAccept,
|
|
176
205
|
multiple,
|
|
177
206
|
className: "hidden"
|
|
178
207
|
}
|
|
@@ -193,10 +222,10 @@ const UploaderComponent = ({
|
|
|
193
222
|
]
|
|
194
223
|
}
|
|
195
224
|
),
|
|
196
|
-
/* @__PURE__ */ jsxs("span", { className: "text-xs", children: [
|
|
225
|
+
formatsHint ? /* @__PURE__ */ jsx("span", { className: "text-center text-xs", children: formatsHint }) : acceptsAnyType ? /* @__PURE__ */ jsx("span", { className: "text-xs", children: t("uploader.anyFormatUpTo", { size: MAX_FILE_SIZE_MB }) }) : /* @__PURE__ */ jsxs("span", { className: "text-xs", children: [
|
|
197
226
|
t("uploader.allowedFormats"),
|
|
198
227
|
" ",
|
|
199
|
-
|
|
228
|
+
acceptedTypes.map((type) => type.startsWith(".") ? type : "." + type.split("/")[1]).join(" "),
|
|
200
229
|
" ",
|
|
201
230
|
t("uploader.upTo"),
|
|
202
231
|
" ",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UploaderComponent.js","sources":["../../../src/components/Upload/UploaderComponent.tsx"],"sourcesContent":["import { useId, useState } from 'react';\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\n\nimport { useNotification } from '../../hooks/useNotification';\nimport ControlledButton from '../Form/ControlledButton';\nimport { MaterialSymbol } from '../UI/MaterialSymbol';\n\ninterface IUploaderComponentProps {\n allowedTypes: Array<string>;\n handleFilesSelected: (files: Array<File>) => void;\n multiple?: boolean;\n className?: string;\n simpleLayout?: boolean;\n maxSizeMB?: number;\n /**\n * When true, valid files are sent immediately via `handleFilesSelected` instead of\n * being staged behind a manual \"send\" button. Keeps the default behavior elsewhere.\n */\n autoUpload?: boolean;\n /**\n * Visual style of the full dropzone. `'default'` keeps the neutral gray boxed look used\n * across the app; `'borderless'` drops the dashed frame/background and shows only the\n * centered content with the product accent (lilac icon and link, softer typography).\n * For panels where drag/paste already works anywhere and the frame is redundant.\n */\n variant?: 'default' | 'borderless';\n /**\n * When true, the component stops handling its own drag/drop (it still opens the file\n * picker on click and handles paste). Use when a parent container owns drag-and-drop for\n * a larger area and should be the single drop target, avoiding duplicated uploads.\n */\n disableDragDrop?: boolean;\n}\n\nconst UploaderComponent: React.FC<IUploaderComponentProps> = ({\n allowedTypes,\n handleFilesSelected,\n multiple = false,\n className,\n simpleLayout = false,\n maxSizeMB = 1,\n autoUpload = false,\n variant = 'default',\n disableDragDrop = false,\n}) => {\n const { t } = useTranslation('ui');\n const { notify } = useNotification();\n const isBorderless = variant === 'borderless';\n\n const MAX_FILE_SIZE_MB = maxSizeMB;\n const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024;\n const [files, setFiles] = useState<Array<File>>([]);\n const [isDragging, setIsDragging] = useState(false);\n const inputId = useId();\n\n const matchesAllowedType = (file: File): boolean => {\n if (allowedTypes.includes(file.type)) return true;\n const extension = '.' + (file.name.split('.').pop() ?? '').toLowerCase();\n return allowedTypes.some((type) => type.toLowerCase() === extension);\n };\n\n const handleFiles = (newFiles: Array<File>) => {\n if (autoUpload) {\n handleFilesSelected(newFiles);\n return;\n }\n setFiles(newFiles);\n if (!multiple && newFiles.length === 1) {\n handleFilesSelected(newFiles);\n }\n };\n\n const acceptExternalFiles = (candidates: Array<File>) => {\n const typeMatched = candidates.filter(matchesAllowedType);\n const validFiles = typeMatched.filter((file) => file.size <= MAX_FILE_SIZE_BYTES);\n\n if (validFiles.length < typeMatched.length) {\n notify({ message: t('uploader.filesIgnoredMaxSize', { size: MAX_FILE_SIZE_MB }), type: 'error' });\n }\n\n if (validFiles.length > 0) {\n handleFiles(validFiles);\n } else {\n notify({ message: t('uploader.invalidFormat'), type: 'error' });\n }\n };\n\n const clipboardFiles = (clipboardData: DataTransfer | null): Array<File> => {\n const fromFiles = Array.from(clipboardData?.files ?? []);\n if (fromFiles.length > 0) return fromFiles;\n return Array.from(clipboardData?.items ?? [])\n .filter((item) => item.kind === 'file')\n .map((item) => item.getAsFile())\n .filter((file): file is File => file !== null);\n };\n\n const handlePaste: React.ClipboardEventHandler<HTMLDivElement> = (event) => {\n const pasted = clipboardFiles(event.clipboardData);\n if (pasted.length === 0) return;\n event.preventDefault();\n acceptExternalFiles(pasted);\n };\n\n const handleDragEnterOrOver: React.DragEventHandler<HTMLDivElement> = (event) => {\n event.preventDefault();\n if (!isDragging) setIsDragging(true);\n };\n\n const handleDragLeave: React.DragEventHandler<HTMLDivElement> = (event) => {\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;\n setIsDragging(false);\n };\n\n const handleFileChange: React.ChangeEventHandler<HTMLInputElement> = (event) => {\n const selectedFiles = event.target.files;\n if (selectedFiles && selectedFiles.length > 0) {\n const newFiles = Array.from(selectedFiles).filter((file) => file.size <= MAX_FILE_SIZE_BYTES);\n\n if (newFiles.length < selectedFiles.length) {\n notify({\n message: t('uploader.filesIgnoredMaxSize', { size: MAX_FILE_SIZE_MB }),\n type: 'error',\n });\n }\n\n if (newFiles.length > 0) {\n handleFiles(newFiles);\n }\n }\n };\n\n const handleDrop: React.DragEventHandler<HTMLDivElement> = (event) => {\n event.preventDefault();\n setIsDragging(false);\n acceptExternalFiles(Array.from(event.dataTransfer.files));\n };\n\n const handleRemoveFile = (index: number) => {\n setFiles((prevFiles) => {\n const next = prevFiles.filter((_, i) => i !== index);\n if (!multiple && next.length === 0) {\n handleFilesSelected([]);\n }\n return next;\n });\n };\n\n if (simpleLayout) {\n return (\n <div\n tabIndex={0}\n className={classNames(\n 'aspect-square w-[4.5rem] cursor-pointer rounded-lg border-2 border-dashed p-4 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-border',\n isDragging ? 'border-brand bg-brand-soft' : 'border-border-strong hover:bg-muted',\n className,\n )}\n onDrop={handleDrop}\n onDragEnter={handleDragEnterOrOver}\n onDragOver={handleDragEnterOrOver}\n onDragLeave={handleDragLeave}\n onPaste={handlePaste}\n >\n <input\n type=\"file\"\n id={inputId}\n onChange={handleFileChange}\n accept={allowedTypes.join(', ')}\n multiple={multiple}\n className=\"hidden\"\n />\n <label htmlFor={inputId} className=\"flex size-full cursor-pointer items-center justify-center\">\n <MaterialSymbol icon=\"add_photo_alternate\" size={23} color=\"rgb(var(--color-foreground-subtle))\" />\n </label>\n </div>\n );\n }\n\n return (\n <div\n tabIndex={0}\n className={classNames(\n 'flex w-full flex-col items-center justify-center rounded-lg transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-border',\n isBorderless ? 'py-4' : 'border-2 border-dashed px-4 py-8',\n !isBorderless && (isDragging ? 'border-brand bg-brand-soft' : 'border-border-strong'),\n isBorderless && isDragging && 'bg-brand-soft/60',\n className,\n )}\n onDrop={disableDragDrop ? undefined : handleDrop}\n onDragEnter={disableDragDrop ? undefined : handleDragEnterOrOver}\n onDragOver={disableDragDrop ? undefined : handleDragEnterOrOver}\n onDragLeave={disableDragDrop ? undefined : handleDragLeave}\n onPaste={handlePaste}\n >\n <div\n className={classNames(\n 'flex flex-col items-center justify-center gap-y-2',\n isBorderless ? 'text-foreground-muted' : 'text-foreground',\n )}\n >\n {/* Sem `color`: herda o `currentColor` do bloco acima, que já nomeia um token nos dois ramos. */}\n <MaterialSymbol icon=\"cloud_upload\" size={30} className={isBorderless ? 'text-brand-emphasis' : undefined} />\n <div\n className={classNames(\n 'flex flex-row flex-wrap justify-center gap-x-1',\n isBorderless ? 'font-medium' : 'font-bold',\n )}\n >\n <input\n type=\"file\"\n id={inputId}\n onChange={handleFileChange}\n accept={allowedTypes.join(', ')}\n multiple={multiple}\n className=\"hidden\"\n />\n <span>{t('uploader.dragOr')}</span>\n <label\n htmlFor={inputId}\n className={classNames(\n 'cursor-pointer underline underline-offset-2',\n isBorderless ? 'font-semibold text-brand-emphasis' : 'text-underline',\n )}\n >\n {t('uploader.selectFile')}\n </label>\n <span className=\"font-normal text-foreground-subtle\">{t('uploader.orPaste')}</span>\n </div>\n <span className=\"text-xs\">\n {t('uploader.allowedFormats')}{' '}\n {allowedTypes.map((type) => (type.startsWith('.') ? type : '.' + type.split('/')[1])).join(' ')}{' '}\n {t('uploader.upTo')} {MAX_FILE_SIZE_MB}\n {t('uploader.megabytesSuffix')}\n </span>\n </div>\n\n {files.length > 0 && (\n <div className=\"my-5 flex max-h-40 w-full flex-col gap-y-2 overflow-y-scroll\">\n {files.map((file, index) => (\n <div\n className=\"flex items-center justify-between rounded-lg border border-border-emphasis p-2\"\n key={`${file.name}-${file.size}-${file.lastModified}`}\n >\n <div className=\"flex flex-1 flex-col gap-1\">\n <p className=\"m-0 text-sm text-foreground\">{file.name}</p>\n </div>\n <div className=\"cursor-pointer\" onClick={() => handleRemoveFile(index)}>\n <ControlledTooltip content={t('actions.remove')}>\n <MaterialSymbol size={20} icon=\"delete_sweep\" color=\"rgb(var(--color-danger))\" />\n </ControlledTooltip>\n </div>\n </div>\n ))}\n </div>\n )}\n\n {files.length > 0 && multiple && (\n <ControlledButton\n variant=\"outlined\"\n tone=\"neutral\"\n size=\"sm\"\n className=\"inter-font flex items-center justify-center gap-x-2 rounded-md normal-case text-foreground\"\n onClick={() => handleFilesSelected(files)}\n >\n {t('uploader.sendFiles')}\n <MaterialSymbol icon=\"difference\" size={16} color=\"rgb(var(--color-foreground))\" />\n </ControlledButton>\n )}\n </div>\n );\n};\n\nexport default UploaderComponent;\n"],"names":[],"mappings":";;;;;;;;AAsCA,MAAM,oBAAuD,CAAC;AAAA,EAC5D;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AAAA,EACV,kBAAkB;AACpB,MAAM;AACJ,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AACjC,QAAM,EAAE,OAAA,IAAW,gBAAA;AACnB,QAAM,eAAe,YAAY;AAEjC,QAAM,mBAAmB;AACzB,QAAM,sBAAsB,mBAAmB,OAAO;AACtD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAsB,CAAA,CAAE;AAClD,QAAM,CAAC,YAAY,aAAa,IAAI,SAAS,KAAK;AAClD,QAAM,UAAU,MAAA;AAEhB,QAAM,q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AAA,oBAAC,gBAAA,EAAe,MAAM,IAAI,MAAK,gBAAe,OAAM,2BAAA,CAA2B,EAAA,CACjF,EAAA,CACF;AAAA,YAAA;AAAA,UAAA;AAAA,UATK,GAAG,KAAK,IAAI,IAAI,KAAK,IAAI,IAAI,KAAK,YAAY;AAAA,QAAA,CAWtD,GACH;AAAA,QAGD,MAAM,SAAS,KAAK,YACnB;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,SAAQ;AAAA,YACR,MAAK;AAAA,YACL,MAAK;AAAA,YACL,WAAU;AAAA,YACV,SAAS,MAAM,oBAAoB,KAAK;AAAA,YAEvC,UAAA;AAAA,cAAA,EAAE,oBAAoB;AAAA,kCACtB,gBAAA,EAAe,MAAK,cAAa,MAAM,IAAI,OAAM,+BAAA,CAA+B;AAAA,YAAA;AAAA,UAAA;AAAA,QAAA;AAAA,MACnF;AAAA,IAAA;AAAA,EAAA;AAIR;"}
|
|
1
|
+
{"version":3,"file":"UploaderComponent.js","sources":["../../../src/components/Upload/UploaderComponent.tsx"],"sourcesContent":["import { useId, useState } from 'react';\nimport * as React from 'react';\nimport classNames from 'classnames';\nimport { useTranslation } from 'react-i18next';\n\nimport ControlledTooltip from '@/components/UI/ControlledTooltip';\n\nimport { useNotification } from '../../hooks/useNotification';\nimport ControlledButton from '../Form/ControlledButton';\nimport { MaterialSymbol } from '../UI/MaterialSymbol';\n\ninterface IUploaderComponentProps {\n /**\n * MIME types (`image/png`) or extensions (`.pdf`) the uploader accepts. An EMPTY list accepts\n * any type, minus `blockedExtensions`, and stops filtering the system file picker.\n */\n allowedTypes: Array<string>;\n /** Extensions (`.exe`) refused on every path (picker, drop and paste), whatever `allowedTypes` says. */\n blockedExtensions?: Array<string>;\n /**\n * Replaces the generated \"allowed formats ... up to N MB\" line, for a policy that a list of\n * extensions cannot say well. The host composes it from `t()`.\n */\n formatsHint?: string;\n handleFilesSelected: (files: Array<File>) => void;\n multiple?: boolean;\n className?: string;\n simpleLayout?: boolean;\n maxSizeMB?: number;\n /**\n * When true, valid files are sent immediately via `handleFilesSelected` instead of\n * being staged behind a manual \"send\" button. Keeps the default behavior elsewhere.\n */\n autoUpload?: boolean;\n /**\n * Visual style of the full dropzone. `'default'` keeps the neutral gray boxed look used\n * across the app; `'borderless'` drops the dashed frame/background and shows only the\n * centered content with the product accent (lilac icon and link, softer typography).\n * For panels where drag/paste already works anywhere and the frame is redundant.\n */\n variant?: 'default' | 'borderless';\n /**\n * When true, the component stops handling its own drag/drop (it still opens the file\n * picker on click and handles paste). Use when a parent container owns drag-and-drop for\n * a larger area and should be the single drop target, avoiding duplicated uploads.\n */\n disableDragDrop?: boolean;\n /**\n * When true, every chosen file reaches `handleFilesSelected` unchecked (type, size and\n * `blockedExtensions` are ignored) and the component raises no toast. Use when the host already\n * validates the same files from other entry points and must report local refusals and server\n * failures in ONE message: only one toast is on screen at a time, so two validators erase each\n * other's reasons.\n */\n disableFileValidation?: boolean;\n}\n\ninterface IUploadCandidatesPartition {\n validFiles: Array<File>;\n blockedFiles: Array<File>;\n oversizedFiles: Array<File>;\n wrongTypeFiles: Array<File>;\n}\n\nconst normalizeExtension = (extension: string): string => {\n const lowered = extension.trim().toLowerCase();\n return lowered.startsWith('.') ? lowered : `.${lowered}`;\n};\n\n/** Windows opens `setup.exe.` as `setup.exe`, so trailing dots and spaces never hide an extension. */\nconst extensionOfFileName = (fileName: string): string => {\n const cleanName = fileName.trim().replace(/[.\\s]+$/, '');\n const dotIndex = cleanName.lastIndexOf('.');\n return dotIndex > 0 ? cleanName.slice(dotIndex).toLowerCase() : '';\n};\n\nconst fileNamesOf = (files: Array<File>): string => files.map((file) => file.name).join(', ');\n\nconst UploaderComponent: React.FC<IUploaderComponentProps> = ({\n allowedTypes,\n blockedExtensions,\n formatsHint,\n handleFilesSelected,\n multiple = false,\n className,\n simpleLayout = false,\n maxSizeMB = 1,\n autoUpload = false,\n variant = 'default',\n disableDragDrop = false,\n disableFileValidation = false,\n}) => {\n const { t } = useTranslation('ui');\n const { notify } = useNotification();\n const isBorderless = variant === 'borderless';\n\n const MAX_FILE_SIZE_MB = maxSizeMB;\n const MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024;\n const [files, setFiles] = useState<Array<File>>([]);\n const [isDragging, setIsDragging] = useState(false);\n const inputId = useId();\n\n const acceptedTypes = Array.isArray(allowedTypes) ? allowedTypes : [];\n const acceptsAnyType = acceptedTypes.length === 0;\n const pickerAccept = acceptsAnyType ? undefined : acceptedTypes.join(', ');\n const blockedExtensionSet = new Set((blockedExtensions ?? []).map(normalizeExtension));\n\n const matchesAllowedType = (file: File): boolean => {\n if (acceptsAnyType) return true;\n if (acceptedTypes.includes(file.type)) return true;\n const extension = '.' + (file.name.split('.').pop() ?? '').toLowerCase();\n return acceptedTypes.some((type) => type.toLowerCase() === extension);\n };\n\n const isBlockedFile = (file: File): boolean => blockedExtensionSet.has(extensionOfFileName(file.name));\n\n const partitionCandidates = (\n candidates: Array<File>,\n { checkType }: { checkType: boolean },\n ): IUploadCandidatesPartition => {\n const partition: IUploadCandidatesPartition = {\n validFiles: [],\n blockedFiles: [],\n oversizedFiles: [],\n wrongTypeFiles: [],\n };\n candidates.forEach((file) => {\n if (isBlockedFile(file)) partition.blockedFiles.push(file);\n else if (checkType && !matchesAllowedType(file)) partition.wrongTypeFiles.push(file);\n else if (file.size > MAX_FILE_SIZE_BYTES) partition.oversizedFiles.push(file);\n else partition.validFiles.push(file);\n });\n return partition;\n };\n\n /** Only one toast is on screen at a time, so every reason a file was left out goes in the same one. */\n const notifyRejections = ({ blockedFiles, oversizedFiles, wrongTypeFiles }: IUploadCandidatesPartition) => {\n const reasons = [\n blockedFiles.length > 0 ? t('uploader.filesBlocked', { files: fileNamesOf(blockedFiles) }) : null,\n wrongTypeFiles.length > 0 ? t('uploader.invalidFormat') : null,\n oversizedFiles.length > 0\n ? t('uploader.filesOverMaxSize', { size: MAX_FILE_SIZE_MB, files: fileNamesOf(oversizedFiles) })\n : null,\n ].filter((reason): reason is string => Boolean(reason));\n\n if (reasons.length > 0) notify({ message: reasons.join(' '), type: 'error' });\n };\n\n const handleFiles = (newFiles: Array<File>) => {\n if (autoUpload) {\n handleFilesSelected(newFiles);\n return;\n }\n setFiles(newFiles);\n if (!multiple && newFiles.length === 1) {\n handleFilesSelected(newFiles);\n }\n };\n\n const acceptCandidates = (candidates: Array<File>, { checkType }: { checkType: boolean }) => {\n if (disableFileValidation) {\n handleFiles(candidates);\n return;\n }\n const partition = partitionCandidates(candidates, { checkType });\n notifyRejections(partition);\n if (partition.validFiles.length > 0) handleFiles(partition.validFiles);\n };\n\n const clipboardFiles = (clipboardData: DataTransfer | null): Array<File> => {\n const fromFiles = Array.from(clipboardData?.files ?? []);\n if (fromFiles.length > 0) return fromFiles;\n return Array.from(clipboardData?.items ?? [])\n .filter((item) => item.kind === 'file')\n .map((item) => item.getAsFile())\n .filter((file): file is File => file !== null);\n };\n\n const handlePaste: React.ClipboardEventHandler<HTMLDivElement> = (event) => {\n const pasted = clipboardFiles(event.clipboardData);\n if (pasted.length === 0) return;\n event.preventDefault();\n acceptCandidates(pasted, { checkType: true });\n };\n\n const handleDragEnterOrOver: React.DragEventHandler<HTMLDivElement> = (event) => {\n event.preventDefault();\n if (!isDragging) setIsDragging(true);\n };\n\n const handleDragLeave: React.DragEventHandler<HTMLDivElement> = (event) => {\n if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;\n setIsDragging(false);\n };\n\n /** The picker already filters by `accept`; a file picked through \"All files\" keeps going, as before. */\n const handleFileChange: React.ChangeEventHandler<HTMLInputElement> = (event) => {\n const selectedFiles = Array.from(event.target.files ?? []);\n event.target.value = '';\n if (selectedFiles.length > 0) acceptCandidates(selectedFiles, { checkType: false });\n };\n\n const handleDrop: React.DragEventHandler<HTMLDivElement> = (event) => {\n event.preventDefault();\n setIsDragging(false);\n acceptCandidates(Array.from(event.dataTransfer.files), { checkType: true });\n };\n\n const handleRemoveFile = (index: number) => {\n setFiles((prevFiles) => {\n const next = prevFiles.filter((_, i) => i !== index);\n if (!multiple && next.length === 0) {\n handleFilesSelected([]);\n }\n return next;\n });\n };\n\n if (simpleLayout) {\n return (\n <div\n tabIndex={0}\n className={classNames(\n 'aspect-square w-[4.5rem] cursor-pointer rounded-lg border-2 border-dashed p-4 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-border',\n isDragging ? 'border-brand bg-brand-soft' : 'border-border-strong hover:bg-muted',\n className,\n )}\n onDrop={handleDrop}\n onDragEnter={handleDragEnterOrOver}\n onDragOver={handleDragEnterOrOver}\n onDragLeave={handleDragLeave}\n onPaste={handlePaste}\n >\n <input\n type=\"file\"\n id={inputId}\n onChange={handleFileChange}\n accept={pickerAccept}\n multiple={multiple}\n className=\"hidden\"\n />\n <label htmlFor={inputId} className=\"flex size-full cursor-pointer items-center justify-center\">\n <MaterialSymbol icon=\"add_photo_alternate\" size={23} color=\"rgb(var(--color-foreground-subtle))\" />\n </label>\n </div>\n );\n }\n\n return (\n <div\n tabIndex={0}\n className={classNames(\n 'flex w-full flex-col items-center justify-center rounded-lg transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-border',\n isBorderless ? 'py-4' : 'border-2 border-dashed px-4 py-8',\n !isBorderless && (isDragging ? 'border-brand bg-brand-soft' : 'border-border-strong'),\n isBorderless && isDragging && 'bg-brand-soft/60',\n className,\n )}\n onDrop={disableDragDrop ? undefined : handleDrop}\n onDragEnter={disableDragDrop ? undefined : handleDragEnterOrOver}\n onDragOver={disableDragDrop ? undefined : handleDragEnterOrOver}\n onDragLeave={disableDragDrop ? undefined : handleDragLeave}\n onPaste={handlePaste}\n >\n <div\n className={classNames(\n 'flex flex-col items-center justify-center gap-y-2',\n isBorderless ? 'text-foreground-muted' : 'text-foreground',\n )}\n >\n {/* Sem `color`: herda o `currentColor` do bloco acima, que já nomeia um token nos dois ramos. */}\n <MaterialSymbol icon=\"cloud_upload\" size={30} className={isBorderless ? 'text-brand-emphasis' : undefined} />\n <div\n className={classNames(\n 'flex flex-row flex-wrap justify-center gap-x-1',\n isBorderless ? 'font-medium' : 'font-bold',\n )}\n >\n <input\n type=\"file\"\n id={inputId}\n onChange={handleFileChange}\n accept={pickerAccept}\n multiple={multiple}\n className=\"hidden\"\n />\n <span>{t('uploader.dragOr')}</span>\n <label\n htmlFor={inputId}\n className={classNames(\n 'cursor-pointer underline underline-offset-2',\n isBorderless ? 'font-semibold text-brand-emphasis' : 'text-underline',\n )}\n >\n {t('uploader.selectFile')}\n </label>\n <span className=\"font-normal text-foreground-subtle\">{t('uploader.orPaste')}</span>\n </div>\n {formatsHint ? (\n <span className=\"text-center text-xs\">{formatsHint}</span>\n ) : acceptsAnyType ? (\n <span className=\"text-xs\">{t('uploader.anyFormatUpTo', { size: MAX_FILE_SIZE_MB })}</span>\n ) : (\n <span className=\"text-xs\">\n {t('uploader.allowedFormats')}{' '}\n {acceptedTypes.map((type) => (type.startsWith('.') ? type : '.' + type.split('/')[1])).join(' ')}{' '}\n {t('uploader.upTo')} {MAX_FILE_SIZE_MB}\n {t('uploader.megabytesSuffix')}\n </span>\n )}\n </div>\n\n {files.length > 0 && (\n <div className=\"my-5 flex max-h-40 w-full flex-col gap-y-2 overflow-y-scroll\">\n {files.map((file, index) => (\n <div\n className=\"flex items-center justify-between rounded-lg border border-border-emphasis p-2\"\n key={`${file.name}-${file.size}-${file.lastModified}`}\n >\n <div className=\"flex flex-1 flex-col gap-1\">\n <p className=\"m-0 text-sm text-foreground\">{file.name}</p>\n </div>\n <div className=\"cursor-pointer\" onClick={() => handleRemoveFile(index)}>\n <ControlledTooltip content={t('actions.remove')}>\n <MaterialSymbol size={20} icon=\"delete_sweep\" color=\"rgb(var(--color-danger))\" />\n </ControlledTooltip>\n </div>\n </div>\n ))}\n </div>\n )}\n\n {files.length > 0 && multiple && (\n <ControlledButton\n variant=\"outlined\"\n tone=\"neutral\"\n size=\"sm\"\n className=\"inter-font flex items-center justify-center gap-x-2 rounded-md normal-case text-foreground\"\n onClick={() => handleFilesSelected(files)}\n >\n {t('uploader.sendFiles')}\n <MaterialSymbol icon=\"difference\" size={16} color=\"rgb(var(--color-foreground))\" />\n </ControlledButton>\n )}\n </div>\n );\n};\n\nexport default UploaderComponent;\n"],"names":[],"mappings":";;;;;;;;AAgEA,MAAM,qBAAqB,CAAC,cAA8B;AACxD,QAAM,UAAU,UAAU,KAAA,EAAO,YAAA;AACjC,SAAO,QAAQ,WAAW,GAAG,IAAI,UAAU,IAAI,OAAO;AACxD;AAGA,MAAM,sBAAsB,CAAC,aAA6B;AACxD,QAAM,YAAY,SAAS,KAAA,EAAO,QAAQ,WAAW,EAAE;AACvD,QAAM,WAAW,UAAU,YAAY,GAAG;AAC1C,SAAO,WAAW,IAAI,UAAU,MAAM,QAAQ,EAAE,gBAAgB;AAClE;AAEA,MAAM,cAAc,CAAC,UAA+B,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,EAAE,KAAK,IAAI;AAE5F,MAAM,oBAAuD,CAAC;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU;AAAA,EACV,kBAAkB;AAAA,EAClB,wBAAwB;AAC1B,MAAM;AACJ,QAAM,EAAE,EAAA,IAAM,eAAe,IAAI;AACjC,QAAM,EAAE,OAAA,IAAW,gBAAA;AACnB,QAAM,eAAe,YAAY;AAEjC,QAAM,mBAAmB;AACzB,QAAM,sBAAsB,mBAAmB,OAAO;AACtD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAsB,CAAA,CAAE;AAClD,QAAM,CAAC,YAAY,aAAa,IAAI,SAAS,KAAK;AAClD,QAAM,UAAU,MAAA;AAEhB,QAAM,gBAAgB,MAAM,QAAQ,YAAY,IAAI,eAAe,CAAA;AACnE,QAAM,iBAAiB,cAAc,WAAW;AAChD,QAAM,eAAe,iBAAiB,SAAY,cAAc,KAAK,IAAI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AAS,MAAM,oBAAoB,KAAK;AAAA,YAEvC,UAAA;AAAA,cAAA,EAAE,oBAAoB;AAAA,kCACtB,gBAAA,EAAe,MAAK,cAAa,MAAM,IAAI,OAAM,+BAAA,CAA+B;AAAA,YAAA;AAAA,UAAA;AAAA,QAAA;AAAA,MACnF;AAAA,IAAA;AAAA,EAAA;AAIR;"}
|
|
@@ -659,7 +659,10 @@ declare const _default: {
|
|
|
659
659
|
"sendFiles": "Send file(s)",
|
|
660
660
|
"filesIgnoredMaxSize": "Some files were ignored because they exceeded the maximum size of {{size}}MB",
|
|
661
661
|
"invalidFormat": "Please add files in the allowed formats",
|
|
662
|
-
"allowedFormatsTooltip": "Allowed formats: {{formats}} up to {{size}}MB"
|
|
662
|
+
"allowedFormatsTooltip": "Allowed formats: {{formats}} up to {{size}}MB",
|
|
663
|
+
"anyFormatUpTo": "Any format up to {{size}} MB",
|
|
664
|
+
"filesBlocked": "This file type is not accepted: {{files}}.",
|
|
665
|
+
"filesOverMaxSize": "Over the {{size}} MB limit: {{files}}."
|
|
663
666
|
},
|
|
664
667
|
"urlLinkCell": {
|
|
665
668
|
"clickToAccess": "Click to access"
|
|
@@ -32,7 +32,7 @@ const sidebar = { "home": "Home", "logout": "Sign out", "openSidebar": "Open sid
|
|
|
32
32
|
const theme = { "toggle": "Theme", "light": "Light theme", "dark": "Dark theme", "system": "Follow system", "halloween": "Halloween theme" };
|
|
33
33
|
const toast = { "learnMore": "Learn more" };
|
|
34
34
|
const unifiedSearchBar = { "clearFilter": "Clear filter" };
|
|
35
|
-
const uploader = { "dragOr": "Drag or", "selectFile": "select a file", "orPaste": "or paste (Ctrl+V)", "allowedFormats": "Allowed formats:", "upTo": "up to", "megabytesSuffix": "MB", "sendFiles": "Send file(s)", "filesIgnoredMaxSize": "Some files were ignored because they exceeded the maximum size of {{size}}MB", "invalidFormat": "Please add files in the allowed formats", "allowedFormatsTooltip": "Allowed formats: {{formats}} up to {{size}}MB" };
|
|
35
|
+
const uploader = { "dragOr": "Drag or", "selectFile": "select a file", "orPaste": "or paste (Ctrl+V)", "allowedFormats": "Allowed formats:", "upTo": "up to", "megabytesSuffix": "MB", "sendFiles": "Send file(s)", "filesIgnoredMaxSize": "Some files were ignored because they exceeded the maximum size of {{size}}MB", "invalidFormat": "Please add files in the allowed formats", "allowedFormatsTooltip": "Allowed formats: {{formats}} up to {{size}}MB", "anyFormatUpTo": "Any format up to {{size}} MB", "filesBlocked": "This file type is not accepted: {{files}}.", "filesOverMaxSize": "Over the {{size}} MB limit: {{files}}." };
|
|
36
36
|
const urlLinkCell = { "clickToAccess": "Click to access" };
|
|
37
37
|
const userMenu = { "loading": "Loading...", "yourAccounts": "Your Accounts", "searchAccount": "Search account", "noAccounts": "No active accounts available", "logout": "Sign out" };
|
|
38
38
|
const voiceInput = { "start": "Transcribe by voice", "stop": "Stop transcription", "listeningInPauses": "Listening. The text shows up at each pause in your speech.", "transcribing": "Transcribing what you said...", "commandsHint": "Voice commands: say {{commands}} to insert punctuation or delete the last word.", "errors": { "permission": "Microphone access was blocked. Allow the microphone in your browser permissions and try again.", "microphone": "No microphone was found. Connect a microphone and try again.", "network": "The transcription service did not respond. Check your connection and try again.", "unavailable": "Voice transcription is not available in this browser. Use Google Chrome or Microsoft Edge." } };
|
package/dist/locales/index.d.ts
CHANGED
|
@@ -662,6 +662,9 @@ export declare const uiLocales: {
|
|
|
662
662
|
filesIgnoredMaxSize: string;
|
|
663
663
|
invalidFormat: string;
|
|
664
664
|
allowedFormatsTooltip: string;
|
|
665
|
+
anyFormatUpTo: string;
|
|
666
|
+
filesBlocked: string;
|
|
667
|
+
filesOverMaxSize: string;
|
|
665
668
|
};
|
|
666
669
|
urlLinkCell: {
|
|
667
670
|
clickToAccess: string;
|
|
@@ -1349,6 +1352,9 @@ export declare const uiLocales: {
|
|
|
1349
1352
|
filesIgnoredMaxSize: string;
|
|
1350
1353
|
invalidFormat: string;
|
|
1351
1354
|
allowedFormatsTooltip: string;
|
|
1355
|
+
anyFormatUpTo: string;
|
|
1356
|
+
filesBlocked: string;
|
|
1357
|
+
filesOverMaxSize: string;
|
|
1352
1358
|
};
|
|
1353
1359
|
urlLinkCell: {
|
|
1354
1360
|
clickToAccess: string;
|
|
@@ -659,7 +659,10 @@ declare const _default: {
|
|
|
659
659
|
"sendFiles": "Enviar arquivo(s)",
|
|
660
660
|
"filesIgnoredMaxSize": "Alguns arquivos foram ignorados porque excederam o tamanho máximo de {{size}}MB",
|
|
661
661
|
"invalidFormat": "Por favor, insira arquivos nos formatos permitidos",
|
|
662
|
-
"allowedFormatsTooltip": "Formatos permitidos: {{formats}} até {{size}}MB"
|
|
662
|
+
"allowedFormatsTooltip": "Formatos permitidos: {{formats}} até {{size}}MB",
|
|
663
|
+
"anyFormatUpTo": "Qualquer formato até {{size}} MB",
|
|
664
|
+
"filesBlocked": "Este tipo de arquivo não é aceito: {{files}}.",
|
|
665
|
+
"filesOverMaxSize": "Passou do limite de {{size}} MB: {{files}}."
|
|
663
666
|
},
|
|
664
667
|
"urlLinkCell": {
|
|
665
668
|
"clickToAccess": "Clique para acessar"
|
|
@@ -32,7 +32,7 @@ const sidebar = { "home": "Início", "logout": "Sair", "openSidebar": "Abrir bar
|
|
|
32
32
|
const theme = { "toggle": "Tema", "light": "Tema claro", "dark": "Tema escuro", "system": "Seguir o sistema", "halloween": "Tema de Halloween" };
|
|
33
33
|
const toast = { "learnMore": "Saiba Mais" };
|
|
34
34
|
const unifiedSearchBar = { "clearFilter": "Limpar Filtro" };
|
|
35
|
-
const uploader = { "dragOr": "Arraste ou", "selectFile": "selecione um arquivo", "orPaste": "ou cole (Ctrl+V)", "allowedFormats": "Formatos permitidos:", "upTo": "até", "megabytesSuffix": "MB", "sendFiles": "Enviar arquivo(s)", "filesIgnoredMaxSize": "Alguns arquivos foram ignorados porque excederam o tamanho máximo de {{size}}MB", "invalidFormat": "Por favor, insira arquivos nos formatos permitidos", "allowedFormatsTooltip": "Formatos permitidos: {{formats}} até {{size}}MB" };
|
|
35
|
+
const uploader = { "dragOr": "Arraste ou", "selectFile": "selecione um arquivo", "orPaste": "ou cole (Ctrl+V)", "allowedFormats": "Formatos permitidos:", "upTo": "até", "megabytesSuffix": "MB", "sendFiles": "Enviar arquivo(s)", "filesIgnoredMaxSize": "Alguns arquivos foram ignorados porque excederam o tamanho máximo de {{size}}MB", "invalidFormat": "Por favor, insira arquivos nos formatos permitidos", "allowedFormatsTooltip": "Formatos permitidos: {{formats}} até {{size}}MB", "anyFormatUpTo": "Qualquer formato até {{size}} MB", "filesBlocked": "Este tipo de arquivo não é aceito: {{files}}.", "filesOverMaxSize": "Passou do limite de {{size}} MB: {{files}}." };
|
|
36
36
|
const urlLinkCell = { "clickToAccess": "Clique para acessar" };
|
|
37
37
|
const userMenu = { "loading": "Carregando...", "yourAccounts": "Suas Contas", "searchAccount": "Buscar conta", "noAccounts": "Nenhuma conta ativa disponível", "logout": "Sair" };
|
|
38
38
|
const voiceInput = { "start": "Transcrever por voz", "stop": "Parar transcrição", "listeningInPauses": "Ouvindo. O texto aparece a cada pausa na fala.", "transcribing": "Transcrevendo o que você falou...", "commandsHint": "Comandos de voz: diga {{commands}} para inserir pontuação ou apagar a última palavra.", "errors": { "permission": "O acesso ao microfone foi bloqueado. Libere o microfone nas permissões do navegador e tente de novo.", "microphone": "Nenhum microfone foi encontrado. Conecte um microfone e tente de novo.", "network": "O serviço de transcrição não respondeu. Verifique a conexão e tente de novo.", "unavailable": "A transcrição por voz não está disponível neste navegador. Use o Google Chrome ou o Microsoft Edge." } };
|