UNPKG

@uploadcare/file-uploader

Version:

Building blocks for Uploadcare products integration

1,613 lines (1,573 loc) 90.7 kB
import * as lit_html from 'lit-html'; import { PropertyValues, nothing, LitElement, TemplateResult } from 'lit'; import * as lit_html_directives_ref_js from 'lit-html/directives/ref.js'; import * as _uploadcare_upload_client from '@uploadcare/upload-client'; import { UploadcareFile, Metadata, UploadError, NetworkError, UploadcareGroup, FileFromOptions, Queue } from '@uploadcare/upload-client'; import { Ref } from 'lit/directives/ref.js'; import { TelemetryRequest } from '@uploadcare/quality-insights'; type Unsubscriber = () => void; declare class PubSub<T extends Record<string, unknown>> { private static _contexts; private _store; private _ctxId; private constructor(); get id(): string; pub<K extends keyof T>(key: K, value: T[K]): void; sub<K extends keyof T>(key: K, callback: (value: T[K]) => void, init?: boolean): Unsubscriber; read<K extends keyof T>(key: K): T[K]; add<K extends keyof T>(key: K, value: T[K], rewrite?: boolean): void; has(key: keyof T): boolean; get store(): T; static registerCtx<T extends Record<string, unknown>>(initialValue: T, ctxId: string): PubSub<T>; static deleteCtx(ctxId: string): void; static getCtx<T extends Record<string, unknown> = Record<string, unknown>>(ctxId: string): PubSub<T> | null; static hasCtx(ctxId: string): boolean; } type Constructor<T = unknown> = new (...args: any[]) => T; type SymbioteStateBag<T extends Record<string, unknown>> = T; /** * Interface for components using SymbioteMixin */ declare class SymbioteComponent<TState extends Record<string, unknown> = Record<string, unknown>> { $: SymbioteStateBag<TState>; sub<TKey extends keyof TState>(key: TKey, callback: (value: TState[TKey]) => void, init?: boolean): () => void; pub<TKey extends keyof TState>(key: TKey, value: TState[TKey]): void; set$<T extends { [K in keyof T]: K extends keyof TState ? TState[K] : never; }>(obj: T): void; has<TKey extends keyof TState>(key: TKey): boolean; add<TKey extends keyof TState>(key: TKey, val: TState[TKey], rewrite?: boolean): void; add$<T extends { [K in keyof T]: K extends keyof TState ? TState[K] : never; }>(obj: T, rewrite?: boolean): void; initCallback(): void; sharedCtx: PubSub<TState>; ctxName: string; ctxOwner: boolean; } type Uid = string & { __uid: true; }; declare function defineComponents(blockExports: Record<string, any>): void; declare const UC_WINDOW_KEY = "UC"; type IndexModule = Record<string, any>; declare global { interface Window { [UC_WINDOW_KEY]?: IndexModule; } } declare const _default: { 'locale-id': string; 'social-source-lang': string; 'upload-file': string; 'upload-files': string; 'choose-file': string; 'choose-files': string; 'drop-files-here': string; 'drop-file-here': string; 'select-file-source': string; selected: string; upload: string; 'add-more': string; cancel: string; 'start-from-cancel': string; clear: string; 'camera-shot': string; 'upload-url': string; 'upload-url-placeholder': string; 'edit-image': string; 'edit-detail': string; back: string; done: string; ok: string; 'remove-from-list': string; no: string; yes: string; 'confirm-your-action': string; 'are-you-sure': string; 'selected-count': string; 'select-all': string; 'deselect-all': string; 'upload-error': string; 'validation-error': string; 'no-files': string; browse: string; 'not-uploaded-yet': string; file__one: string; file__other: string; error__one: string; error__other: string; 'header-uploading': string; 'header-failed': string; 'header-succeed': string; 'header-total': string; 'src-type-local': string; 'src-type-from-url': string; 'src-type-camera': string; 'src-type-mobile-video-camera': string; 'src-type-mobile-photo-camera': string; 'src-type-draw': string; 'src-type-facebook': string; 'src-type-dropbox': string; 'src-type-gdrive': string; 'src-type-ngdrive': string; 'src-type-gphotos': string; 'src-type-flickr': string; 'src-type-vk': string; 'src-type-evernote': string; 'src-type-box': string; 'src-type-onedrive': string; 'src-type-huddle': string; 'src-type-other': string; 'caption-from-url': string; 'caption-camera': string; 'caption-draw': string; 'caption-edit-file': string; 'file-no-name': string; 'toggle-fullscreen': string; 'toggle-guides': string; rotate: string; 'flip-vertical': string; 'flip-horizontal': string; apply: string; brightness: string; contrast: string; saturation: string; exposure: string; gamma: string; vibrance: string; warmth: string; enhance: string; original: string; resize: string; crop: string; 'select-color': string; text: string; draw: string; 'cancel-edit': string; 'tab-view': string; 'tab-details': string; 'file-name': string; 'file-size': string; 'cdn-url': string; 'file-size-unknown': string; 'camera-permissions-denied': string; 'camera-permissions-prompt': string; 'camera-permissions-request': string; 'files-count-limit-error-title': string; 'files-count-limit-error-too-few': string; 'files-count-limit-error-too-many': string; 'files-max-size-limit-error': string; 'has-validation-errors': string; 'images-only-accepted': string; 'file-type-not-allowed': string; 'some-files-were-not-uploaded': string; 'file-item-edit-button': string; 'file-item-remove-button': string; 'a11y-editor-tab-filters': string; 'a11y-editor-tab-tuning': string; 'a11y-editor-tab-crop': string; 'a11y-activity-header-button-close': string; flip: string; mirror: string; 'a11y-cloud-editor-apply-filter': string; 'a11y-cloud-editor-apply-crop': string; 'a11y-cloud-editor-apply-tuning': string; 'a11y-cloud-editor-apply-aspect-ratio': string; finished: string; failed: string; uploading: string; idle: string; 'a11y-file-item-status': string; 'waiting-for': string; 'queued-uploading': string; 'queued-validation': string; validation: string; 'crop-to-shape': string; custom: string; 'freeform-crop': string; }; type LocaleDefinition = typeof _default; declare class Modal extends LitBlock { static styleAttrs: string[]; private _mouseDownTarget; /** WARNING: Do not rename/change this, it's used in dashboard */ protected dialogEl: lit_html_directives_ref_js.Ref<HTMLDialogElement>; /** * CSS-only attribute */ strokes: boolean; /** * CSS-only attribute */ blockBodyScrolling: boolean; /** WARNING: Do not rename/change this, it's used in dashboard */ protected closeDialog: () => void; private _handleDialogClose; private _handleDialogMouseDown; private _handleDialogMouseUp; show(): void; hide(): void; private _handleModalOpen; private _handleModalClose; private _handleModalCloseAll; initCallback(): void; disconnectedCallback(): void; private _handleDialogRef; render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-modal': Modal; } } declare const InternalEventType: Readonly<{ readonly INIT_SOLUTION: "init-solution"; readonly CHANGE_CONFIG: "change-config"; readonly ACTION_EVENT: "action-event"; readonly ERROR_EVENT: "error-event"; }>; declare const EventType: Readonly<{ readonly FILE_ADDED: "file-added"; readonly FILE_REMOVED: "file-removed"; readonly FILE_UPLOAD_START: "file-upload-start"; readonly FILE_UPLOAD_PROGRESS: "file-upload-progress"; readonly FILE_UPLOAD_SUCCESS: "file-upload-success"; readonly FILE_UPLOAD_FAILED: "file-upload-failed"; readonly FILE_URL_CHANGED: "file-url-changed"; readonly MODAL_OPEN: "modal-open"; readonly MODAL_CLOSE: "modal-close"; readonly DONE_CLICK: "done-click"; readonly UPLOAD_CLICK: "upload-click"; readonly ACTIVITY_CHANGE: "activity-change"; readonly COMMON_UPLOAD_START: "common-upload-start"; readonly COMMON_UPLOAD_PROGRESS: "common-upload-progress"; readonly COMMON_UPLOAD_SUCCESS: "common-upload-success"; readonly COMMON_UPLOAD_FAILED: "common-upload-failed"; readonly CHANGE: "change"; readonly GROUP_CREATED: "group-created"; }>; type EventKey = (typeof EventType)[keyof typeof EventType]; type InternalEventKey = (typeof InternalEventType)[keyof typeof InternalEventType]; type EventPayload = { [EventType.FILE_ADDED]: OutputFileEntry<'idle'>; [EventType.FILE_REMOVED]: OutputFileEntry<'removed'>; [EventType.FILE_UPLOAD_START]: OutputFileEntry<'uploading'>; [EventType.FILE_UPLOAD_PROGRESS]: OutputFileEntry<'uploading'>; [EventType.FILE_UPLOAD_SUCCESS]: OutputFileEntry<'success'>; [EventType.FILE_UPLOAD_FAILED]: OutputFileEntry<'failed'>; [EventType.FILE_URL_CHANGED]: OutputFileEntry<'success'>; [EventType.MODAL_OPEN]: { modalId: ModalId; }; [EventType.MODAL_CLOSE]: { modalId: ModalId; hasActiveModals: boolean; }; [EventType.ACTIVITY_CHANGE]: { activity: ActivityType; }; [EventType.UPLOAD_CLICK]: undefined; [EventType.DONE_CLICK]: OutputCollectionState; [EventType.COMMON_UPLOAD_START]: OutputCollectionState<'uploading'>; [EventType.COMMON_UPLOAD_PROGRESS]: OutputCollectionState<'uploading'>; [EventType.COMMON_UPLOAD_SUCCESS]: OutputCollectionState<'success'>; [EventType.COMMON_UPLOAD_FAILED]: OutputCollectionState<'failed'>; [EventType.CHANGE]: OutputCollectionState; [EventType.GROUP_CREATED]: OutputCollectionState<'success', 'has-group'>; }; declare class EventEmitter extends SharedInstance { private _timeoutStore; private _targets; bindTarget(target: LitBlock): () => void; private _dispatch; emit<T extends EventKey, TDebounce extends boolean | number | undefined = undefined>(type: T, payload?: TDebounce extends false | undefined ? EventPayload[T] : () => EventPayload[T], options?: { debounce?: TDebounce; }): void; destroy(): void; } type PasteScope = 'local' | 'global' | false; declare class ClipboardLayer extends SharedInstance { private scopes; private listener; constructor(sharedInstancesBag: SharedInstancesBag); private openUploadList; private _listener; private handlePaste; registerBlock(scope: Node): () => void; destroy(): void; } declare class ActivityHeader extends LitActivityBlock { } declare global { interface HTMLElementTagNameMap { 'uc-activity-header': ActivityHeader; } } declare class Icon extends LitBlock { name: string; private _resolvedHref; private _iconHrefResolver; initCallback(): void; protected willUpdate(changedProperties: PropertyValues<this>): void; private _updateResolvedHref; render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-icon': Icon; } } type SelectOption = { text: string; value: string; }; declare class Select extends LitBlock { value: string; disabled: boolean; options: SelectOption[]; render(): lit_html.TemplateResult<1>; private _handleChange; } declare global { interface HTMLElementTagNameMap { 'uc-select': Select; } } type CameraMode = 'photo' | 'video'; declare class CameraSource extends LitUploaderBlock { couldBeCtxOwner: boolean; activityType: "camera"; private _unsubPermissions; private _capturing; private _chunks; private _mediaRecorder; private _stream; private _selectedAudioId; private _selectedCameraId; private _activeTab; private _options; private _canvas; private _ctx; private _cameraDevices; private _audioDevices; private _permissionResponses; private _permissionCleanupFns; private _currentVideoSource; private readonly _handlePreviewPlay; private readonly _handlePreviewPause; private _timerRef; private _lineRef; private _videoRef; private _switcherRef; private _startTime; private _elapsedTime; private _videoTransformCss; private _videoHidden; private _messageHidden; private _requestBtnHidden; private _cameraSelectOptions; private _cameraSelectHidden; private _l10nMessage; private _timerHidden; private _cameraHidden; private _cameraActionsHidden; private _audioSelectOptions; private _audioSelectHidden; private _audioSelectDisabled; private _audioToggleMicrophoneHidden; private _tabCameraHidden; private _tabVideoHidden; private _currentIcon; private _currentTimelineIcon; private _toggleMicrophoneIcon; private _mutableClassButton; private _chooseActionWithCamera; private _handleCameraSelectChange; private _handleAudioSelectChange; private _handleRequestPermissions; private _handleStartCamera; private _handleToggleRecording; private _handleToggleAudio; private _handleRetake; private _handleAccept; private _handleClickTab; private _updateTimer; private _startTimer; private _stopTimer; private _startTimeline; private _stopTimeline; private _animationFrameId; private _startRecording; private _stopRecording; /** This method is used to toggle recording pause/resume */ private _toggleRecording; private _toggleEnableAudio; /** * Previewing the video that was recorded on the camera */ private _previewVideo; private _attachPreviewListeners; private _detachPreviewListeners; private _setVideoSource; /** * Do not bind srcObject directly in the template, because it stops video pausing on shot. * I really don'y know why but that's how it is. Assigning srcObject manually fixes the issue. */ private _applyVideoSource; private _retake; private _accept; private _handlePhoto; private _handleVideo; private _setCameraState; private _shot; private _handleActiveTab; private _createFile; private _guessExtensionByMime; /** * The send file to the server */ private _toSend; private get _cameraModes(); private _setPermissionsState; private _makeStreamInactive; private _stopCapture; private _capture; private _handlePermissionsChange; private _permissionAccess; private _teardownPermissionListeners; private _requestDeviceAccess; private _getDevices; private _onActivate; private _onDeactivate; private _handleCameraModes; initCallback(): void; firstUpdated(changedProperties: PropertyValues<this>): void; updated(changedProperties: PropertyValues<this>): void; private _destroy; disconnectedCallback(): void; render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-camera-source': CameraSource; } } /** * Config keys that can't be passed as attribute (because they are object or function) */ declare const complexConfigKeys: readonly ["metadata", "localeDefinitionOverride", "secureUploadsSignatureResolver", "secureDeliveryProxyUrlResolver", "iconHrefResolver", "fileValidators", "collectionValidators", "mediaRecorderOptions"]; /** Mapping of attribute names to state */ declare const attrStateMapping: Record<string, string>; declare class Config extends LitBlock { attributesMeta: Partial<ConfigPlainType> & { 'ctx-name': string; }; init$: LitBlock["init$"] & ConfigType; private _computationControllers; private _flushValueToAttribute; private _flushValueToState; private _setValue; private _getValue; private _assertSameValueDifferentReference; initCallback(): void; attributeChangedCallback(name: keyof typeof attrStateMapping, oldVal: string, newVal: string): void; static get observedAttributes(): string[]; } interface Config extends ConfigType { } declare global { interface HTMLElementTagNameMap { 'uc-config': Config; } } declare class TypedData<T extends Record<string, unknown>> { private _ctxId; private _data; constructor(initialValue: T); get uid(): Uid; setValue<K extends keyof T>(prop: K, value: T[K]): void; setMultipleValues(updObj: Partial<T>): void; getValue<K extends keyof T>(prop: K): T[K]; subscribe<K extends keyof T>(prop: K, handler: (newVal: T[K]) => void): Unsubscriber; destroy(): void; } interface UploadEntryData extends Record<string, unknown> { file: File | null; externalUrl: string | null; fileName: string | null; fileSize: number | null; lastModified: number; uploadProgress: number; uuid: string | null; isImage: boolean; mimeType: string | null; ctxName: string | null; cdnUrl: string | null; cdnUrlModifiers: string | null; fileInfo: UploadcareFile | null; isUploading: boolean; abortController: AbortController | null; thumbUrl: string | null; silent: boolean; source: string | null; fullPath: string | null; metadata: Metadata | null; errors: OutputErrorFile[]; uploadError: Error | null; isRemoved: boolean; isQueuedForUploading: boolean; isValidationPending: boolean; isQueuedForValidation: boolean; } type UploadEntryTypedData = TypedData<UploadEntryData>; type UploadEntryKeys = keyof UploadEntryData; declare class FileItemConfig extends LitUploaderBlock { private _entrySubs; protected entry: UploadEntryTypedData | null; protected withEntry<A extends unknown[], R>(fn: (entry: UploadEntryTypedData, ...args: A) => R): (...args: A) => R | undefined; protected subEntry<K extends UploadEntryKeys>(prop: K, handler: (value: UploadEntryData[K]) => void): void; protected reset(): void; disconnectedCallback(): void; } declare class Thumb extends FileItemConfig { badgeIcon: string; uid: Uid; private _thumbUrl; private _renderedGridOnce; private _thumbRect; private _isIntersecting; private _firstViewMode; private _observer?; private _pendingThumbUpdate?; private _calculateThumbSize; private _generateThumbnail; private _debouncedGenerateThumb; private _decodeImage; private _cancelPendingThumbUpdate; private _scheduleThumbUpdate; private _requestThumbGeneration; protected firstUpdated(changedProperties: PropertyValues<this>): void; protected updated(changedProperties: PropertyValues<this>): void; private _observerCallback; protected reset(): void; private _bindToEntry; initCallback(): void; connectedCallback(): void; disconnectedCallback(): void; render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-thumb': Thumb; } } declare class ProgressBar extends LitBlock { hasFileName: boolean; value: number; visible: boolean; private _progressValue; private readonly _fakeProgressLineRef; private readonly _handleFakeProgressAnimation; protected firstUpdated(changedProperties: PropertyValues<this>): void; protected updated(changedProperties: PropertyValues<this>): void; disconnectedCallback(): void; private _normalizeProgressValue; private _updateProgressValueStyle; render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-progress-bar': ProgressBar; } } declare class FileItem extends FileItemConfig { protected couldBeCtxOwner: boolean; private _pauseRender; uid: Uid; private _itemName; private _errorText; private _hint; private _progressValue; private _progressVisible; private _badgeIcon; private _isFinished; private _isFailed; private _isUploading; private _isFocused; private _isEditable; private _showFileNames; private _ariaLabelStatusFile; private _renderedOnce; private _observer?; private _handleEdit; private _handleRemove; private _handleUploadClick; private _calculateState; private _debouncedCalculateState; private _updateHintAndProgress; private _handleState; protected reset(): void; private _observerCallback; private _handleEntryId; private _updateShowFileNames; protected willUpdate(changedProperties: PropertyValues<this>): void; initCallback(): void; connectedCallback(): void; disconnectedCallback(): void; private _upload; static activeInstances: Set<FileItem>; protected shouldUpdate(changedProperties: PropertyValues<this>): boolean; render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-file-item': FileItem; } } declare class DropArea extends LitUploaderBlock { static styleAttrs: string[]; /** * CSS-only attribute */ single: boolean; /** * CSS-only attribute */ ghost: boolean; disabled: boolean; clickable: boolean; withIcon: boolean; fullscreen: boolean; initflow: boolean; text?: string; private _isEnabled; private _isVisible; private _dropTextKey; private _isMultiple; private _updateDropText; private _destroyDropzone; private _destroyContentWrapperDropzone; private _contentWrapperRef; private readonly _handleAreaInteraction; private _sourceListAllowsLocal; private _clickableListenersAttached; isActive(): boolean; initCallback(): void; protected willUpdate(changedProperties: PropertyValues<this & { localeId: string; }>): void; protected updated(changedProperties: PropertyValues<this>): void; /** Ignore drop events if there are other visible drop areas on the page. */ private _shouldIgnore; private _couldHandleFiles; private _updateIsEnabled; private _updateVisibility; private _updateDragStateAttribute; private _setupContentWrapperDropzone; private _updateClickableListeners; disconnectedCallback(): void; render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-drop-area': DropArea; } } type FilesViewMode = 'grid' | 'list'; declare class UploadList extends LitUploaderBlock { couldBeCtxOwner: boolean; protected historyTracked: boolean; activityType: "upload-list"; private _doneBtnVisible; private _doneBtnEnabled; private _uploadBtnVisible; private _addMoreBtnVisible; private _addMoreBtnEnabled; private _commonErrorMessage; private _hasFiles; private _latestSummary; private get _headerText(); private _handleAdd; private _handleUpload; private _handleDone; private _handleCancel; private _throttledHandleCollectionUpdate; private _updateUploadsState; private _getHeaderText; get couldOpenActivity(): boolean; initCallback(): void; disconnectedCallback(): void; render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-upload-list': UploadList; } } declare const ExternalUploadSource: Readonly<{ readonly FACEBOOK: "facebook"; readonly DROPBOX: "dropbox"; readonly DROPBOX_CHOOSER: "dropboxchooser"; readonly GDRIVE: "gdrive"; readonly GPHOTOS: "gphotos"; readonly FLICKR: "flickr"; readonly VK: "vk"; readonly EVERNOTE: "evernote"; readonly BOX: "box"; readonly ONEDRIVE: "onedrive"; readonly HUDDLE: "huddle"; }>; declare const UploadSource: Readonly<{ readonly FACEBOOK: "facebook"; readonly DROPBOX: "dropbox"; readonly DROPBOX_CHOOSER: "dropboxchooser"; readonly GDRIVE: "gdrive"; readonly GPHOTOS: "gphotos"; readonly FLICKR: "flickr"; readonly VK: "vk"; readonly EVERNOTE: "evernote"; readonly BOX: "box"; readonly ONEDRIVE: "onedrive"; readonly HUDDLE: "huddle"; readonly MOBILE_VIDEO_CAMERA: "mobile-video-camera"; readonly MOBILE_PHOTO_CAMERA: "mobile-photo-camera"; readonly LOCAL: "local"; readonly DROP_AREA: "drop-area"; readonly CAMERA: "camera"; readonly EXTERNAL: "external"; readonly API: "js-api"; readonly URL: "url"; readonly DRAW: "draw"; }>; type SourceTypes = (typeof UploadSource)[keyof typeof UploadSource]; type ChangeMap<T extends Record<string, unknown>> = Record<keyof T, Set<Uid>>; type TypedCollectionPropertyObserver<T extends Record<string, unknown>> = (changeMap: ChangeMap<T>) => void; type TypedCollectionObserverHandler<T extends Record<string, unknown>> = (list: Uid[], added: Set<TypedData<T>>, removed: Set<TypedData<T>>) => void; type TypedCollectionOptions<T extends Record<string, unknown>> = { initialValue: T; watchList?: (keyof T)[]; handler?: TypedCollectionObserverHandler<T>; }; declare class TypedCollection<T extends Record<string, unknown>> { private static readonly _destroyDelayMs; private _ctxId; private _data; private _watchList; private _subsMap; private _propertyObservers; private _collectionObservers; private _items; private _removed; private _added; private _markedToDestroy; private _observeTimeout?; private _notifyTimeout?; private _destroyTimeout?; private _notifyObservers; private _initialValue; constructor(options: TypedCollectionOptions<T>); private _notify; private _scheduleDestroyMarkedItems; observeCollection(handler: TypedCollectionObserverHandler<T>): () => void; unobserveCollection(handler: TypedCollectionObserverHandler<T>): void; add(init: Partial<T>): Uid; hasItem(id: Uid): boolean; read(id: Uid): TypedData<T> | null; readProp<K extends keyof T>(id: Uid, propName: K): T[K]; publishProp<K extends keyof T>(id: Uid, propName: K, value: T[K]): void; remove(id: Uid): void; clearAll(): void; observeProperties(handler: TypedCollectionPropertyObserver<T>): () => void; unobserveProperties(handler: TypedCollectionPropertyObserver<T>): void; findItems(checkFn: (item: TypedData<T>) => boolean): Uid[]; items(): Uid[]; get size(): number; destroy(): void; } declare const CameraSourceTypes: Readonly<{ PHOTO: "photo"; VIDEO: "video"; }>; type ModeCameraType = (typeof CameraSourceTypes)[keyof typeof CameraSourceTypes]; declare function buildOutputCollectionState<TCollectionStatus extends OutputCollectionStatus, TGroupFlag extends GroupFlag = 'maybe-has-group'>(bag: SharedInstancesBag): OutputCollectionState<TCollectionStatus, TGroupFlag>; type ApiAddFileCommonOptions = { silent?: boolean; fileName?: string; source?: string; }; declare class UploaderPublicApi extends SharedInstance { private _l10n; get _uploadCollection(): TypedCollection<UploadEntryData>; get cfg(): Readonly<ConfigType>; get l10n(): (str: string, variables?: Record<string, string | number>) => string; /** * TODO: Probably we should not allow user to override `source` property */ addFileFromUrl: (url: string, { silent, fileName, source }?: ApiAddFileCommonOptions) => OutputFileEntry<"idle">; addFileFromUuid: (uuid: string, { silent, fileName, source }?: ApiAddFileCommonOptions) => OutputFileEntry<"idle">; addFileFromCdnUrl: (cdnUrl: string, { silent, fileName, source }?: ApiAddFileCommonOptions) => OutputFileEntry<"idle">; addFileFromObject: (file: File, { silent, fileName, source, fullPath, }?: ApiAddFileCommonOptions & { fullPath?: string; }) => OutputFileEntry<"idle">; removeFileByInternalId: (internalId: string) => void; removeAllFiles(): void; uploadAll: () => void; openSystemDialog: (options?: { captureCamera?: boolean; modeCamera?: ModeCameraType; }) => void; getOutputItem<TStatus extends OutputFileStatus>(entryId: string): OutputFileEntry<TStatus>; getOutputCollectionState<TStatus extends OutputCollectionStatus>(): ReturnType<typeof buildOutputCollectionState<TStatus>>; initFlow: (force?: boolean) => void; doneFlow: () => void; setCurrentActivity: <T extends RegisteredActivityType>(activityType: T, ...params: T extends keyof ActivityParamsMap ? [ActivityParamsMap[T]] : T extends RegisteredActivityType ? [undefined?] : [never]) => void; getCurrentActivity: () => ActivityType; setModalState: (opened: boolean) => void; private get _sourceList(); } type MetadataCallback = (fileEntry: OutputFileEntry) => Promise<Metadata> | Metadata; type LocaleDefinitionOverride = Record<string, Partial<LocaleDefinition>>; type SecureDeliveryProxyUrlResolver = (previewUrl: string, urlParts: { uuid: string; cdnUrlModifiers: string; fileName: string; }) => Promise<string> | string; type SecureUploadsSignatureAndExpire = { secureSignature: string; secureExpire: string; }; type SecureUploadsSignatureResolver = () => Promise<SecureUploadsSignatureAndExpire | null>; type IconHrefResolver = (iconName: string) => string; type FileValidators = FileValidator[]; type CollectionValidators = FuncCollectionValidator[]; type ConfigType = { /** * Your project’s Public Key. */ pubkey: string; /** * Allow multiple file uploads. */ multiple: boolean; /** * Minimum number of files to upload. */ multipleMin: number; /** * Maximum number of files to upload. */ multipleMax: number; /** * Require user confirmation before uploading. */ confirmUpload: boolean; /** * Allow only image files. */ imgOnly: boolean; /** * Native file input accept attribute value. Also affects client validation settings. */ accept: string; /** * Preferred types for external sources. * See [here](https://uploadcare.com/docs/file-uploader/options/#external-sources-preferred-types) */ externalSourcesPreferredTypes: string; /** * Provide custom CSS to the social sources iframe */ externalSourcesEmbedCss: string; /** * Store uploaded files. */ store: boolean | 'auto'; /** * Mirror the camera view. */ cameraMirror: boolean; /** * Default camera capture mode. */ cameraCapture: 'user' | 'environment' | ''; /** * List of sources for file uploads. */ sourceList: string; /** * Top-level origin for the uploader. * This is used for Google Drive Picker if there is no access to the origin due to the cross-origin policy. */ topLevelOrigin: string; /** * Maximum size of local files in bytes. */ maxLocalFileSizeBytes: number; /** * Thumbnail size. */ thumbSize: number; /** * Show the upload list even if it is empty. */ showEmptyList: boolean; /** * Use local image editor. */ useLocalImageEditor: boolean; /** * Enable cloud image editing. */ useCloudImageEditor: boolean; /** * Tabs to show in the cloud image editor. * * @default 'crop, tuning, filters' */ cloudImageEditorTabs: string; /** * Remove copyright information. */ removeCopyright: boolean; /** * Defines the crop behavior. When uploading images, your users can select a crop area with a defined aspect ratio. */ cropPreset: string; /** * Image shrink options. */ imageShrink: string; /** * Lock scroll when modal is open. */ modalScrollLock: boolean; /** * Show strokes on modal backdrop. */ modalBackdropStrokes: boolean; /** * Wrap the source list. */ sourceListWrap: boolean; /** * Key to revoke Custom OAuth access. See [OAuth docs](https://uploadcare.com/docs/upload-sources/#oauth) for details. */ remoteTabSessionKey: string; /** * Set custom CNAME. */ cdnCname: string; /** * Set CNAME base domain for prefixed CDN URLs. */ cdnCnamePrefixed: string; /** * Set a custom upload URL. */ baseUrl: string; /** * Set a custom social sources URL. */ socialBaseUrl: string; /** * Secure signature for uploads. */ secureSignature: string; /** * Expiry time for secure uploads. */ secureExpire: string; /** * Proxy URL for secure delivery. */ secureDeliveryProxy: string; /** * Maximum number of retry attempts for throttled requests. */ retryThrottledRequestMaxTimes: number; /** * Maximum number of retry attempts for network errors. */ retryNetworkErrorMaxTimes: number; /** * Minimum file size for multipart uploads. */ multipartMinFileSize: number; /** * Chunk size for multipart uploads. */ multipartChunkSize: number; /** * Maximum number of concurrent requests. */ maxConcurrentRequests: number; /** * Maximum number of concurrent multipart requests. */ multipartMaxConcurrentRequests: number; /** * Maximum number of attempts for multipart uploads. */ multipartMaxAttempts: number; /** * Check for URL duplicates. */ checkForUrlDuplicates: boolean; /** * Save URL for recurrent uploads. */ saveUrlForRecurrentUploads: boolean; /** * Group output files. */ groupOutput: boolean; /** * User agent integration string. */ userAgentIntegration: string; /** * Enable debug mode. */ debug: boolean; /** * Locale name for the uploader. */ localeName: string; /** * Expiry threshold for secure uploads. */ secureUploadsExpireThreshold: number; /** * Metadata for the file. */ metadata: Metadata | MetadataCallback | null; /** * Override locale definitions. */ localeDefinitionOverride: LocaleDefinitionOverride | null; /** * Resolver for secure uploads signature. */ secureUploadsSignatureResolver: SecureUploadsSignatureResolver | null; /** * Resolver for secure delivery proxy URL. */ secureDeliveryProxyUrlResolver: SecureDeliveryProxyUrlResolver | null; /** * Resolver for icon href. */ iconHrefResolver: IconHrefResolver | null; /** * Validators for individual files. */ fileValidators: FileValidators; /** * Validators for file collections. */ collectionValidators: CollectionValidators; /** * Timeout for async validation functions, in milliseconds. */ validationTimeout: number; /** * The number of files to validate concurrently. */ validationConcurrency: number; /** * The camera modes to enable in the camera modal, * it is possible to select photo or video capture. * The first mode is the default mode. * @default 'photo,video' */ cameraModes: string; /** * The default tab to open in the camera modal, * it is possible to select video or photo capture * @default 'null' * @deprecated - use `cameraModes` instead */ defaultCameraMode: CameraMode | null; /** * Enable audio recording. * @default true */ enableAudioRecording: boolean; /** * Enable video recording. * @deprecated - use `cameraModes` instead * @default null */ enableVideoRecording: boolean | null; /** * The maximum duration of the video recording in seconds * @default null */ maxVideoRecordingDuration: number | null; /** * A dictionary object that can contain * the following properties from MediaRecorderOptions */ mediaRecorderOptions: MediaRecorderOptions | null; filesViewMode: FilesViewMode; gridShowFileNames: boolean; cloudImageEditorAutoOpen: boolean; qualityInsights: boolean; cloudImageEditorMaskHref: string | null; /** * Adds data-testid attributes to the each block. Needed for testing purposes. * @default false */ testMode: boolean; /** * Define the clipboard paste scope. */ pasteScope: PasteScope; }; type ConfigComplexType = Pick<ConfigType, (typeof complexConfigKeys)[number]>; type ConfigPlainType = Omit<ConfigType, keyof ConfigComplexType>; type OutputFileStatus = 'idle' | 'uploading' | 'success' | 'failed' | 'removed'; type OutputCustomErrorType = 'CUSTOM_ERROR'; type OutputFileErrorType = OutputCustomErrorType | 'NOT_AN_IMAGE' | 'FORBIDDEN_FILE_TYPE' | 'FILE_SIZE_EXCEEDED' | 'UPLOAD_ERROR' | 'NETWORK_ERROR' | 'UNKNOWN_ERROR'; type OutputCollectionErrorType = OutputCustomErrorType | 'SOME_FILES_HAS_ERRORS' | 'TOO_MANY_FILES' | 'TOO_FEW_FILES'; type OutputFileErrorPayload = { entry: OutputFileEntry; }; type OutputErrorTypePayload = { NOT_AN_IMAGE: OutputFileErrorPayload; FORBIDDEN_FILE_TYPE: OutputFileErrorPayload; FILE_SIZE_EXCEEDED: OutputFileErrorPayload; SOME_FILES_HAS_ERRORS: { [k: string]: never; }; TOO_MANY_FILES: { min: number; max: number; total: number; }; TOO_FEW_FILES: { min: number; max: number; total: number; }; UPLOAD_ERROR: OutputFileErrorPayload & { error: UploadError; }; NETWORK_ERROR: OutputFileErrorPayload & { error: NetworkError; }; UNKNOWN_ERROR: OutputFileErrorPayload & { error?: Error; }; CUSTOM_ERROR: Record<string, unknown>; }; type OutputError<T extends OutputFileErrorType | OutputCollectionErrorType> = T extends OutputCustomErrorType ? { type?: T; message: string; payload?: OutputErrorTypePayload[T]; } : T extends keyof OutputErrorTypePayload ? { type: T; message: string; payload?: OutputErrorTypePayload[T]; } : never; type OutputErrorFile = OutputError<OutputFileErrorType>; type OutputErrorCollection = OutputError<OutputCollectionErrorType>; type OutputFileEntry<TStatus extends OutputFileStatus = OutputFileStatus> = { status: TStatus; internalId: string; name: string; size: number; isImage: boolean; mimeType: string; metadata: Metadata | null; file: File | Blob | null; externalUrl: string | null; uploadProgress: number; fullPath: string | null; source: SourceTypes | null; isValidationPending: boolean; } & ({ status: 'success'; fileInfo: UploadcareFile; uuid: string; cdnUrl: string; cdnUrlModifiers: string; isUploading: false; isSuccess: true; isFailed: false; isRemoved: false; errors: []; } | { status: 'failed'; fileInfo: UploadcareFile | null; uuid: string | null; cdnUrl: string | null; cdnUrlModifiers: string | null; isUploading: false; isSuccess: false; isFailed: true; isRemoved: false; errors: OutputError<OutputFileErrorType>[]; } | { status: 'uploading'; fileInfo: null; uuid: null; cdnUrl: null; cdnUrlModifiers: null; isUploading: true; isSuccess: false; isFailed: false; isRemoved: false; errors: []; } | { status: 'removed'; fileInfo: UploadcareFile | null; uuid: string | null; cdnUrl: string | null; cdnUrlModifiers: string | null; isUploading: false; isSuccess: false; isFailed: false; isRemoved: true; errors: OutputError<OutputFileErrorType>[]; } | { status: 'idle'; fileInfo: null; uuid: null; cdnUrl: null; cdnUrlModifiers: null; isUploading: false; isSuccess: false; isFailed: false; isRemoved: false; errors: []; }); type OutputCollectionStatus = 'idle' | 'uploading' | 'success' | 'failed'; type GroupFlag = 'has-group' | 'maybe-has-group'; type OutputCollectionState<TStatus extends OutputCollectionStatus = OutputCollectionStatus, TGroupFlag extends GroupFlag = 'maybe-has-group'> = { status: TStatus; totalCount: number; successCount: number; failedCount: number; uploadingCount: number; progress: number; successEntries: OutputFileEntry<'success'>[]; failedEntries: OutputFileEntry<'failed'>[]; uploadingEntries: OutputFileEntry<'uploading'>[]; idleEntries: OutputFileEntry<'idle'>[]; } & (TGroupFlag extends 'has-group' ? { group: UploadcareGroup; } : TGroupFlag extends 'maybe-has-group' ? { group: UploadcareGroup | null; } : never) & ({ status: 'idle'; isFailed: false; isUploading: false; isSuccess: false; errors: []; allEntries: OutputFileEntry<'idle' | 'success'>[]; } | { status: 'uploading'; isFailed: false; isUploading: true; isSuccess: false; errors: []; allEntries: OutputFileEntry[]; } | { status: 'success'; isFailed: false; isUploading: false; isSuccess: true; errors: []; allEntries: OutputFileEntry<'success'>[]; } | { status: 'failed'; isFailed: true; isUploading: false; isSuccess: false; errors: OutputError<OutputCollectionErrorType>[]; allEntries: OutputFileEntry[]; }); declare class SecureUploadsManager extends SharedInstance { private _secureToken; getSecureToken(): Promise<SecureUploadsSignatureAndExpire | null>; destroy(): void; } declare class LitUploaderBlock extends LitActivityBlock { static extSrcList: Readonly<typeof ExternalUploadSource>; static sourceTypes: Readonly<typeof UploadSource>; protected couldBeCtxOwner: boolean; private _isCtxOwner; private _unobserveCollection?; private _unobserveCollectionProperties?; init$: { '*commonProgress': number; '*uploadList': never[]; '*uploadQueue': _uploadcare_upload_client.Queue; '*collectionErrors': OutputErrorCollection[]; '*collectionState': OutputCollectionState | null; '*groupInfo': _uploadcare_upload_client.UploadcareGroup | null; '*uploadTrigger': Set<string>; '*currentActivity': null; '*currentActivityParams': {}; '*history': never[]; '*historyBack': null; '*closeModal': () => void; }; private get _hasCtxOwner(); initCallback(): void; getAPI(): UploaderPublicApi; get validationManager(): ValidationManager; get api(): UploaderPublicApi; get uploadCollection(): TypedCollection<UploadEntryData>; get secureUploadsManager(): SecureUploadsManager; disconnectedCallback(): void; connectedCallback(): void; private _initCtxOwner; private _observeUploadCollection; private _unobserveUploadCollection; private _createGroup; private _flushOutputItems; private _handleCollectionUpdate; private _handleCollectionPropertiesUpdate; private _flushCommonUploadProgress; private _openCloudImageEditor; private _setInitialCrop; protected getMetadataFor(entryId: string): Promise<_uploadcare_upload_client.Metadata | undefined>; protected getUploadClientOptions(): Promise<FileFromOptions>; getOutputData(): OutputFileEntry[]; } /** * Mapping of loading resources per operation */ type LoadingOperations = Map<string, Map<string, boolean>>; /** * Image size */ interface ImageSize { width: number; height: number; } interface Transformations { enhance?: number; brightness?: number; exposure?: number; gamma?: number; contrast?: number; saturation?: number; vibrance?: number; warmth?: number; rotate?: number; mirror?: boolean; flip?: boolean; filter?: { name: string; amount: number; }; crop?: { dimensions: [number, number]; coords: [number, number]; }; } interface ApplyResult { originalUrl: string; cdnUrlModifiers: string; cdnUrl: string; transformations: Transformations; } type ChangeResult = ApplyResult; interface CropAspectRatio { type: 'aspect-ratio'; width: number; height: number; id: string; hasFreeform?: boolean; } type CropPresetList = CropAspectRatio[]; declare class CloudImageEditor extends CloudImageEditorBlock { static styleAttrs: string[]; constructor(); initCallback(): void; } declare global { interface HTMLElementTagNameMap { 'uc-cloud-image-editor': CloudImageEditor; } } type ActivityParams$1 = { internalId: string; }; declare class CloudImageEditorActivity extends LitUploaderBlock { couldBeCtxOwner: boolean; activityType: "cloud-image-edit"; private _entry?; private _editorConfig; get activityParams(): ActivityParams$1; initCallback(): void; private _handleApply; private _handleCancel; handleChange(event: CustomEvent<ChangeResult>): void; private _mountEditor; private _unmountEditor; render(): lit_html.TemplateResult<1> | typeof nothing; private _createEditorConfig; } declare global { interface HTMLElementTagNameMap { 'uc-cloud-image-editor-activity': CloudImageEditorActivity; } } declare class Spinner extends LitBlock { render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-spinner': Spinner; } } type ActivityParams = { externalSourceType: string; }; declare class ExternalSource extends LitUploaderBlock { couldBeCtxOwner: boolean; activityType: "external"; private _messageBridge?; private _iframeRef; private _latestSelectionSummary; private _selectedList; private _isSelectionReady; private _isDoneBtnEnabled; private _couldSelectAll; private _couldDeselectAll; private _showSelectionStatus; private _showDoneBtn; private _doneBtnTextClass; private _toolbarVisible; private get _counterText(); get activityParams(): ActivityParams; initCallback(): void; private _extractUrlFromSelectedFile; private _handleToolbarStateChange; private _handleSelectedFilesChange; private _handleIframeLoad; private _applyTheme; private _applyEmbedCss; private _setupL10n; private _remoteUrl; private _handleDone; private _handleCancel; private _handleSelectAll; private _handleDeselectAll; private _setSelectionSummary; private _mountIframe; private _unmountIframe; private _resetSelectionStatus; disconnectedCallback(): void; render(): lit_html.TemplateResult<1>; } declare global { interface HTMLElementTagNameMap { 'uc-external-source': ExternalSource; } } declare const ACTIVITY_TYPES: Readonly<{ START_FROM: "start-from"; CAMERA: "camera"; DRAW: "draw"; UPLOAD_LIST: "upload-list"; URL: "url"; CLOUD_IMG_EDIT: "cloud-image-edit"; EXTERNAL: "external"; }>; type RegisteredActivityType = (typeof ACTIVITY_TYPES)[keyof typeof ACTIVITY_TYPES]; type ActivityType = RegisteredActivityType | (string & {}) | null; declare const ACTIVE_PROP = "___ACTIVITY_IS_ACTIVE___"; type ActivityParamsMap = { 'cloud-image-edit': ActivityParams$1; external: ActivityParams; }; declare class LitActivityBlock extends LitBlock { protected historyTracked: boolean; private [ACTIVE_PROP]?; init$: { '*currentActivity': null; '*currentActivityParams': {}; '*history': never[]; '*historyBack': null; '*closeModal': () => void; }; private _debouncedHistoryFlush; private _deactivate; private _activate; initCallback(): void; private _historyFlush; private _isActivityRegistered; private static _activityCallbacks; static activities: Readonly<{ START_FROM: 'start-from'; CAMERA: 'camera'; DRAW: 'draw'; UPLOAD_LIST: 'upload-list'; URL: 'url'; CLOUD_IMG_EDIT: 'cloud-image-edit'; EXTERNAL: 'external'; }>; protected get isActivityActive(): boolean; get couldOpenActivity(): boolean; /** TODO: remove name argument */ protected registerActivity(_name: string, options?: { onActivate?: () => void; onDeactivate?: () => void; }): void; private _unregisterActivity; disconnectedCallback(): void; get activityParams(): ActivityParamsMap[keyof ActivityParamsMap]; get initActivity(): string | null; get doneActivity(): string | null; historyBack(): void; } declare const ModalEvents: Readonly<{ readonly ADD: "modal:add"; readonly DELETE: "modal:delete"; readonly OPEN: "modal:open"; readonly CLOSE: "modal:close"; readonly CLOSE_ALL: "modal:closeAll"; readonly DESTROY: "modal:destroy"; }>; type ModalId = ActivityType; type ModalCb = (data: { id: ModalId; modal: Modal; }) => void; type ModalEventType = (typeof ModalEvents)[keyof typeof ModalEvents]; declare class ModalManager extends SharedInstance { private _modals; private _activeModals; private _subscribers; /** * Register a modal with the manager * @param id Unique identifier for the modal * @param modal Modal component instance */ registerModal(id: ModalId, modal: Modal): void; /** Remove a modal by ID. */ deleteModal(id: ModalId): boolean; /** Open a modal by its ID. */ open(id: ModalId): boolean; /** Close a specific modal by ID. */ close(id: ModalId): boolean; /** Toggle a modal - open if closed, close if open. */ toggle(id: ModalId): boolean; /** True if there are any active modals. */ get hasActiveModals(): boolean; /** Close the most recently opened modal and return to the previous one. */ back(): boolean; /** Close all open modals. */ closeAll(): number; /** * Subscribe to modal events * @returns Unsubscribe function */ subscribe(event: ModalEventType, callback: ModalCb): () => void; /** Unsubscribe from modal events */ unsubs