diff --git a/abstract/UploaderBlock.js b/abstract/UploaderBlock.js index 8e0ab5a7a..619deaf36 100644 --- a/abstract/UploaderBlock.js +++ b/abstract/UploaderBlock.js @@ -2,18 +2,21 @@ import { ActivityBlock } from './ActivityBlock.js'; import { Data } from '@symbiotejs/symbiote'; -import { IMAGE_ACCEPT_LIST, mergeFileTypes, fileIsImage, matchMimeType, matchExtension } from '../utils/fileTypes.js'; -import { uploadEntrySchema } from './uploadEntrySchema.js'; -import { customUserAgent } from '../blocks/utils/userAgent.js'; -import { TypedCollection } from './TypedCollection.js'; -import { uploaderBlockCtx } from './CTX.js'; -import { EVENT_TYPES, EventData, EventManager } from './EventManager.js'; +import { calculateMaxCenteredCropFrame } from '../blocks/CloudImageEditor/src/crop-utils.js'; +import { parseCropPreset } from '../blocks/CloudImageEditor/src/lib/parseCropPreset.js'; import { Modal } from '../blocks/Modal/Modal.js'; -import { stringToArray } from '../utils/stringToArray.js'; -import { warnOnce } from '../utils/warnOnce.js'; import { UploadSource } from '../blocks/utils/UploadSource.js'; -import { prettyBytes } from '../utils/prettyBytes.js'; import { debounce } from '../blocks/utils/debounce.js'; +import { customUserAgent } from '../blocks/utils/userAgent.js'; +import { createCdnUrl, createCdnUrlModifiers } from '../utils/cdn-utils.js'; +import { IMAGE_ACCEPT_LIST, fileIsImage, matchExtension, matchMimeType, mergeFileTypes } from '../utils/fileTypes.js'; +import { prettyBytes } from '../utils/prettyBytes.js'; +import { stringToArray } from '../utils/stringToArray.js'; +import { warnOnce } from '../utils/warnOnce.js'; +import { uploaderBlockCtx } from './CTX.js'; +import { EVENT_TYPES, EventData, EventManager } from './EventManager.js'; +import { TypedCollection } from './TypedCollection.js'; +import { uploadEntrySchema } from './uploadEntrySchema.js'; export class UploaderBlock extends ActivityBlock { couldBeUploadCollectionOwner = false; @@ -457,6 +460,9 @@ export class UploaderBlock extends ActivityBlock { ); } if (changeMap.fileInfo) { + if (this.cfg.cropPreset) { + this.setInitialCrop(); + } let loadedItems = uploadCollection.findItems((entry) => { return !!entry.getValue('fileInfo'); }); @@ -527,6 +533,43 @@ export class UploaderBlock extends ActivityBlock { } }; + /** @private */ + setInitialCrop() { + const cropPreset = parseCropPreset(this.cfg.cropPreset); + if (cropPreset) { + const [aspectRatioPreset] = cropPreset; + + const entries = this.uploadCollection + .findItems( + (entry) => + entry.getValue('fileInfo') && + entry.getValue('isImage') && + !entry.getValue('cdnUrlModifiers')?.includes('/crop/') + ) + .map((id) => this.uploadCollection.read(id)); + + for (const entry of entries) { + const fileInfo = entry.getValue('fileInfo'); + const { width, height } = fileInfo.imageInfo; + const expectedAspectRatio = aspectRatioPreset.width / aspectRatioPreset.height; + const crop = calculateMaxCenteredCropFrame(width, height, expectedAspectRatio); + const cdnUrlModifiers = createCdnUrlModifiers(`crop/${crop.width}x${crop.height}/${crop.x},${crop.y}`); + entry.setMultipleValues({ + cdnUrlModifiers, + cdnUrl: createCdnUrl(entry.getValue('cdnUrl'), cdnUrlModifiers), + }); + if ( + this.uploadCollection.size === 1 && + this.cfg.useCloudImageEditor && + this.hasBlockInCtx((block) => block.activityType === ActivityBlock.activities.CLOUD_IMG_EDIT) + ) { + this.$['*focusedEntry'] = entry; + this.$['*currentActivity'] = ActivityBlock.activities.CLOUD_IMG_EDIT; + } + } + } + } + /** @private */ async getMetadata() { const configValue = this.cfg.metadata ?? /** @type {import('../types').Metadata} */ (this.$['*uploadMetadata']); @@ -614,41 +657,47 @@ UploaderBlock.sourceTypes = Object.freeze({ }); Object.values(EVENT_TYPES).forEach((eType) => { - let eName = EventManager.eName(eType); - window.addEventListener(eName, (e) => { - let outputTypes = [EVENT_TYPES.UPLOAD_FINISH, EVENT_TYPES.REMOVE, EVENT_TYPES.CDN_MODIFICATION]; - // @ts-ignore TODO: fix this - if (outputTypes.includes(e.detail.type)) { + const eName = EventManager.eName(eType); + const cb = debounce( + /** @param {CustomEvent} e */ + (e) => { + let outputTypes = [EVENT_TYPES.UPLOAD_FINISH, EVENT_TYPES.REMOVE, EVENT_TYPES.CDN_MODIFICATION]; // @ts-ignore TODO: fix this - let dataCtx = Data.getCtx(e.detail.ctx); - /** @type {TypedCollection} */ - let uploadCollection = dataCtx.read('uploadCollection'); - // @ts-ignore TODO: fix this - let data = []; - uploadCollection.items().forEach((id) => { - let uploadEntryData = Data.getCtx(id).store; - /** @type {import('@uploadcare/upload-client').UploadcareFile} */ - let fileInfo = uploadEntryData.fileInfo; - if (fileInfo) { - let outputItem = { - ...fileInfo, - cdnUrlModifiers: uploadEntryData.cdnUrlModifiers, - cdnUrl: uploadEntryData.cdnUrl || fileInfo.cdnUrl, - }; - data.push(outputItem); - } - }); - EventManager.emit( - new EventData({ - type: EVENT_TYPES.DATA_OUTPUT, - // @ts-ignore TODO: fix this - ctx: e.detail.ctx, - // @ts-ignore TODO: fix this - data, - }) - ); - // @ts-ignore TODO: fix this - dataCtx.pub('outputData', data); - } - }); + if (outputTypes.includes(e.detail.type)) { + // @ts-ignore TODO: fix this + let dataCtx = Data.getCtx(e.detail.ctx); + /** @type {TypedCollection} */ + let uploadCollection = dataCtx.read('uploadCollection'); + // @ts-ignore TODO: fix this + let data = []; + uploadCollection.items().forEach((id) => { + let uploadEntryData = Data.getCtx(id).store; + /** @type {import('@uploadcare/upload-client').UploadcareFile} */ + let fileInfo = uploadEntryData.fileInfo; + if (fileInfo) { + let outputItem = { + ...fileInfo, + cdnUrlModifiers: uploadEntryData.cdnUrlModifiers, + cdnUrl: uploadEntryData.cdnUrl || fileInfo.cdnUrl, + }; + data.push(outputItem); + } + }); + EventManager.emit( + new EventData({ + type: EVENT_TYPES.DATA_OUTPUT, + // @ts-ignore TODO: fix this + ctx: e.detail.ctx, + // @ts-ignore TODO: fix this + data, + }) + ); + // @ts-ignore TODO: fix this + dataCtx.pub('outputData', data); + } + }, + 0 + ); + // @ts-ignore TODO: fix this + window.addEventListener(eName, cb); }); diff --git a/blocks/CloudImageEditor/src/CloudImageEditorBlock.js b/blocks/CloudImageEditor/src/CloudImageEditorBlock.js index e49a27573..d72ee22d0 100644 --- a/blocks/CloudImageEditor/src/CloudImageEditorBlock.js +++ b/blocks/CloudImageEditor/src/CloudImageEditorBlock.js @@ -7,9 +7,10 @@ import { extractUuid, } from '../../../utils/cdn-utils.js'; import { TRANSPARENT_PIXEL_SRC } from '../../../utils/transparentPixelSrc.js'; +import { debounce } from '../../utils/debounce.js'; import { CloudImageEditorBase } from './CloudImageEditorBase.js'; import { classNames } from './lib/classNames.js'; -import { debounce } from './lib/debounce.js'; +import { parseCropPreset } from './lib/parseCropPreset.js'; import { operationsToTransformations, transformationsToOperations } from './lib/transformationUtils.js'; import { initState } from './state.js'; import { TEMPLATE } from './template.js'; @@ -18,12 +19,14 @@ import { TabId } from './toolbar-constants.js'; export class CloudImageEditorBlock extends CloudImageEditorBase { static className = 'cloud-image-editor'; - // @ts-ignore TODO: fix this - init$ = { - ...this.init$, - // @ts-ignore TODO: fix this - ...initState(this), - }; + constructor() { + super(); + + this.init$ = { + ...this.init$, + ...initState(this), + }; + } /** Force cloud editor to always use own context */ get ctxName() { @@ -74,6 +77,48 @@ export class CloudImageEditorBlock extends CloudImageEditorBase { this.initEditor(); } + async updateImage() { + await this._waitForSize(); + + if (this.$['*tabId'] === TabId.CROP) { + this.$['*cropperEl'].deactivate({ reset: true }); + } else { + this.$['*faderEl'].deactivate(); + } + + this.$['*editorTransformations'] = {}; + + if (this.$.cdnUrl) { + let uuid = extractUuid(this.$.cdnUrl); + this.$['*originalUrl'] = createOriginalUrl(this.$.cdnUrl, uuid); + let operations = extractOperations(this.$.cdnUrl); + let transformations = operationsToTransformations(operations); + this.$['*editorTransformations'] = transformations; + } else if (this.$.uuid) { + this.$['*originalUrl'] = createOriginalUrl(this.cfg.cdnCname, this.$.uuid); + } else { + throw new Error('No UUID nor CDN URL provided'); + } + + try { + const cdnUrl = createCdnUrl(this.$['*originalUrl'], createCdnUrlModifiers('json')); + const json = await fetch(cdnUrl).then((response) => response.json()); + + const { width, height } = /** @type {{ width: number; height: number }} */ (json); + this.$['*imageSize'] = { width, height }; + + if (this.$['*tabId'] === TabId.CROP) { + this.$['*cropperEl'].activate(this.$['*imageSize']); + } else { + this.$['*faderEl'].activate({ url: this.$['*originalUrl'] }); + } + } catch (err) { + if (err) { + console.error('Failed to load image info', err); + } + } + } + async initEditor() { try { await this._waitForSize(); @@ -109,6 +154,10 @@ export class CloudImageEditorBlock extends CloudImageEditorBase { } }); + this.sub('cropPreset', (val) => { + this.$['*cropPresetList'] = parseCropPreset(val); + }); + this.sub('*tabId', (tabId) => { this.ref['img-el'].className = classNames('image', { image_hidden_to_cropper: tabId === TabId.CROP, @@ -116,18 +165,6 @@ export class CloudImageEditorBlock extends CloudImageEditorBase { }); }); - if (this.$.cdnUrl) { - let uuid = extractUuid(this.$.cdnUrl); - this.$['*originalUrl'] = createOriginalUrl(this.$.cdnUrl, uuid); - let operations = extractOperations(this.$.cdnUrl); - let transformations = operationsToTransformations(operations); - this.$['*editorTransformations'] = transformations; - } else if (this.$.uuid) { - this.$['*originalUrl'] = createOriginalUrl(this.cfg.cdnCname, this.$.uuid); - } else { - throw new Error('No UUID nor CDN URL provided'); - } - this.classList.add('editor_ON'); this.sub('*networkProblems', (networkProblems) => { @@ -138,6 +175,9 @@ export class CloudImageEditorBlock extends CloudImageEditorBase { this.sub( '*editorTransformations', (transformations) => { + if (Object.keys(transformations).length === 0) { + return; + } let originalUrl = this.$['*originalUrl']; let cdnUrlModifiers = createCdnUrlModifiers(transformationsToOperations(transformations)); let cdnUrl = createCdnUrl(originalUrl, createCdnUrlModifiers(cdnUrlModifiers, 'preview')); @@ -160,18 +200,8 @@ export class CloudImageEditorBlock extends CloudImageEditorBase { false ); - try { - fetch(createCdnUrl(this.$['*originalUrl'], createCdnUrlModifiers('json'))) - .then((response) => response.json()) - .then((json) => { - const { width, height } = /** @type {{ width: number; height: number }} */ (json); - this.$['*imageSize'] = { width, height }; - }); - } catch (err) { - if (err) { - console.error('Failed to load image info', err); - } - } + this.sub('uuid', (val) => val && this.updateImage()); + this.sub('cdnUrl', (val) => val && this.updateImage()); } } @@ -179,4 +209,5 @@ CloudImageEditorBlock.template = TEMPLATE; CloudImageEditorBlock.bindAttributes({ uuid: 'uuid', 'cdn-url': 'cdnUrl', + 'crop-preset': 'cropPreset', }); diff --git a/blocks/CloudImageEditor/src/CropFrame.js b/blocks/CloudImageEditor/src/CropFrame.js index 4b8f8d62c..b8b34d3fd 100644 --- a/blocks/CloudImageEditor/src/CropFrame.js +++ b/blocks/CloudImageEditor/src/CropFrame.js @@ -1,13 +1,14 @@ +// @ts-check import { CloudImageEditorBase } from './CloudImageEditorBase.js'; import { + clamp, constraintRect, cornerPath, createSvgNode, - expandRect, - intersectionRect, - minRectSize, moveRect, rectContainsPoint, + resizeRect, + roundRect, setSvgNodeAttrs, sidePath, thumbCursor, @@ -15,22 +16,25 @@ import { import { GUIDE_STROKE_WIDTH, GUIDE_THIRD, + MAX_INTERACTION_SIZE, MIN_CROP_SIZE, + MIN_INTERACTION_SIZE, THUMB_CORNER_SIZE, THUMB_OFFSET, + THUMB_SIDE_SIZE, THUMB_STROKE_WIDTH, } from './cropper-constants.js'; import { classNames } from './lib/classNames.js'; export class CropFrame extends CloudImageEditorBase { - init$ = { - ...this.init$, - dragging: false, - }; - constructor() { super(); + this.init$ = { + ...this.init$, + dragging: false, + }; + /** @private */ this._handlePointerUp = this._handlePointerUp_.bind(this); @@ -41,6 +45,10 @@ export class CropFrame extends CloudImageEditorBase { this._handleSvgPointerMove = this._handleSvgPointerMove_.bind(this); } + /** + * @private + * @param {import('./types.js').Direction} direction + */ _shouldThumbBeDisabled(direction) { let imageBox = this.$['*imageBox']; if (!imageBox) { @@ -56,6 +64,7 @@ export class CropFrame extends CloudImageEditorBase { return tooHigh || tooWide; } + /** @private */ _createBackdrop() { /** @type {import('./types.js').Rectangle} */ let cropBox = this.$['*cropBox']; @@ -99,17 +108,23 @@ export class CropFrame extends CloudImageEditorBase { this._backdropMaskInner = maskRectInner; } - /** Super tricky workaround for the chromium bug See https://bugs.chromium.org/p/chromium/issues/detail?id=330815 */ + /** + * @private Super Tricky workaround for the chromium bug See + * https://bugs.chromium.org/p/chromium/issues/detail?id=330815 + */ _resizeBackdrop() { if (!this._backdropMask) { return; } this._backdropMask.style.display = 'none'; window.requestAnimationFrame(() => { - this._backdropMask.style.display = 'block'; + if (this._backdropMask) { + this._backdropMask.style.display = 'block'; + } }); } + /** @private */ _updateBackdrop() { /** @type {import('./types.js').Rectangle} */ let cropBox = this.$['*cropBox']; @@ -118,31 +133,55 @@ export class CropFrame extends CloudImageEditorBase { } let { x, y, width, height } = cropBox; - setSvgNodeAttrs(this._backdropMaskInner, { x, y, width, height }); + this._backdropMaskInner && setSvgNodeAttrs(this._backdropMaskInner, { x, y, width, height }); } + /** @private */ _updateFrame() { /** @type {import('./types.js').Rectangle} */ let cropBox = this.$['*cropBox']; - if (!cropBox) { + + if (!cropBox || !this._frameGuides || !this._frameThumbs) { return; } for (let thumb of Object.values(this._frameThumbs)) { let { direction, pathNode, interactionNode, groupNode } = thumb; let isCenter = direction === ''; let isCorner = direction.length === 2; + let { x, y, width, height } = cropBox; if (isCenter) { - let { x, y, width, height } = cropBox; - let center = [x + width / 2, y + height / 2]; + const moveThumbRect = { + x: x + width / 3, + y: y + height / 3, + width: width / 3, + height: height / 3, + }; + setSvgNodeAttrs(interactionNode, moveThumbRect); + } else { + const thumbSizeMultiplier = clamp( + Math.min(width, height) / (THUMB_CORNER_SIZE * 2 + THUMB_SIDE_SIZE) / 2, + 0, + 1 + ); + + let { d, center } = isCorner + ? cornerPath(cropBox, direction, thumbSizeMultiplier) + : sidePath( + cropBox, + /** @type {Extract} */ (direction), + thumbSizeMultiplier + ); + const size = Math.max( + MAX_INTERACTION_SIZE * clamp(Math.min(width, height) / MAX_INTERACTION_SIZE / 3, 0, 1), + MIN_INTERACTION_SIZE + ); setSvgNodeAttrs(interactionNode, { - r: Math.min(width, height) / 3, - cx: center[0], - cy: center[1], + x: center[0] - size, + y: center[1] - size, + width: size * 2, + height: size * 2, }); - } else { - let { d, center } = isCorner ? cornerPath(cropBox, direction) : sidePath(cropBox, direction); - setSvgNodeAttrs(interactionNode, { cx: center[0], cy: center[1] }); setSvgNodeAttrs(pathNode, { d }); } @@ -156,8 +195,7 @@ export class CropFrame extends CloudImageEditorBase { ); } - let frameGuides = this._frameGuides; - setSvgNodeAttrs(frameGuides, { + setSvgNodeAttrs(this._frameGuides, { x: cropBox.x - GUIDE_STROKE_WIDTH * 0.5, y: cropBox.y - GUIDE_STROKE_WIDTH * 0.5, width: cropBox.width + GUIDE_STROKE_WIDTH, @@ -165,17 +203,27 @@ export class CropFrame extends CloudImageEditorBase { }); } + /** @private */ _createThumbs() { - let frameThumbs = {}; + /** + * @type {Partial<{ + * [K in import('./types.js').Direction]: { + * direction: import('./types.js').Direction; + * pathNode: SVGElement; + * interactionNode: SVGElement; + * groupNode: SVGElement; + * }; + * }>} + */ + const frameThumbs = {}; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { - let direction = `${['n', '', 's'][i]}${['w', '', 'e'][j]}`; + let direction = /** @type {import('./types.js').Direction} */ (`${['n', '', 's'][i]}${['w', '', 'e'][j]}`); let groupNode = createSvgNode('g'); groupNode.classList.add('thumb'); groupNode.setAttribute('with-effects', ''); - let interactionNode = createSvgNode('circle', { - r: THUMB_CORNER_SIZE + THUMB_OFFSET, + let interactionNode = createSvgNode('rect', { fill: 'transparent', }); let pathNode = createSvgNode('path', { @@ -199,6 +247,7 @@ export class CropFrame extends CloudImageEditorBase { return frameThumbs; } + /** @private */ _createGuides() { let svg = createSvgNode('svg'); @@ -245,6 +294,7 @@ export class CropFrame extends CloudImageEditorBase { return svg; } + /** @private */ _createFrame() { let svg = this.ref['svg-el']; let fr = document.createDocumentFragment(); @@ -262,7 +312,13 @@ export class CropFrame extends CloudImageEditorBase { this._frameGuides = frameGuides; } + /** + * @private + * @param {import('./types.js').Direction} direction + * @param {PointerEvent} e + */ _handlePointerDown(direction, e) { + if (!this._frameThumbs) return; let thumb = this._frameThumbs[direction]; if (this._shouldThumbBeDisabled(direction)) { return; @@ -280,6 +336,10 @@ export class CropFrame extends CloudImageEditorBase { this._dragStartCrop = { ...cropBox }; } + /** + * @private + * @param {PointerEvent} e + */ _handlePointerUp_(e) { this._updateCursor(); @@ -292,8 +352,12 @@ export class CropFrame extends CloudImageEditorBase { this.$.dragging = false; } + /** + * @private + * @param {PointerEvent} e + */ _handlePointerMove_(e) { - if (!this.$.dragging) { + if (!this.$.dragging || !this._dragStartPoint || !this._draggingThumb) { return; } e.stopPropagation(); @@ -307,20 +371,31 @@ export class CropFrame extends CloudImageEditorBase { let dy = y - this._dragStartPoint[1]; let { direction } = this._draggingThumb; + const movedCropBox = this._calcCropBox(direction, [dx, dy]); + if (movedCropBox) { + this.$['*cropBox'] = movedCropBox; + } + } + + /** + * @private + * @param {import('./types.js').Direction} direction + * @param {[Number, Number]} delta + */ + _calcCropBox(direction, delta) { + const [dx, dy] = delta; /** @type {import('./types.js').Rectangle} */ let imageBox = this.$['*imageBox']; - let rect = this._dragStartCrop; + let rect = /** @type {import('./types.js').Rectangle} */ (this._dragStartCrop) ?? this.$['*cropBox']; + /** @type {import('./types.js').CropPresetList[0]} */ + const cropPreset = this.$['*cropPresetList']?.[0]; + const aspectRatio = cropPreset ? cropPreset.width / cropPreset.height : undefined; if (direction === '') { - rect = moveRect(rect, [dx, dy]); - rect = constraintRect(rect, imageBox); + rect = moveRect({ rect, delta: [dx, dy], imageBox }); } else { - rect = expandRect(rect, [dx, dy], direction); - rect = intersectionRect(rect, imageBox); + rect = resizeRect({ rect, delta: [dx, dy], direction, aspectRatio, imageBox }); } - /** @type {[Number, Number]} */ - let minCropRect = [Math.min(imageBox.width, MIN_CROP_SIZE), Math.min(imageBox.height, MIN_CROP_SIZE)]; - rect = minRectSize(rect, minCropRect, direction); if (!Object.values(rect).every((number) => Number.isFinite(number) && number >= 0)) { console.error('CropFrame is trying to create invalid rectangle', { @@ -328,15 +403,21 @@ export class CropFrame extends CloudImageEditorBase { }); return; } - this.$['*cropBox'] = rect; + return constraintRect(roundRect(rect), this.$['*imageBox']); } + /** + * @private + * @param {PointerEvent} e + */ _handleSvgPointerMove_(e) { + if (!this._frameThumbs) return; + let hoverThumb = Object.values(this._frameThumbs).find((thumb) => { if (this._shouldThumbBeDisabled(thumb.direction)) { return false; } - let node = thumb.groupNode; + let node = thumb.interactionNode; let bounds = node.getBoundingClientRect(); let rect = { x: bounds.x, @@ -352,17 +433,21 @@ export class CropFrame extends CloudImageEditorBase { this._updateCursor(); } + /** @private */ _updateCursor() { let hoverThumb = this._hoverThumb; this.ref['svg-el'].style.cursor = hoverThumb ? thumbCursor(hoverThumb.direction) : 'initial'; } + /** @private */ _render() { this._updateBackdrop(); this._updateFrame(); } + /** @param {boolean} visible */ toggleThumbs(visible) { + if (!this._frameThumbs) return; Object.values(this._frameThumbs) .map(({ groupNode }) => groupNode) .forEach((groupNode) => { @@ -400,6 +485,7 @@ export class CropFrame extends CloudImageEditorBase { }); this.sub('dragging', (dragging) => { + if (!this._frameGuides) return; this._frameGuides.setAttribute( 'class', classNames({ diff --git a/blocks/CloudImageEditor/src/EditorImageCropper.js b/blocks/CloudImageEditor/src/EditorImageCropper.js index f75ab81f6..afc978577 100644 --- a/blocks/CloudImageEditor/src/EditorImageCropper.js +++ b/blocks/CloudImageEditor/src/EditorImageCropper.js @@ -1,8 +1,11 @@ +// @ts-check + +import { debounce } from '../../utils/debounce.js'; +import { throttle } from '../../utils/throttle.js'; import { CloudImageEditorBase } from './CloudImageEditorBase.js'; -import { constraintRect, minRectSize } from './crop-utils.js'; -import { CROP_PADDING, MIN_CROP_SIZE } from './cropper-constants.js'; +import { clamp, constraintRect, isRectInsideRect, rotateSize, roundRect } from './crop-utils.js'; +import { CROP_PADDING } from './cropper-constants.js'; import { classNames } from './lib/classNames.js'; -import { debounce } from './lib/debounce.js'; import { pick } from './lib/pick.js'; import { preloadImage } from './lib/preloadImage.js'; import { viewerImageSrc } from './util.js'; @@ -14,26 +17,6 @@ import { viewerImageSrc } from './util.js'; * @property {Number} rotate */ -/** - * @param {Number} value - * @param {Number} min - * @param {Number} max - * @returns {Number} - */ -function clamp(value, min, max) { - return Math.min(Math.max(value, min), max); -} - -/** - * @param {import('./types.js').ImageSize} imageSize - * @param {Number} angle - * @returns {import('./types.js').ImageSize} - */ -function rotateSize({ width, height }, angle) { - let swap = (angle / 90) % 2 !== 0; - return { width: swap ? height : width, height: swap ? width : height }; -} - /** * @param {import('./types.js').Transformations['crop']} crop * @returns {boolean} @@ -42,7 +25,7 @@ function validateCrop(crop) { if (!crop) { return true; } - /** @type {((arg: typeof crop) => boolean)[]} */ + /** @type {((arg: NonNullable) => boolean)[]} */ let shouldMatch = [ ({ dimensions, coords }) => [...dimensions, ...coords].every((number) => Number.isInteger(number) && Number.isFinite(number)), @@ -52,49 +35,54 @@ function validateCrop(crop) { } export class EditorImageCropper extends CloudImageEditorBase { - init$ = { - ...this.init$, - image: null, - '*padding': CROP_PADDING, - /** @type {Operations} */ - '*operations': { - rotate: 0, - mirror: false, - flip: false, - }, - /** @type {import('./types.js').Rectangle} */ - '*imageBox': { - x: 0, - y: 0, - width: 0, - height: 0, - }, - /** @type {import('./types.js').Rectangle} */ - '*cropBox': { - x: 0, - y: 0, - width: 0, - height: 0, - }, - }; - constructor() { super(); + this.init$ = { + ...this.init$, + image: null, + '*padding': CROP_PADDING, + /** @type {Operations} */ + '*operations': { + rotate: 0, + mirror: false, + flip: false, + }, + /** @type {import('./types.js').Rectangle} */ + '*imageBox': { + x: 0, + y: 0, + width: 0, + height: 0, + }, + /** @type {import('./types.js').Rectangle} */ + '*cropBox': { + x: 0, + y: 0, + width: 0, + height: 0, + }, + }; + /** @private */ this._commitDebounced = debounce(this._commit.bind(this), 300); /** @private */ - this._handleResizeDebounced = debounce(this._handleResize.bind(this), 10); + this._handleResizeThrottled = throttle(this._handleResize.bind(this), 100); + + this._imageSize = { width: 0, height: 0 }; } /** @private */ _handleResize() { - if (!this.isConnected) { + if (!this.isConnected || !this._isActive) { return; } - this.deactivate(); - this.activate(this._imageSize, { fromViewer: false }); + this._initCanvas(); + this._syncTransformations(); + this._alignImage(); + this._alignCrop(); + this._draw(); } /** @private */ @@ -118,7 +106,7 @@ export class EditorImageCropper extends CloudImageEditorBase { canvas.style.height = `${height}px`; canvas.width = width * dpr; canvas.height = height * dpr; - ctx.scale(dpr, dpr); + ctx?.scale(dpr, dpr); this._canvas = canvas; this._ctx = ctx; @@ -137,6 +125,7 @@ export class EditorImageCropper extends CloudImageEditorBase { let bounds = { width: this.offsetWidth, height: this.offsetHeight }; let naturalSize = rotateSize({ width: image.naturalWidth, height: image.naturalHeight }, rotate); + let imageBox; if (naturalSize.width > bounds.width - padding * 2 || naturalSize.height > bounds.height - padding * 2) { let imageAspectRatio = naturalSize.width / naturalSize.height; @@ -147,20 +136,22 @@ export class EditorImageCropper extends CloudImageEditorBase { let height = width / imageAspectRatio; let x = 0 + padding; let y = padding + (bounds.height - padding * 2) / 2 - height / 2; - this.$['*imageBox'] = { x, y, width, height }; + imageBox = { x, y, width, height }; } else { let height = bounds.height - padding * 2; let width = height * imageAspectRatio; let x = padding + (bounds.width - padding * 2) / 2 - width / 2; let y = 0 + padding; - this.$['*imageBox'] = { x, y, width, height }; + imageBox = { x, y, width, height }; } } else { let { width, height } = naturalSize; let x = padding + (bounds.width - padding * 2) / 2 - width / 2; let y = padding + (bounds.height - padding * 2) / 2 - height / 2; - this.$['*imageBox'] = { x, y, width, height }; + imageBox = { x, y, width, height }; } + + this.$['*imageBox'] = roundRect(imageBox); } /** @private */ @@ -169,45 +160,60 @@ export class EditorImageCropper extends CloudImageEditorBase { let imageBox = this.$['*imageBox']; let operations = this.$['*operations']; let { rotate } = operations; - let transformation = this.$['*editorTransformations']['crop']; + let cropTransformation = this.$['*editorTransformations']['crop']; + let { width: previewWidth, x: previewX, y: previewY } = this.$['*imageBox']; - if (transformation) { + if (cropTransformation) { let { dimensions: [width, height], coords: [x, y], - } = transformation; - let { width: previewWidth, x: previewX, y: previewY } = this.$['*imageBox']; + } = cropTransformation; let { width: sourceWidth } = rotateSize(this._imageSize, rotate); let ratio = previewWidth / sourceWidth; + cropBox = constraintRect( + roundRect({ + x: previewX + x * ratio, + y: previewY + y * ratio, + width: width * ratio, + height: height * ratio, + }), + this.$['*imageBox'] + ); + } + + if (!cropTransformation || !isRectInsideRect(cropBox, imageBox)) { + /** @type {import('./types.js').CropPresetList[0]} */ + const cropPreset = this.$['*cropPresetList']?.[0]; + const cropRatio = cropPreset ? cropPreset.width / cropPreset.height : undefined; + const ratio = imageBox.width / imageBox.height; + let width = imageBox.width; + let height = imageBox.height; + if (cropRatio) { + if (ratio > cropRatio) { + width = Math.min(imageBox.height * cropRatio, imageBox.width); + } else { + height = Math.min(imageBox.width / cropRatio, imageBox.height); + } + } cropBox = { - x: previewX + x * ratio, - y: previewY + y * ratio, - width: width * ratio, - height: height * ratio, - }; - } else { - cropBox = { - x: imageBox.x, - y: imageBox.y, - width: imageBox.width, - height: imageBox.height, + x: imageBox.x + imageBox.width / 2 - width / 2, + y: imageBox.y + imageBox.height / 2 - height / 2, + width, + height, }; } - /** @type {[Number, Number]} */ - let minCropRect = [Math.min(imageBox.width, MIN_CROP_SIZE), Math.min(imageBox.height, MIN_CROP_SIZE)]; - cropBox = minRectSize(cropBox, minCropRect, 'se'); - cropBox = constraintRect(cropBox, imageBox); - this.$['*cropBox'] = cropBox; + this.$['*cropBox'] = constraintRect(roundRect(cropBox), this.$['*imageBox']); } /** @private */ _drawImage() { + let ctx = this._ctx; + if (!ctx) return; let image = this.$.image; let imageBox = this.$['*imageBox']; let operations = this.$['*operations']; let { mirror, flip, rotate } = operations; - let ctx = this._ctx; let rotated = rotateSize({ width: imageBox.width, height: imageBox.height }, rotate); ctx.save(); ctx.translate(imageBox.x + imageBox.width / 2, imageBox.y + imageBox.height / 2); @@ -219,7 +225,7 @@ export class EditorImageCropper extends CloudImageEditorBase { /** @private */ _draw() { - if (!this._isActive || !this.$.image) { + if (!this._isActive || !this.$.image || !this._canvas || !this._ctx) { return; } let canvas = this._canvas; @@ -230,7 +236,10 @@ export class EditorImageCropper extends CloudImageEditorBase { this._drawImage(); } - /** @private */ + /** + * @private + * @param {{ fromViewer?: boolean }} options + */ _animateIn({ fromViewer }) { if (this.$.image) { this.ref['frame-el'].toggleThumbs(true); @@ -247,9 +256,9 @@ export class EditorImageCropper extends CloudImageEditorBase { /** * @private - * @returns {import('./types.js').Transformations['crop']['dimensions']} + * @returns {NonNullable['dimensions']} */ - _calculateDimensions() { + _getCropDimensions() { let cropBox = this.$['*cropBox']; let imageBox = this.$['*imageBox']; let operations = this.$['*operations']; @@ -273,7 +282,7 @@ export class EditorImageCropper extends CloudImageEditorBase { * @private * @returns {import('./types.js').Transformations['crop']} */ - _calculateCrop() { + _getCropTransformation() { let cropBox = this.$['*cropBox']; let imageBox = this.$['*imageBox']; let operations = this.$['*operations']; @@ -284,7 +293,7 @@ export class EditorImageCropper extends CloudImageEditorBase { let ratioW = previewWidth / sourceWidth; let ratioH = previewHeight / sourceHeight; - let dimensions = this._calculateDimensions(); + let dimensions = this._getCropDimensions(); let crop = { dimensions, coords: /** @type {[Number, Number]} */ ([ @@ -312,7 +321,7 @@ export class EditorImageCropper extends CloudImageEditorBase { } let operations = this.$['*operations']; let { rotate, mirror, flip } = operations; - let crop = this._calculateCrop(); + let crop = this._getCropTransformation(); /** @type {import('./types.js').Transformations} */ let editorTransformations = this.$['*editorTransformations']; let transformations = { @@ -359,31 +368,35 @@ export class EditorImageCropper extends CloudImageEditorBase { * @param {import('./types.js').ImageSize} imageSize * @param {{ fromViewer?: boolean }} options */ - async activate(imageSize, { fromViewer }) { + async activate(imageSize, { fromViewer } = {}) { if (this._isActive) { return; } this._isActive = true; this._imageSize = imageSize; this.removeEventListener('transitionend', this._reset); - this._initCanvas(); try { this.$.image = await this._waitForImage(this.$['*originalUrl'], this.$['*editorTransformations']); this._syncTransformations(); - this._alignImage(); - this._alignCrop(); - this._draw(); this._animateIn({ fromViewer }); } catch (err) { console.error('Failed to activate cropper', { error: err }); } + + this._observer = new ResizeObserver(([entry]) => { + const nonZeroSize = entry.contentRect.width > 0 && entry.contentRect.height > 0; + if (nonZeroSize && this._isActive && this.$.image) { + this._handleResizeThrottled(); + } + }); + this._observer.observe(this); } - deactivate() { + deactivate({ reset = false } = {}) { if (!this._isActive) { return; } - this._commit(); + !reset && this._commit(); this._isActive = false; this._transitionToCrop(); @@ -396,11 +409,12 @@ export class EditorImageCropper extends CloudImageEditorBase { this.ref['frame-el'].toggleThumbs(false); this.addEventListener('transitionend', this._reset, { once: true }); + this._observer?.disconnect(); } /** @private */ _transitionToCrop() { - let dimensions = this._calculateDimensions(); + let dimensions = this._getCropDimensions(); let scaleX = Math.min(this.offsetWidth, dimensions[0]) / this.$['*cropBox'].width; let scaleY = Math.min(this.offsetHeight, dimensions[1]) / this.$['*cropBox'].height; let scale = Math.min(scaleX, scaleY); @@ -491,24 +505,20 @@ export class EditorImageCropper extends CloudImageEditorBase { initCallback() { super.initCallback(); - this._observer = new ResizeObserver(([entry]) => { - const nonZeroSize = entry.contentRect.width > 0 && entry.contentRect.height > 0; - if (nonZeroSize && this._isActive && this.$.image) { - this._handleResizeDebounced(); - } - }); - this._observer.observe(this); - this.sub('*imageBox', () => { this._draw(); }); - this.sub('*cropBox', (cropBox) => { + this.sub('*cropBox', () => { if (this.$.image) { this._commitDebounced(); } }); + this.sub('*cropPresetList', () => { + this._alignCrop(); + }); + setTimeout(() => { this.sub('*networkProblems', (networkProblems) => { if (!networkProblems) { diff --git a/blocks/CloudImageEditor/src/EditorImageFader.js b/blocks/CloudImageEditor/src/EditorImageFader.js index ee6ab0e85..97d90ecb3 100644 --- a/blocks/CloudImageEditor/src/EditorImageFader.js +++ b/blocks/CloudImageEditor/src/EditorImageFader.js @@ -1,6 +1,6 @@ +import { debounce } from '../../utils/debounce.js'; import { CloudImageEditorBase } from './CloudImageEditorBase.js'; import { classNames } from './lib/classNames.js'; -import { debounce } from './lib/debounce.js'; import { linspace } from './lib/linspace.js'; import { batchPreloadImages } from './lib/preloadImage.js'; import { COLOR_OPERATIONS_CONFIG } from './toolbar-constants.js'; diff --git a/blocks/CloudImageEditor/src/EditorToolbar.js b/blocks/CloudImageEditor/src/EditorToolbar.js index d6266b6ab..b060eb205 100644 --- a/blocks/CloudImageEditor/src/EditorToolbar.js +++ b/blocks/CloudImageEditor/src/EditorToolbar.js @@ -1,9 +1,9 @@ +import { debounce } from '../../utils/debounce.js'; import { CloudImageEditorBase } from './CloudImageEditorBase.js'; import { EditorCropButtonControl } from './EditorCropButtonControl.js'; import { EditorFilterControl } from './EditorFilterControl.js'; import { EditorOperationControl } from './EditorOperationControl.js'; import { FAKE_ORIGINAL_FILTER } from './EditorSlider.js'; -import { debounce } from './lib/debounce.js'; import { batchPreloadImages } from './lib/preloadImage.js'; import { ALL_COLOR_OPERATIONS, diff --git a/blocks/CloudImageEditor/src/crop-utils.js b/blocks/CloudImageEditor/src/crop-utils.js index c8a569a2c..200c87afc 100644 --- a/blocks/CloudImageEditor/src/crop-utils.js +++ b/blocks/CloudImageEditor/src/crop-utils.js @@ -1,4 +1,5 @@ -import { THUMB_CORNER_SIZE, THUMB_OFFSET, THUMB_SIDE_SIZE } from './cropper-constants.js'; +// @ts-check +import { MIN_CROP_SIZE, THUMB_CORNER_SIZE, THUMB_OFFSET, THUMB_SIDE_SIZE } from './cropper-constants.js'; /** * @param {SVGElement} node @@ -21,9 +22,10 @@ export function createSvgNode(name, attrs = {}) { /** * @param {import('./types.js').Rectangle} rect - * @param {String} direction + * @param {import('./types.js').Direction} direction + * @param {number} sizeMultiplier */ -export function cornerPath(rect, direction) { +export function cornerPath(rect, direction, sizeMultiplier) { let { x, y, width, height } = rect; let wMul = direction.includes('w') ? 0 : 1; @@ -33,11 +35,11 @@ export function cornerPath(rect, direction) { let p1 = [ x + wMul * width + THUMB_OFFSET * xSide, - y + hMul * height + THUMB_OFFSET * ySide - THUMB_CORNER_SIZE * ySide, + y + hMul * height + THUMB_OFFSET * ySide - THUMB_CORNER_SIZE * sizeMultiplier * ySide, ]; let p2 = [x + wMul * width + THUMB_OFFSET * xSide, y + hMul * height + THUMB_OFFSET * ySide]; let p3 = [ - x + wMul * width - THUMB_CORNER_SIZE * xSide + THUMB_OFFSET * xSide, + x + wMul * width - THUMB_CORNER_SIZE * sizeMultiplier * xSide + THUMB_OFFSET * xSide, y + hMul * height + THUMB_OFFSET * ySide, ]; @@ -52,23 +54,28 @@ export function cornerPath(rect, direction) { /** * @param {import('./types.js').Rectangle} rect - * @param {String} direction + * @param {Extract} direction + * @param {number} sizeMultiplier */ -export function sidePath(rect, direction) { +export function sidePath(rect, direction, sizeMultiplier) { let { x, y, width, height } = rect; - let wMul = ['n', 's'].includes(direction) ? 0.5 : { w: 0, e: 1 }[direction]; - let hMul = ['w', 'e'].includes(direction) ? 0.5 : { n: 0, s: 1 }[direction]; + let wMul = ['n', 's'].includes(direction) + ? 0.5 + : { w: 0, e: 1 }[/** @type {Extract} */ (direction)]; + let hMul = ['w', 'e'].includes(direction) + ? 0.5 + : { n: 0, s: 1 }[/** @type {Extract} */ (direction)]; let xSide = [-1, 1][wMul]; let ySide = [-1, 1][hMul]; let p1, p2; if (['n', 's'].includes(direction)) { - p1 = [x + wMul * width - THUMB_SIDE_SIZE / 2, y + hMul * height + THUMB_OFFSET * ySide]; - p2 = [x + wMul * width + THUMB_SIDE_SIZE / 2, y + hMul * height + THUMB_OFFSET * ySide]; + p1 = [x + wMul * width - (THUMB_SIDE_SIZE * sizeMultiplier) / 2, y + hMul * height + THUMB_OFFSET * ySide]; + p2 = [x + wMul * width + (THUMB_SIDE_SIZE * sizeMultiplier) / 2, y + hMul * height + THUMB_OFFSET * ySide]; } else { - p1 = [x + wMul * width + THUMB_OFFSET * xSide, y + hMul * height - THUMB_SIDE_SIZE / 2]; - p2 = [x + wMul * width + THUMB_OFFSET * xSide, y + hMul * height + THUMB_SIDE_SIZE / 2]; + p1 = [x + wMul * width + THUMB_OFFSET * xSide, y + hMul * height - (THUMB_SIDE_SIZE * sizeMultiplier) / 2]; + p2 = [x + wMul * width + THUMB_OFFSET * xSide, y + hMul * height + (THUMB_SIDE_SIZE * sizeMultiplier) / 2]; } let path = `M ${p1[0]} ${p1[1]} L ${p2[0]} ${p2[1]}`; let center = [p2[0] - (p2[0] - p1[0]) / 2, p2[1] - (p2[1] - p1[1]) / 2]; @@ -76,7 +83,7 @@ export function sidePath(rect, direction) { return { d: path, center }; } -/** @param {String} direction */ +/** @param {import('./types.js').Direction} direction */ export function thumbCursor(direction) { if (direction === '') { return 'move'; @@ -94,15 +101,21 @@ export function thumbCursor(direction) { } /** - * @param {import('./types.js').Rectangle} rect - * @param {[Number, Number]} delta + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * imageBox: import('./types.js').Rectangle; + * }} options */ -export function moveRect(rect, [dx, dy]) { - return { - ...rect, - x: rect.x + dx, - y: rect.y + dy, - }; +export function moveRect({ rect, delta: [dx, dy], imageBox }) { + return constraintRect( + { + ...rect, + x: rect.x + dx, + y: rect.y + dy, + }, + imageBox + ); } /** @@ -131,76 +144,497 @@ export function constraintRect(rect1, rect2) { } /** - * @param {import('./types.js').Rectangle} rect - * @param {[Number, Number]} delta - * @param {String} direction + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * aspectRatio?: number; + * imageBox: import('./types.js').Rectangle; + * }} options + */ +function resizeNorth({ rect, delta, aspectRatio, imageBox }) { + const [, dy] = delta; + let { y, width, height } = rect; + + y += dy; + height -= dy; + if (aspectRatio) { + width = height * aspectRatio; + } + let x = rect.x + rect.width / 2 - width / 2; + if (y <= imageBox.y) { + y = imageBox.y; + height = rect.y + rect.height - y; + if (aspectRatio) { + width = height * aspectRatio; + x = rect.x + rect.width / 2 - width / 2; + } + } + if (x <= imageBox.x) { + x = imageBox.x; + y = rect.y + rect.height - height; + } + if (x + width >= imageBox.x + imageBox.width) { + x = Math.max(imageBox.x, imageBox.x + imageBox.width - width); + width = imageBox.x + imageBox.width - x; + if (aspectRatio) { + height = width / aspectRatio; + } + y = rect.y + rect.height - height; + } + if (height < MIN_CROP_SIZE) { + height = MIN_CROP_SIZE; + if (aspectRatio) { + width = height * aspectRatio; + x = rect.x + rect.width / 2 - width / 2; + } + y = rect.y + rect.height - height; + } + if (width < MIN_CROP_SIZE) { + width = MIN_CROP_SIZE; + if (aspectRatio) { + height = width / aspectRatio; + x = rect.x + rect.width / 2 - width / 2; + } + y = rect.y + rect.height - height; + } + + return { x, y, width, height }; +} + +/** + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * aspectRatio?: number; + * imageBox: import('./types.js').Rectangle; + * }} options + */ +function resizeWest({ rect, delta, aspectRatio, imageBox }) { + const [dx] = delta; + let { x, width, height } = rect; + + x += dx; + width -= dx; + if (aspectRatio) { + height = width / aspectRatio; + } + let y = rect.y + rect.height / 2 - height / 2; + if (x <= imageBox.x) { + x = imageBox.x; + width = rect.x + rect.width - x; + if (aspectRatio) { + height = width / aspectRatio; + y = rect.y + rect.height / 2 - height / 2; + } + } + if (y <= imageBox.y) { + y = imageBox.y; + x = rect.x + rect.width - width; + } + if (y + height >= imageBox.y + imageBox.height) { + y = Math.max(imageBox.y, imageBox.y + imageBox.height - height); + height = imageBox.y + imageBox.height - y; + if (aspectRatio) { + width = height * aspectRatio; + } + x = rect.x + rect.width - width; + } + if (height < MIN_CROP_SIZE) { + height = MIN_CROP_SIZE; + if (aspectRatio) { + width = height * aspectRatio; + } + y = rect.y + rect.height / 2 - height / 2; + x = rect.x + rect.width - width; + } + if (width < MIN_CROP_SIZE) { + width = MIN_CROP_SIZE; + if (aspectRatio) { + height = width / aspectRatio; + } + y = rect.y + rect.height / 2 - height / 2; + x = rect.x + rect.width - width; + } + + return { x, y, width, height }; +} + +/** + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * aspectRatio?: number; + * imageBox: import('./types.js').Rectangle; + * }} options + */ +function resizeSouth({ rect, delta, aspectRatio, imageBox }) { + const [, dy] = delta; + let { y, width, height } = rect; + + height += dy; + if (aspectRatio) { + width = height * aspectRatio; + } + let x = rect.x + rect.width / 2 - width / 2; + if (y + height >= imageBox.y + imageBox.height) { + height = imageBox.y + imageBox.height - y; + if (aspectRatio) { + width = height * aspectRatio; + } + x = rect.x + rect.width / 2 - width / 2; + } + if (x <= imageBox.x) { + x = imageBox.x; + y = rect.y; + } + if (x + width >= imageBox.x + imageBox.width) { + x = Math.max(imageBox.x, imageBox.x + imageBox.width - width); + width = imageBox.x + imageBox.width - x; + if (aspectRatio) { + height = width / aspectRatio; + } + y = rect.y; + } + if (height < MIN_CROP_SIZE) { + height = MIN_CROP_SIZE; + if (aspectRatio) { + width = height * aspectRatio; + } + x = rect.x + rect.width / 2 - width / 2; + } + if (width < MIN_CROP_SIZE) { + width = MIN_CROP_SIZE; + if (aspectRatio) { + height = width / aspectRatio; + } + x = rect.x + rect.width / 2 - width / 2; + } + + return { x, y, width, height }; +} + +/** + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * aspectRatio?: number; + * imageBox: import('./types.js').Rectangle; + * }} options */ -export function expandRect(rect, [dx, dy], direction) { +function resizeEast({ rect, delta, aspectRatio, imageBox }) { + const [dx] = delta; + let { x, width, height } = rect; + + width += dx; + if (aspectRatio) { + height = width / aspectRatio; + } + let y = rect.y + rect.height / 2 - height / 2; + if (x + width >= imageBox.x + imageBox.width) { + width = imageBox.x + imageBox.width - x; + if (aspectRatio) { + height = width / aspectRatio; + } + y = rect.y + rect.height / 2 - height / 2; + } + if (y <= imageBox.y) { + y = imageBox.y; + x = rect.x; + } + if (y + height >= imageBox.y + imageBox.height) { + y = Math.max(imageBox.y, imageBox.y + imageBox.height - height); + height = imageBox.y + imageBox.height - y; + if (aspectRatio) { + width = height * aspectRatio; + } + x = rect.x; + } + if (height < MIN_CROP_SIZE) { + height = MIN_CROP_SIZE; + if (aspectRatio) { + width = height * aspectRatio; + } + y = rect.y + rect.height / 2 - height / 2; + } + if (width < MIN_CROP_SIZE) { + width = MIN_CROP_SIZE; + if (aspectRatio) { + height = width / aspectRatio; + } + y = rect.y + rect.height / 2 - height / 2; + } + + return { x, y, width, height }; +} + +/** + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * aspectRatio?: number; + * imageBox: import('./types.js').Rectangle; + * }} options + */ +function resizeNorthWest({ rect, delta, aspectRatio, imageBox }) { + let [dx, dy] = delta; let { x, y, width, height } = rect; - if (direction.includes('n')) { - y += dy; - height -= dy; + if (x + dx < imageBox.x) { + dx = imageBox.x - x; } - if (direction.includes('s')) { + if (y + dy < imageBox.y) { + dy = imageBox.y - y; + } + x += dx; + width -= dx; + y += dy; + height -= dy; + if (aspectRatio && Math.abs(width / height) > aspectRatio) { + dy = width / aspectRatio - height; height += dy; + y -= dy; + if (y <= imageBox.y) { + height = height - (imageBox.y - y); + width = height * aspectRatio; + x = rect.x + rect.width - width; + y = imageBox.y; + } + } else if (aspectRatio) { + dx = height * aspectRatio - width; + width = width + dx; + x -= dx; + if (x <= imageBox.x) { + width = width - (imageBox.x - x); + height = width / aspectRatio; + x = imageBox.x; + y = rect.y + rect.height - height; + } + } + if (height < MIN_CROP_SIZE) { + height = MIN_CROP_SIZE; + if (aspectRatio) { + width = height * aspectRatio; + } + x = rect.x + rect.width - width; + y = rect.y + rect.height - height; } - if (direction.includes('w')) { - x += dx; - width -= dx; + if (width < MIN_CROP_SIZE) { + width = MIN_CROP_SIZE; + if (aspectRatio) { + height = width / aspectRatio; + } + x = rect.x + rect.width - width; + y = rect.y + rect.height - height; } - if (direction.includes('e')) { + + return { x, y, width, height }; +} + +/** + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * aspectRatio?: number; + * imageBox: import('./types.js').Rectangle; + * }} options + */ +function resizeNorthEast({ rect, delta, aspectRatio, imageBox }) { + let [dx, dy] = delta; + let { x, y, width, height } = rect; + + if (x + width + dx > imageBox.x + imageBox.width) { + dx = imageBox.x + imageBox.width - x - width; + } + if (y + dy < imageBox.y) { + dy = imageBox.y - y; + } + width += dx; + y += dy; + height -= dy; + if (aspectRatio && Math.abs(width / height) > aspectRatio) { + dy = width / aspectRatio - height; + height += dy; + y -= dy; + if (y <= imageBox.y) { + height = height - (imageBox.y - y); + width = height * aspectRatio; + x = rect.x; + y = imageBox.y; + } + } else if (aspectRatio) { + dx = height * aspectRatio - width; width += dx; + if (x + width >= imageBox.x + imageBox.width) { + width = imageBox.x + imageBox.width - x; + height = width / aspectRatio; + x = imageBox.x + imageBox.width - width; + y = rect.y + rect.height - height; + } } - return { - x, - y, - width, - height, - }; + if (height < MIN_CROP_SIZE) { + height = MIN_CROP_SIZE; + if (aspectRatio) { + width = height * aspectRatio; + } + y = rect.y + rect.height - height; + } + if (width < MIN_CROP_SIZE) { + width = MIN_CROP_SIZE; + if (aspectRatio) { + height = width / aspectRatio; + } + y = rect.y + rect.height - height; + } + + return { x, y, width, height }; } /** - * @param {import('./types.js').Rectangle} rect1 - * @param {import('./types.js').Rectangle} rect2 + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * aspectRatio?: number; + * imageBox: import('./types.js').Rectangle; + * }} options */ -export function intersectionRect(rect1, rect2) { - let leftX = Math.max(rect1.x, rect2.x); - let rightX = Math.min(rect1.x + rect1.width, rect2.x + rect2.width); - let topY = Math.max(rect1.y, rect2.y); - let bottomY = Math.min(rect1.y + rect1.height, rect2.y + rect2.height); +function resizeSouthWest({ rect, delta, aspectRatio, imageBox }) { + let [dx, dy] = delta; + let { x, y, width, height } = rect; - return { x: leftX, y: topY, width: rightX - leftX, height: bottomY - topY }; + if (x + dx < imageBox.x) { + dx = imageBox.x - x; + } + if (y + height + dy > imageBox.y + imageBox.height) { + dy = imageBox.y + imageBox.height - y - height; + } + x += dx; + width -= dx; + height += dy; + if (aspectRatio && Math.abs(width / height) > aspectRatio) { + dy = width / aspectRatio - height; + height += dy; + if (y + height >= imageBox.y + imageBox.height) { + height = imageBox.y + imageBox.height - y; + width = height * aspectRatio; + x = rect.x + rect.width - width; + y = imageBox.y + imageBox.height - height; + } + } else if (aspectRatio) { + dx = height * aspectRatio - width; + width += dx; + x -= dx; + if (x <= imageBox.x) { + width = width - (imageBox.x - x); + height = width / aspectRatio; + x = imageBox.x; + y = rect.y; + } + } + if (height < MIN_CROP_SIZE) { + height = MIN_CROP_SIZE; + if (aspectRatio) { + width = height * aspectRatio; + } + x = rect.x + rect.width - width; + } + if (width < MIN_CROP_SIZE) { + width = MIN_CROP_SIZE; + if (aspectRatio) { + height = width / aspectRatio; + } + x = rect.x + rect.width - width; + } + + return { x, y, width, height }; } /** - * @param {import('./types.js').Rectangle} rect - * @param {[Number, Number]} minSize - * @param {String} direction + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * aspectRatio?: number; + * imageBox: import('./types.js').Rectangle; + * }} options */ -export function minRectSize(rect, [minWidth, minHeight], direction) { +function resizeSouthEast({ rect, delta, aspectRatio, imageBox }) { + let [dx, dy] = delta; let { x, y, width, height } = rect; - if (direction.includes('n')) { - let prevHeight = height; - height = Math.max(minHeight, height); - y = y + prevHeight - height; + if (x + width + dx > imageBox.x + imageBox.width) { + dx = imageBox.x + imageBox.width - x - width; + } + if (y + height + dy > imageBox.y + imageBox.height) { + dy = imageBox.y + imageBox.height - y - height; } - if (direction.includes('s')) { - height = Math.max(minHeight, height); + width += dx; + height += dy; + if (aspectRatio && Math.abs(width / height) > aspectRatio) { + dy = width / aspectRatio - height; + height += dy; + if (y + height >= imageBox.y + imageBox.height) { + height = imageBox.y + imageBox.height - y; + width = height * aspectRatio; + x = rect.x; + y = imageBox.y + imageBox.height - height; + } + } else if (aspectRatio) { + dx = height * aspectRatio - width; + width += dx; + if (x + width >= imageBox.x + imageBox.width) { + width = imageBox.x + imageBox.width - x; + height = width / aspectRatio; + x = imageBox.x + imageBox.width - width; + y = rect.y; + } } - if (direction.includes('w')) { - let prevWidth = width; - width = Math.max(minWidth, width); - x = x + prevWidth - width; + if (height < MIN_CROP_SIZE) { + height = MIN_CROP_SIZE; + if (aspectRatio) { + width = height * aspectRatio; + } } - if (direction.includes('e')) { - width = Math.max(minWidth, width); + if (width < MIN_CROP_SIZE) { + width = MIN_CROP_SIZE; + if (aspectRatio) { + height = width / aspectRatio; + } } return { x, y, width, height }; } +/** + * @param {{ + * rect: import('./types.js').Rectangle; + * delta: [Number, Number]; + * direction: import('./types.js').Direction; + * aspectRatio?: number; + * imageBox: import('./types.js').Rectangle; + * }} options + */ +export function resizeRect({ direction, ...rest }) { + switch (direction) { + case 'n': + return resizeNorth(rest); + case 'w': + return resizeWest(rest); + case 's': + return resizeSouth(rest); + case 'e': + return resizeEast(rest); + case 'nw': + return resizeNorthWest(rest); + case 'ne': + return resizeNorthEast(rest); + case 'sw': + return resizeSouthWest(rest); + case 'se': + return resizeSouthEast(rest); + default: + return rest.rect; + } +} + /** * @param {import('./types.js').Rectangle} rect * @param {[Number, Number]} point @@ -208,3 +642,79 @@ export function minRectSize(rect, [minWidth, minHeight], direction) { export function rectContainsPoint(rect, [x, y]) { return rect.x <= x && x <= rect.x + rect.width && rect.y <= y && y <= rect.y + rect.height; } + +/** + * @param {import('./types.js').Rectangle} rect1 + * @param {import('./types.js').Rectangle} rect2 + */ +export function isRectInsideRect(rect1, rect2) { + return ( + rect1.x >= rect2.x && + rect1.y >= rect2.y && + rect1.x + rect1.width <= rect2.x + rect2.width && + rect1.y + rect1.height <= rect2.y + rect2.height + ); +} + +/** + * @param {import('./types.js').ImageSize} imageSize + * @param {Number} angle + * @returns {import('./types.js').ImageSize} + */ +export function rotateSize({ width, height }, angle) { + let swap = (angle / 90) % 2 !== 0; + return { width: swap ? height : width, height: swap ? width : height }; +} + +/** + * @param {number} width + * @param {number} height + * @param {number} aspectRatio + */ +export function calculateMaxCenteredCropFrame(width, height, aspectRatio) { + const imageAspectRatio = width / height; + let cropWidth, cropHeight; + + if (imageAspectRatio > aspectRatio) { + cropWidth = Math.round(height * aspectRatio); + cropHeight = height; + } else { + cropWidth = width; + cropHeight = Math.round(width / aspectRatio); + } + + const cropX = Math.round((width - cropWidth) / 2); + const cropY = Math.round((height - cropHeight) / 2); + + if (cropX + cropWidth > width) { + cropWidth = width - cropX; + } + if (cropY + cropHeight > height) { + cropHeight = height - cropY; + } + + return { x: cropX, y: cropY, width: cropWidth, height: cropHeight }; +} + +/** + * @param {import('./types.js').Rectangle} rect + * @returns {import('./types.js').Rectangle} + */ +export function roundRect(rect) { + return { + x: Math.round(rect.x), + y: Math.round(rect.y), + width: Math.round(rect.width), + height: Math.round(rect.height), + }; +} + +/** + * @param {Number} value + * @param {Number} min + * @param {Number} max + * @returns {Number} + */ +export function clamp(value, min, max) { + return Math.min(Math.max(value, min), max); +} diff --git a/blocks/CloudImageEditor/src/cropper-constants.js b/blocks/CloudImageEditor/src/cropper-constants.js index ff3ac7b97..5245b8f3d 100644 --- a/blocks/CloudImageEditor/src/cropper-constants.js +++ b/blocks/CloudImageEditor/src/cropper-constants.js @@ -6,4 +6,6 @@ export const THUMB_OFFSET = THUMB_STROKE_WIDTH / 2; export const GUIDE_STROKE_WIDTH = 1; export const GUIDE_THIRD = 100 / 3; -export const MIN_CROP_SIZE = THUMB_CORNER_SIZE * 2 + THUMB_SIDE_SIZE; +export const MIN_CROP_SIZE = 1; +export const MAX_INTERACTION_SIZE = 24; +export const MIN_INTERACTION_SIZE = 6; diff --git a/blocks/CloudImageEditor/src/lib/debounce.js b/blocks/CloudImageEditor/src/lib/debounce.js deleted file mode 100644 index 88008ae93..000000000 --- a/blocks/CloudImageEditor/src/lib/debounce.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * @param {function} callback - * @param {Number} wait - * @returns {function} - */ -export function debounce(callback, wait) { - let timer; - let debounced = (...args) => { - clearTimeout(timer); - timer = setTimeout(() => callback(...args), wait); - }; - debounced.cancel = () => { - clearTimeout(timer); - }; - return debounced; -} diff --git a/blocks/CloudImageEditor/src/lib/parseCropPreset.js b/blocks/CloudImageEditor/src/lib/parseCropPreset.js new file mode 100644 index 000000000..025ea40e4 --- /dev/null +++ b/blocks/CloudImageEditor/src/lib/parseCropPreset.js @@ -0,0 +1,14 @@ +// @ts-check + +/** @param {import('../../../../types/exported.d.ts').ConfigType['cropPreset']} cropPreset */ +export const parseCropPreset = (cropPreset) => { + if (!cropPreset) return []; + const [w, h] = cropPreset.split(':').map(Number); + if (!Number.isFinite(w) || !Number.isFinite(h)) { + console.error(`Invalid crop preset: ${cropPreset}`); + return; + } + /** @type {import('../types.js').CropAspectRatio} */ + const aspectRatio = { type: 'aspect-ratio', width: w, height: h }; + return [aspectRatio]; +}; diff --git a/blocks/CloudImageEditor/src/state.js b/blocks/CloudImageEditor/src/state.js index cd9e38b1c..1a029ab55 100644 --- a/blocks/CloudImageEditor/src/state.js +++ b/blocks/CloudImageEditor/src/state.js @@ -1,3 +1,5 @@ +// @ts-check + import { createCdnUrl, createCdnUrlModifiers } from '../../../utils/cdn-utils.js'; import { TRANSPARENT_PIXEL_SRC } from '../../../utils/transparentPixelSrc.js'; import { transformationsToOperations } from './lib/transformationUtils.js'; @@ -14,6 +16,8 @@ export function initState(fnCtx) { '*imageSize': null, /** @type {import('./types.js').Transformations} */ '*editorTransformations': {}, + /** @type {import('./types.js').CropPresetList} */ + '*cropPresetList': [], entry: null, extension: null, @@ -24,8 +28,11 @@ export function initState(fnCtx) { src: TRANSPARENT_PIXEL_SRC, fileType: '', showLoader: false, + + // options uuid: null, cdnUrl: null, + cropPreset: '', 'presence.networkProblems': false, 'presence.modalCaption': true, @@ -41,6 +48,7 @@ export function initState(fnCtx) { } fnCtx.$['*networkProblems'] = false; }, + /** @param {import('./types.js').Transformations} transformations */ '*on.apply': (transformations) => { if (!transformations) { return; diff --git a/blocks/CloudImageEditor/src/types.js b/blocks/CloudImageEditor/src/types.js index e2715e766..6ed699650 100644 --- a/blocks/CloudImageEditor/src/types.js +++ b/blocks/CloudImageEditor/src/types.js @@ -51,4 +51,10 @@ * @property {Transformations} transformations */ +/** @typedef {{ type: 'aspect-ratio'; width: number; height: number }} CropAspectRatio */ + +/** @typedef {CropAspectRatio[]} CropPresetList */ + +/** @typedef {'' | 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw'} Direction */ + export {}; diff --git a/blocks/CloudImageEditorActivity/CloudImageEditorActivity.js b/blocks/CloudImageEditorActivity/CloudImageEditorActivity.js index 6ef259ef7..16bc8c518 100644 --- a/blocks/CloudImageEditorActivity/CloudImageEditorActivity.js +++ b/blocks/CloudImageEditorActivity/CloudImageEditorActivity.js @@ -47,11 +47,17 @@ export class CloudImageEditorActivity extends UploaderBlock { } mountEditor() { - let instance = new CloudImageEditorBlock(); - let cdnUrl = this.$.cdnUrl; + const instance = new CloudImageEditorBlock(); + const cdnUrl = this.$.cdnUrl; + const cropPreset = this.cfg.cropPreset; + instance.setAttribute('ctx-name', this.ctxName); instance.setAttribute('cdn-url', cdnUrl); + if (cropPreset) { + instance.setAttribute('crop-preset', cropPreset); + } + instance.addEventListener('apply', (result) => this.handleApply(result)); instance.addEventListener('cancel', () => this.handleCancel()); diff --git a/blocks/Config/Config.js b/blocks/Config/Config.js index 680adac21..0368efbf9 100644 --- a/blocks/Config/Config.js +++ b/blocks/Config/Config.js @@ -41,16 +41,20 @@ const attrStateMapping = /** @type {Record [ - sharedConfigKey(/** @type {keyof import('../../types').ConfigType} */ (key)), - value, - ]) - ), - }; + constructor() { + super(); + + /** @type {Block['init$'] & import('../../types').ConfigType} */ + this.init$ = { + ...this.init$, + ...Object.fromEntries( + Object.entries(initialConfig).map(([key, value]) => [ + sharedConfigKey(/** @type {keyof import('../../types').ConfigType} */ (key)), + value, + ]) + ), + }; + } initCallback() { super.initCallback(); diff --git a/blocks/Config/initialConfig.js b/blocks/Config/initialConfig.js index 817f4aa98..3ccb80dee 100644 --- a/blocks/Config/initialConfig.js +++ b/blocks/Config/initialConfig.js @@ -24,6 +24,7 @@ export const initialConfig = Object.freeze({ useLocalImageEditor: false, useCloudImageEditor: true, removeCopyright: false, + cropPreset: '', modalScrollLock: true, modalBackdropStrokes: false, diff --git a/blocks/Config/normalizeConfigValue.js b/blocks/Config/normalizeConfigValue.js index b8f317a58..c84a9bcc5 100644 --- a/blocks/Config/normalizeConfigValue.js +++ b/blocks/Config/normalizeConfigValue.js @@ -42,6 +42,7 @@ const mapping = { useLocalImageEditor: asBoolean, useCloudImageEditor: asBoolean, removeCopyright: asBoolean, + cropPreset: asString, modalScrollLock: asBoolean, modalBackdropStrokes: asBoolean, diff --git a/blocks/ExternalSource/ExternalSource.js b/blocks/ExternalSource/ExternalSource.js index ad2c6cfc7..56a55de9f 100644 --- a/blocks/ExternalSource/ExternalSource.js +++ b/blocks/ExternalSource/ExternalSource.js @@ -33,19 +33,30 @@ import { queryString } from './query-string.js'; export class ExternalSource extends UploaderBlock { activityType = ActivityBlock.activities.EXTERNAL; - // @ts-ignore TODO: fix this - init$ = { - ...this.init$, - activityIcon: '', - activityCaption: '', - counter: 0, - onDone: () => { - this.$['*currentActivity'] = ActivityBlock.activities.UPLOAD_LIST; - }, - onCancel: () => { - this.historyBack(); - }, - }; + constructor() { + super(); + + this.init$ = { + ...this.init$, + activityIcon: '', + activityCaption: '', + selectedList: [], + counter: 0, + onDone: () => { + for (const message of this.$.selectedList) { + const url = this.extractUrlFromMessage(message); + const { filename } = message; + const { externalSourceType } = this.activityParams; + this.addFileFromUrl(url, { fileName: filename, source: externalSourceType }); + } + + this.$['*currentActivity'] = ActivityBlock.activities.UPLOAD_LIST; + }, + onCancel: () => { + this.historyBack(); + }, + }; + } /** * @private @@ -64,7 +75,6 @@ export class ExternalSource extends UploaderBlock { activityIcon: externalSourceType, }); - this.$.counter = 0; this.mountIframe(); }, }); @@ -73,6 +83,29 @@ export class ExternalSource extends UploaderBlock { this.unmountIframe(); } }); + this.sub('selectedList', (list) => { + this.$.counter = list.length; + }); + } + + /** + * @private + * @param {SelectedFileMessage} message + */ + extractUrlFromMessage(message) { + if (message.alternatives) { + const preferredTypes = stringToArray(this.cfg.externalSourcesPreferredTypes); + for (const preferredType of preferredTypes) { + const regexp = wildcardRegexp(preferredType); + for (const [type, typeUrl] of Object.entries(message.alternatives)) { + if (regexp.test(type)) { + return typeUrl; + } + } + } + } + + return message.url; } /** @@ -88,27 +121,7 @@ export class ExternalSource extends UploaderBlock { * @param {SelectedFileMessage} message */ async handleFileSelected(message) { - console.log(message); - this.$.counter = this.$.counter + 1; - - const url = (() => { - if (message.alternatives) { - const preferredTypes = stringToArray(this.cfg.externalSourcesPreferredTypes); - for (const preferredType of preferredTypes) { - const regexp = wildcardRegexp(preferredType); - for (const [type, typeUrl] of Object.entries(message.alternatives)) { - if (regexp.test(type)) { - return typeUrl; - } - } - } - } - return message.url; - })(); - - let { filename } = message; - let { externalSourceType } = this.activityParams; - this.addFileFromUrl(url, { fileName: filename, source: externalSourceType }); + this.$.selectedList = [...this.$.selectedList, message]; } /** @private */ @@ -116,14 +129,14 @@ export class ExternalSource extends UploaderBlock { this.applyStyles(); } - /** @private */ - _inheritedUpdateCssData = this.updateCssData; updateCssData = () => { if (this.isActivityActive) { this._inheritedUpdateCssData(); this.applyStyles(); } }; + /** @private */ + _inheritedUpdateCssData = this.updateCssData; /** * @private @@ -190,6 +203,7 @@ export class ExternalSource extends UploaderBlock { registerMessage('file-selected', iframe.contentWindow, this.handleFileSelected.bind(this)); this._iframe = iframe; + this.$.selectedList = []; } /** @private */ @@ -197,6 +211,8 @@ export class ExternalSource extends UploaderBlock { this._iframe && unregisterMessage('file-selected', this._iframe.contentWindow); this.ref.iframeWrapper.innerHTML = ''; this._iframe = null; + this.$.selectedList = []; + this.$.counter = 0; } } diff --git a/blocks/FileItem/FileItem.js b/blocks/FileItem/FileItem.js index 2f4aeafc5..b9061cfc2 100644 --- a/blocks/FileItem/FileItem.js +++ b/blocks/FileItem/FileItem.js @@ -36,56 +36,59 @@ export class FileItem extends UploaderBlock { /** @private */ _renderedOnce = false; - // @ts-ignore TODO: fix this - init$ = { - ...this.init$, - uid: '', - itemName: '', - errorText: '', - thumbUrl: '', - progressValue: 0, - progressVisible: false, - progressUnknown: false, - badgeIcon: '', - isFinished: false, - isFailed: false, - isUploading: false, - isFocused: false, - isEditable: false, - isLimitOverflow: false, - state: FileItemState.IDLE, - '*uploadTrigger': null, - - onEdit: () => { - this.set$({ - '*focusedEntry': this._entry, - }); - if (this.hasBlockInCtx((b) => b.activityType === ActivityBlock.activities.DETAILS)) { - this.$['*currentActivity'] = ActivityBlock.activities.DETAILS; - } else { - this.$['*currentActivity'] = ActivityBlock.activities.CLOUD_IMG_EDIT; - } - }, - onRemove: () => { - let entryUuid = this._entry.getValue('uuid'); - if (entryUuid) { - let data = this.getOutputData((dataItem) => { - return dataItem.getValue('uuid') === entryUuid; + constructor() { + super(); + + this.init$ = { + ...this.init$, + uid: '', + itemName: '', + errorText: '', + thumbUrl: '', + progressValue: 0, + progressVisible: false, + progressUnknown: false, + badgeIcon: '', + isFinished: false, + isFailed: false, + isUploading: false, + isFocused: false, + isEditable: false, + isLimitOverflow: false, + state: FileItemState.IDLE, + '*uploadTrigger': null, + + onEdit: () => { + this.set$({ + '*focusedEntry': this._entry, }); - EventManager.emit( - new EventData({ - type: EVENT_TYPES.REMOVE, - ctx: this.ctxName, - data, - }) - ); - } - this.uploadCollection.remove(this.$.uid); - }, - onUpload: () => { - this.upload(); - }, - }; + if (this.hasBlockInCtx((b) => b.activityType === ActivityBlock.activities.DETAILS)) { + this.$['*currentActivity'] = ActivityBlock.activities.DETAILS; + } else { + this.$['*currentActivity'] = ActivityBlock.activities.CLOUD_IMG_EDIT; + } + }, + onRemove: () => { + let entryUuid = this._entry.getValue('uuid'); + if (entryUuid) { + let data = this.getOutputData((dataItem) => { + return dataItem.getValue('uuid') === entryUuid; + }); + EventManager.emit( + new EventData({ + type: EVENT_TYPES.REMOVE, + ctx: this.ctxName, + data, + }) + ); + } + this.uploadCollection.remove(this.$.uid); + }, + onUpload: () => { + this.upload(); + }, + }; + } _reset() { for (let sub of this._entrySubs) { @@ -296,7 +299,7 @@ export class FileItem extends UploaderBlock { isUploading: state === FileItemState.UPLOADING, isFinished: state === FileItemState.FINISHED, progressVisible: state === FileItemState.UPLOADING, - isEditable: this.cfg.useCloudImageEditor && state === FileItemState.FINISHED && this._entry?.getValue('isImage'), + isEditable: this.cfg.useCloudImageEditor && this._entry?.getValue('isImage') && this._entry?.getValue('cdnUrl'), errorText: this._entry.getValue('uploadError')?.message || this._entry.getValue('validationErrorMsg') || diff --git a/blocks/Modal/Modal.js b/blocks/Modal/Modal.js index 5432eb1c2..81d7f173e 100644 --- a/blocks/Modal/Modal.js +++ b/blocks/Modal/Modal.js @@ -4,6 +4,16 @@ import { Block } from '../../abstract/Block.js'; export class Modal extends Block { static StateConsumerScope = 'modal'; + constructor() { + super(); + this.init$ = { + ...this.init$, + '*modalActive': false, + isOpen: false, + closeClicked: this._handleDialogClose, + }; + } + _handleBackdropClick = () => { this._closeDialog(); }; @@ -17,20 +27,12 @@ export class Modal extends Block { }; /** @param {Event} e */ - _handleDialogClick = (e) => { + _handleDialogPointerUp = (e) => { if (e.target === this.ref.dialog) { this._closeDialog(); } }; - // @ts-ignore TODO: fix this - init$ = { - ...this.init$, - '*modalActive': false, - isOpen: false, - closeClicked: this._handleDialogClose, - }; - show() { if (this.ref.dialog.showModal) { this.ref.dialog.showModal(); @@ -51,7 +53,7 @@ export class Modal extends Block { super.initCallback(); if (typeof HTMLDialogElement === 'function') { this.ref.dialog.addEventListener('close', this._handleDialogClose); - this.ref.dialog.addEventListener('click', this._handleDialogClick); + this.ref.dialog.addEventListener('pointerup', this._handleDialogPointerUp); } else { this.setAttribute('dialog-fallback', ''); let backdrop = document.createElement('div'); @@ -93,7 +95,7 @@ export class Modal extends Block { super.destroyCallback(); document.body.style.overflow = ''; this.ref.dialog.removeEventListener('close', this._handleDialogClose); - this.ref.dialog.removeEventListener('click', this._handleDialogClick); + this.ref.dialog.removeEventListener('click', this._handleDialogPointerUp); } } diff --git a/blocks/SimpleBtn/SimpleBtn.js b/blocks/SimpleBtn/SimpleBtn.js index b65ccaff3..570162d16 100644 --- a/blocks/SimpleBtn/SimpleBtn.js +++ b/blocks/SimpleBtn/SimpleBtn.js @@ -2,14 +2,17 @@ import { UploaderBlock } from '../../abstract/UploaderBlock.js'; export class SimpleBtn extends UploaderBlock { - // @ts-ignore TODO: fix this - init$ = { - ...this.init$, - '*simpleButtonText': '', - onClick: () => { - this.initFlow(); - }, - }; + constructor() { + super(); + + this.init$ = { + ...this.init$, + '*simpleButtonText': '', + onClick: () => { + this.initFlow(); + }, + }; + } initCallback() { super.initCallback(); diff --git a/blocks/UploadList/UploadList.js b/blocks/UploadList/UploadList.js index 8c56c2a58..1a9680f3a 100644 --- a/blocks/UploadList/UploadList.js +++ b/blocks/UploadList/UploadList.js @@ -20,41 +20,44 @@ export class UploadList extends UploaderBlock { historyTracked = true; activityType = ActivityBlock.activities.UPLOAD_LIST; - // @ts-ignore TODO: fix this - init$ = { - ...this.init$, - doneBtnVisible: false, - doneBtnEnabled: false, - uploadBtnVisible: false, - addMoreBtnVisible: false, - addMoreBtnEnabled: false, - headerText: '', - - hasFiles: false, - onAdd: () => { - this.initFlow(true); - }, - onUpload: () => { - this.uploadAll(); - this._updateUploadsState(); - }, - onDone: () => { - this.doneFlow(); - }, - onCancel: () => { - let data = this.getOutputData((dataItem) => { - return !!dataItem.getValue('fileInfo'); - }); - EventManager.emit( - new EventData({ - type: EVENT_TYPES.REMOVE, - ctx: this.ctxName, - data, - }) - ); - this.uploadCollection.clearAll(); - }, - }; + constructor() { + super(); + + this.init$ = { + ...this.init$, + doneBtnVisible: false, + doneBtnEnabled: false, + uploadBtnVisible: false, + addMoreBtnVisible: false, + addMoreBtnEnabled: false, + headerText: '', + + hasFiles: false, + onAdd: () => { + this.initFlow(true); + }, + onUpload: () => { + this.uploadAll(); + this._updateUploadsState(); + }, + onDone: () => { + this.doneFlow(); + }, + onCancel: () => { + let data = this.getOutputData((dataItem) => { + return !!dataItem.getValue('fileInfo'); + }); + EventManager.emit( + new EventData({ + type: EVENT_TYPES.REMOVE, + ctx: this.ctxName, + data, + }) + ); + this.uploadCollection.clearAll(); + }, + }; + } _debouncedHandleCollectionUpdate = debounce(() => { if (!this.isConnected) { diff --git a/blocks/test/cloud-image-editor.htm b/blocks/test/cloud-image-editor.htm new file mode 100644 index 000000000..99200bc0a --- /dev/null +++ b/blocks/test/cloud-image-editor.htm @@ -0,0 +1,31 @@ + + + + + + + + + + + + + diff --git a/blocks/test/raw-regular.htm b/blocks/test/raw-regular.htm index 6bb0abfc0..dd3dd5d90 100644 --- a/blocks/test/raw-regular.htm +++ b/blocks/test/raw-regular.htm @@ -30,4 +30,5 @@ - + + \ No newline at end of file diff --git a/blocks/utils/debounce.js b/blocks/utils/debounce.js index 454ab449b..09c1c5c76 100644 --- a/blocks/utils/debounce.js +++ b/blocks/utils/debounce.js @@ -1,18 +1,22 @@ +// @ts-check + /** - * @template {Function} T + * @template {{ (...args: any[]): any }} T * @param {T} callback * @param {number} wait - * @returns {T & { cancel: function }} + * @returns {T & { cancel: () => void }} } */ export function debounce(callback, wait) { + /** @type {NodeJS.Timeout} */ let timer; - /** @type {any} */ - let debounced = (...args) => { - clearTimeout(timer); - timer = setTimeout(() => callback(...args), wait); - }; + const debounced = + /** @param {...any} args */ + (...args) => { + clearTimeout(timer); + timer = setTimeout(() => callback(...args), wait); + }; debounced.cancel = () => { clearTimeout(timer); }; - return debounced; + return /** @type {T & { cancel: () => void }} } */ (debounced); } diff --git a/blocks/utils/throttle.js b/blocks/utils/throttle.js new file mode 100644 index 000000000..edfed5da3 --- /dev/null +++ b/blocks/utils/throttle.js @@ -0,0 +1,30 @@ +// @ts-check + +/** + * @param {Function} fn + * @param {number} wait + */ +export const throttle = (fn, wait) => { + /** @type {boolean} */ + let inThrottle; + /** @type {ReturnType} */ + let lastFn; + /** @type {number} */ + let lastTime; + /** @param {...any} args */ + return (...args) => { + if (!inThrottle) { + fn(...args); + lastTime = Date.now(); + inThrottle = true; + } else { + clearTimeout(lastFn); + lastFn = setTimeout(() => { + if (Date.now() - lastTime >= wait) { + fn(...args); + lastTime = Date.now(); + } + }, Math.max(wait - (Date.now() - lastTime), 0)); + } + }; +}; diff --git a/package-lock.json b/package-lock.json index c97837ed0..1fec86e4e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -18,7 +18,7 @@ "@esm-bundle/chai": "^4.3.4-fix.0", "@happy-dom/global-registrator": "^9.8.4", "@jam-do/jam-tools": "^0.0.4", - "@total-typescript/ts-reset": "^0.4.2", + "@total-typescript/ts-reset": "^0.5.1", "@types/chai": "^4.3.4", "@types/mocha": "^10.0.1", "@types/node": "^18.15.11", @@ -44,7 +44,7 @@ "stylelint-config-standard": "^32.0.0", "stylelint-declaration-block-no-ignored-properties": "^2.7.0", "stylelint-order": "^6.0.3", - "typescript": "^5.0.4" + "typescript": "^5.2.2" } }, "node_modules/@75lb/deep-merge": { @@ -2674,9 +2674,9 @@ "integrity": "sha512-fUOJwzuldeApJ533YeTdrfnpp4nsA+ss1eiNBodX7RHf4LnhPB2Z9HP4fF3m2YhKYnxK0whjXaKA+wrxTRP5qA==" }, "node_modules/@total-typescript/ts-reset": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/@total-typescript/ts-reset/-/ts-reset-0.4.2.tgz", - "integrity": "sha512-vqd7ZUDSrXFVT1n8b2kc3LnklncDQFPvR58yUS1kEP23/nHPAO9l1lMjUfnPrXYYk4Hj54rrLKMW5ipwk7k09A==", + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@total-typescript/ts-reset/-/ts-reset-0.5.1.tgz", + "integrity": "sha512-AqlrT8YA1o7Ff5wPfMOL0pvL+1X+sw60NN6CcOCqs658emD6RfiXhF7Gu9QcfKBH7ELY2nInLhKSCWVoNL70MQ==", "dev": true }, "node_modules/@types/accepts": { @@ -12225,16 +12225,16 @@ } }, "node_modules/typescript": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.4.tgz", - "integrity": "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==", + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", + "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", "dev": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" }, "engines": { - "node": ">=12.20" + "node": ">=14.17" } }, "node_modules/typical": { @@ -14599,9 +14599,9 @@ "integrity": "sha512-fUOJwzuldeApJ533YeTdrfnpp4nsA+ss1eiNBodX7RHf4LnhPB2Z9HP4fF3m2YhKYnxK0whjXaKA+wrxTRP5qA==" }, "@total-typescript/ts-reset": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/@total-typescript/ts-reset/-/ts-reset-0.4.2.tgz", - "integrity": "sha512-vqd7ZUDSrXFVT1n8b2kc3LnklncDQFPvR58yUS1kEP23/nHPAO9l1lMjUfnPrXYYk4Hj54rrLKMW5ipwk7k09A==", + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@total-typescript/ts-reset/-/ts-reset-0.5.1.tgz", + "integrity": "sha512-AqlrT8YA1o7Ff5wPfMOL0pvL+1X+sw60NN6CcOCqs658emD6RfiXhF7Gu9QcfKBH7ELY2nInLhKSCWVoNL70MQ==", "dev": true }, "@types/accepts": { @@ -21711,9 +21711,9 @@ } }, "typescript": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.0.4.tgz", - "integrity": "sha512-cW9T5W9xY37cc+jfEnaUvX91foxtHkza3Nw3wkoF4sSlKn0MONdkdEndig/qPBWXNkmplh3NzayQzCiHM4/hqw==", + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", + "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", "dev": true }, "typical": { diff --git a/package.json b/package.json index 8b7b53ed2..c0b539d8c 100644 --- a/package.json +++ b/package.json @@ -98,7 +98,7 @@ "@esm-bundle/chai": "^4.3.4-fix.0", "@happy-dom/global-registrator": "^9.8.4", "@jam-do/jam-tools": "^0.0.4", - "@total-typescript/ts-reset": "^0.4.2", + "@total-typescript/ts-reset": "^0.5.1", "@types/chai": "^4.3.4", "@types/mocha": "^10.0.1", "@types/node": "^18.15.11", @@ -124,7 +124,7 @@ "stylelint-config-standard": "^32.0.0", "stylelint-declaration-block-no-ignored-properties": "^2.7.0", "stylelint-order": "^6.0.3", - "typescript": "^5.0.4" + "typescript": "^5.2.2" }, "author": "Uploadcare Inc.", "license": "MIT", diff --git a/solutions/file-uploader/minimal/FileUploaderMinimal.js b/solutions/file-uploader/minimal/FileUploaderMinimal.js index e7730405d..6ad79c5f2 100644 --- a/solutions/file-uploader/minimal/FileUploaderMinimal.js +++ b/solutions/file-uploader/minimal/FileUploaderMinimal.js @@ -1,6 +1,5 @@ -import { SolutionBlock } from '../../../abstract/SolutionBlock.js'; import { ActivityBlock } from '../../../abstract/ActivityBlock.js'; -import { sharedConfigKey } from '../../../abstract/sharedConfigKey.js'; +import { SolutionBlock } from '../../../abstract/SolutionBlock.js'; export class FileUploaderMinimal extends SolutionBlock { pauseRender = true; @@ -22,15 +21,15 @@ export class FileUploaderMinimal extends SolutionBlock { } }); - this.sub(sharedConfigKey('sourceList'), (sourceList) => { + this.subConfigValue('sourceList', (sourceList) => { if (sourceList !== 'local') { - this.$[sharedConfigKey('sourceList')] = 'local'; + this.cfg.sourceList = 'local'; } }); - this.sub(sharedConfigKey('confirmUpload'), (confirmUpload) => { + this.subConfigValue('confirmUpload', (confirmUpload) => { if (confirmUpload !== false) { - this.$[sharedConfigKey('confirmUpload')] = false; + this.cfg.confirmUpload = false; } }); } diff --git a/types/exported.d.ts b/types/exported.d.ts index cb9c3422e..64107e4a6 100644 --- a/types/exported.d.ts +++ b/types/exported.d.ts @@ -18,6 +18,7 @@ export type ConfigType = { useLocalImageEditor: boolean; useCloudImageEditor: boolean; removeCopyright: boolean; + cropPreset: string; modalScrollLock: boolean; modalBackdropStrokes: boolean; sourceListWrap: boolean; diff --git a/web/blocks.iife.min.js b/web/blocks.iife.min.js index fa94ef9b4..2d0b10b3b 100644 --- a/web/blocks.iife.min.js +++ b/web/blocks.iife.min.js @@ -23,5 +23,5 @@ * SOFTWARE. * */ -"use strict";var LR=(()=>{var Re=Object.defineProperty;var Nr=Object.getOwnPropertyDescriptor;var Dr=Object.getOwnPropertyNames;var Br=Object.prototype.hasOwnProperty;var Fr=(s,i,t)=>i in s?Re(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var n=(s,i)=>Re(s,"name",{value:i,configurable:!0});var Vr=(s,i)=>{for(var t in i)Re(s,t,{get:i[t],enumerable:!0})},zr=(s,i,t,e)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Dr(i))!Br.call(s,r)&&r!==t&&Re(s,r,{get:()=>i[r],enumerable:!(e=Nr(i,r))||e.enumerable});return s};var jr=s=>zr(Re({},"__esModule",{value:!0}),s);var u=(s,i,t)=>(Fr(s,typeof i!="symbol"?i+"":i,t),t),Di=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var F=(s,i,t)=>(Di(s,i,"read from private field"),t?t.call(s):i.get(s)),Mt=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},Le=(s,i,t,e)=>(Di(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var hi=(s,i,t)=>(Di(s,i,"access private method"),t);var Xn={};Vr(Xn,{ActivityBlock:()=>_,ActivityHeader:()=>li,BaseComponent:()=>Nt,Block:()=>b,CameraSource:()=>de,CloudImageEditor:()=>ui,CloudImageEditorActivity:()=>ai,CloudImageEditorBlock:()=>it,Config:()=>oe,ConfirmationDialog:()=>me,Copyright:()=>Se,CropFrame:()=>_e,Data:()=>A,DataOutput:()=>Ut,DropArea:()=>Wt,EditorCropButtonControl:()=>Ot,EditorFilterControl:()=>Tt,EditorImageCropper:()=>ye,EditorImageFader:()=>ni,EditorOperationControl:()=>Rt,EditorScroller:()=>Ce,EditorSlider:()=>be,EditorToolbar:()=>xe,ExternalSource:()=>Ae,FileItem:()=>ot,FilePreview:()=>qt,FileUploaderInline:()=>Oe,FileUploaderMinimal:()=>Ie,FileUploaderRegular:()=>ke,Icon:()=>jt,Img:()=>Ke,LineLoaderUi:()=>we,LrBtnUi:()=>Yt,MessageBox:()=>ce,Modal:()=>P,PACKAGE_NAME:()=>rs,PACKAGE_VERSION:()=>os,PresenceToggle:()=>Te,ProgressBar:()=>ge,ProgressBarCommon:()=>fe,Select:()=>$e,ShadowWrapper:()=>Jt,SimpleBtn:()=>le,SliderUi:()=>Ee,SourceBtn:()=>Xt,SourceList:()=>Ze,StartFrom:()=>Ye,Tabs:()=>Zt,UploadCtxProvider:()=>ti,UploadDetails:()=>pe,UploadList:()=>ue,UploaderBlock:()=>v,UrlSource:()=>he,Video:()=>J,connectBlocksFrom:()=>Pr,registerBlocks:()=>Mi,shadowed:()=>ci,toKebabCase:()=>at});var Hr=Object.defineProperty,Wr=n((s,i,t)=>i in s?Hr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,"__defNormalProp"),Fi=n((s,i,t)=>(Wr(s,typeof i!="symbol"?i+"":i,t),t),"__publicField");function Xr(s){let i=n(t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}},"clone");return i(s)}n(Xr,"cloneObj");var A=n(class{constructor(s){s.constructor===Object?this.store=Xr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(A.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){A.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(A.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=A.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new A(s),A.globalStore.set(i,t)),t}static deleteCtx(s){A.globalStore.delete(s)}static getCtx(s,i=!0){return A.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}},"Data");A.globalStore=new Map;var C=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),gs="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",qr=gs.length-1,Pe=n(class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}n(Gr,"kebabToCamel");function Kr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=n(class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}},"itemClass");let a=t.innerHTML;r.template=a,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let o=t.getAttribute(C.REPEAT_ATTR);i.sub(o,a=>{if(!a){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],c,h=n(d=>{d.forEach((m,g)=>{if(l[g])if(l[g].set$)setTimeout(()=>{l[g].set$(m)});else for(let f in m)l[g][f]=m[f];else{c||(c=new DocumentFragment);let f=new r;Object.assign(f.init$,m),c.appendChild(f)}}),c&&t.appendChild(c);let p=l.slice(d.length,l.length);for(let m of p)m.remove()},"fillItems");if(a.constructor===Array)h(a);else if(a.constructor===Object){let d=[];for(let p in a){let m=a[p];Object.defineProperty(m,"_KEY_",{value:p,enumerable:!0}),d.push(m)}h(d)}else console.warn("Symbiote repeat data type error:"),console.log(a)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}n(Kr,"repeatProcessor");var ms="__default__";function Yr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let o=r.getAttribute("name")||ms;e[o]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var o;let a=ms;r instanceof Element&&r.hasAttribute("slot")&&(a=r.getAttribute("slot"),r.removeAttribute("slot")),(o=e[a])==null||o.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(o,r.slot)}else r.slot.remove()})}n(Yr,"slotProcessor");function Zr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}n(Zr,"refProcessor");function Jr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let a=Gr(o.name.replace("-",""));r.push(a+":"+o.value),t.removeAttribute(o.name)}}),r.forEach(o=>{if(!o)return;let a=o.split(":").map(d=>d.trim()),l=a[0],c;l.indexOf(C.ATTR_BIND_PRFX)===0&&(c=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let h=a[1].split(",").map(d=>d.trim());for(let d of h){let p;d.startsWith("!!")?(p="double",d=d.replace("!!","")):d.startsWith("!")&&(p="single",d=d.replace("!","")),i.sub(d,m=>{p==="double"?m=!!m:p==="single"&&(m=!m),c?(m==null?void 0:m.constructor)===Boolean?m?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,m):_s(t,l,m)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=m)})}}),t.removeAttribute(C.BIND_ATTR)})}n(Jr,"domSetProcessor");var di="{{",Ue="}}",Qr="skip-text";function to(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var o;return!((o=r.parentElement)!=null&&o.hasAttribute(Qr))&&r.textContent.includes(di)&&r.textContent.includes(Ue)&&1}});for(;i=e.nextNode();)t.push(i);return t}n(to,"getTextNodesWithTokens");var eo=n(function(s,i){to(s).forEach(e=>{let r=[],o;for(;e.textContent.includes(Ue);)e.textContent.startsWith(di)?(o=e.textContent.indexOf(Ue)+Ue.length,e.splitText(o),r.push(e)):(o=e.textContent.indexOf(di),e.splitText(o)),e=e.nextSibling;r.forEach(a=>{let l=a.textContent.replace(di,"").replace(Ue,"");a.textContent="",i.sub(l,c=>{a.textContent=c})})})},"txtNodesProcessor"),io=[Kr,Yr,Zr,Jr,eo],pi="'",te='"',so=/\\([0-9a-fA-F]{1,6} ?)/g;function ro(s){return(s[0]===te||s[0]===pi)&&(s[s.length-1]===te||s[s.length-1]===pi)}n(ro,"hasLeadingTrailingQuotes");function oo(s){return(s[0]===te||s[0]===pi)&&(s=s.slice(1)),(s[s.length-1]===te||s[s.length-1]===pi)&&(s=s.slice(0,-1)),s}n(oo,"trimQuotes");function no(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=no(i),i=te+i+te);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}n(ao,"parseCssPropertyValue");var fs=0,Qt=null,bt=null,At=n(class extends HTMLElement{constructor(){super(),Fi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return At}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let o=this.getRootNode(),a=(o==null?void 0:o.querySelector(r))||document.querySelector(r);a?s=a.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=n(()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()},"addFr");if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Pe.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=A.registerCtx({},this)),this.__localCtx}get nodeCtx(){return A.getCtx(this.ctxName,!1)||A.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=A.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n(o=>{this.isConnected&&i(o)},"subCb"),r=At.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=At.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=At.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=At.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=At.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=At.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let o=A.getCtx(e,!1);o||(o=A.registerCtx({},e)),o.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])_s(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of io)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);bt==null||bt.delete(this.updateCssData),bt!=null&&bt.size||(Qt==null||Qt.disconnect(),Qt=null,bt=null)},100)))}static reg(s,i=!1){s||(fs++,s=`${C.AUTO_TAG_PRFX}-${fs}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=ao(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){bt||(bt=new Set),bt.add(this.updateCssData),Qt||(Qt=new MutationObserver(s=>{s[0].type==="attributes"&&bt.forEach(i=>{i()})}),Qt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},"_BaseComponent"),Nt=At;Fi(Nt,"template");var Bi=n(class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Bi.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let o in i)i[o]===!0?e+=this.separator+o:e+=this.separator+o+`=${i[o]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=A.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Bi.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}},"AppRouter");Bi.appMap=Object.create(null);function lo(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}n(lo,"applyStyles");function co(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}n(co,"applyAttributes");function Me(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&co(i,s.attributes),s.styles&&lo(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Me(t);i.appendChild(e)}),i}n(Me,"create");var bs="idb-store-ready",uo="symbiote-db",ho="symbiote-idb-update_",po=n(class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(bs,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return ho+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=o=>{var a;(a=o.target.result)!=null&&a._value?e(o.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=o=>{r(o)}})}write(s,i,t=!1){let e={_key:s,_value:i},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((a,l)=>{o.onsuccess=c=>{t||this._notifySubscribers(s),a(c.target.result)},o.onerror=c=>{l(c)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,o)=>{e.onsuccess=a=>{i||this._notifySubscribers(s),r(a)},e.onerror=a=>{o(a)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let o=r.target.result;t(o.map(a=>a._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,vs.clear(this.name)}},"DbInstance"),vs=n(class{static get readyEventName(){return bs}static open(s=uo,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new po(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}},"IDB");Fi(vs,"_reg",Object.create(null));function K(s,i){let t,e=n((...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)},"debounced");return e.cancel=()=>{clearTimeout(t)},e}n(K,"debounce");var mo="--uploadcare-blocks-window-height",mi="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Vi(){return typeof window[mi]=="undefined"?!1:!!window[mi]}n(Vi,"getIsWindowHeightTracked");function ys(){if(Vi())return;let s=n(()=>{document.documentElement.style.setProperty(mo,`${window.innerHeight}px`),window[mi]=!0},"callback"),i=K(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[mi]=!1,window.removeEventListener("resize",i)}}n(ys,"createWindowHeightTracker");var fo=n(s=>s,"DEFAULT_TRANSFORMER"),zi="{{",xs="}}",Cs="plural:";function Ne(s,i,t={}){var a;let{openToken:e=zi,closeToken:r=xs,transform:o=fo}=t;for(let l in i){let c=(a=i[l])==null?void 0:a.toString();s=s.replaceAll(e+l+r,typeof c=="string"?o(c):c)}return s}n(Ne,"applyTemplateData");function ws(s){let i=[],t=s.indexOf(zi);for(;t!==-1;){let e=s.indexOf(xs,t),r=s.substring(t+2,e);if(r.startsWith(Cs)){let o=s.substring(t+2,e).replace(Cs,""),a=o.substring(0,o.indexOf("(")),l=o.substring(o.indexOf("(")+1,o.indexOf(")"));i.push({variable:r,pluralKey:a,countVariable:l})}t=s.indexOf(zi,e)}return i}n(ws,"getPluralObjects");function Ts(s){return Object.prototype.toString.call(s)==="[object Object]"}n(Ts,"isObject");var go=/\W|_/g;function _o(s){return s.split(go).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}n(_o,"camelizeString");function Es(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>xt(t,{ignoreKeys:i})):s}n(Es,"camelizeArrayItems");function xt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return Es(s,{ignoreKeys:i});if(!Ts(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Ts(r)?r=xt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=Es(r,{ignoreKeys:i})),t[_o(e)]=r}return t}n(xt,"camelizeKeys");var bo=n(s=>new Promise(i=>setTimeout(i,s)),"delay");function Xi({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let o="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:o,integration:r});let a=[s,i,e].filter(Boolean).join("/"),l=[o,r].filter(Boolean).join("; ");return`${a} (${l})`}n(Xi,"getUserAgent$1");var vo={factor:2,time:100};function yo(s,i=vo){let t=0;function e(r){let o=Math.round(i.time*i.factor**t);return r({attempt:t,retry:n(l=>bo(l!=null?l:o).then(()=>(t+=1,e(r))),"retry")})}return n(e,"runAttempt"),e(s)}n(yo,"retrier");var Ft=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Ft.prototype),this.originalProgressEvent=t}};n(Ft,"UploadcareNetworkError");var vi=n((s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},"onCancel"),vt=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,vt.prototype)}};n(vt,"CancelError");var Co=500,$s=n(({check:s,interval:i=Co,timeout:t,signal:e})=>new Promise((r,o)=>{let a,l;vi(e,()=>{a&&clearTimeout(a),o(new vt("Poll cancelled"))}),t&&(l=setTimeout(()=>{a&&clearTimeout(a),o(new vt("Timed out"))},t));let c=n(()=>{try{Promise.resolve(s(e)).then(h=>{h?(l&&clearTimeout(l),r(h)):a=setTimeout(c,i)}).catch(h=>{l&&clearTimeout(l),o(h)})}catch(h){l&&clearTimeout(l),o(h)}},"tick");a=setTimeout(c,0)}),"poll"),E={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},yi="application/octet-stream",Ss="original",$t=n(({method:s,url:i,data:t,headers:e={},signal:r,onProgress:o})=>new Promise((a,l)=>{let c=new XMLHttpRequest,h=(s==null?void 0:s.toUpperCase())||"GET",d=!1;c.open(h,i,!0),e&&Object.entries(e).forEach(p=>{let[m,g]=p;typeof g!="undefined"&&!Array.isArray(g)&&c.setRequestHeader(m,g)}),c.responseType="text",vi(r,()=>{d=!0,c.abort(),l(new vt)}),c.onload=()=>{if(c.status!=200)l(new Error(`Error ${c.status}: ${c.statusText}`));else{let p={method:h,url:i,data:t,headers:e||void 0,signal:r,onProgress:o},m=c.getAllResponseHeaders().trim().split(/[\r\n]+/),g={};m.forEach(function(w){let $=w.split(": "),T=$.shift(),x=$.join(": ");T&&typeof T!="undefined"&&(g[T]=x)});let f=c.response,y=c.status;a({request:p,data:f,headers:g,status:y})}},c.onerror=p=>{d||l(new Ft(p))},o&&typeof o=="function"&&(c.upload.onprogress=p=>{p.lengthComputable?o({isComputable:!0,value:p.loaded/p.total}):o({isComputable:!1})}),t?c.send(t):c.send()}),"request");function xo(s,...i){return s}n(xo,"identity");var wo=n(({name:s})=>s?[s]:[],"getFileOptions"),To=xo,Eo=n(()=>new FormData,"getFormData"),ks=n(s=>!1,"isBuffer"),Ci=n(s=>typeof Blob!="undefined"&&s instanceof Blob,"isBlob"),xi=n(s=>typeof File!="undefined"&&s instanceof File,"isFile"),wi=n(s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string","isReactNativeAsset"),Be=n(s=>Ci(s)||xi(s)||ks()||wi(s),"isFileData"),Ao=n(s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined","isSimpleValue"),$o=n(s=>!!s&&typeof s=="object"&&!Array.isArray(s),"isObjectValue"),So=n(s=>!!s&&typeof s=="object"&&"data"in s&&Be(s.data),"isFileValue");function ko(s,i,t){if(So(t)){let{name:e,contentType:r}=t,o=To(t.data,e,r!=null?r:yi),a=wo({name:e,contentType:r});s.push([i,o,...a])}else if($o(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else Ao(t)&&t&&s.push([i,t.toString()])}n(ko,"collectParams");function Io(s){let i=[];for(let[t,e]of Object.entries(s))ko(i,t,e);return i}n(Io,"getFormDataParams");function qi(s){let i=Eo(),t=Io(s);for(let e of t){let[r,o,...a]=e;i.append(r,o,...a)}return i}n(qi,"buildFormData");var O=class extends Error{constructor(t,e,r,o,a){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=o,this.headers=a,Object.setPrototypeOf(this,O.prototype)}};n(O,"UploadClientError");var Oo=n(s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var o;return(o=r[1])!=null?o:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},"buildSearchParams"),Ct=n((s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=Oo(t)),e.toString()},"getUrl"),Ro="6.6.1",Lo="UploadcareUploadClient",Uo=Ro;function Vt(s){return Xi({libraryName:Lo,libraryVersion:Uo,...s})}n(Vt,"getUserAgent");var Po="RequestThrottledError",As=15e3,Mo=1e3;function No(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return As;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:As}n(No,"getTimeoutFromThrottledRequest");function St(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return yo(({attempt:r,retry:o})=>s().catch(a=>{if("response"in a&&(a==null?void 0:a.code)===Po&&r{let i="";return(Ci(s)||xi(s)||wi(s))&&(i=s.type),i||yi},"getContentType"),Os=n(s=>{let i="";return xi(s)&&s.name?i=s.name:Ci(s)||ks()?i="":wi(s)&&s.name&&(i=s.name),i||Ss},"getFileName");function Gi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}n(Gi,"getStoreValue");function Do(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=E.baseURL,secureSignature:o,secureExpire:a,store:l,signal:c,onProgress:h,source:d="local",integration:p,userAgent:m,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=E.retryNetworkErrorMaxTimes,metadata:y}){return St(()=>$t({method:"POST",url:Ct(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Vt({publicKey:i,integration:p,userAgent:m})},data:qi({file:{data:s,name:t||Os(s),contentType:e||Is(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Gi(l),signature:o,expire:a,source:d,metadata:y}),signal:c,onProgress:h}).then(({data:w,headers:$,request:T})=>{let x=xt(JSON.parse(w));if("error"in x)throw new O(x.error.content,x.error.errorCode,T,x,$);return x}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:g})}n(Do,"base");var Wi;(function(s){s.Token="token",s.FileInfo="file_info"})(Wi||(Wi={}));function Bo(s,{publicKey:i,baseURL:t=E.baseURL,store:e,fileName:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:a,secureSignature:l,secureExpire:c,source:h="url",signal:d,integration:p,userAgent:m,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=E.retryNetworkErrorMaxTimes,metadata:y}){return St(()=>$t({method:"POST",headers:{"X-UC-User-Agent":Vt({publicKey:i,integration:p,userAgent:m})},url:Ct(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Gi(e),filename:r,check_URL_duplicates:o?1:void 0,save_URL_duplicates:a?1:void 0,signature:l,expire:c,source:h,metadata:y}),signal:d}).then(({data:w,headers:$,request:T})=>{let x=xt(JSON.parse(w));if("error"in x)throw new O(x.error.content,x.error.errorCode,T,x,$);return x}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:g})}n(Bo,"fromUrl");var q;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(q||(q={}));var Fo=n(s=>"status"in s&&s.status===q.Error,"isErrorResponse");function Vo(s,{publicKey:i,baseURL:t=E.baseURL,signal:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:a=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=E.retryNetworkErrorMaxTimes}={}){return St(()=>$t({method:"GET",headers:i?{"X-UC-User-Agent":Vt({publicKey:i,integration:r,userAgent:o})}:void 0,url:Ct(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:c,headers:h,request:d})=>{let p=xt(JSON.parse(c));if("error"in p&&!Fo(p))throw new O(p.error.content,void 0,d,p,h);return p}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:a})}n(Vo,"fromUrlStatus");function zo(s,{publicKey:i,baseURL:t=E.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:o,signal:a,source:l,integration:c,userAgent:h,retryThrottledRequestMaxTimes:d=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=E.retryNetworkErrorMaxTimes}){return St(()=>$t({method:"POST",headers:{"X-UC-User-Agent":Vt({publicKey:i,integration:c,userAgent:h})},url:Ct(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:o,source:l}),signal:a}).then(({data:m,headers:g,request:f})=>{let y=xt(JSON.parse(m));if("error"in y)throw new O(y.error.content,y.error.errorCode,f,y,g);return y}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:d})}n(zo,"group");function Rs(s,{publicKey:i,baseURL:t=E.baseURL,signal:e,source:r,integration:o,userAgent:a,retryThrottledRequestMaxTimes:l=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=E.retryNetworkErrorMaxTimes}){return St(()=>$t({method:"GET",headers:{"X-UC-User-Agent":Vt({publicKey:i,integration:o,userAgent:a})},url:Ct(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:h,headers:d,request:p})=>{let m=xt(JSON.parse(h));if("error"in m)throw new O(m.error.content,m.error.errorCode,p,m,d);return m}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:c})}n(Rs,"info");function jo(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=E.multipartChunkSize,baseURL:o="",secureSignature:a,secureExpire:l,store:c,signal:h,source:d="local",integration:p,userAgent:m,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=E.retryNetworkErrorMaxTimes,metadata:y}){return St(()=>$t({method:"POST",url:Ct(o,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Vt({publicKey:i,integration:p,userAgent:m})},data:qi({filename:e||Ss,size:s,content_type:t||yi,part_size:r,UPLOADCARE_STORE:Gi(c),UPLOADCARE_PUB_KEY:i,signature:a,expire:l,source:d,metadata:y}),signal:h}).then(({data:w,headers:$,request:T})=>{let x=xt(JSON.parse(w));if("error"in x)throw new O(x.error.content,x.error.errorCode,T,x,$);return x.parts=Object.keys(x.parts).map(W=>x.parts[W]),x}),{retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:f})}n(jo,"multipartStart");function Ho(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:o=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=E.retryNetworkErrorMaxTimes}){return St(()=>$t({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||yi}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a})}n(Ho,"multipartUpload");function Wo(s,{publicKey:i,baseURL:t=E.baseURL,source:e="local",signal:r,integration:o,userAgent:a,retryThrottledRequestMaxTimes:l=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=E.retryNetworkErrorMaxTimes}){return St(()=>$t({method:"POST",url:Ct(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Vt({publicKey:i,integration:o,userAgent:a})},data:qi({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:h,headers:d,request:p})=>{let m=xt(JSON.parse(h));if("error"in m)throw new O(m.error.content,m.error.errorCode,p,m,d);return m}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:c})}n(Wo,"multipartComplete");function Ki({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l,signal:c,onProgress:h}){return $s({check:d=>Rs(s,{publicKey:i,baseURL:t,signal:d,source:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l}).then(p=>p.isReady?p:(h&&h({isComputable:!0,value:1}),!1)),signal:c})}n(Ki,"isReadyPoll");var yt=class{constructor(i,{baseCDN:t=E.baseCDN,fileName:e}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);let{uuid:r,s3Bucket:o}=i,a=Ct(t,`${r}/`),l=o?Ct(`https://${o}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=a,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=o||null,this.s3Url=l}};n(yt,"UploadcareFile");var Xo=n((s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:a,contentType:l,signal:c,onProgress:h,source:d,integration:p,userAgent:m,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:f,baseCDN:y,metadata:w})=>Do(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:o,store:a,signal:c,onProgress:h,source:d,integration:p,userAgent:m,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:f,metadata:w}).then(({file:$})=>Ki({file:$,publicKey:i,baseURL:e,source:d,integration:p,userAgent:m,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:f,onProgress:h,signal:c})).then($=>new yt($,{baseCDN:y})),"uploadDirect"),qo=n((s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:o,source:a,integration:l,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d,baseCDN:p})=>Rs(s,{publicKey:i,baseURL:e,signal:r,source:a,integration:l,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d}).then(m=>new yt(m,{baseCDN:p,fileName:t})).then(m=>(o&&o({isComputable:!0,value:1}),m)),"uploadFromUploaded"),Go=n((s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),o=n(a=>()=>{e=a,r.forEach((l,c)=>c!==a&&l.abort())},"createStopRaceCallback");return vi(i,()=>{r.forEach(a=>a.abort())}),Promise.all(s.map((a,l)=>{let c=o(l);return Promise.resolve().then(()=>a({stopRace:c,signal:r[l].signal})).then(h=>(c(),h)).catch(h=>(t=h,null))})).then(a=>{if(e===null)throw t;return a[e]})},"race"),Ko=window.WebSocket,fi=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}};n(fi,"Events");var Yo=n((s,i)=>s==="success"?{status:q.Success,...i}:s==="progress"?{status:q.Progress,...i}:{status:q.Error,...i},"response"),gi=class{constructor(i,t=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new fi);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Ko(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,Yo(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=n(()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1},"actualDisconect");this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}};n(gi,"Pusher");var ji=null,Yi=n(s=>{if(!ji){let i=typeof window=="undefined"?0:3e4;ji=new gi(s,i)}return ji},"getPusher"),Zo=n(s=>{Yi(s).connect()},"preconnect");function Jo({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a,onProgress:l,signal:c}){return $s({check:h=>Vo(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a,signal:h}).then(d=>{switch(d.status){case q.Error:return new O(d.error,d.errorCode);case q.Waiting:return!1;case q.Unknown:return new O(`Token "${s}" was not found.`);case q.Progress:return l&&(d.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:d.done/d.total})),!1;case q.Success:return l&&l({isComputable:!0,value:d.done/d.total}),d;default:throw new Error("Unknown status")}}),signal:c})}n(Jo,"pollStrategy");var Qo=n(({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,o)=>{let a=Yi(i),l=a.onError(o),c=n(()=>{l(),a.unsubscribe(s)},"destroy");vi(t,()=>{c(),o(new vt("pusher cancelled"))}),a.subscribe(s,h=>{switch(h.status){case q.Progress:{e&&(h.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:h.done/h.total}));break}case q.Success:{c(),e&&e({isComputable:!0,value:h.done/h.total}),r(h);break}case q.Error:c(),o(new O(h.msg,h.error_code))}})}),"pushStrategy"),tn=n((s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:a,secureSignature:l,secureExpire:c,store:h,signal:d,onProgress:p,source:m,integration:g,userAgent:f,retryThrottledRequestMaxTimes:y,pusherKey:w=E.pusherKey,metadata:$})=>Promise.resolve(Zo(w)).then(()=>Bo(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:a,secureSignature:l,secureExpire:c,store:h,signal:d,source:m,integration:g,userAgent:f,retryThrottledRequestMaxTimes:y,metadata:$})).catch(T=>{let x=Yi(w);return x==null||x.disconnect(),Promise.reject(T)}).then(T=>T.type===Wi.FileInfo?T:Go([({signal:x})=>Jo({token:T.token,publicKey:i,baseURL:e,integration:g,userAgent:f,retryThrottledRequestMaxTimes:y,onProgress:p,signal:x}),({signal:x})=>Qo({token:T.token,pusherKey:w,signal:x,onProgress:p})],{signal:d})).then(T=>{if(T instanceof O)throw T;return T}).then(T=>Ki({file:T.uuid,publicKey:i,baseURL:e,integration:g,userAgent:f,retryThrottledRequestMaxTimes:y,onProgress:p,signal:d})).then(T=>new yt(T,{baseCDN:r})),"uploadFromUrl"),Hi=new WeakMap,en=n(async s=>{if(Hi.has(s))return Hi.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Hi.set(s,i),i},"getBlobFromReactNativeAsset"),Ls=n(async s=>{if(xi(s)||Ci(s))return s.size;if(wi(s))return(await en(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},"getFileSize"),sn=n((s,i=E.multipartMinFileSize)=>s>=i,"isMultipart"),Us=n(s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!Be(s)&&t.test(s)},"isUuid"),Ps=n(s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!Be(s)&&t.test(s)},"isUrl"),rn=n((s,i)=>new Promise((t,e)=>{let r=[],o=!1,a=i.length,l=[...i],c=n(()=>{let h=i.length-l.length,d=l.shift();d&&d().then(p=>{o||(r[h]=p,a-=1,a?c():t(r))}).catch(p=>{o=!0,e(p)})},"run");for(let h=0;h{let r=e*i,o=Math.min(r+e,t);return s.slice(r,o)},"sliceChunk"),nn=n(async(s,i,t)=>e=>on(s,e,i,t),"prepareChunks"),an=n((s,i,{publicKey:t,contentType:e,onProgress:r,signal:o,integration:a,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:c})=>Ho(s,i,{publicKey:t,contentType:e,onProgress:r,signal:o,integration:a,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:c}),"uploadPart"),ln=n(async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:o,secureExpire:a,store:l,signal:c,onProgress:h,source:d,integration:p,userAgent:m,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:f,contentType:y,multipartChunkSize:w=E.multipartChunkSize,maxConcurrentRequests:$=E.maxConcurrentRequests,baseCDN:T,metadata:x})=>{let W=e!=null?e:await Ls(s),ft,Pt=n((L,Q)=>{if(!h)return;ft||(ft=Array(L).fill(0));let gt=n(X=>X.reduce((_t,Ni)=>_t+Ni,0),"sum");return X=>{X.isComputable&&(ft[Q]=X.value,h({isComputable:!0,value:gt(ft)/L}))}},"createProgressHandler");return y||(y=Is(s)),jo(W,{publicKey:i,contentType:y,fileName:t||Os(s),baseURL:r,secureSignature:o,secureExpire:a,store:l,signal:c,source:d,integration:p,userAgent:m,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:f,metadata:x}).then(async({uuid:L,parts:Q})=>{let gt=await nn(s,W,w);return Promise.all([L,rn($,Q.map((X,_t)=>()=>an(gt(_t),X,{publicKey:i,contentType:y,onProgress:Pt(Q.length,_t),signal:c,integration:p,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:f})))])}).then(([L])=>Wo(L,{publicKey:i,baseURL:r,source:d,integration:p,userAgent:m,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:f})).then(L=>L.isReady?L:Ki({file:L.uuid,publicKey:i,baseURL:r,source:d,integration:p,userAgent:m,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:f,onProgress:h,signal:c})).then(L=>new yt(L,{baseCDN:T}))},"uploadMultipart");async function Zi(s,{publicKey:i,fileName:t,baseURL:e=E.baseURL,secureSignature:r,secureExpire:o,store:a,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:g,contentType:f,multipartMinFileSize:y,multipartChunkSize:w,maxConcurrentRequests:$,baseCDN:T=E.baseCDN,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:W,pusherKey:ft,metadata:Pt}){if(Be(s)){let L=await Ls(s);return sn(L,y)?ln(s,{publicKey:i,contentType:f,multipartChunkSize:w,fileSize:L,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:a,signal:l,onProgress:c,source:h,integration:d,userAgent:p,maxConcurrentRequests:$,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:g,baseCDN:T,metadata:Pt}):Xo(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:o,store:a,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:g,baseCDN:T,metadata:Pt})}if(Ps(s))return tn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:W,secureSignature:r,secureExpire:o,store:a,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:g,pusherKey:ft,metadata:Pt});if(Us(s))return qo(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:g,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}n(Zi,"uploadFile");var _i=class{constructor(i,t){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}};n(_i,"UploadcareGroup");var cn=n(s=>{for(let i of s)if(!Be(i))return!1;return!0},"isFileDataArray"),un=n(s=>{for(let i of s)if(!Us(i))return!1;return!0},"isUuidArray"),hn=n(s=>{for(let i of s)if(!Ps(i))return!1;return!0},"isUrlArray");function Ms(s,{publicKey:i,fileName:t,baseURL:e=E.baseURL,secureSignature:r,secureExpire:o,store:a,signal:l,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:g,contentType:f,multipartChunkSize:y=E.multipartChunkSize,baseCDN:w=E.baseCDN,checkForUrlDuplicates:$,saveUrlForRecurrentUploads:T,jsonpCallback:x}){if(!cn(s)&&!hn(s)&&!un(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let W,ft=!0,Pt=s.length,L=n((Q,gt)=>{if(!c)return;W||(W=Array(Q).fill(0));let X=n(_t=>_t.reduce((Ni,Mr)=>Ni+Mr)/Q,"normalize");return _t=>{if(!_t.isComputable||!ft){ft=!1,c({isComputable:!1});return}W[gt]=_t.value,c({isComputable:!0,value:X(W)})}},"createProgressHandler");return Promise.all(s.map((Q,gt)=>Zi(Q,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:a,signal:l,onProgress:L(Pt,gt),source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:g,contentType:f,multipartChunkSize:y,baseCDN:w,checkForUrlDuplicates:$,saveUrlForRecurrentUploads:T}))).then(Q=>{let gt=Q.map(X=>X.uuid);return zo(gt,{publicKey:i,baseURL:e,jsonpCallback:x,secureSignature:r,secureExpire:o,signal:l,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:g}).then(X=>new _i(X,Q)).then(X=>(c&&c({isComputable:!0,value:1}),X))})}n(Ms,"uploadFileGroup");var Dt,ee,Bt,ie,se,re,bi,De=class{constructor(i){Mt(this,re);Mt(this,Dt,1);Mt(this,ee,[]);Mt(this,Bt,0);Mt(this,ie,new WeakMap);Mt(this,se,new WeakMap);Le(this,Dt,i)}add(i){return new Promise((t,e)=>{F(this,ie).set(i,t),F(this,se).set(i,e),F(this,ee).push(i),hi(this,re,bi).call(this)})}get pending(){return F(this,ee).length}get running(){return F(this,Bt)}set concurrency(i){Le(this,Dt,i),hi(this,re,bi).call(this)}get concurrency(){return F(this,Dt)}};n(De,"Queue"),Dt=new WeakMap,ee=new WeakMap,Bt=new WeakMap,ie=new WeakMap,se=new WeakMap,re=new WeakSet,bi=n(function(){let i=F(this,Dt)-F(this,Bt);for(let t=0;t{F(this,ie).delete(e),F(this,se).delete(e),Le(this,Bt,F(this,Bt)-1),hi(this,re,bi).call(this)}).then(a=>r(a)).catch(a=>o(a))}},"#run");var Ji=n(()=>({"*blocksRegistry":new Set}),"blockCtx"),Qi=n(s=>({...Ji(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),"activityBlockCtx"),Ti=n(s=>({...Qi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new De(1)}),"uploaderBlockCtx");function Ns(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let a=e.split(":");r=a[0],e=a[1]}let o="l10n:"+e;i.__l10nKeys.push(o),i.add(o,e),i.sub(o,a=>{t[r]=i.l10n(a)}),t.removeAttribute("l10n")})}n(Ns,"l10nProcessor");var U=n(s=>`*cfg/${s}`,"sharedConfigKey");var at=n(s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")},"toKebabCase");var Ds=new Set;function Ei(s){Ds.has(s)||(Ds.add(s),console.warn(s))}n(Ei,"warnOnce");var Ai=n((s,i)=>new Intl.PluralRules(s).select(i),"getPluralForm");var ts="lr-",b=class extends Nt{constructor(){super();u(this,"allowCustomTemplate",!0);u(this,"init$",Ji());u(this,"updateCtxCssData",n(()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()},"updateCtxCssData"));this.activityType=null,this.addTemplateProcessor(Ns),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,o=ws(r);for(let l of o)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return Ne(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",o=Ai(r,e);return this.l10n(`${t}__${o}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setForCtxTarget(t,e,r){this.hasBlockInCtx(o=>o.constructor.StateConsumerScope===t)&&(this.$[e]=r)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${ts}${t}`,!0),Vi()||(this._destroyInnerHeightTracker=ys()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],o=n(h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h,"getUnit");if(t===0)return`0 ${o(r[0])}`;let a=1024,l=e<0?0:e,c=Math.floor(Math.log(t)/Math.log(a));return parseFloat((t/a**c).toFixed(l))+" "+o(r[c])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Ne(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let o=U(r),a=this.parseCfgProp(o);return a.ctx.has(a.name)?a.ctx.read(a.name):(Ei("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${at(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(U(t));r.ctx.has(r.name)?this.sub(U(t),e):(this.bindCssData(`--cfg-${at(t)}`),this.sub(`--cfg-${at(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(ts)?t:ts+t)}};n(b,"Block"),u(b,"StateConsumerScope",null),u(b,"className","");var es=class extends b{constructor(){super(...arguments);u(this,"_handleBackdropClick",n(()=>{this._closeDialog()},"_handleBackdropClick"));u(this,"_closeDialog",n(()=>{this.setForCtxTarget(es.StateConsumerScope,"*modalActive",!1)},"_closeDialog"));u(this,"_handleDialogClose",n(()=>{this._closeDialog()},"_handleDialogClose"));u(this,"_handleDialogClick",n(t=>{t.target===this.ref.dialog&&this._closeDialog()},"_handleDialogClick"));u(this,"init$",{...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose})}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("click",this._handleDialogClick);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogClick)}},P=es;n(P,"Modal"),u(P,"StateConsumerScope","modal");P.template=``;var Bs="active",Fe="___ACTIVITY_IS_ACTIVE___",lt=class extends b{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",Qi(this));u(this,"_debouncedHistoryFlush",K(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=lt._activityRegistry[this.activityKey];this[Fe]=!1,this.removeAttribute(Bs),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=lt._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[Fe]=!0,this.setAttribute(Bs,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[Fe]?this._deactivate():this.activityType===t&&!this[Fe]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!lt._activityRegistry[this.activityKey]}get isActivityActive(){return this[Fe]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:o}=e;lt._activityRegistry||(lt._activityRegistry=Object.create(null)),lt._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:o}}unregisterActivity(){this.isActivityActive&&this._deactivate(),lt._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(lt._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setForCtxTarget(P.StateConsumerScope,"*modalActive",!1)}}},_=lt;n(_,"ActivityBlock"),u(_,"_activityRegistry",Object.create(null));_.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var M=n((s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0),"stringToArray");var Ve=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],is=n(s=>s?s.filter(i=>typeof i=="string").map(i=>M(i)).flat():[],"mergeFileTypes"),ss=n((s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),"matchMimeType"),Fs=n((s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),"matchExtension"),ze=n(s=>{let i=s==null?void 0:s.type;return i?ss(i,Ve):!1},"fileIsImage");var Vs=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:yt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var rs="blocks",os="0.25.6";function zs(s){return Xi({...s,libraryName:rs,libraryVersion:os})}n(zs,"customUserAgent");var js="[Typed State] Wrong property name: ",dn="[Typed State] Wrong property type: ",je=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||Pe.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=A.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(js+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(dn+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(js+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){A.deleteCtx(this.__ctxId)}};n(je,"TypedData");var He=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Pe.generate(),this.__data=A.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(o=>{o({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new je(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){A.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};n(He,"TypedCollection");var R={UPLOAD_START:"UPLOAD_START",REMOVE:"REMOVE",UPLOAD_PROGRESS:"UPLOAD_PROGRESS",UPLOAD_FINISH:"UPLOAD_FINISH",UPLOAD_ERROR:"UPLOAD_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",CDN_MODIFICATION:"CLOUD_MODIFICATION",DATA_OUTPUT:"DATA_OUTPUT",DONE_FLOW:"DONE_FLOW",INIT_FLOW:"INIT_FLOW"},N=class{constructor(i){this.ctx=i.ctx,this.type=i.type,this.data=i.data}};n(N,"EventData");var S=class{static eName(i){return"LR_"+i}static emit(i,t=window,e=!0){let r=n(()=>{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))},"dispatch");if(!e){r();return}let o=i.type+i.ctx;this._timeoutStore[o]&&window.clearTimeout(this._timeoutStore[o]),this._timeoutStore[o]=window.setTimeout(()=>{r(),delete this._timeoutStore[o]},20)}};n(S,"EventManager"),u(S,"_timeoutStore",Object.create(null));var tt=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var ct=1e3,zt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),We=n(s=>Math.ceil(s*100)/100,"round"),Hs=n((s,i=zt.AUTO)=>{let t=i===zt.AUTO;if(i===zt.BYTE||t&&s{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(o=>[...o]).flat())].map(o=>e.read(o)).filter(Boolean);for(let o of r)this._runValidatorsForEntry(o);if(t.uploadProgress){let o=0,a=e.findItems(c=>!c.getValue("uploadError"));a.forEach(c=>{o+=e.readProp(c,"uploadProgress")});let l=Math.round(o/a.length);this.$["*commonProgress"]=l,S.emit(new N({type:R.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){let o=e.findItems(l=>!!l.getValue("fileInfo")),a=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-a.length===o.length){let l=this.getOutputData(c=>!!c.getValue("fileInfo")&&!c.getValue("silentUpload"));l.length>0&&S.emit(new N({type:R.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(a=>!!a.getValue("uploadError")).forEach(a=>{S.emit(new N({type:R.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(a,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(a=>!!a.getValue("validationErrorMsg")).forEach(a=>{S.emit(new N({type:R.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(a,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(a=>!!a.getValue("cdnUrlModifiers")).forEach(a=>{S.emit(new N({type:R.CDN_MODIFICATION,ctx:this.ctxName,data:A.getCtx(a).store}),void 0,!1)})},"_handleCollectionUpdate"))}setUploadMetadata(t){Ei("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new He({typedSchema:Vs,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=n(()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1),"hasUploadCollectionOwner");this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,o)=>{var a;this._runValidators();for(let l of o)(a=l==null?void 0:l.getValue("abortController"))==null||a.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:o!=null?o:tt.API})}addFileFromUuid(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:o!=null?o:tt.API})}addFileFromObject(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({file:t,isImage:ze(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:o!=null?o:tt.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:ze(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=is([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?Ve:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Ve.join(",")):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(o=>this.addFileFromObject(o,{source:tt.LOCAL})),this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this.setForCtxTarget(P.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=M(this.cfg.sourceList)),t}initFlow(t=!1){var e,r;if((e=this.$["*uploadList"])!=null&&e.length&&!t)this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setForCtxTarget(P.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let o=this.sourceList[0];o==="local"?(this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(o)?this.set$({"*currentActivityParams":{externalSourceType:o},"*currentActivity":_.activities.EXTERNAL}):this.$["*currentActivity"]=o,this.setForCtxTarget(P.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":_.activities.START_FROM}),this.setForCtxTarget(P.StateConsumerScope,"*modalActive",!0);S.emit(new N({type:R.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(P.StateConsumerScope,"*modalActive",!1),S.emit(new N({type:R.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,o=is([...e?Ve:[],r]);if(!o.length)return;let a=t.getValue("mimeType"),l=t.getValue("fileName");if(!a||!l)return;let c=ss(a,o),h=Fs(l,o);if(!c&&!h)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:Hs(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),o=this.cfg.multiple?this.cfg.multipleMax:1;if(o&&r>=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:zs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(o=>{let a=A.getCtx(o).store,l=a.fileInfo||{name:a.fileName,fileSize:a.fileSize,isImage:a.isImage,mimeType:a.mimeType},c={...l,cdnUrlModifiers:a.cdnUrlModifiers,cdnUrl:a.cdnUrl||l.cdnUrl};e.push(c)}),e}};n(v,"UploaderBlock");v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(R).forEach(s=>{let i=S.eName(s);window.addEventListener(i,t=>{if([R.UPLOAD_FINISH,R.REMOVE,R.CDN_MODIFICATION].includes(t.detail.type)){let r=A.getCtx(t.detail.ctx),o=r.read("uploadCollection"),a=[];o.items().forEach(l=>{let c=A.getCtx(l).store,h=c.fileInfo;if(h){let d={...h,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||h.cdnUrl};a.push(d)}}),S.emit(new N({type:R.DATA_OUTPUT,ctx:t.detail.ctx,data:a})),r.pub("outputData",a)}})});var pn="https://ucarecdn.com",mn="https://upload.uploadcare.com",fn="https://social.uploadcare.com",Xe=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:pn,baseUrl:mn,socialBaseUrl:fn,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var et=n(s=>String(s),"asString"),ut=n(s=>Number(s),"asNumber"),z=n(s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,"asBoolean"),gn=n(s=>s==="auto"?s:z(s),"asStore"),_n={pubkey:et,multiple:z,multipleMin:ut,multipleMax:ut,confirmUpload:z,imgOnly:z,accept:et,externalSourcesPreferredTypes:et,store:gn,cameraMirror:z,sourceList:et,maxLocalFileSizeBytes:ut,thumbSize:ut,showEmptyList:z,useLocalImageEditor:z,useCloudImageEditor:z,removeCopyright:z,modalScrollLock:z,modalBackdropStrokes:z,sourceListWrap:z,remoteTabSessionKey:et,cdnCname:et,baseUrl:et,socialBaseUrl:et,secureSignature:et,secureExpire:et,secureDeliveryProxy:et,retryThrottledRequestMaxTimes:ut,multipartMinFileSize:ut,multipartChunkSize:ut,maxConcurrentRequests:ut,multipartMaxConcurrentRequests:ut,multipartMaxAttempts:ut,checkForUrlDuplicates:z,saveUrlForRecurrentUploads:z,groupOutput:z,userAgentIntegration:et},Ws=n((s,i)=>{if(!(typeof i=="undefined"||i===null))return _n[s](i)},"normalizeConfigValue");var $i=Object.keys(Xe),bn=["metadata"],vn=n(s=>bn.includes(s),"isComplexKey"),ns=$i.filter(s=>!vn(s)),yn={...Object.fromEntries(ns.map(s=>[at(s),s])),...Object.fromEntries(ns.map(s=>[s.toLowerCase(),s]))},Cn={...Object.fromEntries($i.map(s=>[at(s),U(s)])),...Object.fromEntries($i.map(s=>[s.toLowerCase(),U(s)]))},oe=class extends b{constructor(){super(...arguments);u(this,"ctxOwner",!0);u(this,"init$",{...this.init$,...Object.fromEntries(Object.entries(Xe).map(([t,e])=>[U(t),e]))})}initCallback(){super.initCallback();for(let t of $i){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:o=>{if(e[r]=o,ns.includes(t)){let a=[...new Set([at(t),t.toLowerCase()])];for(let l of a)typeof o=="undefined"||o===null?this.removeAttribute(l):this.setAttribute(l,o.toString())}this.$[U(t)]!==o&&(typeof o=="undefined"||o===null?this.$[U(t)]=Xe[t]:this.$[U(t)]=o)},get:()=>this.$[U(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let o=yn[t],a=Ws(o,r),l=a!=null?a:Xe[o],c=this;c[o]=l}};n(oe,"Config");oe.bindAttributes(Cn);var jt=class extends b{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};n(jt,"Icon");jt.template=``;jt.bindAttributes({name:"name",size:"size"});var Xs=n(s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},"normalizeCdnOperation"),Si=n((...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Xs(i)).join("/-/"),"joinCdnOperations"),D=n((...s)=>{let i=Si(...s);return i?`-/${i}/`:""},"createCdnUrlModifiers");function qs(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),o="";return e>=0?o=t.slice(e):r>=0&&(o=t.slice(r+1)),o}n(qs,"extractFilename");function Gs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}n(Gs,"extractUuid");function Ks(s){let i=Ys(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(o=>Xs(o))}n(Ks,"extractOperations");function Ys(s){let i=new URL(s),t=qs(s),e=Zs(t)?Js(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}n(Ys,"trimFilename");function Zs(s){return s.startsWith("http")}n(Zs,"isFileUrl");function Js(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}n(Js,"splitFileUrl");var k=n((s,i,t)=>{let e=new URL(Ys(s));if(t=t||qs(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Zs(t)){let r=Js(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},"createCdnUrl"),kt=n((s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()},"createOriginalUrl");var xn="https://ucarecdn.com",Ht=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:xn},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var Qs=n(s=>[...new Set(s)],"uniqueArray");var qe="--lr-img-",tr="unresolved",ne=2,ae=3,er=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),sr=Object.create(null),ir;for(let s in Ht)sr[qe+s]=((ir=Ht[s])==null?void 0:ir.default)||"";var Ge=class extends Nt{constructor(){super(...arguments);u(this,"cssInit$",sr)}$$(t){return this.$[qe+t]}set$$(t){for(let e in t)this.$[qe+e]=t[e]}sub$$(t,e){this.sub(qe+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!er&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return D(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Ht.format.default}`,`quality/${this.$$("quality")||Ht.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(er&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return k(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(k(kt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(k(kt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(k(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(k(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Ne(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let o=t.getBoundingClientRect(),a=e*Math.round(o.width),l=r?"":e*Math.round(o.height);return a||l?`${a||""}x${l||""}`:null}_setupEventProxy(t){let e=n(o=>{o.stopPropagation();let a=new Event(o.type,o);this.dispatchEvent(a)},"proxifyEvent"),r=["load","error"];for(let o of r)t.addEventListener(o,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(tr,""),this.img.onload=()=>{this.img.removeAttribute(tr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Ht[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?Qs(M(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(o=>{e.add(`url("${this._getUrlBase(o+"x")}") ${o}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(o*ne+"x")}") ${o*ne}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(o*ae+"x")}") ${o*ae}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,ne))}") ${ne}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,ae))}") ${ae}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*ne+"x")+` ${e*ne}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*ae+"x")+` ${e*ae}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(o=>{o.forEach(a=>{a.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null)}static get observedAttributes(){return Object.keys(Ht)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[qe+t]=r})}};n(Ge,"ImgBase");var Ke=class extends Ge{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};n(Ke,"Img");var le=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,"*simpleButtonText":"",onClick:()=>{this.initFlow()}})}initCallback(){super.initCallback(),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};n(le,"SimpleBtn");le.template=``;var Ye=class extends _{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};n(Ye,"StartFrom");function wn(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=n(r=>{r.type!=="loadend"&&t.abort(),i(!1)},"onLoad");t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}n(wn,"checkIsDirectory");function Tn(s,i){return new Promise(t=>{let e=0,r=[],o=n(l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(c=>{e--;let h=new File([c],c.name,{type:c.type||i});r.push(h),e===0&&t(r)})):l.isDirectory&&a(l.createReader())},"readEntry"),a=n(l=>{e++,l.readEntries(c=>{e--;for(let h of c)o(h);e===0&&t(r)})},"readReaderContent");o(s)})}n(Tn,"readEntryContentAsync");function rr(s){let i=[],t=[];for(let e=0;e{i.push(...c)}));continue}let a=r.getAsFile();t.push(wn(a).then(l=>{l||i.push(a)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(o=>{r.getAsString(a=>{i.push(a),o()})}))}return Promise.all(t).then(()=>i)}n(rr,"getDropItems");var j={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},or=["focus"],En=100,as=new Map;function An(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}n(An,"distance");function ls(s){let i=0,t=document.body,e=new Set,r=n(f=>e.add(f),"handleSwitch"),o=j.INACTIVE,a=n(f=>{s.shouldIgnore()&&f!==j.INACTIVE||(o!==f&&e.forEach(y=>y(f)),o=f)},"setState"),l=n(()=>i>0,"isDragging");r(f=>s.onChange(f));let c=n(()=>{i=0,a(j.INACTIVE)},"onResetEvent"),h=n(()=>{i+=1,o===j.INACTIVE&&a(j.ACTIVE)},"onDragEnter"),d=n(()=>{i-=1,l()||a(j.INACTIVE)},"onDragLeave"),p=n(f=>{f.preventDefault(),i=0,a(j.INACTIVE)},"onDrop"),m=n(f=>{l()||(i+=1),f.preventDefault();let y=[f.x,f.y],w=s.element.getBoundingClientRect(),$=Math.floor(An(y,w)),T=${if(s.shouldIgnore())return;f.preventDefault();let y=await rr(f.dataTransfer);s.onItems(y),a(j.INACTIVE)},"onElementDrop");return t.addEventListener("drop",p),t.addEventListener("dragleave",d),t.addEventListener("dragenter",h),t.addEventListener("dragover",m),s.element.addEventListener("drop",g),or.forEach(f=>{window.addEventListener(f,c)}),()=>{as.delete(s.element),t.removeEventListener("drop",p),t.removeEventListener("dragleave",d),t.removeEventListener("dragenter",h),t.removeEventListener("dragover",m),s.element.removeEventListener("drop",g),or.forEach(f=>{window.removeEventListener(f,c)})}}n(ls,"addDropzone");var Wt=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,state:j.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),o=window.getComputedStyle(this),a=o.visibility!=="hidden"&&o.display!=="none";return e&&a&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!e})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:typeof e=="string"})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:typeof e=="string"})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:typeof e=="string"})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=ls({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:tt.DROP_AREA});return}this.addFileFromObject(r,{source:tt.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setForCtxTarget(P.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=ls({element:t,onChange:e=>{var o;let r=(o=Object.entries(j).find(([,a])=>a===e))==null?void 0:o[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var o;let r=(o=Object.entries(j).find(([,a])=>a===e))==null?void 0:o[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=M(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,o;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(o=this._destroyContentWrapperDropzone)==null||o.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};n(Wt,"DropArea");Wt.template=`
{{text}}
`;Wt.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var $n="src-type-",Xt=class extends v{constructor(){super(...arguments);u(this,"_registeredTypes",{});u(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:_.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:_.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:_.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:_.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:o=t,activity:a,onClick:l,activityParams:c={}}=e;this.applyL10nKey("src-type",`${$n}${r}`),this.$.iconName=o,this.onclick=h=>{(l?l(h):!!a)&&this.set$({"*currentActivityParams":c,"*currentActivity":a})}}};n(Xt,"SourceBtn");Xt.template=`
`;Xt.bindAttributes({type:null});var Ze=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=M(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};n(Ze,"SourceList");function nr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}n(nr,"createSvgBlobUrl");function ar(s="#fff",i="rgba(0, 0, 0, .1)"){return nr(``)}n(ar,"checkerboardCssBg");function Je(s="hsl(209, 21%, 65%)",i=32,t=32){return nr(``)}n(Je,"fileCssBg");function lr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,o=new Promise((a,l)=>{r.onload=()=>{let c=r.height/r.width;c>1?(t.width=i,t.height=i*c):(t.height=i,t.width=i/c),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(h=>{if(!h){l();return}let d=URL.createObjectURL(h);a(d)})},r.onerror=c=>{l(c)}});return r.src=URL.createObjectURL(s),o}n(lr,"generateThumb");var V=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),ot=class extends v{constructor(){super(...arguments);u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",K(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",K(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);u(this,"init$",{...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:V.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===_.activities.DETAILS)?this.$["*currentActivity"]=_.activities.DETAILS:this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);S.emit(new N({type:R.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}})}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=V.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=V.FAILED:t.getValue("validationMultipleLimitMsg")?e=V.LIMIT_OVERFLOW:t.getValue("isUploading")?e=V.UPLOADING:t.getValue("fileInfo")&&(e=V.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,o=this.proxyUrl(k(kt(this.cfg.cdnCname,this._entry.getValue("uuid")),D(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),a=t.getValue("thumbUrl");a!==o&&(t.setValue("thumbUrl",o),a!=null&&a.startsWith("blob:")&&URL.revokeObjectURL(a));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await lr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let o=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Je(o))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",Je(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,o=>{this.isConnected&&e(o)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",o=>{this.$.progressValue=o}),this._subEntry("fileName",o=>{this.$.itemName=o||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",o=>{this.$.itemName=e.getValue("fileName")||o||this.l10n("file-no-name")}),this._subEntry("uuid",o=>{this._debouncedCalculateState(),o&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",o=>{this.$.thumbUrl=o?`url(${o})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{ot.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),ot.activeInstances.add(this)}_handleState(t){var e,r;this.set$({isFailed:t===V.FAILED,isLimitOverflow:t===V.LIMIT_OVERFLOW,isUploading:t===V.UPLOADING,isFinished:t===V.FINISHED,progressVisible:t===V.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&t===V.FINISHED&&((e=this._entry)==null?void 0:e.getValue("isImage")),errorText:((r=this._entry.getValue("uploadError"))==null?void 0:r.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===V.FAILED||t===V.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===V.FINISHED&&(this.$.badgeIcon="badge-success"),t===V.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),ot.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var o,a,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(c=>!c.getValue("fileInfo"));S.emit(new N({type:R.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let c=new AbortController;t.setValue("abortController",c);let h=n(async()=>{let p=await this.getUploadClientOptions();return Zi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...p,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:m=>{if(m.isComputable){let g=m.value*100;t.setValue("uploadProgress",g)}this.$.progressUnknown=!m.isComputable},signal:c.signal})},"uploadTask"),d=await this.$["*uploadQueue"].add(h);t.setMultipleValues({fileInfo:d,isUploading:!1,fileName:d.originalFilename,fileSize:d.size,isImage:d.isImage,mimeType:(l=(a=(o=d.contentInfo)==null?void 0:o.mime)==null?void 0:a.mime)!=null?l:d.mimeType,uuid:d.uuid,cdnUrl:d.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(c){console.warn("Upload error",c),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),c instanceof O?c.isCancel||t.setValue("uploadError",c):t.setValue("uploadError",new Error("Unexpected error"))}}};n(ot,"FileItem");ot.template=`
{{itemName}}{{errorText}}
`;ot.activeInstances=new Set;var Qe=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}};n(Qe,"UiMessage");var ce=class extends b{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};n(ce,"MessageBox");ce.template=`
{{captionTxt}}
{{msgTxt}}
`;var ue=class extends v{constructor(){super(...arguments);u(this,"couldBeUploadCollectionOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",_.activities.UPLOAD_LIST);u(this,"init$",{...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));S.emit(new N({type:R.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}});u(this,"_debouncedHandleCollectionUpdate",K(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0))}_validateFilesCount(){var d,p;let t=!!this.cfg.multiple,e=t?(d=this.cfg.multipleMin)!=null?d:0:1,r=t?(p=this.cfg.multipleMax)!=null?p:0:1,o=this.uploadCollection.size,a=e?or:!1;return{passed:!a&&!l,tooFew:a,tooMany:l,min:e,max:r,exact:r===o}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new Qe,o=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(o,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let g of t){let f=this.uploadCollection.read(g);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:o,tooMany:a,exact:l}=this._validateFilesCount(),c=r.failed===0&&r.limitOverflow===0,h=!1,d=!1,p=!1;r.total-r.succeed-r.uploading-r.failed>0&&o?h=!0:(d=!0,p=r.total===r.succeed&&o&&c),this.set$({doneBtnVisible:d,doneBtnEnabled:p,uploadBtnVisible:h,addMoreBtnEnabled:r.total===0||!a&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=n(r=>{let o=t[r];return this.l10n(`header-${r}`,{count:o})},"localizedText");return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};n(ue,"UploadList");ue.template=`{{headerText}}
`;var he=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.URL);u(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:tt.URL_TAB}),this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};n(he,"UrlSource");he.template=`
`;var cs=n(()=>typeof navigator.permissions!="undefined","canUsePermissionsApi");var de=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.CAMERA);u(this,"_unsubPermissions",null);u(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:cs(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});u(this,"_onActivate",n(()=>{cs()&&this._subscribePermissions(),this._capture()},"_onActivate"));u(this,"_onDeactivate",n(()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()},"_onDeactivate"));u(this,"_handlePermissionsChange",n(()=>{this._capture()},"_handlePermissionsChange"));u(this,"_setPermissionsState",K(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let o=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(o,{source:tt.CAMERA}),this.set$({"*currentActivity":_.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,o)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${o+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};n(de,"CameraSource");de.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var ti=class extends v{};n(ti,"UploadCtxProvider");var pe=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.DETAILS);u(this,"pauseRender",!0);u(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=Je(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(o=>{this._entrySubs.delete(o),o.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let o=ze(this._file);o&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),o||this.showNonImageThumb()}let r=n((o,a)=>{this._entrySubs.add(this.entry.subscribe(o,a))},"tmpSub");r("fileName",o=>{this.$.fileName=o,this.$.onNameInput=()=>{let a=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:a}),this.entry.setValue("fileName",a)}}),r("fileSize",o=>{this.$.fileSize=Number.isFinite(o)?this.fileSizeFmt(o):this.l10n("file-size-unknown")}),r("uploadError",o=>{this.$.errorTxt=o==null?void 0:o.message}),r("externalUrl",o=>{o&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",o=>{let a=this.cfg.useCloudImageEditor&&o&&this.entry.getValue("isImage");if(o&&this.ref.filePreview.clear(),this.set$({cdnUrl:o,cloudEditBtnHidden:!a}),o&&this.entry.getValue("isImage")){let l=k(o,D("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};n(pe,"UploadDetails");pe.template=`
{{fileSize}}
{{errorTxt}}
`;var ki=class{constructor(){u(this,"captionL10nStr","confirm-your-action");u(this,"messageL10Str","are-you-sure");u(this,"confirmL10nStr","yes");u(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}};n(ki,"UiConfirmation");var me=class extends _{constructor(){super(...arguments);u(this,"activityType",_.activities.CONFIRMATION);u(this,"_defaults",new ki);u(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":_.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};n(me,"ConfirmationDialog");me.template=`{{activityCaption}}
{{messageTxt}}
`;var fe=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};n(fe,"ProgressBarCommon");fe.template=``;var ge=class extends b{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};n(ge,"ProgressBar");ge.template='
';var Y="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var qt=class extends b{constructor(){super();u(this,"init$",{...this.init$,checkerboard:!1,src:Y})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${ar()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Y}};n(qt,"FilePreview");qt.template='';qt.bindAttributes({checkerboard:"checkerboard"});var cr="--cfg-ctx-name",I=class extends b{get cfgCssCtxName(){return this.getCssData(cr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(cr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:A.getCtx(this.cfgCtxName)}}};n(I,"CloudImageEditorBase");function ur(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}n(ur,"normalize");function B(...s){let i=ur(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}n(B,"classNames");function hr(s,...i){let t=ur(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}n(hr,"applyClassNames");function ht(s,i){let t,e=n((...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)},"debounced");return e.cancel=()=>{clearTimeout(t)},e}n(ht,"debounce");var Z={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function Sn(s,i){if(typeof i=="number")return Z[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Z[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Z[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}n(Sn,"transformationToStr");var pr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function It(s){return Si(...pr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return Sn(i,t)}).filter(i=>!!i))}n(It,"transformationsToOperations");var Ii=Si("format/auto","progressive/yes"),wt=n(([s])=>typeof s!="undefined"?Number(s):void 0,"asNumber"),dr=n(()=>!0,"asBoolean"),kn=n(([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),"asFilter"),In=n(([s,i])=>({dimensions:M(s,"x").map(Number),coords:M(i).map(Number)}),"asCrop"),On={enhance:wt,brightness:wt,exposure:wt,gamma:wt,contrast:wt,saturation:wt,vibrance:wt,warmth:wt,filter:kn,mirror:dr,flip:dr,rotate:wt,crop:In};function mr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!pr.includes(e))continue;let o=On[e],a=o(r);i[e]=a}return i}n(mr,"operationsToTransformations");function fr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Y,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Y,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=D(It(i)),r=k(t,D(e,"preview")),o={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:o,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}n(fr,"initState");var gr=`
Network error
{{fileType}}
{{msg}}
`;var H={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},Oi=[H.CROP,H.SLIDERS,H.FILTERS],_r=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],br=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],vr=["rotate","mirror","flip"],dt={brightness:{zero:Z.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Z.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Z.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Z.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Z.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Z.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Z.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Z.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Z.filter,range:[0,100],keypointsNumber:1}};var it=class extends I{constructor(){super(...arguments);u(this,"init$",{...this.init$,...fr(this)});u(this,"_debouncedShowLoader",ht(this._showLoader.bind(this),300))}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let o=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),a=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(o),a.disconnect())});a.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}if(this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Y&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Y)}),this.sub("*tabId",t=>{this.ref["img-el"].className=B("image",{image_hidden_to_cropper:t===H.CROP,image_hidden_effects:t!==H.CROP})}),this.$.cdnUrl){let t=Gs(this.$.cdnUrl);this.$["*originalUrl"]=kt(this.$.cdnUrl,t);let e=Ks(this.$.cdnUrl),r=mr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=kt(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{let e=this.$["*originalUrl"],r=D(It(t)),o=k(e,D(r,"preview")),a={originalUrl:e,cdnUrlModifiers:r,cdnUrl:o,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:a,bubbles:!0,composed:!0}))},!1);try{fetch(k(this.$["*originalUrl"],D("json"))).then(t=>t.json()).then(t=>{let{width:e,height:r}=t;this.$["*imageSize"]={width:e,height:r}})}catch(t){t&&console.error("Failed to load image info",t)}}};n(it,"CloudImageEditorBlock"),u(it,"className","cloud-image-editor");it.template=gr;it.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl"});var ei=33.333333333333336,st=24*2+34;function Gt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}n(Gt,"setSvgNodeAttrs");function rt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Gt(t,i),t}n(rt,"createSvgNode");function yr(s,i){let{x:t,y:e,width:r,height:o}=s,a=i.includes("w")?0:1,l=i.includes("n")?0:1,c=[-1,1][a],h=[-1,1][l],d=[t+a*r+1.5*c,e+l*o+1.5*h-24*h],p=[t+a*r+1.5*c,e+l*o+1.5*h],m=[t+a*r-24*c+1.5*c,e+l*o+1.5*h];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}n(yr,"cornerPath");function Cr(s,i){let{x:t,y:e,width:r,height:o}=s,a=["n","s"].includes(i)?.5:{w:0,e:1}[i],l=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][a],h=[-1,1][l],d,p;["n","s"].includes(i)?(d=[t+a*r-34/2,e+l*o+1.5*h],p=[t+a*r+34/2,e+l*o+1.5*h]):(d=[t+a*r+1.5*c,e+l*o-34/2],p=[t+a*r+1.5*c,e+l*o+34/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,g=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:g}}n(Cr,"sidePath");function xr(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}n(xr,"thumbCursor");function wr(s,[i,t]){return{...s,x:s.x+i,y:s.y+t}}n(wr,"moveRect");function Ri(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}n(Ri,"constraintRect");function Tr(s,[i,t],e){let{x:r,y:o,width:a,height:l}=s;return e.includes("n")&&(o+=t,l-=t),e.includes("s")&&(l+=t),e.includes("w")&&(r+=i,a-=i),e.includes("e")&&(a+=i),{x:r,y:o,width:a,height:l}}n(Tr,"expandRect");function Er(s,i){let t=Math.max(s.x,i.x),e=Math.min(s.x+s.width,i.x+i.width),r=Math.max(s.y,i.y),o=Math.min(s.y+s.height,i.y+i.height);return{x:t,y:r,width:e-t,height:o-r}}n(Er,"intersectionRect");function Li(s,[i,t],e){let{x:r,y:o,width:a,height:l}=s;if(e.includes("n")){let c=l;l=Math.max(t,l),o=o+c-l}if(e.includes("s")&&(l=Math.max(t,l)),e.includes("w")){let c=a;a=Math.max(i,a),r=r+c-a}return e.includes("e")&&(a=Math.max(i,a)),{x:r,y:o,width:a,height:l}}n(Li,"minRectSize");function Ar(s,[i,t]){return s.x<=i&&i<=s.x+s.width&&s.y<=t&&t<=s.y+s.height}n(Ar,"rectContainsPoint");var _e=class extends I{constructor(){super();u(this,"init$",{...this.init$,dragging:!1});this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(t){let e=this.$["*imageBox"];if(!e)return;if(t===""&&e.height<=st&&e.width<=st)return!0;let r=e.height<=st&&(t.includes("n")||t.includes("s")),o=e.width<=st&&(t.includes("e")||t.includes("w"));return r||o}_createBackdrop(){let t=this.$["*cropBox"];if(!t)return;let{x:e,y:r,width:o,height:a}=t,l=this.ref["svg-el"],c=rt("mask",{id:"backdrop-mask"}),h=rt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),d=rt("rect",{x:e,y:r,width:o,height:a,fill:"black"});c.appendChild(h),c.appendChild(d);let p=rt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});l.appendChild(p),l.appendChild(c),this._backdropMask=c,this._backdropMaskInner=d}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask.style.display="block"}))}_updateBackdrop(){let t=this.$["*cropBox"];if(!t)return;let{x:e,y:r,width:o,height:a}=t;Gt(this._backdropMaskInner,{x:e,y:r,width:o,height:a})}_updateFrame(){let t=this.$["*cropBox"];if(!t)return;for(let r of Object.values(this._frameThumbs)){let{direction:o,pathNode:a,interactionNode:l,groupNode:c}=r,h=o==="",d=o.length===2;if(h){let{x:m,y:g,width:f,height:y}=t,w=[m+f/2,g+y/2];Gt(l,{r:Math.min(f,y)/3,cx:w[0],cy:w[1]})}else{let{d:m,center:g}=d?yr(t,o):Cr(t,o);Gt(l,{cx:g[0],cy:g[1]}),Gt(a,{d:m})}let p=this._shouldThumbBeDisabled(o);c.setAttribute("class",B("thumb",{"thumb--hidden":p,"thumb--visible":!p}))}let e=this._frameGuides;Gt(e,{x:t.x-1*.5,y:t.y-1*.5,width:t.width+1,height:t.height+1})}_createThumbs(){let t={};for(let e=0;e<3;e++)for(let r=0;r<3;r++){let o=`${["n","","s"][e]}${["w","","e"][r]}`,a=rt("g");a.classList.add("thumb"),a.setAttribute("with-effects","");let l=rt("circle",{r:24+1.5,fill:"transparent"}),c=rt("path",{stroke:"currentColor",fill:"none","stroke-width":3});a.appendChild(c),a.appendChild(l),t[o]={direction:o,pathNode:c,interactionNode:l,groupNode:a},l.addEventListener("pointerdown",this._handlePointerDown.bind(this,o))}return t}_createGuides(){let t=rt("svg"),e=rt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});t.appendChild(e);for(let r=1;r<=2;r++){let o=rt("line",{x1:`${ei*r}%`,y1:"0%",x2:`${ei*r}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});t.appendChild(o)}for(let r=1;r<=2;r++){let o=rt("line",{x1:"0%",y1:`${ei*r}%`,x2:"100%",y2:`${ei*r}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});t.appendChild(o)}return t.classList.add("guides","guides--semi-hidden"),t}_createFrame(){let t=this.ref["svg-el"],e=document.createDocumentFragment(),r=this._createGuides();e.appendChild(r);let o=this._createThumbs();for(let{groupNode:a}of Object.values(o))e.appendChild(a);t.appendChild(e),this._frameThumbs=o,this._frameGuides=r}_handlePointerDown(t,e){let r=this._frameThumbs[t];if(this._shouldThumbBeDisabled(t))return;let o=this.$["*cropBox"],{x:a,y:l}=this.ref["svg-el"].getBoundingClientRect(),c=e.x-a,h=e.y-l;this.$.dragging=!0,this._draggingThumb=r,this._dragStartPoint=[c,h],this._dragStartCrop={...o}}_handlePointerUp_(t){this._updateCursor(),this.$.dragging&&(t.stopPropagation(),t.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(t){if(!this.$.dragging)return;t.stopPropagation(),t.preventDefault();let e=this.ref["svg-el"],{x:r,y:o}=e.getBoundingClientRect(),a=t.x-r,l=t.y-o,c=a-this._dragStartPoint[0],h=l-this._dragStartPoint[1],{direction:d}=this._draggingThumb,p=this.$["*imageBox"],m=this._dragStartCrop;d===""?(m=wr(m,[c,h]),m=Ri(m,p)):(m=Tr(m,[c,h],d),m=Er(m,p));let g=[Math.min(p.width,st),Math.min(p.height,st)];if(m=Li(m,g,d),!Object.values(m).every(f=>Number.isFinite(f)&&f>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:m});return}this.$["*cropBox"]=m}_handleSvgPointerMove_(t){let e=Object.values(this._frameThumbs).find(r=>{if(this._shouldThumbBeDisabled(r.direction))return!1;let a=r.groupNode.getBoundingClientRect(),l={x:a.x,y:a.y,width:a.width,height:a.height};return Ar(l,[t.x,t.y])});this._hoverThumb=e,this._updateCursor()}_updateCursor(){let t=this._hoverThumb;this.ref["svg-el"].style.cursor=t?xr(t.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(t){Object.values(this._frameThumbs).map(({groupNode:e})=>e).forEach(e=>{e.setAttribute("class",B("thumb",{"thumb--hidden":!t,"thumb--visible":t}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",t=>{t&&(this._guidesHidden=t.height<=st||t.width<=st,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",t=>{this._frameGuides.setAttribute("class",B({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&t,"guides--semi-hidden":!this._guidesHidden&&!t}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};n(_e,"CropFrame");_e.template='';var pt=class extends I{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=B({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};n(pt,"EditorButtonControl");pt.template=`
{{title}}
`;function Ln(s){let i=s+90;return i=i>=360?0:i,i}n(Ln,"nextAngle");function Un(s,i){return s==="rotate"?Ln(i):["mirror","flip"].includes(s)?!i:null}n(Un,"nextValue");var Ot=class extends pt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Un(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};n(Ot,"EditorCropButtonControl");var ii={FILTER:"filter",COLOR_OPERATION:"color_operation"},mt="original",be=class extends I{constructor(){super(...arguments);u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?ii.FILTER:ii.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===mt?void 0:this.$.value,filter:this._filter===mt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=dt[this._operation],[r,o]=t;this.$.min=r,this.$.max=o,this.$.zero=e;let a=this.$["*editorTransformations"][this._operation];if(this._controlType===ii.FILTER){let l=o;if(a){let{name:c,amount:h}=a;l=c===this._filter?h:o}this.$.value=l,this.$.defaultValue=l}if(this._controlType===ii.COLOR_OPERATION){let l=typeof a!="undefined"?a:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===ii.FILTER?this._filter===mt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};n(be,"EditorSlider");be.template=``;function si(s){let i=new Image;return{promise:new Promise((r,o)=>{i.src=s,i.onload=r,i.onerror=o}),image:i,cancel:n(()=>{i.naturalWidth===0&&(i.src=Y)},"cancel")}}n(si,"preloadImage");function ri(s){let i=[];for(let o of s){let a=si(o);i.push(a)}let t=i.map(o=>o.image);return{promise:Promise.allSettled(i.map(o=>o.promise)),images:t,cancel:n(()=>{i.forEach(o=>{o.cancel()})},"cancel")}}n(ri,"batchPreloadImages");var Tt=class extends pt{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),o=e>=2?"lightest":"normal",a=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==mt?{name:this._filter,amount:a}:void 0,k(this._originalUrl,D(Ii,It(l),`quality/${o}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let o=this.proxyUrl(this._previewSrc()),a=this.ref["preview-el"],{promise:l,cancel:c}=si(o);this._cancelPreload=c,l.catch(h=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:h})}).finally(()=>{a.style.backgroundImage=`url(${o})`,a.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===mt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let o=this.ref["preview-el"];e?o.style.opacity="0":o.style.backgroundImage&&(o.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"];o.style.backgroundImage&&(o.style.backgroundImage="none",o.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};n(Tt,"EditorFilterControl");Tt.template=`
`;var Rt=class extends pt{constructor(){super(...arguments);u(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=dt[this._operation],r=t[this._operation],o=typeof r!="undefined"?r!==e:!1;this.$.active=o})}};n(Rt,"EditorOperationControl");function $r(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}n($r,"pick");function ve(s,i,t){let r=window.devicePixelRatio,o=Math.min(Math.ceil(i*r),3e3),a=r>=2?"lightest":"normal";return k(s,D(Ii,It(t),`quality/${a}`,`stretch/off/-/resize/${o}x`))}n(ve,"viewerImageSrc");function Ui(s,i,t){return Math.min(Math.max(s,i),t)}n(Ui,"clamp");function oi({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}n(oi,"rotateSize");function Mn(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}n(Mn,"validateCrop");var ye=class extends I{constructor(){super();u(this,"init$",{...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}});this._commitDebounced=ht(this._commit.bind(this),300),this._handleResizeDebounced=ht(this._handleResize.bind(this),10)}_handleResize(){this.isConnected&&(this.deactivate(),this.activate(this._imageSize,{fromViewer:!1}))}_syncTransformations(){let t=this.$["*editorTransformations"],e=$r(t,Object.keys(this.$["*operations"])),r={...this.$["*operations"],...e};this.$["*operations"]=r}_initCanvas(){let t=this.ref["canvas-el"],e=t.getContext("2d"),r=this.offsetWidth,o=this.offsetHeight,a=window.devicePixelRatio;t.style.width=`${r}px`,t.style.height=`${o}px`,t.width=r*a,t.height=o*a,e.scale(a,a),this._canvas=t,this._ctx=e}_alignImage(){if(!this._isActive||!this.$.image)return;let t=this.$.image,e=this.$["*padding"],r=this.$["*operations"],{rotate:o}=r,a={width:this.offsetWidth,height:this.offsetHeight},l=oi({width:t.naturalWidth,height:t.naturalHeight},o);if(l.width>a.width-e*2||l.height>a.height-e*2){let c=l.width/l.height,h=a.width/a.height;if(c>h){let d=a.width-e*2,p=d/c,m=0+e,g=e+(a.height-e*2)/2-p/2;this.$["*imageBox"]={x:m,y:g,width:d,height:p}}else{let d=a.height-e*2,p=d*c,m=e+(a.width-e*2)/2-p/2,g=0+e;this.$["*imageBox"]={x:m,y:g,width:p,height:d}}}else{let{width:c,height:h}=l,d=e+(a.width-e*2)/2-c/2,p=e+(a.height-e*2)/2-h/2;this.$["*imageBox"]={x:d,y:p,width:c,height:h}}}_alignCrop(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,a=this.$["*editorTransformations"].crop;if(a){let{dimensions:[c,h],coords:[d,p]}=a,{width:m,x:g,y:f}=this.$["*imageBox"],{width:y}=oi(this._imageSize,o),w=m/y;t={x:g+d*w,y:f+p*w,width:c*w,height:h*w}}else t={x:e.x,y:e.y,width:e.width,height:e.height};let l=[Math.min(e.width,st),Math.min(e.height,st)];t=Li(t,l,"se"),t=Ri(t,e),this.$["*cropBox"]=t}_drawImage(){let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:o,flip:a,rotate:l}=r,c=this._ctx,h=oi({width:e.width,height:e.height},l);c.save(),c.translate(e.x+e.width/2,e.y+e.height/2),c.rotate(l*Math.PI*-1/180),c.scale(o?-1:1,a?-1:1),c.drawImage(t,-h.width/2,-h.height/2,h.width,h.height),c.restore()}_draw(){if(!this._isActive||!this.$.image)return;let t=this._canvas;this._ctx.clearRect(0,0,t.width,t.height),this._drawImage()}_animateIn({fromViewer:t}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=B({active_from_viewer:t,active_from_editor:!t,inactive_to_editor:!1})}))}_calculateDimensions(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:a,height:l}=e,{width:c,height:h}=oi(this._imageSize,o),{width:d,height:p}=t,m=a/c,g=l/h;return[Ui(Math.round(d/m),1,c),Ui(Math.round(p/g),1,h)]}_calculateCrop(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:a,height:l,x:c,y:h}=e,{width:d,height:p}=oi(this._imageSize,o),{x:m,y:g}=t,f=a/d,y=l/p,w=this._calculateDimensions(),$={dimensions:w,coords:[Ui(Math.round((m-c)/f),0,d-w[0]),Ui(Math.round((g-h)/y),0,p-w[1])]};if(!Mn($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(w[0]===d&&w[1]===p))return $}_commit(){if(!this.isConnected)return;let t=this.$["*operations"],{rotate:e,mirror:r,flip:o}=t,a=this._calculateCrop(),c={...this.$["*editorTransformations"],crop:a,rotate:e,mirror:r,flip:o};this.$["*editorTransformations"]=c}setValue(t,e){console.log(`Apply cropper operation [${t}=${e}]`),this.$["*operations"]={...this.$["*operations"],[t]:e},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(t){return this.$["*operations"][t]}async activate(t,{fromViewer:e}){if(!this._isActive){this._isActive=!0,this._imageSize=t,this.removeEventListener("transitionend",this._reset),this._initCanvas();try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw(),this._animateIn({fromViewer:e})}catch(r){console.error("Failed to activate cropper",{error:r})}}}deactivate(){this._isActive&&(this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=B({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}))}_transitionToCrop(){let t=this._calculateDimensions(),e=Math.min(this.offsetWidth,t[0])/this.$["*cropBox"].width,r=Math.min(this.offsetHeight,t[1])/this.$["*cropBox"].height,o=Math.min(e,r),a=this.$["*cropBox"].x+this.$["*cropBox"].width/2,l=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${o}) translate(${(this.offsetWidth/2-a)/o}px, ${(this.offsetHeight/2-l)/o}px)`,this.style.transformOrigin=`${a}px ${l}px`}_transitionToImage(){let t=this.$["*cropBox"].x+this.$["*cropBox"].width/2,e=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${t}px ${e}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(t,e){let r=this.offsetWidth;e={...e,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let o=this.proxyUrl(ve(t,r,e)),{promise:a,cancel:l,image:c}=si(o),h=this._handleImageLoading(o);return c.addEventListener("load",h,{once:!0}),c.addEventListener("error",h,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=l,a.then(()=>c).catch(d=>(console.error("Failed to load image",{error:d}),this.$["*networkProblems"]=!0,Promise.resolve(c)))}_handleImageLoading(t){let e="crop",r=this.$["*loadingOperations"];return r.get(e)||r.set(e,new Map),r.get(e).get(t)||(r.set(e,r.get(e).set(t,!0)),this.$["*loadingOperations"]=r),()=>{var o;(o=r==null?void 0:r.get(e))!=null&&o.has(t)&&(r.get(e).delete(t),this.$["*loadingOperations"]=r)}}initCallback(){super.initCallback(),this._observer=new ResizeObserver(([t])=>{t.contentRect.width>0&&t.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeDebounced()}),this._observer.observe(this),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",t=>{this.$.image&&this._commitDebounced()}),setTimeout(()=>{this.sub("*networkProblems",t=>{t||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect()}};n(ye,"EditorImageCropper");ye.template=``;function ds(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}n(ds,"linspace");function Nn(s){return s.reduce((i,t,e)=>er<=i&&i<=o);return s.map(r=>{let o=Math.abs(e[0]-e[1]),a=Math.abs(i-e[0])/o;return e[0]===r?i>t?1:1-a:e[1]===r?i>=t?a:1:0})}n(Dn,"calculateOpacities");function Bn(s,i){return s.map((t,e)=>to-a)}n(Sr,"keypointsRange");var ni=class extends I{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=ht(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let o={...this._transformations};e&&(o[e]=t?{name:t,amount:r}:r);let a=this.offsetWidth;return this.proxyUrl(ve(i,a,o))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=n(()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(c=>c.value===e),"shouldSkip");if(r())return;let o=this._constructKeypoint(i,e),a=new Image;a.src=o.src;let l=this._handleImageLoading(o.src);a.addEventListener("load",l,{once:!0}),a.addEventListener("error",l,{once:!0}),o.image=a,a.classList.add("fader-image"),a.addEventListener("load",()=>{if(r())return;let c=this._keypoints,h=c.findIndex(p=>p.value>e),d=h{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=dt[i],r=this._keypoints.map(l=>l.value),o=Dn(r,t,e),a=Bn(r,e);for(let[l,c]of Object.entries(this._keypoints))c.opacity=o[l],c.zIndex=a[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(h=>h.src),{images:r,promise:o,cancel:a}=ri(e);r.forEach(h=>{let d=this._handleImageLoading(h.src);h.addEventListener("load",d),h.addEventListener("error",d)}),this._cancelLastImages=()=>{a(),this._cancelLastImages=void 0};let l=this._operation,c=this._filter;await o,this._isActive&&this._isSame(l,c)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((h,d)=>{let p=r[d];p.classList.add("fader-image"),h.image=p,this._container.appendChild(p)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let a=Sr(e,r).map(c=>this._imageSrc({url:i,filter:t,operation:e,value:c})),{cancel:l}=ri(a);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=B({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=B({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:o}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=o,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Sr(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=B({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};n(ni,"EditorImageFader");var Fn=1,Ce=class extends I{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Fn?this.scrollLeft+=e:this.scrollLeft+=t})}};n(Ce,"EditorScroller");Ce.template=" ";function Vn(s){return``}n(Vn,"renderTabToggle");function zn(s){return`
`}n(zn,"renderTabContent");var xe=class extends I{constructor(){super();u(this,"_updateInfoTooltip",ht(()=>{var o,a;let t=this.$["*editorTransformations"],e="",r=!1;if(this.$["*tabId"]===H.FILTERS)if(r=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let l=((a=t==null?void 0:t.filter)==null?void 0:a.amount)||100;e=this.l10n(this.$["*currentFilter"])+" "+l}else e=this.l10n(mt);else if(this.$["*tabId"]===H.SLIDERS&&this.$["*currentOperation"]){r=!0;let l=(t==null?void 0:t[this.$["*currentOperation"]])||dt[this.$["*currentOperation"]].zero;e=this.$["*currentOperation"]+" "+l}r&&(this.$["*operationTooltip"]=e),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",r)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":mt,"*currentOperation":null,"*tabId":H.CROP,showLoader:!1,filters:br,colorOperations:_r,cropOperations:vr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":t=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":t=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":t=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":t=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=ht(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===H.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=Rt.is&&new Rt;return e.operation=t,e}_createFilterControl(t){let e=Tt.is&&new Tt;return e.filter=t,e}_createToggleControl(t){let e=Ot.is&&new Ot;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===H.CROP?this.$.cropOperations.forEach(o=>{let a=this._createToggleControl(o);r.appendChild(a)}):t===H.FILTERS?[mt,...this.$.filters].forEach(o=>{let a=this._createFilterControl(o);r.appendChild(a)}):t===H.SLIDERS&&this.$.colorOperations.forEach(o=>{let a=this._createOperationControl(o);r.appendChild(a)}),r.childNodes.forEach((o,a)=>{a===r.childNodes.length-1&&o.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===H.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of Oi){let o=r===t,a=this.ref[`tab-toggle-${r}`];a.active=o,o?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=o}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ve(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=ri([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",t=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,o]of r.entries())if(o){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this._updateInfoTooltip()}};n(xe,"EditorToolbar");xe.template=`
{{*operationTooltip}}
${Oi.map(zn).join("")}
${Oi.map(Vn).join("")}
`;var Yt=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return B("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};n(Yt,"LrBtnUi");Yt.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Yt.template=`
{{text}}
`;var we=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};n(we,"LineLoaderUi");we.template=`
`;var Pi={transition:"transition",visible:"visible",hidden:"hidden"},Te=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=Pi.visible,this._hiddenStyle=Pi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",hr(this,{[Pi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(Pi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};n(Te,"PresenceToggle");Te.template=" ";var Ee=class extends b{constructor(){super();u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),a=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${a}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),a=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${a}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),o=Math.ceil(r/2),a=Math.ceil(o/15)-2;if(this._stepsCount===a)return;let l=document.createDocumentFragment(),c=document.createElement("div"),h=document.createElement("div");c.className="minor-step",h.className="border-step",l.appendChild(h);for(let p=0;p
`;var ai=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.CLOUD_IMG_EDIT);u(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new it,e=this.$.cdnUrl;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),t.addEventListener("apply",r=>this.handleApply(r)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};n(ai,"CloudImageEditorActivity");var jn=n(function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},"escapeRegExp"),kr=n(function(s,i="i"){let t=s.split("*").map(jn);return new RegExp("^"+t.join(".+")+"$",i)},"wildcardRegexp");var Hn=n(s=>Object.keys(s).reduce((t,e)=>{let r=s[e],o=Object.keys(r).reduce((a,l)=>{let c=r[l];return a+`${l}: ${c};`},"");return t+`${e}{${o}}`},""),"styleToCss");function Ir({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let o=`solid 1px ${r}`;return Hn({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":o},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":o},".list-table-body .list-items":{"border-bottom":o},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}n(Ir,"buildStyles");var Lt={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in Lt){let t=Lt[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Or=n(function(s,i,t){s in Lt||(Lt[s]=[]),Lt[s].push([i,t])},"registerMessage"),Rr=n(function(s,i){s in Lt&&(Lt[s]=Lt[s].filter(t=>t[0]!==i))},"unregisterMessage");function Lr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}n(Lr,"queryString");var Ae=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.EXTERNAL);u(this,"init$",{...this.init$,activityIcon:"",activityCaption:"",counter:0,onDone:()=>{this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}});u(this,"_iframe",null);u(this,"_inheritedUpdateCssData",this.updateCssData);u(this,"updateCssData",n(()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())},"updateCssData"))}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.$.counter=0,this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()})}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){console.log(t),this.$.counter=this.$.counter+1;let e=(()=>{if(t.alternatives){let a=M(this.cfg.externalSourcesPreferredTypes);for(let l of a){let c=kr(l);for(let[h,d]of Object.entries(t.alternatives))if(c.test(h))return d}}return t.url})(),{filename:r}=t,{externalSourceType:o}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:o})}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Ir(t)})}remoteUrl(){var l,c;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,o={lang:((c=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:c[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},a=new URL(this.cfg.socialBaseUrl);return a.pathname=`/window3/${r}`,a.search=Lr(o),a.toString()}mountIframe(){let t=Me({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Or("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t}unmountIframe(){this._iframe&&Rr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null}};n(Ae,"ExternalSource");Ae.template=`
{{activityCaption}}
{{counter}}
`;var Zt=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;M(i).forEach(e=>{let r=Me({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};n(Zt,"Tabs");Zt.bindAttributes({"tab-list":null,default:null});Zt.template=`
`;var Ut=class extends v{constructor(){super(...arguments);u(this,"processInnerHtml",!0);u(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Ut.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let o=document.createElement("input");o.type="hidden",o.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,o.value=r,this._dynamicInputsContainer.appendChild(o)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(a=>a.uuid),r=await this.getUploadClientOptions(),o=await Ms(e,{...r});this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};n(Ut,"DataOutput");Ut.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var li=class extends _{};n(li,"ActivityHeader");var $e=class extends b{constructor(){super(...arguments);u(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(o=>{e+=``}),this.$.selectHtml=e})}};n($e,"Select");$e.template=``;var G={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Ur={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},J=class extends b{constructor(){super(...arguments);u(this,"init$",{...this.init$,src:"",ppIcon:G.PLAY,fsIcon:G.FS_ON,volIcon:G.VOL_ON,capIcon:G.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Ur.exitFullscreen():Ur.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===G.CAP_OFF?(this.$.capIcon=G.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(J.is+":captions","1")):(this.$.capIcon=G.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(J.is+":captions"))}toggleSound(){this.$.volIcon===G.VOL_ON?(this.$.volIcon=G.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=G.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(J.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let o=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${o}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(J.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=G.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=G.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=G.FS_OFF:this.$.fsIcon=G.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let o="";r==null||r.sources.forEach(a=>{o+=``}),r.tracks&&(r.tracks.forEach(a=>{o+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=o,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(J.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};n(J,"Video");J.template=`
{{currentTime}} / {{totalTime}}
`;J.bindAttributes({video:"video",src:"src"});var Wn="css-src";function ci(s){return class extends s{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Wn);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}n(ci,"shadowed");var Jt=class extends ci(b){};n(Jt,"ShadowWrapper");var Se=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};n(Se,"Copyright"),u(Se,"template",`Powered by Uploadcare`);var Et=class extends Jt{constructor(){super(...arguments);u(this,"init$",Ti(this));u(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};n(Et,"SolutionBlock");var ke=class extends Et{};n(ke,"FileUploaderRegular");ke.template=``;var Ie=class extends Et{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=_.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||_.activities.START_FROM}),this.sub(U("sourceList"),e=>{e!=="local"&&(this.$[U("sourceList")]="local")}),this.sub(U("confirmUpload"),e=>{e!==!1&&(this.$[U("confirmUpload")]=!1)})}};n(Ie,"FileUploaderMinimal");Ie.template=``;var Oe=class extends Et{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||_.activities.START_FROM)&&(this.$["*currentActivity"]=_.activities.UPLOAD_LIST)})}};n(Oe,"FileUploaderInline");Oe.template=``;var ui=class extends ci(it){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};n(ui,"CloudImageEditor");function Mi(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}n(Mi,"registerBlocks");var ps="LR";async function Pr(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[ps]){t(window[ps]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let o=window[ps];i&&Mi(o),t(o)},document.head.appendChild(r)})}n(Pr,"connectBlocksFrom");return jr(Xn);})(); \ No newline at end of file +"use strict";var LR=(()=>{var Me=Object.defineProperty;var Br=Object.getOwnPropertyDescriptor;var zr=Object.getOwnPropertyNames;var jr=Object.prototype.hasOwnProperty;var Hr=(s,i,t)=>i in s?Me(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var l=(s,i)=>Me(s,"name",{value:i,configurable:!0});var Wr=(s,i)=>{for(var t in i)Me(s,t,{get:i[t],enumerable:!0})},Xr=(s,i,t,e)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of zr(i))!jr.call(s,r)&&r!==t&&Me(s,r,{get:()=>i[r],enumerable:!(e=Br(i,r))||e.enumerable});return s};var qr=s=>Xr(Me({},"__esModule",{value:!0}),s);var u=(s,i,t)=>(Hr(s,typeof i!="symbol"?i+"":i,t),t),Vi=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var z=(s,i,t)=>(Vi(s,i,"read from private field"),t?t.call(s):i.get(s)),Mt=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},Ne=(s,i,t,e)=>(Vi(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var fi=(s,i,t)=>(Vi(s,i,"access private method"),t);var sl={};Wr(sl,{ActivityBlock:()=>_,ActivityHeader:()=>ui,BaseComponent:()=>Nt,Block:()=>y,CameraSource:()=>ge,CloudImageEditor:()=>pi,CloudImageEditorActivity:()=>hi,CloudImageEditorBlock:()=>rt,Config:()=>ce,ConfirmationDialog:()=>be,Copyright:()=>Le,CropFrame:()=>Ce,Data:()=>A,DataOutput:()=>Ut,DropArea:()=>Xt,EditorCropButtonControl:()=>Ot,EditorFilterControl:()=>xt,EditorImageCropper:()=>Te,EditorImageFader:()=>ci,EditorOperationControl:()=>Lt,EditorScroller:()=>Ee,EditorSlider:()=>we,EditorToolbar:()=>Ae,ExternalSource:()=>Ie,FileItem:()=>nt,FilePreview:()=>Gt,FileUploaderInline:()=>Pe,FileUploaderMinimal:()=>Ue,FileUploaderRegular:()=>Re,Icon:()=>Ht,Img:()=>ti,LineLoaderUi:()=>$e,LrBtnUi:()=>Yt,MessageBox:()=>pe,Modal:()=>N,PACKAGE_NAME:()=>ns,PACKAGE_VERSION:()=>os,PresenceToggle:()=>Se,ProgressBar:()=>ve,ProgressBarCommon:()=>ye,Select:()=>Oe,ShadowWrapper:()=>Jt,SimpleBtn:()=>de,SliderUi:()=>ke,SourceBtn:()=>qt,SourceList:()=>ii,StartFrom:()=>ei,Tabs:()=>Zt,UploadCtxProvider:()=>ni,UploadDetails:()=>_e,UploadList:()=>fe,UploaderBlock:()=>v,UrlSource:()=>me,Video:()=>Q,connectBlocksFrom:()=>Fr,registerBlocks:()=>Di,shadowed:()=>di,toKebabCase:()=>ot});var Gr=Object.defineProperty,Kr=l((s,i,t)=>i in s?Gr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,"__defNormalProp"),zi=l((s,i,t)=>(Kr(s,typeof i!="symbol"?i+"":i,t),t),"__publicField");function Yr(s){let i=l(t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}},"clone");return i(s)}l(Yr,"cloneObj");var A=l(class{constructor(s){s.constructor===Object?this.store=Yr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(A.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){A.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(A.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=A.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new A(s),A.globalStore.set(i,t)),t}static deleteCtx(s){A.globalStore.delete(s)}static getCtx(s,i=!0){return A.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}},"Data");A.globalStore=new Map;var w=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),_s="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Zr=_s.length-1,Fe=l(class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{ai&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}l(Jr,"kebabToCamel");function Qr(s,i){[...s.querySelectorAll(`[${w.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(w.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=l(class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}},"itemClass");let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(w.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let a=[...t.children],c,h=l(d=>{d.forEach((f,g)=>{if(a[g])if(a[g].set$)setTimeout(()=>{a[g].set$(f)});else for(let m in f)a[g][m]=f[m];else{c||(c=new DocumentFragment);let m=new r;Object.assign(m.init$,f),c.appendChild(m)}}),c&&t.appendChild(c);let p=a.slice(d.length,a.length);for(let f of p)f.remove()},"fillItems");if(o.constructor===Array)h(o);else if(o.constructor===Object){let d=[];for(let p in o){let f=o[p];Object.defineProperty(f,"_KEY_",{value:p,enumerable:!0}),d.push(f)}h(d)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(w.REPEAT_ATTR),t.removeAttribute(w.REPEAT_ITEM_TAG_ATTR)})}l(Qr,"repeatProcessor");var ms="__default__";function tn(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||ms;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=ms;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}l(tn,"slotProcessor");function en(s,i){[...s.querySelectorAll(`[${w.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(w.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(w.EL_REF_ATTR)})}l(en,"refProcessor");function sn(s,i){[...s.querySelectorAll(`[${w.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(w.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Jr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(d=>d.trim()),a=o[0],c;a.indexOf(w.ATTR_BIND_PRFX)===0&&(c=!0,a=a.replace(w.ATTR_BIND_PRFX,""));let h=o[1].split(",").map(d=>d.trim());for(let d of h){let p;d.startsWith("!!")?(p="double",d=d.replace("!!","")):d.startsWith("!")&&(p="single",d=d.replace("!","")),i.sub(d,f=>{p==="double"?f=!!f:p==="single"&&(f=!f),c?(f==null?void 0:f.constructor)===Boolean?f?t.setAttribute(a,""):t.removeAttribute(a):t.setAttribute(a,f):bs(t,a,f)||(t[w.SET_LATER_KEY]||(t[w.SET_LATER_KEY]=Object.create(null)),t[w.SET_LATER_KEY][a]=f)})}}),t.removeAttribute(w.BIND_ATTR)})}l(sn,"domSetProcessor");var mi="{{",De="}}",rn="skip-text";function nn(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(rn))&&r.textContent.includes(mi)&&r.textContent.includes(De)&&1}});for(;i=e.nextNode();)t.push(i);return t}l(nn,"getTextNodesWithTokens");var on=l(function(s,i){nn(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(De);)e.textContent.startsWith(mi)?(n=e.textContent.indexOf(De)+De.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(mi),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let a=o.textContent.replace(mi,"").replace(De,"");o.textContent="",i.sub(a,c=>{o.textContent=c})})})},"txtNodesProcessor"),ln=[Qr,tn,en,sn,on],gi="'",te='"',an=/\\([0-9a-fA-F]{1,6} ?)/g;function cn(s){return(s[0]===te||s[0]===gi)&&(s[s.length-1]===te||s[s.length-1]===gi)}l(cn,"hasLeadingTrailingQuotes");function hn(s){return(s[0]===te||s[0]===gi)&&(s=s.slice(1)),(s[s.length-1]===te||s[s.length-1]===gi)&&(s=s.slice(0,-1)),s}l(hn,"trimQuotes");function un(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ +`,"\\n"),i=un(i),i=te+i+te);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}l(dn,"parseCssPropertyValue");var gs=0,Qt=null,_t=null,Et=l(class extends HTMLElement{constructor(){super(),zi(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return Et}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(w.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=l(()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()},"addFr");if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Fe.generate(),this.style.setProperty(w.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(w.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=A.registerCtx({},this)),this.__localCtx}get nodeCtx(){return A.getCtx(this.ctxName,!1)||A.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(w.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(w.EXT_DATA_CTX_PRFX,"");else if(s.includes(w.NAMED_DATA_CTX_SPLTR)){let r=s.split(w.NAMED_DATA_CTX_SPLTR);t=A.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=l(n=>{this.isConnected&&i(n)},"subCb"),r=Et.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=Et.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=Et.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=Et.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=Et.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=Et.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(w.CTX_OWNER_ATTR)&&this.getAttribute(w.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(w.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(w.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(w.NAMED_DATA_CTX_SPLTR)){let t=i.split(w.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=A.getCtx(e,!1);n||(n=A.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(w.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(w.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[w.SET_LATER_KEY]){for(let t in this[w.SET_LATER_KEY])bs(this,t,this[w.SET_LATER_KEY][t]);delete this[w.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of ln)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${w.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(w.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);_t==null||_t.delete(this.updateCssData),_t!=null&&_t.size||(Qt==null||Qt.disconnect(),Qt=null,_t=null)},100)))}static reg(s,i=!1){s||(gs++,s=`${w.AUTO_TAG_PRFX}-${gs}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=dn(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){_t||(_t=new Set),_t.add(this.updateCssData),Qt||(Qt=new MutationObserver(s=>{s[0].type==="attributes"&&_t.forEach(i=>{i()})}),Qt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},"_BaseComponent"),Nt=Et;zi(Nt,"template");var Bi=l(class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Bi.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=A.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Bi.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}},"AppRouter");Bi.appMap=Object.create(null);function pn(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}l(pn,"applyStyles");function fn(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}l(fn,"applyAttributes");function Ve(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&fn(i,s.attributes),s.styles&&pn(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=Ve(t);i.appendChild(e)}),i}l(Ve,"create");var ys="idb-store-ready",mn="symbiote-db",gn="symbiote-idb-update_",_n=l(class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ys,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return gn+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,a)=>{n.onsuccess=c=>{t||this._notifySubscribers(s),o(c.target.result)},n.onerror=c=>{a(c)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,vs.clear(this.name)}},"DbInstance"),vs=l(class{static get readyEventName(){return ys}static open(s=mn,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new _n(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}},"IDB");zi(vs,"_reg",Object.create(null));function k(s,i){let t,e=l((...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)},"debounced");return e.cancel=()=>{clearTimeout(t)},e}l(k,"debounce");var bn="--uploadcare-blocks-window-height",_i="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ji(){return typeof window[_i]=="undefined"?!1:!!window[_i]}l(ji,"getIsWindowHeightTracked");function Cs(){if(ji())return;let s=l(()=>{document.documentElement.style.setProperty(bn,`${window.innerHeight}px`),window[_i]=!0},"callback"),i=k(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[_i]=!1,window.removeEventListener("resize",i)}}l(Cs,"createWindowHeightTracker");var yn=l(s=>s,"DEFAULT_TRANSFORMER"),Hi="{{",xs="}}",ws="plural:";function Be(s,i,t={}){var o;let{openToken:e=Hi,closeToken:r=xs,transform:n=yn}=t;for(let a in i){let c=(o=i[a])==null?void 0:o.toString();s=s.replaceAll(e+a+r,typeof c=="string"?n(c):c)}return s}l(Be,"applyTemplateData");function Ts(s){let i=[],t=s.indexOf(Hi);for(;t!==-1;){let e=s.indexOf(xs,t),r=s.substring(t+2,e);if(r.startsWith(ws)){let n=s.substring(t+2,e).replace(ws,""),o=n.substring(0,n.indexOf("(")),a=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:a})}t=s.indexOf(Hi,e)}return i}l(Ts,"getPluralObjects");function Es(s){return Object.prototype.toString.call(s)==="[object Object]"}l(Es,"isObject");var vn=/\W|_/g;function Cn(s){return s.split(vn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}l(Cn,"camelizeString");function As(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>Ct(t,{ignoreKeys:i})):s}l(As,"camelizeArrayItems");function Ct(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return As(s,{ignoreKeys:i});if(!Es(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Es(r)?r=Ct(r,{ignoreKeys:i}):Array.isArray(r)&&(r=As(r,{ignoreKeys:i})),t[Cn(e)]=r}return t}l(Ct,"camelizeKeys");var wn=l(s=>new Promise(i=>setTimeout(i,s)),"delay");function Gi({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),a=[n,r].filter(Boolean).join("; ");return`${o} (${a})`}l(Gi,"getUserAgent$1");var xn={factor:2,time:100};function Tn(s,i=xn){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l(a=>wn(a!=null?a:n).then(()=>(t+=1,e(r))),"retry")})}return l(e,"runAttempt"),e(s)}l(Tn,"retrier");var Vt=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,Vt.prototype),this.originalProgressEvent=t}};l(Vt,"UploadcareNetworkError");var wi=l((s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},"onCancel"),bt=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,bt.prototype)}};l(bt,"CancelError");var En=500,Ss=l(({check:s,interval:i=En,timeout:t,signal:e})=>new Promise((r,n)=>{let o,a;wi(e,()=>{o&&clearTimeout(o),n(new bt("Poll cancelled"))}),t&&(a=setTimeout(()=>{o&&clearTimeout(o),n(new bt("Timed out"))},t));let c=l(()=>{try{Promise.resolve(s(e)).then(h=>{h?(a&&clearTimeout(a),r(h)):o=setTimeout(c,i)}).catch(h=>{a&&clearTimeout(a),n(h)})}catch(h){a&&clearTimeout(a),n(h)}},"tick");o=setTimeout(c,0)}),"poll"),E={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},xi="application/octet-stream",ks="original",At=l(({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,a)=>{let c=new XMLHttpRequest,h=(s==null?void 0:s.toUpperCase())||"GET",d=!1;c.open(h,i,!0),e&&Object.entries(e).forEach(p=>{let[f,g]=p;typeof g!="undefined"&&!Array.isArray(g)&&c.setRequestHeader(f,g)}),c.responseType="text",wi(r,()=>{d=!0,c.abort(),a(new bt)}),c.onload=()=>{if(c.status!=200)a(new Error(`Error ${c.status}: ${c.statusText}`));else{let p={method:h,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},f=c.getAllResponseHeaders().trim().split(/[\r\n]+/),g={};f.forEach(function(S){let $=S.split(": "),T=$.shift(),x=$.join(": ");T&&typeof T!="undefined"&&(g[T]=x)});let m=c.response,b=c.status;o({request:p,data:m,headers:g,status:b})}},c.onerror=p=>{d||a(new Vt(p))},n&&typeof n=="function"&&(c.upload.onprogress=p=>{p.lengthComputable?n({isComputable:!0,value:p.loaded/p.total}):n({isComputable:!1})}),t?c.send(t):c.send()}),"request");function An(s,...i){return s}l(An,"identity");var $n=l(({name:s})=>s?[s]:[],"getFileOptions"),Sn=An,kn=l(()=>new FormData,"getFormData"),Is=l(s=>!1,"isBuffer"),Ti=l(s=>typeof Blob!="undefined"&&s instanceof Blob,"isBlob"),Ei=l(s=>typeof File!="undefined"&&s instanceof File,"isFile"),Ai=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string","isReactNativeAsset"),je=l(s=>Ti(s)||Ei(s)||Is()||Ai(s),"isFileData"),In=l(s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined","isSimpleValue"),On=l(s=>!!s&&typeof s=="object"&&!Array.isArray(s),"isObjectValue"),Ln=l(s=>!!s&&typeof s=="object"&&"data"in s&&je(s.data),"isFileValue");function Rn(s,i,t){if(Ln(t)){let{name:e,contentType:r}=t,n=Sn(t.data,e,r!=null?r:xi),o=$n({name:e,contentType:r});s.push([i,n,...o])}else if(On(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else In(t)&&t&&s.push([i,t.toString()])}l(Rn,"collectParams");function Un(s){let i=[];for(let[t,e]of Object.entries(s))Rn(i,t,e);return i}l(Un,"getFormDataParams");function Ki(s){let i=kn(),t=Un(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}l(Ki,"buildFormData");var U=class extends Error{constructor(t,e,r,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,U.prototype)}};l(U,"UploadClientError");var Pn=l(s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},"buildSearchParams"),vt=l((s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=Pn(t)),e.toString()},"getUrl"),Mn="6.6.1",Nn="UploadcareUploadClient",Dn=Mn;function Bt(s){return Gi({libraryName:Nn,libraryVersion:Dn,...s})}l(Bt,"getUserAgent");var Fn="RequestThrottledError",$s=15e3,Vn=1e3;function Bn(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return $s;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:$s}l(Bn,"getTimeoutFromThrottledRequest");function $t(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return Tn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Fn&&r{let i="";return(Ti(s)||Ei(s)||Ai(s))&&(i=s.type),i||xi},"getContentType"),Ls=l(s=>{let i="";return Ei(s)&&s.name?i=s.name:Ti(s)||Is()?i="":Ai(s)&&s.name&&(i=s.name),i||ks},"getFileName");function Yi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}l(Yi,"getStoreValue");function zn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=E.baseURL,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=E.retryNetworkErrorMaxTimes,metadata:b}){return $t(()=>At({method:"POST",url:vt(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Bt({publicKey:i,integration:p,userAgent:f})},data:Ki({file:{data:s,name:t||Ls(s),contentType:e||Os(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Yi(a),signature:n,expire:o,source:d,metadata:b}),signal:c,onProgress:h}).then(({data:S,headers:$,request:T})=>{let x=Ct(JSON.parse(S));if("error"in x)throw new U(x.error.content,x.error.errorCode,T,x,$);return x}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(zn,"base");var qi;(function(s){s.Token="token",s.FileInfo="file_info"})(qi||(qi={}));function jn(s,{publicKey:i,baseURL:t=E.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,source:h="url",signal:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=E.retryNetworkErrorMaxTimes,metadata:b}){return $t(()=>At({method:"POST",headers:{"X-UC-User-Agent":Bt({publicKey:i,integration:p,userAgent:f})},url:vt(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Yi(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:a,expire:c,source:h,metadata:b}),signal:d}).then(({data:S,headers:$,request:T})=>{let x=Ct(JSON.parse(S));if("error"in x)throw new U(x.error.content,x.error.errorCode,T,x,$);return x}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:g})}l(jn,"fromUrl");var G;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(G||(G={}));var Hn=l(s=>"status"in s&&s.status===G.Error,"isErrorResponse");function Wn(s,{publicKey:i,baseURL:t=E.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=E.retryNetworkErrorMaxTimes}={}){return $t(()=>At({method:"GET",headers:i?{"X-UC-User-Agent":Bt({publicKey:i,integration:r,userAgent:n})}:void 0,url:vt(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:c,headers:h,request:d})=>{let p=Ct(JSON.parse(c));if("error"in p&&!Hn(p))throw new U(p.error.content,void 0,d,p,h);return p}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:o})}l(Wn,"fromUrlStatus");function Xn(s,{publicKey:i,baseURL:t=E.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:a,integration:c,userAgent:h,retryThrottledRequestMaxTimes:d=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=E.retryNetworkErrorMaxTimes}){return $t(()=>At({method:"POST",headers:{"X-UC-User-Agent":Bt({publicKey:i,integration:c,userAgent:h})},url:vt(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:a}),signal:o}).then(({data:f,headers:g,request:m})=>{let b=Ct(JSON.parse(f));if("error"in b)throw new U(b.error.content,b.error.errorCode,m,b,g);return b}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:d})}l(Xn,"group");function Rs(s,{publicKey:i,baseURL:t=E.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=E.retryNetworkErrorMaxTimes}){return $t(()=>At({method:"GET",headers:{"X-UC-User-Agent":Bt({publicKey:i,integration:n,userAgent:o})},url:vt(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:h,headers:d,request:p})=>{let f=Ct(JSON.parse(h));if("error"in f)throw new U(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Rs,"info");function qn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=E.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:a,store:c,signal:h,source:d="local",integration:p,userAgent:f,retryThrottledRequestMaxTimes:g=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=E.retryNetworkErrorMaxTimes,metadata:b}){return $t(()=>At({method:"POST",url:vt(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Bt({publicKey:i,integration:p,userAgent:f})},data:Ki({filename:e||ks,size:s,content_type:t||xi,part_size:r,UPLOADCARE_STORE:Yi(c),UPLOADCARE_PUB_KEY:i,signature:o,expire:a,source:d,metadata:b}),signal:h}).then(({data:S,headers:$,request:T})=>{let x=Ct(JSON.parse(S));if("error"in x)throw new U(x.error.content,x.error.errorCode,T,x,$);return x.parts=Object.keys(x.parts).map(X=>x.parts[X]),x}),{retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})}l(qn,"multipartStart");function Gn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=E.retryNetworkErrorMaxTimes}){return $t(()=>At({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||xi}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}l(Gn,"multipartUpload");function Kn(s,{publicKey:i,baseURL:t=E.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:a=E.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:c=E.retryNetworkErrorMaxTimes}){return $t(()=>At({method:"POST",url:vt(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Bt({publicKey:i,integration:n,userAgent:o})},data:Ki({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:h,headers:d,request:p})=>{let f=Ct(JSON.parse(h));if("error"in f)throw new U(f.error.content,f.error.errorCode,p,f,d);return f}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})}l(Kn,"multipartComplete");function Zi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a,signal:c,onProgress:h}){return Ss({check:d=>Rs(s,{publicKey:i,baseURL:t,signal:d,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:a}).then(p=>p.isReady?p:(h&&h({isComputable:!0,value:1}),!1)),signal:c})}l(Zi,"isReadyPoll");var yt=class{constructor(i,{baseCDN:t=E.baseCDN,fileName:e}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=vt(t,`${r}/`),a=n?vt(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=a}};l(yt,"UploadcareFile");var Yn=l((s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:S})=>zn(s,{publicKey:i,fileName:t,contentType:a,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:S}).then(({file:$})=>Zi({file:$,publicKey:i,baseURL:e,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then($=>new yt($,{baseCDN:b})),"uploadDirect"),Zn=l((s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d,baseCDN:p})=>Rs(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:a,userAgent:c,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:d}).then(f=>new yt(f,{baseCDN:p,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),"uploadFromUploaded"),Jn=l((s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=l(o=>()=>{e=o,r.forEach((a,c)=>c!==o&&a.abort())},"createStopRaceCallback");return wi(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,a)=>{let c=n(a);return Promise.resolve().then(()=>o({stopRace:c,signal:r[a].signal})).then(h=>(c(),h)).catch(h=>(t=h,null))})).then(o=>{if(e===null)throw t;return o[e]})},"race"),Qn=window.WebSocket,bi=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}};l(bi,"Events");var to=l((s,i)=>s==="success"?{status:G.Success,...i}:s==="progress"?{status:G.Progress,...i}:{status:G.Error,...i},"response"),yi=class{constructor(i,t=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new bi);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Qn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,to(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=l(()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1},"actualDisconect");this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}};l(yi,"Pusher");var Wi=null,Ji=l(s=>{if(!Wi){let i=typeof window=="undefined"?0:3e4;Wi=new yi(s,i)}return Wi},"getPusher"),eo=l(s=>{Ji(s).connect()},"preconnect");function io({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:a,signal:c}){return Ss({check:h=>Wn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:h}).then(d=>{switch(d.status){case G.Error:return new U(d.error,d.errorCode);case G.Waiting:return!1;case G.Unknown:return new U(`Token "${s}" was not found.`);case G.Progress:return a&&(d.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:d.done/d.total})),!1;case G.Success:return a&&a({isComputable:!0,value:d.done/d.total}),d;default:throw new Error("Unknown status")}}),signal:c})}l(io,"pollStrategy");var so=l(({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Ji(i),a=o.onError(n),c=l(()=>{a(),o.unsubscribe(s)},"destroy");wi(t,()=>{c(),n(new bt("pusher cancelled"))}),o.subscribe(s,h=>{switch(h.status){case G.Progress:{e&&(h.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:h.done/h.total}));break}case G.Success:{c(),e&&e({isComputable:!0,value:h.done/h.total}),r(h);break}case G.Error:c(),n(new U(h.msg,h.error_code))}})}),"pushStrategy"),ro=l((s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,onProgress:p,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,pusherKey:S=E.pusherKey,metadata:$})=>Promise.resolve(eo(S)).then(()=>jn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:a,secureExpire:c,store:h,signal:d,source:f,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,metadata:$})).catch(T=>{let x=Ji(S);return x==null||x.disconnect(),Promise.reject(T)}).then(T=>T.type===qi.FileInfo?T:Jn([({signal:x})=>io({token:T.token,publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:p,signal:x}),({signal:x})=>so({token:T.token,pusherKey:S,signal:x,onProgress:p})],{signal:d})).then(T=>{if(T instanceof U)throw T;return T}).then(T=>Zi({file:T.uuid,publicKey:i,baseURL:e,integration:g,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:p,signal:d})).then(T=>new yt(T,{baseCDN:r})),"uploadFromUrl"),Xi=new WeakMap,no=l(async s=>{if(Xi.has(s))return Xi.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Xi.set(s,i),i},"getBlobFromReactNativeAsset"),Us=l(async s=>{if(Ei(s)||Ti(s))return s.size;if(Ai(s))return(await no(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},"getFileSize"),oo=l((s,i=E.multipartMinFileSize)=>s>=i,"isMultipart"),Ps=l(s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!je(s)&&t.test(s)},"isUuid"),Ms=l(s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!je(s)&&t.test(s)},"isUrl"),lo=l((s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,a=[...i],c=l(()=>{let h=i.length-a.length,d=a.shift();d&&d().then(p=>{n||(r[h]=p,o-=1,o?c():t(r))}).catch(p=>{n=!0,e(p)})},"run");for(let h=0;h{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},"sliceChunk"),co=l(async(s,i,t)=>e=>ao(s,e,i,t),"prepareChunks"),ho=l((s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c})=>Gn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:c}),"uploadPart"),uo=l(async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,onProgress:h,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,contentType:b,multipartChunkSize:S=E.multipartChunkSize,maxConcurrentRequests:$=E.maxConcurrentRequests,baseCDN:T,metadata:x})=>{let X=e!=null?e:await Us(s),ft,Pt=l((M,tt)=>{if(!h)return;ft||(ft=Array(M).fill(0));let mt=l(q=>q.reduce((gt,Fi)=>gt+Fi,0),"sum");return q=>{q.isComputable&&(ft[tt]=q.value,h({isComputable:!0,value:mt(ft)/M}))}},"createProgressHandler");return b||(b=Os(s)),qn(X,{publicKey:i,contentType:b,fileName:t||Ls(s),baseURL:r,secureSignature:n,secureExpire:o,store:a,signal:c,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,metadata:x}).then(async({uuid:M,parts:tt})=>{let mt=await co(s,X,S);return Promise.all([M,lo($,tt.map((q,gt)=>()=>ho(mt(gt),q,{publicKey:i,contentType:b,onProgress:Pt(tt.length,gt),signal:c,integration:p,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})))])}).then(([M])=>Kn(M,{publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m})).then(M=>M.isReady?M:Zi({file:M.uuid,publicKey:i,baseURL:r,source:d,integration:p,userAgent:f,retryThrottledRequestMaxTimes:g,retryNetworkErrorMaxTimes:m,onProgress:h,signal:c})).then(M=>new yt(M,{baseCDN:T}))},"uploadMultipart");async function Qi(s,{publicKey:i,fileName:t,baseURL:e=E.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartMinFileSize:b,multipartChunkSize:S,maxConcurrentRequests:$,baseCDN:T=E.baseCDN,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:X,pusherKey:ft,metadata:Pt}){if(je(s)){let M=await Us(s);return oo(M,b)?uo(s,{publicKey:i,contentType:m,multipartChunkSize:S,fileSize:M,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,maxConcurrentRequests:$,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:T,metadata:Pt}):Yn(s,{publicKey:i,fileName:t,contentType:m,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:T,metadata:Pt})}if(Ms(s))return ro(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:T,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:X,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,pusherKey:ft,metadata:Pt});if(Ps(s))return Zn(s,{publicKey:i,fileName:t,baseURL:e,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,baseCDN:T});throw new TypeError(`File uploading from "${s}" is not supported`)}l(Qi,"uploadFile");var vi=class{constructor(i,t){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}};l(vi,"UploadcareGroup");var po=l(s=>{for(let i of s)if(!je(i))return!1;return!0},"isFileDataArray"),fo=l(s=>{for(let i of s)if(!Ps(i))return!1;return!0},"isUuidArray"),mo=l(s=>{for(let i of s)if(!Ms(i))return!1;return!0},"isUrlArray");function Ns(s,{publicKey:i,fileName:t,baseURL:e=E.baseURL,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:b=E.multipartChunkSize,baseCDN:S=E.baseCDN,checkForUrlDuplicates:$,saveUrlForRecurrentUploads:T,jsonpCallback:x}){if(!po(s)&&!mo(s)&&!fo(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let X,ft=!0,Pt=s.length,M=l((tt,mt)=>{if(!c)return;X||(X=Array(tt).fill(0));let q=l(gt=>gt.reduce((Fi,Vr)=>Fi+Vr)/tt,"normalize");return gt=>{if(!gt.isComputable||!ft){ft=!1,c({isComputable:!1});return}X[mt]=gt.value,c({isComputable:!0,value:q(X)})}},"createProgressHandler");return Promise.all(s.map((tt,mt)=>Qi(tt,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:M(Pt,mt),source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g,contentType:m,multipartChunkSize:b,baseCDN:S,checkForUrlDuplicates:$,saveUrlForRecurrentUploads:T}))).then(tt=>{let mt=tt.map(q=>q.uuid);return Xn(mt,{publicKey:i,baseURL:e,jsonpCallback:x,secureSignature:r,secureExpire:n,signal:a,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:g}).then(q=>new vi(q,tt)).then(q=>(c&&c({isComputable:!0,value:1}),q))})}l(Ns,"uploadFileGroup");var Dt,ee,Ft,ie,se,re,Ci,ze=class{constructor(i){Mt(this,re);Mt(this,Dt,1);Mt(this,ee,[]);Mt(this,Ft,0);Mt(this,ie,new WeakMap);Mt(this,se,new WeakMap);Ne(this,Dt,i)}add(i){return new Promise((t,e)=>{z(this,ie).set(i,t),z(this,se).set(i,e),z(this,ee).push(i),fi(this,re,Ci).call(this)})}get pending(){return z(this,ee).length}get running(){return z(this,Ft)}set concurrency(i){Ne(this,Dt,i),fi(this,re,Ci).call(this)}get concurrency(){return z(this,Dt)}};l(ze,"Queue"),Dt=new WeakMap,ee=new WeakMap,Ft=new WeakMap,ie=new WeakMap,se=new WeakMap,re=new WeakSet,Ci=l(function(){let i=z(this,Dt)-z(this,Ft);for(let t=0;t{z(this,ie).delete(e),z(this,se).delete(e),Ne(this,Ft,z(this,Ft)-1),fi(this,re,Ci).call(this)}).then(o=>r(o)).catch(o=>n(o))}},"#run");var ts=l(()=>({"*blocksRegistry":new Set}),"blockCtx"),es=l(s=>({...ts(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),"activityBlockCtx"),$i=l(s=>({...es(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new ze(1)}),"uploaderBlockCtx");function Ds(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}l(Ds,"l10nProcessor");var et=l(s=>`*cfg/${s}`,"sharedConfigKey");var ot=l(s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")},"toKebabCase");var Fs=new Set;function Si(s){Fs.has(s)||(Fs.add(s),console.warn(s))}l(Si,"warnOnce");var ki=l((s,i)=>new Intl.PluralRules(s).select(i),"getPluralForm");var is="lr-",y=class extends Nt{constructor(){super();u(this,"allowCustomTemplate",!0);u(this,"init$",ts());u(this,"updateCtxCssData",l(()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()},"updateCtxCssData"));this.activityType=null,this.addTemplateProcessor(Ds),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=Ts(r);for(let a of n)e[a.variable]=this.pluralize(a.pluralKey,Number(e[a.countVariable]));return Be(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=ki(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setForCtxTarget(t,e,r){this.hasBlockInCtx(n=>n.constructor.StateConsumerScope===t)&&(this.$[e]=r)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${is}${t}`,!0),ji()||(this._destroyInnerHeightTracker=Cs()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=l(h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h,"getUnit");if(t===0)return`0 ${n(r[0])}`;let o=1024,a=e<0?0:e,c=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**c).toFixed(a))+" "+n(r[c])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?Be(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=et(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Si("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${ot(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(et(t));r.ctx.has(r.name)?this.sub(et(t),e):(this.bindCssData(`--cfg-${ot(t)}`),this.sub(`--cfg-${ot(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(is)?t:is+t)}};l(y,"Block"),u(y,"StateConsumerScope",null),u(y,"className","");var ss=class extends y{constructor(){super();u(this,"_handleBackdropClick",l(()=>{this._closeDialog()},"_handleBackdropClick"));u(this,"_closeDialog",l(()=>{this.setForCtxTarget(ss.StateConsumerScope,"*modalActive",!1)},"_closeDialog"));u(this,"_handleDialogClose",l(()=>{this._closeDialog()},"_handleDialogClose"));u(this,"_handleDialogPointerUp",l(t=>{t.target===this.ref.dialog&&this._closeDialog()},"_handleDialogPointerUp"));this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}},N=ss;l(N,"Modal"),u(N,"StateConsumerScope","modal");N.template=``;var Vs="active",He="___ACTIVITY_IS_ACTIVE___",lt=class extends y{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",es(this));u(this,"_debouncedHistoryFlush",k(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=lt._activityRegistry[this.activityKey];this[He]=!1,this.removeAttribute(Vs),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=lt._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[He]=!0,this.setAttribute(Vs,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[He]?this._deactivate():this.activityType===t&&!this[He]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!lt._activityRegistry[this.activityKey]}get isActivityActive(){return this[He]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;lt._activityRegistry||(lt._activityRegistry=Object.create(null)),lt._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),lt._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(lt._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setForCtxTarget(N.StateConsumerScope,"*modalActive",!1)}}},_=lt;l(_,"ActivityBlock"),u(_,"_activityRegistry",Object.create(null));_.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var We=33.333333333333336,C=1,rs=24,Bs=6;function zt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}l(zt,"setSvgNodeAttrs");function it(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return zt(t,i),t}l(it,"createSvgNode");function zs(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=i.includes("w")?0:1,c=i.includes("n")?0:1,h=[-1,1][a],d=[-1,1][c],p=[e+a*n+1.5*h,r+c*o+1.5*d-24*t*d],f=[e+a*n+1.5*h,r+c*o+1.5*d],g=[e+a*n-24*t*h+1.5*h,r+c*o+1.5*d];return{d:`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]} L ${g[0]} ${g[1]}`,center:f}}l(zs,"cornerPath");function js(s,i,t){let{x:e,y:r,width:n,height:o}=s,a=["n","s"].includes(i)?.5:{w:0,e:1}[i],c=["w","e"].includes(i)?.5:{n:0,s:1}[i],h=[-1,1][a],d=[-1,1][c],p,f;["n","s"].includes(i)?(p=[e+a*n-34*t/2,r+c*o+1.5*d],f=[e+a*n+34*t/2,r+c*o+1.5*d]):(p=[e+a*n+1.5*h,r+c*o-34*t/2],f=[e+a*n+1.5*h,r+c*o+34*t/2]);let g=`M ${p[0]} ${p[1]} L ${f[0]} ${f[1]}`,m=[f[0]-(f[0]-p[0])/2,f[1]-(f[1]-p[1])/2];return{d:g,center:m}}l(js,"sidePath");function Hs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}l(Hs,"thumbCursor");function Ws({rect:s,delta:[i,t],imageBox:e}){return oe({...s,x:s.x+i,y:s.y+t},e)}l(Ws,"moveRect");function oe(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}l(oe,"constraintRect");function go({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:a}=s;n+=r,a-=r,t&&(o=a*t);let c=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,a=s.y+s.height-n,t&&(o=a*t,c=s.x+s.width/2-o/2)),c<=e.x&&(c=e.x,n=s.y+s.height-a),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y+s.height-a),a=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x+s.width-o),a=e.y+e.height&&(a=e.y+e.height-n,t&&(o=a*t),c=s.x+s.width/2-o/2),c<=e.x&&(c=e.x,n=s.y),c+o>=e.x+e.width&&(c=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-c,t&&(a=o/t),n=s.y),a=e.x+e.width&&(o=e.x+e.width-n,t&&(a=o/t),c=s.y+s.height/2-a/2),c<=e.y&&(c=e.y,n=s.x),c+a>=e.y+e.height&&(c=Math.max(e.y,e.y+e.height-a),a=e.y+e.height-c,t&&(o=a*t),n=s.x),at?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x+s.width-c,a=e.y)):t&&(r=h*t-c,c=c+r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y+s.height-h)),he.x+e.width&&(r=e.x+e.width-o-c),a+nt?(n=c/t-h,h+=n,a-=n,a<=e.y&&(h=h-(e.y-a),c=h*t,o=s.x,a=e.y)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y+s.height-h)),he.y+e.height&&(n=e.y+e.height-a-h),o+=r,c-=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x+s.width-c,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o-=r,o<=e.x&&(c=c-(e.x-o),h=c/t,o=e.x,a=s.y)),he.x+e.width&&(r=e.x+e.width-o-c),a+h+n>e.y+e.height&&(n=e.y+e.height-a-h),c+=r,h+=n,t&&Math.abs(c/h)>t?(n=c/t-h,h+=n,a+h>=e.y+e.height&&(h=e.y+e.height-a,c=h*t,o=s.x,a=e.y+e.height-h)):t&&(r=h*t-c,c+=r,o+c>=e.x+e.width&&(c=e.x+e.width-o,h=c/t,o=e.x+e.width-c,a=s.y)),h=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}l(Gs,"isRectInsideRect");function le({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}l(le,"rotateSize");function Ks(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),a=Math.round((i-n)/2);return o+r>s&&(r=s-o),a+n>i&&(n=i-a),{x:o,y:a,width:r,height:n}}l(Ks,"calculateMaxCenteredCropFrame");function ae(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}l(ae,"roundRect");function St(s,i,t){return Math.min(Math.max(s,i),t)}l(St,"clamp");var Oi=l(s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]},"parseCropPreset");var st=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var ns="blocks",os="0.25.6";function Ys(s){return Gi({...s,libraryName:ns,libraryVersion:os})}l(Ys,"customUserAgent");var Zs=l(s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},"normalizeCdnOperation"),Li=l((...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Zs(i)).join("/-/"),"joinCdnOperations"),O=l((...s)=>{let i=Li(...s);return i?`-/${i}/`:""},"createCdnUrlModifiers");function Js(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}l(Js,"extractFilename");function Qs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}l(Qs,"extractUuid");function tr(s){let i=er(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Zs(n))}l(tr,"extractOperations");function er(s){let i=new URL(s),t=Js(s),e=ir(t)?sr(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}l(er,"trimFilename");function ir(s){return s.startsWith("http")}l(ir,"isFileUrl");function sr(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}l(sr,"splitFileUrl");var I=l((s,i,t)=>{let e=new URL(er(s));if(t=t||Js(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),ir(t)){let r=sr(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},"createCdnUrl"),kt=l((s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()},"createOriginalUrl");var D=l((s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0),"stringToArray");var Xe=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],ls=l(s=>s?s.filter(i=>typeof i=="string").map(i=>D(i)).flat():[],"mergeFileTypes"),as=l((s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),"matchMimeType"),rr=l((s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),"matchExtension"),qe=l(s=>{let i=s==null?void 0:s.type;return i?as(i,Xe):!1},"fileIsImage");var ct=1e3,jt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),Ge=l(s=>Math.ceil(s*100)/100,"round"),nr=l((s,i=jt.AUTO)=>{let t=i===jt.AUTO;if(i===jt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))},"dispatch");if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};l(L,"EventManager"),u(L,"_timeoutStore",Object.create(null));var or="[Typed State] Wrong property name: ",To="[Typed State] Wrong property type: ",Ke=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||Fe.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=A.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(or+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(To+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(or+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){A.deleteCtx(this.__ctxId)}};l(Ke,"TypedData");var Ye=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Fe.generate(),this.__data=A.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Ke(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){A.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};l(Ye,"TypedCollection");var lr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:yt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var v=class extends _{constructor(){super(...arguments);u(this,"couldBeUploadCollectionOwner",!1);u(this,"isUploadCollectionOwner",!1);u(this,"init$",$i(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",k(this._runValidators.bind(this),100));u(this,"_handleCollectionUpdate",l(t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(c=>!c.getValue("uploadError"));o.forEach(c=>{n+=e.readProp(c,"uploadProgress")});let a=Math.round(n/o.length);this.$["*commonProgress"]=a,L.emit(new F({type:P.UPLOAD_PROGRESS,ctx:this.ctxName,data:a}),void 0,a===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(a=>!!a.getValue("fileInfo")),o=e.findItems(a=>!!a.getValue("uploadError")||!!a.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let a=this.getOutputData(c=>!!c.getValue("fileInfo")&&!c.getValue("silentUpload"));a.length>0&&L.emit(new F({type:P.UPLOAD_FINISH,ctx:this.ctxName,data:a}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{L.emit(new F({type:P.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{L.emit(new F({type:P.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{L.emit(new F({type:P.CDN_MODIFICATION,ctx:this.ctxName,data:A.getCtx(o).store}),void 0,!1)})},"_handleCollectionUpdate"))}setUploadMetadata(t){Si("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Ye({typedSchema:lr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=l(()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1),"hasUploadCollectionOwner");this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let a of n)(o=a==null?void 0:a.getValue("abortController"))==null||o.abort(),a==null||a.setValue("abortController",null),URL.revokeObjectURL(a==null?void 0:a.getValue("thumbUrl"));this.$["*uploadList"]=e.map(a=>({uid:a}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:st.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:st.API})}addFileFromObject(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:qe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:st.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:qe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=ls([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?Xe:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=Xe.join(",")):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:st.LOCAL})),this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this.setForCtxTarget(N.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=D(this.cfg.sourceList)),t}initFlow(t=!1){var e,r;if((e=this.$["*uploadList"])!=null&&e.length&&!t)this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setForCtxTarget(N.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let n=this.sourceList[0];n==="local"?(this.$["*currentActivity"]=_.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(n)?this.set$({"*currentActivityParams":{externalSourceType:n},"*currentActivity":_.activities.EXTERNAL}):this.$["*currentActivity"]=n,this.setForCtxTarget(N.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":_.activities.START_FROM}),this.setForCtxTarget(N.StateConsumerScope,"*modalActive",!0);L.emit(new F({type:P.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(N.StateConsumerScope,"*modalActive",!1),L.emit(new F({type:P.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=ls([...e?Xe:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),a=t.getValue("fileName");if(!o||!a)return;let c=as(o,n),h=rr(a,n);if(!c&&!h)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:nr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=Oi(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:a,height:c}=o.imageInfo,h=e.width/e.height,d=Ks(a,c,h),p=O(`crop/${d.width}x${d.height}/${d.x},${d.y}`);n.setMultipleValues({cdnUrlModifiers:p,cdnUrl:I(n.getValue("cdnUrl"),p)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===_.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Ys,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=A.getCtx(n).store,a=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},c={...a,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||a.cdnUrl};e.push(c)}),e}};l(v,"UploaderBlock");v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(P).forEach(s=>{let i=L.eName(s),t=k(e=>{if([P.UPLOAD_FINISH,P.REMOVE,P.CDN_MODIFICATION].includes(e.detail.type)){let n=A.getCtx(e.detail.ctx),o=n.read("uploadCollection"),a=[];o.items().forEach(c=>{let h=A.getCtx(c).store,d=h.fileInfo;if(d){let p={...d,cdnUrlModifiers:h.cdnUrlModifiers,cdnUrl:h.cdnUrl||d.cdnUrl};a.push(p)}}),L.emit(new F({type:P.DATA_OUTPUT,ctx:e.detail.ctx,data:a})),n.pub("outputData",a)}},0);window.addEventListener(i,t)});var Eo="https://ucarecdn.com",Ao="https://upload.uploadcare.com",$o="https://social.uploadcare.com",Ze=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Eo,baseUrl:Ao,socialBaseUrl:$o,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var Y=l(s=>String(s),"asString"),ht=l(s=>Number(s),"asNumber"),j=l(s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,"asBoolean"),So=l(s=>s==="auto"?s:j(s),"asStore"),ko={pubkey:Y,multiple:j,multipleMin:ht,multipleMax:ht,confirmUpload:j,imgOnly:j,accept:Y,externalSourcesPreferredTypes:Y,store:So,cameraMirror:j,sourceList:Y,maxLocalFileSizeBytes:ht,thumbSize:ht,showEmptyList:j,useLocalImageEditor:j,useCloudImageEditor:j,removeCopyright:j,cropPreset:Y,modalScrollLock:j,modalBackdropStrokes:j,sourceListWrap:j,remoteTabSessionKey:Y,cdnCname:Y,baseUrl:Y,socialBaseUrl:Y,secureSignature:Y,secureExpire:Y,secureDeliveryProxy:Y,retryThrottledRequestMaxTimes:ht,multipartMinFileSize:ht,multipartChunkSize:ht,maxConcurrentRequests:ht,multipartMaxConcurrentRequests:ht,multipartMaxAttempts:ht,checkForUrlDuplicates:j,saveUrlForRecurrentUploads:j,groupOutput:j,userAgentIntegration:Y},ar=l((s,i)=>{if(!(typeof i=="undefined"||i===null))return ko[s](i)},"normalizeConfigValue");var Ri=Object.keys(Ze),Io=["metadata"],Oo=l(s=>Io.includes(s),"isComplexKey"),cs=Ri.filter(s=>!Oo(s)),Lo={...Object.fromEntries(cs.map(s=>[ot(s),s])),...Object.fromEntries(cs.map(s=>[s.toLowerCase(),s]))},Ro={...Object.fromEntries(Ri.map(s=>[ot(s),et(s)])),...Object.fromEntries(Ri.map(s=>[s.toLowerCase(),et(s)]))},ce=class extends y{constructor(){super();u(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Ze).map(([t,e])=>[et(t),e]))}}initCallback(){super.initCallback();for(let t of Ri){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,cs.includes(t)){let o=[...new Set([ot(t),t.toLowerCase()])];for(let a of o)typeof n=="undefined"||n===null?this.removeAttribute(a):this.setAttribute(a,n.toString())}this.$[et(t)]!==n&&(typeof n=="undefined"||n===null?this.$[et(t)]=Ze[t]:this.$[et(t)]=n)},get:()=>this.$[et(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=Lo[t],o=ar(n,r),a=o!=null?o:Ze[n],c=this;c[n]=a}};l(ce,"Config");ce.bindAttributes(Ro);var Ht=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};l(Ht,"Icon");Ht.template=``;Ht.bindAttributes({name:"name",size:"size"});var Uo="https://ucarecdn.com",Wt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Uo},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var cr=l(s=>[...new Set(s)],"uniqueArray");var Je="--lr-img-",hr="unresolved",he=2,ue=3,ur=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),pr=Object.create(null),dr;for(let s in Wt)pr[Je+s]=((dr=Wt[s])==null?void 0:dr.default)||"";var Qe=class extends Nt{constructor(){super(...arguments);u(this,"cssInit$",pr)}$$(t){return this.$[Je+t]}set$$(t){for(let e in t)this.$[Je+e]=t[e]}sub$$(t,e){this.sub(Je+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!ur&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return O(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Wt.format.default}`,`quality/${this.$$("quality")||Wt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(ur&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return I(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(I(kt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(I(kt(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(I(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(I(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?Be(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),a=r?"":e*Math.round(n.height);return o||a?`${o||""}x${a||""}`:null}_setupEventProxy(t){let e=l(n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},"proxifyEvent"),r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(hr,""),this.img.onload=()=>{this.img.removeAttribute(hr)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Wt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?cr(D(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*he+"x")}") ${n*he}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*ue+"x")}") ${n*ue}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,he))}") ${he}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,ue))}") ${ue}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*he+"x")+` ${e*he}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*ue+"x")+` ${e*ue}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null)}static get observedAttributes(){return Object.keys(Wt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[Je+t]=r})}};l(Qe,"ImgBase");var ti=class extends Qe{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};l(ti,"Img");var de=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};l(de,"SimpleBtn");de.template=``;var ei=class extends _{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};l(ei,"StartFrom");function Po(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=l(r=>{r.type!=="loadend"&&t.abort(),i(!1)},"onLoad");t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}l(Po,"checkIsDirectory");function Mo(s,i){return new Promise(t=>{let e=0,r=[],n=l(a=>{a||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),a.isFile?(e++,a.file(c=>{e--;let h=new File([c],c.name,{type:c.type||i});r.push(h),e===0&&t(r)})):a.isDirectory&&o(a.createReader())},"readEntry"),o=l(a=>{e++,a.readEntries(c=>{e--;for(let h of c)n(h);e===0&&t(r)})},"readReaderContent");n(s)})}l(Mo,"readEntryContentAsync");function fr(s){let i=[],t=[];for(let e=0;e{i.push(...c)}));continue}let o=r.getAsFile();t.push(Po(o).then(a=>{a||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}l(fr,"getDropItems");var H={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},mr=["focus"],No=100,hs=new Map;function Do(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}l(Do,"distance");function us(s){let i=0,t=document.body,e=new Set,r=l(m=>e.add(m),"handleSwitch"),n=H.INACTIVE,o=l(m=>{s.shouldIgnore()&&m!==H.INACTIVE||(n!==m&&e.forEach(b=>b(m)),n=m)},"setState"),a=l(()=>i>0,"isDragging");r(m=>s.onChange(m));let c=l(()=>{i=0,o(H.INACTIVE)},"onResetEvent"),h=l(()=>{i+=1,n===H.INACTIVE&&o(H.ACTIVE)},"onDragEnter"),d=l(()=>{i-=1,a()||o(H.INACTIVE)},"onDragLeave"),p=l(m=>{m.preventDefault(),i=0,o(H.INACTIVE)},"onDrop"),f=l(m=>{a()||(i+=1),m.preventDefault();let b=[m.x,m.y],S=s.element.getBoundingClientRect(),$=Math.floor(Do(b,S)),T=${if(s.shouldIgnore())return;m.preventDefault();let b=await fr(m.dataTransfer);s.onItems(b),o(H.INACTIVE)},"onElementDrop");return t.addEventListener("drop",p),t.addEventListener("dragleave",d),t.addEventListener("dragenter",h),t.addEventListener("dragover",f),s.element.addEventListener("drop",g),mr.forEach(m=>{window.addEventListener(m,c)}),()=>{hs.delete(s.element),t.removeEventListener("drop",p),t.removeEventListener("dragleave",d),t.removeEventListener("dragenter",h),t.removeEventListener("dragover",f),s.element.removeEventListener("drop",g),mr.forEach(m=>{window.removeEventListener(m,c)})}}l(us,"addDropzone");var Xt=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,state:H.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return e&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!e})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:typeof e=="string"})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:typeof e=="string"})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:typeof e=="string"})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=us({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:st.DROP_AREA});return}this.addFileFromObject(r,{source:st.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":_.activities.UPLOAD_LIST}),this.setForCtxTarget(N.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=us({element:t,onChange:e=>{var n;let r=(n=Object.entries(H).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var n;let r=(n=Object.entries(H).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=D(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,n;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};l(Xt,"DropArea");Xt.template=`
{{text}}
`;Xt.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Fo="src-type-",qt=class extends v{constructor(){super(...arguments);u(this,"_registeredTypes",{});u(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:_.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:_.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:_.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:_.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:a,activityParams:c={}}=e;this.applyL10nKey("src-type",`${Fo}${r}`),this.$.iconName=n,this.onclick=h=>{(a?a(h):!!o)&&this.set$({"*currentActivityParams":c,"*currentActivity":o})}}};l(qt,"SourceBtn");qt.template=`
`;qt.bindAttributes({type:null});var ii=class extends y{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=D(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};l(ii,"SourceList");function gr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}l(gr,"createSvgBlobUrl");function _r(s="#fff",i="rgba(0, 0, 0, .1)"){return gr(``)}l(_r,"checkerboardCssBg");function si(s="hsl(209, 21%, 65%)",i=32,t=32){return gr(``)}l(si,"fileCssBg");function br(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,a)=>{r.onload=()=>{let c=r.height/r.width;c>1?(t.width=i,t.height=i*c):(t.height=i,t.width=i/c),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(h=>{if(!h){a();return}let d=URL.createObjectURL(h);o(d)})},r.onerror=c=>{a(c)}});return r.src=URL.createObjectURL(s),n}l(br,"generateThumb");var W=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),nt=class extends v{constructor(){super();u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",k(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",k(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:W.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===_.activities.DETAILS)?this.$["*currentActivity"]=_.activities.DETAILS:this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);L.emit(new F({type:P.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=W.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=W.FAILED:t.getValue("validationMultipleLimitMsg")?e=W.LIMIT_OVERFLOW:t.getValue("isUploading")?e=W.UPLOADING:t.getValue("fileInfo")&&(e=W.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(I(kt(this.cfg.cdnCname,this._entry.getValue("uuid")),O(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await br(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",si(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",si(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{nt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),nt.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===W.FAILED,isLimitOverflow:t===W.LIMIT_OVERFLOW,isUploading:t===W.UPLOADING,isFinished:t===W.FINISHED,progressVisible:t===W.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===W.FAILED||t===W.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===W.FINISHED&&(this.$.badgeIcon="badge-success"),t===W.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),nt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,a;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(c=>!c.getValue("fileInfo"));L.emit(new F({type:P.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let c=new AbortController;t.setValue("abortController",c);let h=l(async()=>{let p=await this.getUploadClientOptions();return Qi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...p,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let g=f.value*100;t.setValue("uploadProgress",g)}this.$.progressUnknown=!f.isComputable},signal:c.signal})},"uploadTask"),d=await this.$["*uploadQueue"].add(h);t.setMultipleValues({fileInfo:d,isUploading:!1,fileName:d.originalFilename,fileSize:d.size,isImage:d.isImage,mimeType:(a=(o=(n=d.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?a:d.mimeType,uuid:d.uuid,cdnUrl:d.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(c){console.warn("Upload error",c),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),c instanceof U?c.isCancel||t.setValue("uploadError",c):t.setValue("uploadError",new Error("Unexpected error"))}}};l(nt,"FileItem");nt.template=`
{{itemName}}{{errorText}}
`;nt.activeInstances=new Set;var ri=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}};l(ri,"UiMessage");var pe=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};l(pe,"MessageBox");pe.template=`
{{captionTxt}}
{{msgTxt}}
`;var fe=class extends v{constructor(){super();u(this,"couldBeUploadCollectionOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",_.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",k(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));L.emit(new F({type:P.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var d,p;let t=!!this.cfg.multiple,e=t?(d=this.cfg.multipleMin)!=null?d:0:1,r=t?(p=this.cfg.multipleMax)!=null?p:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!a,tooFew:o,tooMany:a,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new ri,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let g of t){let m=this.uploadCollection.read(g);m.getValue("fileInfo")&&!m.getValue("validationErrorMsg")&&(r.succeed+=1),m.getValue("isUploading")&&(r.uploading+=1),(m.getValue("validationErrorMsg")||m.getValue("uploadError"))&&(r.failed+=1),m.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:a}=this._validateFilesCount(),c=r.failed===0&&r.limitOverflow===0,h=!1,d=!1,p=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?h=!0:(d=!0,p=r.total===r.succeed&&n&&c),this.set$({doneBtnVisible:d,doneBtnEnabled:p,uploadBtnVisible:h,addMoreBtnEnabled:r.total===0||!o&&!a,addMoreBtnVisible:!a||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=l(r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})},"localizedText");return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};l(fe,"UploadList");fe.template=`{{headerText}}
`;var me=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.URL);u(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:st.URL_TAB}),this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};l(me,"UrlSource");me.template=`
`;var ds=l(()=>typeof navigator.permissions!="undefined","canUsePermissionsApi");var ge=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.CAMERA);u(this,"_unsubPermissions",null);u(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:ds(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});u(this,"_onActivate",l(()=>{ds()&&this._subscribePermissions(),this._capture()},"_onActivate"));u(this,"_onDeactivate",l(()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()},"_onDeactivate"));u(this,"_handlePermissionsChange",l(()=>{this._capture()},"_handlePermissionsChange"));u(this,"_setPermissionsState",k(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:st.CAMERA}),this.set$({"*currentActivity":_.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};l(ge,"CameraSource");ge.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var ni=class extends v{};l(ni,"UploadCtxProvider");var _e=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.DETAILS);u(this,"pauseRender",!0);u(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=_.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=si(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=qe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=l((n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))},"tmpSub");r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let a=I(n,O("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(a))}})})}};l(_e,"UploadDetails");_e.template=`
{{fileSize}}
{{errorTxt}}
`;var Ui=class{constructor(){u(this,"captionL10nStr","confirm-your-action");u(this,"messageL10Str","are-you-sure");u(this,"confirmL10nStr","yes");u(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}};l(Ui,"UiConfirmation");var be=class extends _{constructor(){super(...arguments);u(this,"activityType",_.activities.CONFIRMATION);u(this,"_defaults",new Ui);u(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":_.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};l(be,"ConfirmationDialog");be.template=`{{activityCaption}}
{{messageTxt}}
`;var ye=class extends v{constructor(){super(...arguments);u(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};l(ye,"ProgressBarCommon");ye.template=``;var ve=class extends y{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};l(ve,"ProgressBar");ve.template='
';var Z="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var Gt=class extends y{constructor(){super();u(this,"init$",{...this.init$,checkerboard:!1,src:Z})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${_r()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Z}};l(Gt,"FilePreview");Gt.template='';Gt.bindAttributes({checkerboard:"checkerboard"});var yr="--cfg-ctx-name",R=class extends y{get cfgCssCtxName(){return this.getCssData(yr,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(yr,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:A.getCtx(this.cfgCtxName)}}};l(R,"CloudImageEditorBase");function vr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}l(vr,"normalize");function V(...s){let i=vr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}l(V,"classNames");function Cr(s,...i){let t=vr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}l(Cr,"applyClassNames");var J={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function Vo(s,i){if(typeof i=="number")return J[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&J[s]!==i?`${s}`:"";if(s==="filter"){if(!i||J[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}l(Vo,"transformationToStr");var xr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function It(s){return Li(...xr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return Vo(i,t)}).filter(i=>!!i))}l(It,"transformationsToOperations");var Pi=Li("format/auto","progressive/yes"),wt=l(([s])=>typeof s!="undefined"?Number(s):void 0,"asNumber"),wr=l(()=>!0,"asBoolean"),Bo=l(([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),"asFilter"),zo=l(([s,i])=>({dimensions:D(s,"x").map(Number),coords:D(i).map(Number)}),"asCrop"),jo={enhance:wt,brightness:wt,exposure:wt,gamma:wt,contrast:wt,saturation:wt,vibrance:wt,warmth:wt,filter:Bo,mirror:wr,flip:wr,rotate:wt,crop:zo};function Tr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!xr.includes(e))continue;let n=jo[e],o=n(r);i[e]=o}return i}l(Tr,"operationsToTransformations");function Er(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Z,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"","presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Z,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=O(It(i)),r=I(t,O(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}l(Er,"initState");var Ar=`
Network error
{{fileType}}
{{msg}}
`;var B={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},Mi=[B.CROP,B.SLIDERS,B.FILTERS],$r=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],Sr=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],kr=["rotate","mirror","flip"],ut={brightness:{zero:J.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:J.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:J.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:J.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:J.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:J.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:J.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:J.enhance,range:[0,100],keypointsNumber:1},filter:{zero:J.filter,range:[0,100],keypointsNumber:1}};var rt=class extends R{constructor(){super();u(this,"_debouncedShowLoader",k(this._showLoader.bind(this),300));this.init$={...this.init$,...Er(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([a])=>{a.contentRect.width>0&&a.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===B.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Qs(this.$.cdnUrl);this.$["*originalUrl"]=kt(this.$.cdnUrl,t);let e=tr(this.$.cdnUrl),r=Tr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=kt(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=I(this.$["*originalUrl"],O("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===B.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Z&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Z)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=Oi(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=V("image",{image_hidden_to_cropper:t===B.CROP,image_hidden_effects:t!==B.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=O(It(t)),n=I(e,O(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};l(rt,"CloudImageEditorBlock"),u(rt,"className","cloud-image-editor");rt.template=Ar;rt.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset"});var Ce=class extends R{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=C&&t.width<=C)return!0;let e=t.height<=C&&(i.includes("n")||i.includes("s")),r=t.width<=C&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],a=it("mask",{id:"backdrop-mask"}),c=it("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=it("rect",{x:t,y:e,width:r,height:n,fill:"black"});a.appendChild(c),a.appendChild(h);let d=it("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(d),o.appendChild(a),this._backdropMask=a,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&zt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,a=e==="",c=e.length===2,{x:h,y:d,width:p,height:f}=i;if(a){let m={x:h+p/3,y:d+f/3,width:p/3,height:f/3};zt(n,m)}else{let m=St(Math.min(p,f)/(24*2+34)/2,0,1),{d:b,center:S}=c?zs(i,e,m):js(i,e,m),$=Math.max(rs*St(Math.min(p,f)/rs/3,0,1),Bs);zt(n,{x:S[0]-$,y:S[1]-$,width:$*2,height:$*2}),zt(r,{d:b})}let g=this._shouldThumbBeDisabled(e);o.setAttribute("class",V("thumb",{"thumb--hidden":g,"thumb--visible":!g}))}zt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=it("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=it("rect",{fill:"transparent"}),a=it("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(a),n.appendChild(o),i[r]={direction:r,pathNode:a,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=it("svg"),t=it("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=it("line",{x1:`${We*e}%`,y1:"0%",x2:`${We*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=it("line",{x1:"0%",y1:`${We*e}%`,x2:"100%",y2:`${We*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),a=t.x-n,c=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[a,c],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,a=n-this._dragStartPoint[0],c=o-this._dragStartPoint[1],{direction:h}=this._draggingThumb,d=this._calcCropBox(h,[a,c]);d&&(this.$["*cropBox"]=d)}_calcCropBox(i,t){var h,d;let[e,r]=t,n=this.$["*imageBox"],o=(h=this._dragStartCrop)!=null?h:this.$["*cropBox"],a=(d=this.$["*cropPresetList"])==null?void 0:d[0],c=a?a.width/a.height:void 0;if(i===""?o=Ws({rect:o,delta:[e,r],imageBox:n}):o=Xs({rect:o,delta:[e,r],direction:i,aspectRatio:c,imageBox:n}),!Object.values(o).every(p=>Number.isFinite(p)&&p>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return oe(ae(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return qs(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Hs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",V("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=C||i.width<=C,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",V({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};l(Ce,"CropFrame");Ce.template='';var dt=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=V({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};l(dt,"EditorButtonControl");dt.template=`
{{title}}
`;function Wo(s){let i=s+90;return i=i>=360?0:i,i}l(Wo,"nextAngle");function Xo(s,i){return s==="rotate"?Wo(i):["mirror","flip"].includes(s)?!i:null}l(Xo,"nextValue");var Ot=class extends dt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Xo(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};l(Ot,"EditorCropButtonControl");var oi={FILTER:"filter",COLOR_OPERATION:"color_operation"},pt="original",we=class extends R{constructor(){super(...arguments);u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?oi.FILTER:oi.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===pt?void 0:this.$.value,filter:this._filter===pt?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=ut[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===oi.FILTER){let a=n;if(o){let{name:c,amount:h}=o;a=c===this._filter?h:n}this.$.value=a,this.$.defaultValue=a}if(this._controlType===oi.COLOR_OPERATION){let a=typeof o!="undefined"?o:e;this.$.value=a,this.$.defaultValue=a}}apply(){let t;this._controlType===oi.FILTER?this._filter===pt?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};l(we,"EditorSlider");we.template=``;function li(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:l(()=>{i.naturalWidth===0&&(i.src=Z)},"cancel")}}l(li,"preloadImage");function ai(s){let i=[];for(let n of s){let o=li(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:l(()=>{i.forEach(n=>{n.cancel()})},"cancel")}}l(ai,"batchPreloadImages");var xt=class extends dt{constructor(){super(...arguments);u(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,a={...this.$["*editorTransformations"]};return a[this._operation]=this._filter!==pt?{name:this._filter,amount:o}:void 0,I(this._originalUrl,O(Pi,It(a),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:a,cancel:c}=li(n);this._cancelPreload=c,a.catch(h=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:h})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===pt,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};l(xt,"EditorFilterControl");xt.template=`
`;var Lt=class extends dt{constructor(){super(...arguments);u(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=ut[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};l(Lt,"EditorOperationControl");var Ir=l((s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}},"throttle");function Or(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}l(Or,"pick");function xe(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return I(s,O(Pi,It(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}l(xe,"viewerImageSrc");function qo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}l(qo,"validateCrop");var Te=class extends R{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=k(this._commit.bind(this),300),this._handleResizeThrottled=Ir(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=Or(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=le({width:i.naturalWidth,height:i.naturalHeight},r),a;if(o.width>n.width-t*2||o.height>n.height-t*2){let c=o.width/o.height,h=n.width/n.height;if(c>h){let d=n.width-t*2,p=d/c,f=0+t,g=t+(n.height-t*2)/2-p/2;a={x:f,y:g,width:d,height:p}}else{let d=n.height-t*2,p=d*c,f=t+(n.width-t*2)/2-p/2,g=0+t;a={x:f,y:g,width:p,height:d}}}else{let{width:c,height:h}=o,d=t+(n.width-t*2)/2-c/2,p=t+(n.height-t*2)/2-h/2;a={x:d,y:p,width:c,height:h}}this.$["*imageBox"]=ae(a)}_alignCrop(){var h;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:a,y:c}=this.$["*imageBox"];if(n){let{dimensions:[d,p],coords:[f,g]}=n,{width:m}=le(this._imageSize,r),b=o/m;i=oe(ae({x:a+f*b,y:c+g*b,width:d*b,height:p*b}),this.$["*imageBox"])}if(!n||!Gs(i,t)){let d=(h=this.$["*cropPresetList"])==null?void 0:h[0],p=d?d.width/d.height:void 0,f=t.width/t.height,g=t.width,m=t.height;p&&(f>p?g=Math.min(t.height*p,t.width):m=Math.min(t.width/p,t.height)),i={x:t.x+t.width/2-g/2,y:t.y+t.height/2-m/2,width:g,height:m}}this.$["*cropBox"]=oe(ae(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:a}=r,c=le({width:e.width,height:e.height},a);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(a*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-c.width/2,-c.height/2,c.width,c.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=V({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:a,height:c}=le(this._imageSize,r),{width:h,height:d}=i,p=n/a,f=o/c;return[St(Math.round(h/p),1,a),St(Math.round(d/f),1,c)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:a,y:c}=t,{width:h,height:d}=le(this._imageSize,r),{x:p,y:f}=i,g=n/h,m=o/d,b=this._getCropDimensions(),S={dimensions:b,coords:[St(Math.round((p-a)/g),0,h-b[0]),St(Math.round((f-c)/m),0,d-b[1])]};if(!qo(S)){console.error("Cropper is trying to create invalid crop object",{payload:S});return}if(!(b[0]===h&&b[1]===d))return S}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),a={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=a}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=V({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(xe(i,e,t)),{promise:n,cancel:o,image:a}=li(r),c=this._handleImageLoading(r);return a.addEventListener("load",c,{once:!0}),a.addEventListener("error",c,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>a).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(a)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};l(Te,"EditorImageCropper");Te.template=``;function ps(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}l(ps,"linspace");function Go(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}l(Ko,"calculateOpacities");function Yo(s,i){return s.map((t,e)=>tn-o)}l(Lr,"keypointsRange");var ci=class extends R{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=k(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(xe(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=l(()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(c=>c.value===e),"shouldSkip");if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let a=this._handleImageLoading(n.src);o.addEventListener("load",a,{once:!0}),o.addEventListener("error",a,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let c=this._keypoints,h=c.findIndex(p=>p.value>e),d=h{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=ut[i],r=this._keypoints.map(a=>a.value),n=Ko(r,t,e),o=Yo(r,e);for(let[a,c]of Object.entries(this._keypoints))c.opacity=n[a],c.zIndex=o[a];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(h=>h.src),{images:r,promise:n,cancel:o}=ai(e);r.forEach(h=>{let d=this._handleImageLoading(h.src);h.addEventListener("load",d),h.addEventListener("error",d)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let a=this._operation,c=this._filter;await n,this._isActive&&this._isSame(a,c)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((h,d)=>{let p=r[d];p.classList.add("fader-image"),h.image=p,this._container.appendChild(p)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Lr(e,r).map(c=>this._imageSrc({url:i,filter:t,operation:e,value:c})),{cancel:a}=ai(o);this._cancelBatchPreload=a}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=V({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=V({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let a=this._imageSrc({operation:t,value:e});this._setOriginalSrc(a),this._container&&this._container.remove();return}this._keypoints=Lr(t,e).map(a=>this._constructKeypoint(t,a)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=V({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};l(ci,"EditorImageFader");var Zo=1,Ee=class extends R{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Zo?this.scrollLeft+=e:this.scrollLeft+=t})}};l(Ee,"EditorScroller");Ee.template=" ";function Jo(s){return``}l(Jo,"renderTabToggle");function Qo(s){return`
`}l(Qo,"renderTabContent");var Ae=class extends R{constructor(){super();u(this,"_updateInfoTooltip",k(()=>{var n,o;let t=this.$["*editorTransformations"],e="",r=!1;if(this.$["*tabId"]===B.FILTERS)if(r=!0,this.$["*currentFilter"]&&((n=t==null?void 0:t.filter)==null?void 0:n.name)===this.$["*currentFilter"]){let a=((o=t==null?void 0:t.filter)==null?void 0:o.amount)||100;e=this.l10n(this.$["*currentFilter"])+" "+a}else e=this.l10n(pt);else if(this.$["*tabId"]===B.SLIDERS&&this.$["*currentOperation"]){r=!0;let a=(t==null?void 0:t[this.$["*currentOperation"]])||ut[this.$["*currentOperation"]].zero;e=this.$["*currentOperation"]+" "+a}r&&(this.$["*operationTooltip"]=e),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",r)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":pt,"*currentOperation":null,"*tabId":B.CROP,showLoader:!1,filters:Sr,colorOperations:$r,cropOperations:kr,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":t=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":t=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":t=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":t=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=k(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===B.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=Lt.is&&new Lt;return e.operation=t,e}_createFilterControl(t){let e=xt.is&&new xt;return e.filter=t,e}_createToggleControl(t){let e=Ot.is&&new Ot;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===B.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===B.FILTERS?[pt,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===B.SLIDERS&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),r.childNodes.forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===B.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of Mi){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(xe(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=ai([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",t=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this._updateInfoTooltip()}};l(Ae,"EditorToolbar");Ae.template=`
{{*operationTooltip}}
${Mi.map(Qo).join("")}
${Mi.map(Jo).join("")}
`;var Yt=class extends y{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return V("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};l(Yt,"LrBtnUi");Yt.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Yt.template=`
{{text}}
`;var $e=class extends y{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};l($e,"LineLoaderUi");$e.template=`
`;var Ni={transition:"transition",visible:"visible",hidden:"hidden"},Se=class extends y{constructor(){super(),this._visible=!1,this._visibleStyle=Ni.visible,this._hiddenStyle=Ni.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",Cr(this,{[Ni.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(Ni.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};l(Se,"PresenceToggle");Se.template=" ";var ke=class extends y{constructor(){super();u(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let a=document.createDocumentFragment(),c=document.createElement("div"),h=document.createElement("div");c.className="minor-step",h.className="border-step",a.appendChild(h);for(let p=0;p
`;var hi=class extends v{constructor(){super(...arguments);u(this,"activityType",_.activities.CLOUD_IMG_EDIT);u(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new rt,e=this.$.cdnUrl,r=this.cfg.cropPreset;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),t.addEventListener("apply",n=>this.handleApply(n)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};l(hi,"CloudImageEditorActivity");var tl=l(function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},"escapeRegExp"),Rr=l(function(s,i="i"){let t=s.split("*").map(tl);return new RegExp("^"+t.join(".+")+"$",i)},"wildcardRegexp");var el=l(s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,a)=>{let c=r[a];return o+`${a}: ${c};`},"");return t+`${e}{${n}}`},""),"styleToCss");function Ur({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return el({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}l(Ur,"buildStyles");var Rt={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in Rt){let t=Rt[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Pr=l(function(s,i,t){s in Rt||(Rt[s]=[]),Rt[s].push([i,t])},"registerMessage"),Mr=l(function(s,i){s in Rt&&(Rt[s]=Rt[s].filter(t=>t[0]!==i))},"unregisterMessage");function Nr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}l(Nr,"queryString");var Ie=class extends v{constructor(){super();u(this,"activityType",_.activities.EXTERNAL);u(this,"_iframe",null);u(this,"updateCssData",l(()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())},"updateCssData"));u(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=_.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=D(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Rr(r);for(let[o,a]of Object.entries(t.alternatives))if(n.test(o))return a}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Ur(t)})}remoteUrl(){var a,c;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((c=(a=this.getCssData("--l10n-locale-name"))==null?void 0:a.split("-"))==null?void 0:c[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Nr(n),o.toString()}mountIframe(){let t=Ve({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Pr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Mr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};l(Ie,"ExternalSource");Ie.template=`
{{activityCaption}}
{{counter}}
`;var Zt=class extends y{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;D(i).forEach(e=>{let r=Ve({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};l(Zt,"Tabs");Zt.bindAttributes({"tab-list":null,default:null});Zt.template=`
`;var Ut=class extends v{constructor(){super(...arguments);u(this,"processInnerHtml",!0);u(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Ut.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Ns(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};l(Ut,"DataOutput");Ut.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ui=class extends _{};l(ui,"ActivityHeader");var Oe=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};l(Oe,"Select");Oe.template=``;var K={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Dr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},Q=class extends y{constructor(){super(...arguments);u(this,"init$",{...this.init$,src:"",ppIcon:K.PLAY,fsIcon:K.FS_ON,volIcon:K.VOL_ON,capIcon:K.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Dr.exitFullscreen():Dr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===K.CAP_OFF?(this.$.capIcon=K.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(Q.is+":captions","1")):(this.$.capIcon=K.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(Q.is+":captions"))}toggleSound(){this.$.volIcon===K.VOL_ON?(this.$.volIcon=K.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=K.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(Q.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(Q.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=K.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=K.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=K.FS_OFF:this.$.fsIcon=K.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(Q.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};l(Q,"Video");Q.template=`
{{currentTime}} / {{totalTime}}
`;Q.bindAttributes({video:"video",src:"src"});var il="css-src";function di(s){return class extends s{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(il);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}l(di,"shadowed");var Jt=class extends di(y){};l(Jt,"ShadowWrapper");var Le=class extends y{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};l(Le,"Copyright"),u(Le,"template",`Powered by Uploadcare`);var Tt=class extends Jt{constructor(){super(...arguments);u(this,"init$",$i(this));u(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};l(Tt,"SolutionBlock");var Re=class extends Tt{};l(Re,"FileUploaderRegular");Re.template=``;var Ue=class extends Tt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=_.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||_.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};l(Ue,"FileUploaderMinimal");Ue.template=``;var Pe=class extends Tt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||_.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||_.activities.START_FROM)&&(this.$["*currentActivity"]=_.activities.UPLOAD_LIST)})}};l(Pe,"FileUploaderInline");Pe.template=``;var pi=class extends di(rt){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};l(pi,"CloudImageEditor");function Di(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}l(Di,"registerBlocks");var fs="LR";async function Fr(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[fs]){t(window[fs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[fs];i&&Di(n),t(n)},document.head.appendChild(r)})}l(Fr,"connectBlocksFrom");return qr(sl);})(); \ No newline at end of file diff --git a/web/blocks.min.js b/web/blocks.min.js index e46c306df..077d09a06 100644 --- a/web/blocks.min.js +++ b/web/blocks.min.js @@ -23,5 +23,5 @@ * SOFTWARE. * */ -var Ur=Object.defineProperty;var Pr=(s,i,t)=>i in s?Ur(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var c=(s,i,t)=>(Pr(s,typeof i!="symbol"?i+"":i,t),t),wi=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var N=(s,i,t)=>(wi(s,i,"read from private field"),t?t.call(s):i.get(s)),Ot=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},te=(s,i,t,e)=>(wi(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var Ee=(s,i,t)=>(wi(s,i,"access private method"),t);var Mr=Object.defineProperty,Nr=(s,i,t)=>i in s?Mr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,Ei=(s,i,t)=>(Nr(s,typeof i!="symbol"?i+"":i,t),t);function Dr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=Dr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var y=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),ds="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Br=ds.length-1,ie=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{ai&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Vr(s,i){[...s.querySelectorAll(`[${y.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(y.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let n=t.innerHTML;r.template=n,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let o=t.getAttribute(y.REPEAT_ATTR);i.sub(o,n=>{if(!n){for(;t.firstChild;)t.firstChild.remove();return}let a=[...t.children],l,u=h=>{h.forEach((p,f)=>{if(a[f])if(a[f].set$)setTimeout(()=>{a[f].set$(p)});else for(let m in p)a[f][m]=p[m];else{l||(l=new DocumentFragment);let m=new r;Object.assign(m.init$,p),l.appendChild(m)}}),l&&t.appendChild(l);let d=a.slice(h.length,a.length);for(let p of d)p.remove()};if(n.constructor===Array)u(n);else if(n.constructor===Object){let h=[];for(let d in n){let p=n[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),h.push(p)}u(h)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),t.removeAttribute(y.REPEAT_ATTR),t.removeAttribute(y.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function zr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let o=r.getAttribute("name")||us;e[o]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var o;let n=us;r instanceof Element&&r.hasAttribute("slot")&&(n=r.getAttribute("slot"),r.removeAttribute("slot")),(o=e[n])==null||o.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(o,r.slot)}else r.slot.remove()})}function jr(s,i){[...s.querySelectorAll(`[${y.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(y.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(y.EL_REF_ATTR)})}function Hr(s,i){[...s.querySelectorAll(`[${y.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(y.BIND_ATTR).split(";");[...t.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=Fr(o.name.replace("-",""));r.push(n+":"+o.value),t.removeAttribute(o.name)}}),r.forEach(o=>{if(!o)return;let n=o.split(":").map(h=>h.trim()),a=n[0],l;a.indexOf(y.ATTR_BIND_PRFX)===0&&(l=!0,a=a.replace(y.ATTR_BIND_PRFX,""));let u=n[1].split(",").map(h=>h.trim());for(let h of u){let d;h.startsWith("!!")?(d="double",h=h.replace("!!","")):h.startsWith("!")&&(d="single",h=h.replace("!","")),i.sub(h,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),l?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(a,""):t.removeAttribute(a):t.setAttribute(a,p):ps(t,a,p)||(t[y.SET_LATER_KEY]||(t[y.SET_LATER_KEY]=Object.create(null)),t[y.SET_LATER_KEY][a]=p)})}}),t.removeAttribute(y.BIND_ATTR)})}var Ae="{{",ee="}}",Wr="skip-text";function Xr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var o;return!((o=r.parentElement)!=null&&o.hasAttribute(Wr))&&r.textContent.includes(Ae)&&r.textContent.includes(ee)&&1}});for(;i=e.nextNode();)t.push(i);return t}var qr=function(s,i){Xr(s).forEach(e=>{let r=[],o;for(;e.textContent.includes(ee);)e.textContent.startsWith(Ae)?(o=e.textContent.indexOf(ee)+ee.length,e.splitText(o),r.push(e)):(o=e.textContent.indexOf(Ae),e.splitText(o)),e=e.nextSibling;r.forEach(n=>{let a=n.textContent.replace(Ae,"").replace(ee,"");n.textContent="",i.sub(a,l=>{n.textContent=l})})})},Gr=[Vr,zr,jr,Hr,qr],Se="'",Vt='"',Kr=/\\([0-9a-fA-F]{1,6} ?)/g;function Yr(s){return(s[0]===Vt||s[0]===Se)&&(s[s.length-1]===Vt||s[s.length-1]===Se)}function Zr(s){return(s[0]===Vt||s[0]===Se)&&(s=s.slice(1)),(s[s.length-1]===Vt||s[s.length-1]===Se)&&(s=s.slice(0,-1)),s}function Jr(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=Jr(i),i=Vt+i+Vt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var hs=0,Ft=null,mt=null,Ct=class extends HTMLElement{constructor(){super(),Ei(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return Ct}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(y.USE_TPL);if(r){let o=this.getRootNode(),n=(o==null?void 0:o.querySelector(r))||document.querySelector(r);n?s=n.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ie.generate(),this.style.setProperty(y.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(y.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(y.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(y.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(y.EXT_DATA_CTX_PRFX,"");else if(s.includes(y.NAMED_DATA_CTX_SPLTR)){let r=s.split(y.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=o=>{this.isConnected&&i(o)},r=Ct.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=Ct.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=Ct.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=Ct.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=Ct.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=Ct.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(y.CTX_OWNER_ATTR)&&this.getAttribute(y.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(y.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(y.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(y.NAMED_DATA_CTX_SPLTR)){let t=i.split(y.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let o=E.getCtx(e,!1);o||(o=E.registerCtx({},e)),o.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(y.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(y.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[y.SET_LATER_KEY]){for(let t in this[y.SET_LATER_KEY])ps(this,t,this[y.SET_LATER_KEY][t]);delete this[y.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Gr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${y.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(y.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);mt==null||mt.delete(this.updateCssData),mt!=null&&mt.size||(Ft==null||Ft.disconnect(),Ft=null,mt=null)},100)))}static reg(s,i=!1){s||(hs++,s=`${y.AUTO_TAG_PRFX}-${hs}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Qr(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){mt||(mt=new Set),mt.add(this.updateCssData),Ft||(Ft=new MutationObserver(s=>{s[0].type==="attributes"&&mt.forEach(i=>{i()})}),Ft.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=Ct;Ei(zt,"template");var Ti=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Ti.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let o in i)i[o]===!0?e+=this.separator+o:e+=this.separator+o+`=${i[o]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Ti.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Ti.appMap=Object.create(null);function to(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function eo(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function se(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&eo(i,s.attributes),s.styles&&to(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=se(t);i.appendChild(e)}),i}var ms="idb-store-ready",io="symbiote-db",so="symbiote-idb-update_",ro=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return so+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?e(o.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=o=>{r(o)}})}write(s,i,t=!1){let e={_key:s,_value:i},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((n,a)=>{o.onsuccess=l=>{t||this._notifySubscribers(s),n(l.target.result)},o.onerror=l=>{a(l)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,o)=>{e.onsuccess=n=>{i||this._notifySubscribers(s),r(n)},e.onerror=n=>{o(n)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let o=r.target.result;t(o.map(n=>n._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,fs.clear(this.name)}},fs=class{static get readyEventName(){return ms}static open(s=io,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new ro(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Ei(fs,"_reg",Object.create(null));function G(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var oo="--uploadcare-blocks-window-height",$e="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Ai(){return typeof window[$e]=="undefined"?!1:!!window[$e]}function gs(){if(Ai())return;let s=()=>{document.documentElement.style.setProperty(oo,`${window.innerHeight}px`),window[$e]=!0},i=G(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[$e]=!1,window.removeEventListener("resize",i)}}var no=s=>s,Si="{{",bs="}}",_s="plural:";function re(s,i,t={}){var n;let{openToken:e=Si,closeToken:r=bs,transform:o=no}=t;for(let a in i){let l=(n=i[a])==null?void 0:n.toString();s=s.replaceAll(e+a+r,typeof l=="string"?o(l):l)}return s}function vs(s){let i=[],t=s.indexOf(Si);for(;t!==-1;){let e=s.indexOf(bs,t),r=s.substring(t+2,e);if(r.startsWith(_s)){let o=s.substring(t+2,e).replace(_s,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));i.push({variable:r,pluralKey:n,countVariable:a})}t=s.indexOf(Si,e)}return i}function ys(s){return Object.prototype.toString.call(s)==="[object Object]"}var ao=/\W|_/g;function lo(s){return s.split(ao).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Cs(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>gt(t,{ignoreKeys:i})):s}function gt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return Cs(s,{ignoreKeys:i});if(!ys(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ys(r)?r=gt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=Cs(r,{ignoreKeys:i})),t[lo(e)]=r}return t}var co=s=>new Promise(i=>setTimeout(i,s));function Ui({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let o="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:o,integration:r});let n=[s,i,e].filter(Boolean).join("/"),a=[o,r].filter(Boolean).join("; ");return`${n} (${a})`}var uo={factor:2,time:100};function ho(s,i=uo){let t=0;function e(r){let o=Math.round(i.time*i.factor**t);return r({attempt:t,retry:a=>co(a!=null?a:o).then(()=>(t+=1,e(r)))})}return e(s)}var qt=class extends Error{constructor(t){super();c(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,qt.prototype),this.originalProgressEvent=t}},Oe=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},xt=class extends Error{constructor(t="Request canceled"){super(t);c(this,"isCancel",!0);Object.setPrototypeOf(this,xt.prototype)}},po=500,ws=({check:s,interval:i=po,timeout:t,signal:e})=>new Promise((r,o)=>{let n,a;Oe(e,()=>{n&&clearTimeout(n),o(new xt("Poll cancelled"))}),t&&(a=setTimeout(()=>{n&&clearTimeout(n),o(new xt("Timed out"))},t));let l=()=>{try{Promise.resolve(s(e)).then(u=>{u?(a&&clearTimeout(a),r(u)):n=setTimeout(l,i)}).catch(u=>{a&&clearTimeout(a),o(u)})}catch(u){a&&clearTimeout(a),o(u)}};n=setTimeout(l,0)}),T={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Re="application/octet-stream",Ts="original",Tt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:o})=>new Promise((n,a)=>{let l=new XMLHttpRequest,u=(s==null?void 0:s.toUpperCase())||"GET",h=!1;l.open(u,i,!0),e&&Object.entries(e).forEach(d=>{let[p,f]=d;typeof f!="undefined"&&!Array.isArray(f)&&l.setRequestHeader(p,f)}),l.responseType="text",Oe(r,()=>{h=!0,l.abort(),a(new xt)}),l.onload=()=>{if(l.status!=200)a(new Error(`Error ${l.status}: ${l.statusText}`));else{let d={method:u,url:i,data:t,headers:e||void 0,signal:r,onProgress:o},p=l.getAllResponseHeaders().trim().split(/[\r\n]+/),f={};p.forEach(function(x){let A=x.split(": "),w=A.shift(),C=A.join(": ");w&&typeof w!="undefined"&&(f[w]=C)});let m=l.response,b=l.status;n({request:d,data:m,headers:f,status:b})}},l.onerror=d=>{h||a(new qt(d))},o&&typeof o=="function"&&(l.upload.onprogress=d=>{d.lengthComputable?o({isComputable:!0,value:d.loaded/d.total}):o({isComputable:!1})}),t?l.send(t):l.send()});function mo(s,...i){return s}var fo=({name:s})=>s?[s]:[],go=mo,_o=()=>new FormData,Es=s=>!1,Le=s=>typeof Blob!="undefined"&&s instanceof Blob,Ue=s=>typeof File!="undefined"&&s instanceof File,Pe=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",oe=s=>Le(s)||Ue(s)||Es()||Pe(s),bo=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",vo=s=>!!s&&typeof s=="object"&&!Array.isArray(s),yo=s=>!!s&&typeof s=="object"&&"data"in s&&oe(s.data);function Co(s,i,t){if(yo(t)){let{name:e,contentType:r}=t,o=go(t.data,e,r!=null?r:Re),n=fo({name:e,contentType:r});s.push([i,o,...n])}else if(vo(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else bo(t)&&t&&s.push([i,t.toString()])}function xo(s){let i=[];for(let[t,e]of Object.entries(s))Co(i,t,e);return i}function Pi(s){let i=_o(),t=xo(s);for(let e of t){let[r,o,...n]=e;i.append(r,o,...n)}return i}var R=class extends Error{constructor(t,e,r,o,n){super();c(this,"isCancel");c(this,"code");c(this,"request");c(this,"response");c(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=o,this.headers=n,Object.setPrototypeOf(this,R.prototype)}},wo=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var o;return(o=r[1])!=null?o:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=wo(t)),e.toString()},To="6.6.1",Eo="UploadcareUploadClient",Ao=To;function Ut(s){return Ui({libraryName:Eo,libraryVersion:Ao,...s})}var So="RequestThrottledError",xs=15e3,$o=1e3;function ko(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return xs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:xs}function Et(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return ho(({attempt:r,retry:o})=>s().catch(n=>{if("response"in n&&(n==null?void 0:n.code)===So&&r{let i="";return(Le(s)||Ue(s)||Pe(s))&&(i=s.type),i||Re},Ss=s=>{let i="";return Ue(s)&&s.name?i=s.name:Le(s)||Es()?i="":Pe(s)&&s.name&&(i=s.name),i||Ts};function Mi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Io(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=T.baseURL,secureSignature:o,secureExpire:n,store:a,signal:l,onProgress:u,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=T.retryNetworkErrorMaxTimes,metadata:b}){return Et(()=>Tt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:d,userAgent:p})},data:Pi({file:{data:s,name:t||Ss(s),contentType:e||As(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Mi(a),signature:o,expire:n,source:h,metadata:b}),signal:l,onProgress:u}).then(({data:x,headers:A,request:w})=>{let C=gt(JSON.parse(x));if("error"in C)throw new R(C.error.content,C.error.errorCode,w,C,A);return C}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var Ii;(function(s){s.Token="token",s.FileInfo="file_info"})(Ii||(Ii={}));function Oo(s,{publicKey:i,baseURL:t=T.baseURL,store:e,fileName:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,source:u="url",signal:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=T.retryNetworkErrorMaxTimes,metadata:b}){return Et(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Mi(e),filename:r,check_URL_duplicates:o?1:void 0,save_URL_duplicates:n?1:void 0,signature:a,expire:l,source:u,metadata:b}),signal:h}).then(({data:x,headers:A,request:w})=>{let C=gt(JSON.parse(x));if("error"in C)throw new R(C.error.content,C.error.errorCode,w,C,A);return C}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var X;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(X||(X={}));var Ro=s=>"status"in s&&s.status===X.Error;function Lo(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}={}){return Et(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Ut({publicKey:i,integration:r,userAgent:o})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:l,headers:u,request:h})=>{let d=gt(JSON.parse(l));if("error"in d&&!Ro(d))throw new R(d.error.content,void 0,h,d,u);return d}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:n})}function Uo(s,{publicKey:i,baseURL:t=T.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:o,signal:n,source:a,integration:l,userAgent:u,retryThrottledRequestMaxTimes:h=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:l,userAgent:u})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:o,source:a}),signal:n}).then(({data:p,headers:f,request:m})=>{let b=gt(JSON.parse(p));if("error"in b)throw new R(b.error.content,b.error.errorCode,m,b,f);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function $s(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,source:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:o,userAgent:n})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:u,headers:h,request:d})=>{let p=gt(JSON.parse(u));if("error"in p)throw new R(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function Po(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=T.multipartChunkSize,baseURL:o="",secureSignature:n,secureExpire:a,store:l,signal:u,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=T.retryNetworkErrorMaxTimes,metadata:b}){return Et(()=>Tt({method:"POST",url:ft(o,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:d,userAgent:p})},data:Pi({filename:e||Ts,size:s,content_type:t||Re,part_size:r,UPLOADCARE_STORE:Mi(l),UPLOADCARE_PUB_KEY:i,signature:n,expire:a,source:h,metadata:b}),signal:u}).then(({data:x,headers:A,request:w})=>{let C=gt(JSON.parse(x));if("error"in C)throw new R(C.error.content,C.error.errorCode,w,C,A);return C.parts=Object.keys(C.parts).map(H=>C.parts[H]),C}),{retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})}function Mo(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:o=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:n=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Re}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n})}function No(s,{publicKey:i,baseURL:t=T.baseURL,source:e="local",signal:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:o,userAgent:n})},data:Pi({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:u,headers:h,request:d})=>{let p=gt(JSON.parse(u));if("error"in p)throw new R(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function Ni({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a,signal:l,onProgress:u}){return ws({check:h=>$s(s,{publicKey:i,baseURL:t,signal:h,source:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a}).then(d=>d.isReady?d:(u&&u({isComputable:!0,value:1}),!1)),signal:l})}var wt=class{constructor(i,{baseCDN:t=T.baseCDN,fileName:e}={}){c(this,"uuid");c(this,"name",null);c(this,"size",null);c(this,"isStored",null);c(this,"isImage",null);c(this,"mimeType",null);c(this,"cdnUrl",null);c(this,"s3Url",null);c(this,"originalFilename",null);c(this,"imageInfo",null);c(this,"videoInfo",null);c(this,"contentInfo",null);c(this,"metadata",null);c(this,"s3Bucket",null);let{uuid:r,s3Bucket:o}=i,n=ft(t,`${r}/`),a=o?ft(`https://${o}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=n,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=o||null,this.s3Url=a}},Do=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:n,contentType:a,signal:l,onProgress:u,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:x})=>Io(s,{publicKey:i,fileName:t,contentType:a,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:l,onProgress:u,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,metadata:x}).then(({file:A})=>Ni({file:A,publicKey:i,baseURL:e,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,onProgress:u,signal:l})).then(A=>new wt(A,{baseCDN:b})),Bo=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:o,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:u,retryNetworkErrorMaxTimes:h,baseCDN:d})=>$s(s,{publicKey:i,baseURL:e,signal:r,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:u,retryNetworkErrorMaxTimes:h}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(o&&o({isComputable:!0,value:1}),p)),Fo=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),o=n=>()=>{e=n,r.forEach((a,l)=>l!==n&&a.abort())};return Oe(i,()=>{r.forEach(n=>n.abort())}),Promise.all(s.map((n,a)=>{let l=o(a);return Promise.resolve().then(()=>n({stopRace:l,signal:r[a].signal})).then(u=>(l(),u)).catch(u=>(t=u,null))})).then(n=>{if(e===null)throw t;return n[e]})},Vo=window.WebSocket,Oi=class{constructor(){c(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},zo=(s,i)=>s==="success"?{status:X.Success,...i}:s==="progress"?{status:X.Progress,...i}:{status:X.Error,...i},Ri=class{constructor(i,t=3e4){c(this,"key");c(this,"disconnectTime");c(this,"ws");c(this,"queue",[]);c(this,"isConnected",!1);c(this,"subscribers",0);c(this,"emmitter",new Oi);c(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Vo(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,zo(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},$i=null,Di=s=>{if(!$i){let i=typeof window=="undefined"?0:3e4;$i=new Ri(s,i)}return $i},jo=s=>{Di(s).connect()};function Ho({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,onProgress:a,signal:l}){return ws({check:u=>Lo(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,signal:u}).then(h=>{switch(h.status){case X.Error:return new R(h.error,h.errorCode);case X.Waiting:return!1;case X.Unknown:return new R(`Token "${s}" was not found.`);case X.Progress:return a&&(h.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:h.done/h.total})),!1;case X.Success:return a&&a({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:l})}var Wo=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,o)=>{let n=Di(i),a=n.onError(o),l=()=>{a(),n.unsubscribe(s)};Oe(t,()=>{l(),o(new xt("pusher cancelled"))}),n.subscribe(s,u=>{switch(u.status){case X.Progress:{e&&(u.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:u.done/u.total}));break}case X.Success:{l(),e&&e({isComputable:!0,value:u.done/u.total}),r(u);break}case X.Error:l(),o(new R(u.msg,u.error_code))}})}),Xo=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:u,signal:h,onProgress:d,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,pusherKey:x=T.pusherKey,metadata:A})=>Promise.resolve(jo(x)).then(()=>Oo(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:u,signal:h,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,metadata:A})).catch(w=>{let C=Di(x);return C==null||C.disconnect(),Promise.reject(w)}).then(w=>w.type===Ii.FileInfo?w:Fo([({signal:C})=>Ho({token:w.token,publicKey:i,baseURL:e,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:C}),({signal:C})=>Wo({token:w.token,pusherKey:x,signal:C,onProgress:d})],{signal:h})).then(w=>{if(w instanceof R)throw w;return w}).then(w=>Ni({file:w.uuid,publicKey:i,baseURL:e,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:h})).then(w=>new wt(w,{baseCDN:r})),ki=new WeakMap,qo=async s=>{if(ki.has(s))return ki.get(s);let i=await fetch(s.uri).then(t=>t.blob());return ki.set(s,i),i},ks=async s=>{if(Ue(s)||Le(s))return s.size;if(Pe(s))return(await qo(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Go=(s,i=T.multipartMinFileSize)=>s>=i,Is=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!oe(s)&&t.test(s)},Os=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!oe(s)&&t.test(s)},Ko=(s,i)=>new Promise((t,e)=>{let r=[],o=!1,n=i.length,a=[...i],l=()=>{let u=i.length-a.length,h=a.shift();h&&h().then(d=>{o||(r[u]=d,n-=1,n?l():t(r))}).catch(d=>{o=!0,e(d)})};for(let u=0;u{let r=e*i,o=Math.min(r+e,t);return s.slice(r,o)},Zo=async(s,i,t)=>e=>Yo(s,e,i,t),Jo=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:o,integration:n,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})=>Mo(s,i,{publicKey:t,contentType:e,onProgress:r,signal:o,integration:n,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l}),Qo=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:o,secureExpire:n,store:a,signal:l,onProgress:u,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:b,multipartChunkSize:x=T.multipartChunkSize,maxConcurrentRequests:A=T.maxConcurrentRequests,baseCDN:w,metadata:C})=>{let H=e!=null?e:await ks(s),ht,It=(O,Z)=>{if(!u)return;ht||(ht=Array(O).fill(0));let dt=W=>W.reduce((pt,xi)=>pt+xi,0);return W=>{W.isComputable&&(ht[Z]=W.value,u({isComputable:!0,value:dt(ht)/O}))}};return b||(b=As(s)),Po(H,{publicKey:i,contentType:b,fileName:t||Ss(s),baseURL:r,secureSignature:o,secureExpire:n,store:a,signal:l,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,metadata:C}).then(async({uuid:O,parts:Z})=>{let dt=await Zo(s,H,x);return Promise.all([O,Ko(A,Z.map((W,pt)=>()=>Jo(dt(pt),W,{publicKey:i,contentType:b,onProgress:It(Z.length,pt),signal:l,integration:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})))])}).then(([O])=>No(O,{publicKey:i,baseURL:r,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})).then(O=>O.isReady?O:Ni({file:O.uuid,publicKey:i,baseURL:r,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,onProgress:u,signal:l})).then(O=>new wt(O,{baseCDN:w}))};async function Bi(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,contentType:m,multipartMinFileSize:b,multipartChunkSize:x,maxConcurrentRequests:A,baseCDN:w=T.baseCDN,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:H,pusherKey:ht,metadata:It}){if(oe(s)){let O=await ks(s);return Go(O,b)?Qo(s,{publicKey:i,contentType:m,multipartChunkSize:x,fileSize:O,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,baseCDN:w,metadata:It}):Do(s,{publicKey:i,fileName:t,contentType:m,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,baseCDN:w,metadata:It})}if(Os(s))return Xo(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:w,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:H,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,pusherKey:ht,metadata:It});if(Is(s))return Bo(s,{publicKey:i,fileName:t,baseURL:e,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,baseCDN:w});throw new TypeError(`File uploading from "${s}" is not supported`)}var Li=class{constructor(i,t){c(this,"uuid");c(this,"filesCount");c(this,"totalSize");c(this,"isStored");c(this,"isImage");c(this,"cdnUrl");c(this,"files");c(this,"createdAt");c(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},tn=s=>{for(let i of s)if(!oe(i))return!1;return!0},en=s=>{for(let i of s)if(!Is(i))return!1;return!0},sn=s=>{for(let i of s)if(!Os(i))return!1;return!0};function Rs(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,contentType:m,multipartChunkSize:b=T.multipartChunkSize,baseCDN:x=T.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:w,jsonpCallback:C}){if(!tn(s)&&!sn(s)&&!en(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let H,ht=!0,It=s.length,O=(Z,dt)=>{if(!l)return;H||(H=Array(Z).fill(0));let W=pt=>pt.reduce((xi,Lr)=>xi+Lr)/Z;return pt=>{if(!pt.isComputable||!ht){ht=!1,l({isComputable:!1});return}H[dt]=pt.value,l({isComputable:!0,value:W(H)})}};return Promise.all(s.map((Z,dt)=>Bi(Z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:O(It,dt),source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,contentType:m,multipartChunkSize:b,baseCDN:x,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:w}))).then(Z=>{let dt=Z.map(W=>W.uuid);return Uo(dt,{publicKey:i,baseURL:e,jsonpCallback:C,secureSignature:r,secureExpire:o,signal:a,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f}).then(W=>new Li(W,Z)).then(W=>(l&&l({isComputable:!0,value:1}),W))})}var Rt,jt,Lt,Ht,Wt,Xt,ke,Ie=class{constructor(i){Ot(this,Xt);Ot(this,Rt,1);Ot(this,jt,[]);Ot(this,Lt,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);te(this,Rt,i)}add(i){return new Promise((t,e)=>{N(this,Ht).set(i,t),N(this,Wt).set(i,e),N(this,jt).push(i),Ee(this,Xt,ke).call(this)})}get pending(){return N(this,jt).length}get running(){return N(this,Lt)}set concurrency(i){te(this,Rt,i),Ee(this,Xt,ke).call(this)}get concurrency(){return N(this,Rt)}};Rt=new WeakMap,jt=new WeakMap,Lt=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,ke=function(){let i=N(this,Rt)-N(this,Lt);for(let t=0;t{N(this,Ht).delete(e),N(this,Wt).delete(e),te(this,Lt,N(this,Lt)-1),Ee(this,Xt,ke).call(this)}).then(n=>r(n)).catch(n=>o(n))}};var Fi=()=>({"*blocksRegistry":new Set}),Vi=s=>({...Fi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Me=s=>({...Vi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Ie(1)});function Ls(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let n=e.split(":");r=n[0],e=n[1]}let o="l10n:"+e;i.__l10nKeys.push(o),i.add(o,e),i.sub(o,n=>{t[r]=i.l10n(n)}),t.removeAttribute("l10n")})}var L=s=>`*cfg/${s}`;var _t=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Us=new Set;function Ne(s){Us.has(s)||(Us.add(s),console.warn(s))}var De=(s,i)=>new Intl.PluralRules(s).select(i);var zi="lr-",_=class extends zt{constructor(){super();c(this,"allowCustomTemplate",!0);c(this,"init$",Fi());c(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Ls),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,o=vs(r);for(let a of o)e[a.variable]=this.pluralize(a.pluralKey,Number(e[a.countVariable]));return re(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",o=De(r,e);return this.l10n(`${t}__${o}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setForCtxTarget(t,e,r){this.hasBlockInCtx(o=>o.constructor.StateConsumerScope===t)&&(this.$[e]=r)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${zi}${t}`,!0),Ai()||(this._destroyInnerHeightTracker=gs()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],o=u=>this.getCssData("--l10n-unit-"+u.toLowerCase(),!0)||u;if(t===0)return`0 ${o(r[0])}`;let n=1024,a=e<0?0:e,l=Math.floor(Math.log(t)/Math.log(n));return parseFloat((t/n**l).toFixed(a))+" "+o(r[l])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?re(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let o=L(r),n=this.parseCfgProp(o);return n.ctx.has(n.name)?n.ctx.read(n.name):(Ne("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${_t(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(L(t));r.ctx.has(r.name)?this.sub(L(t),e):(this.bindCssData(`--cfg-${_t(t)}`),this.sub(`--cfg-${_t(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(zi)?t:zi+t)}};c(_,"StateConsumerScope",null),c(_,"className","");var ji=class extends _{constructor(){super(...arguments);c(this,"_handleBackdropClick",()=>{this._closeDialog()});c(this,"_closeDialog",()=>{this.setForCtxTarget(ji.StateConsumerScope,"*modalActive",!1)});c(this,"_handleDialogClose",()=>{this._closeDialog()});c(this,"_handleDialogClick",t=>{t.target===this.ref.dialog&&this._closeDialog()});c(this,"init$",{...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose})}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("click",this._handleDialogClick);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogClick)}},F=ji;c(F,"StateConsumerScope","modal");F.template=``;var Ps="active",ne="___ACTIVITY_IS_ACTIVE___",rt=class extends _{constructor(){super(...arguments);c(this,"historyTracked",!1);c(this,"init$",Vi(this));c(this,"_debouncedHistoryFlush",G(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=rt._activityRegistry[this.activityKey];this[ne]=!1,this.removeAttribute(Ps),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=rt._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[ne]=!0,this.setAttribute(Ps,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[ne]?this._deactivate():this.activityType===t&&!this[ne]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!rt._activityRegistry[this.activityKey]}get isActivityActive(){return this[ne]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:o}=e;rt._activityRegistry||(rt._activityRegistry=Object.create(null)),rt._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:o}}unregisterActivity(){this.isActivityActive&&this._deactivate(),rt._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(rt._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!1)}}},g=rt;c(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var U=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var ae=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Hi=s=>s?s.filter(i=>typeof i=="string").map(i=>U(i)).flat():[],Wi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),Ms=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),le=s=>{let i=s==null?void 0:s.type;return i?Wi(i,ae):!1};var Ns=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var Ds="blocks",Bs="0.25.6";function Fs(s){return Ui({...s,libraryName:Ds,libraryVersion:Bs})}var Vs="[Typed State] Wrong property name: ",rn="[Typed State] Wrong property type: ",Be=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||ie.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Vs+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(rn+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Vs+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Fe=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||ie.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(o=>{o({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Be(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var k={UPLOAD_START:"UPLOAD_START",REMOVE:"REMOVE",UPLOAD_PROGRESS:"UPLOAD_PROGRESS",UPLOAD_FINISH:"UPLOAD_FINISH",UPLOAD_ERROR:"UPLOAD_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",CDN_MODIFICATION:"CLOUD_MODIFICATION",DATA_OUTPUT:"DATA_OUTPUT",DONE_FLOW:"DONE_FLOW",INIT_FLOW:"INIT_FLOW"},D=class{constructor(i){this.ctx=i.ctx,this.type=i.type,this.data=i.data}},$=class{static eName(i){return"LR_"+i}static emit(i,t=window,e=!0){let r=()=>{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let o=i.type+i.ctx;this._timeoutStore[o]&&window.clearTimeout(this._timeoutStore[o]),this._timeoutStore[o]=window.setTimeout(()=>{r(),delete this._timeoutStore[o]},20)}};c($,"_timeoutStore",Object.create(null));var J=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var ot=1e3,Pt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ce=s=>Math.ceil(s*100)/100,zs=(s,i=Pt.AUTO)=>{let t=i===Pt.AUTO;if(i===Pt.BYTE||t&&s{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(o=>[...o]).flat())].map(o=>e.read(o)).filter(Boolean);for(let o of r)this._runValidatorsForEntry(o);if(t.uploadProgress){let o=0,n=e.findItems(l=>!l.getValue("uploadError"));n.forEach(l=>{o+=e.readProp(l,"uploadProgress")});let a=Math.round(o/n.length);this.$["*commonProgress"]=a,$.emit(new D({type:k.UPLOAD_PROGRESS,ctx:this.ctxName,data:a}),void 0,a===100)}if(t.fileInfo){let o=e.findItems(a=>!!a.getValue("fileInfo")),n=e.findItems(a=>!!a.getValue("uploadError")||!!a.getValue("validationErrorMsg"));if(e.size-n.length===o.length){let a=this.getOutputData(l=>!!l.getValue("fileInfo")&&!l.getValue("silentUpload"));a.length>0&&$.emit(new D({type:k.UPLOAD_FINISH,ctx:this.ctxName,data:a}))}}t.uploadError&&e.findItems(n=>!!n.getValue("uploadError")).forEach(n=>{$.emit(new D({type:k.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(n,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(n=>!!n.getValue("validationErrorMsg")).forEach(n=>{$.emit(new D({type:k.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(n,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(n=>!!n.getValue("cdnUrlModifiers")).forEach(n=>{$.emit(new D({type:k.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(n).store}),void 0,!1)})})}setUploadMetadata(t){Ne("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Fe({typedSchema:Ns,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,o)=>{var n;this._runValidators();for(let a of o)(n=a==null?void 0:a.getValue("abortController"))==null||n.abort(),a==null||a.setValue("abortController",null),URL.revokeObjectURL(a==null?void 0:a.getValue("thumbUrl"));this.$["*uploadList"]=e.map(a=>({uid:a}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:o!=null?o:J.API})}addFileFromUuid(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:o!=null?o:J.API})}addFileFromObject(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({file:t,isImage:le(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:o!=null?o:J.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:le(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Hi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?ae:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=ae.join(",")):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(o=>this.addFileFromObject(o,{source:J.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=U(this.cfg.sourceList)),t}initFlow(t=!1){var e,r;if((e=this.$["*uploadList"])!=null&&e.length&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let o=this.sourceList[0];o==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(o)?this.set$({"*currentActivityParams":{externalSourceType:o},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=o,this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0);$.emit(new D({type:k.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!1),$.emit(new D({type:k.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,o=Hi([...e?ae:[],r]);if(!o.length)return;let n=t.getValue("mimeType"),a=t.getValue("fileName");if(!n||!a)return;let l=Wi(n,o),u=Ms(a,o);if(!l&&!u)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:zs(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),o=this.cfg.multiple?this.cfg.multipleMax:1;if(o&&r>=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Fs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(o=>{let n=E.getCtx(o).store,a=n.fileInfo||{name:n.fileName,fileSize:n.fileSize,isImage:n.isImage,mimeType:n.mimeType},l={...a,cdnUrlModifiers:n.cdnUrlModifiers,cdnUrl:n.cdnUrl||a.cdnUrl};e.push(l)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(k).forEach(s=>{let i=$.eName(s);window.addEventListener(i,t=>{if([k.UPLOAD_FINISH,k.REMOVE,k.CDN_MODIFICATION].includes(t.detail.type)){let r=E.getCtx(t.detail.ctx),o=r.read("uploadCollection"),n=[];o.items().forEach(a=>{let l=E.getCtx(a).store,u=l.fileInfo;if(u){let h={...u,cdnUrlModifiers:l.cdnUrlModifiers,cdnUrl:l.cdnUrl||u.cdnUrl};n.push(h)}}),$.emit(new D({type:k.DATA_OUTPUT,ctx:t.detail.ctx,data:n})),r.pub("outputData",n)}})});var on="https://ucarecdn.com",nn="https://upload.uploadcare.com",an="https://social.uploadcare.com",ue=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:on,baseUrl:nn,socialBaseUrl:an,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var Q=s=>String(s),nt=s=>Number(s),V=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,ln=s=>s==="auto"?s:V(s),cn={pubkey:Q,multiple:V,multipleMin:nt,multipleMax:nt,confirmUpload:V,imgOnly:V,accept:Q,externalSourcesPreferredTypes:Q,store:ln,cameraMirror:V,sourceList:Q,maxLocalFileSizeBytes:nt,thumbSize:nt,showEmptyList:V,useLocalImageEditor:V,useCloudImageEditor:V,removeCopyright:V,modalScrollLock:V,modalBackdropStrokes:V,sourceListWrap:V,remoteTabSessionKey:Q,cdnCname:Q,baseUrl:Q,socialBaseUrl:Q,secureSignature:Q,secureExpire:Q,secureDeliveryProxy:Q,retryThrottledRequestMaxTimes:nt,multipartMinFileSize:nt,multipartChunkSize:nt,maxConcurrentRequests:nt,multipartMaxConcurrentRequests:nt,multipartMaxAttempts:nt,checkForUrlDuplicates:V,saveUrlForRecurrentUploads:V,groupOutput:V,userAgentIntegration:Q},js=(s,i)=>{if(!(typeof i=="undefined"||i===null))return cn[s](i)};var Ve=Object.keys(ue),un=["metadata"],hn=s=>un.includes(s),Xi=Ve.filter(s=>!hn(s)),dn={...Object.fromEntries(Xi.map(s=>[_t(s),s])),...Object.fromEntries(Xi.map(s=>[s.toLowerCase(),s]))},pn={...Object.fromEntries(Ve.map(s=>[_t(s),L(s)])),...Object.fromEntries(Ve.map(s=>[s.toLowerCase(),L(s)]))},ze=class extends _{constructor(){super(...arguments);c(this,"ctxOwner",!0);c(this,"init$",{...this.init$,...Object.fromEntries(Object.entries(ue).map(([t,e])=>[L(t),e]))})}initCallback(){super.initCallback();for(let t of Ve){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:o=>{if(e[r]=o,Xi.includes(t)){let n=[...new Set([_t(t),t.toLowerCase()])];for(let a of n)typeof o=="undefined"||o===null?this.removeAttribute(a):this.setAttribute(a,o.toString())}this.$[L(t)]!==o&&(typeof o=="undefined"||o===null?this.$[L(t)]=ue[t]:this.$[L(t)]=o)},get:()=>this.$[L(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let o=dn[t],n=js(o,r),a=n!=null?n:ue[o],l=this;l[o]=a}};ze.bindAttributes(pn);var he=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};he.template=``;he.bindAttributes({name:"name",size:"size"});var Hs=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},je=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Hs(i)).join("/-/"),P=(...s)=>{let i=je(...s);return i?`-/${i}/`:""};function Ws(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),o="";return e>=0?o=t.slice(e):r>=0&&(o=t.slice(r+1)),o}function Xs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function qs(s){let i=Gs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(o=>Hs(o))}function Gs(s){let i=new URL(s),t=Ws(s),e=Ks(t)?Ys(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function Ks(s){return s.startsWith("http")}function Ys(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var S=(s,i,t)=>{let e=new URL(Gs(s));if(t=t||Ws(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Ks(t)){let r=Ys(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var mn="https://ucarecdn.com",Mt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:mn},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var Zs=s=>[...new Set(s)];var de="--lr-img-",Js="unresolved",Gt=2,Kt=3,Qs=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),er=Object.create(null),tr;for(let s in Mt)er[de+s]=((tr=Mt[s])==null?void 0:tr.default)||"";var He=class extends zt{constructor(){super(...arguments);c(this,"cssInit$",er)}$$(t){return this.$[de+t]}set$$(t){for(let e in t)this.$[de+e]=t[e]}sub$$(t,e){this.sub(de+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!Qs&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return P(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Mt.format.default}`,`quality/${this.$$("quality")||Mt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(Qs&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return S(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(S(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(S(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(S(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(S(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?re(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let o=t.getBoundingClientRect(),n=e*Math.round(o.width),a=r?"":e*Math.round(o.height);return n||a?`${n||""}x${a||""}`:null}_setupEventProxy(t){let e=o=>{o.stopPropagation();let n=new Event(o.type,o);this.dispatchEvent(n)},r=["load","error"];for(let o of r)t.addEventListener(o,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(Js,""),this.img.onload=()=>{this.img.removeAttribute(Js)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Mt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?Zs(U(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(o=>{e.add(`url("${this._getUrlBase(o+"x")}") ${o}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(o*Gt+"x")}") ${o*Gt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(o*Kt+"x")}") ${o*Kt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Gt))}") ${Gt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Kt))}") ${Kt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Gt+"x")+` ${e*Gt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Kt+"x")+` ${e*Kt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(o=>{o.forEach(n=>{n.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null)}static get observedAttributes(){return Object.keys(Mt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[de+t]=r})}};var qi=class extends He{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var We=class extends v{constructor(){super(...arguments);c(this,"init$",{...this.init$,"*simpleButtonText":"",onClick:()=>{this.initFlow()}})}initCallback(){super.initCallback(),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};We.template=``;var Gi=class extends g{constructor(){super(...arguments);c(this,"historyTracked",!0);c(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function fn(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function gn(s,i){return new Promise(t=>{let e=0,r=[],o=a=>{a||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),a.isFile?(e++,a.file(l=>{e--;let u=new File([l],l.name,{type:l.type||i});r.push(u),e===0&&t(r)})):a.isDirectory&&n(a.createReader())},n=a=>{e++,a.readEntries(l=>{e--;for(let u of l)o(u);e===0&&t(r)})};o(s)})}function ir(s){let i=[],t=[];for(let e=0;e{i.push(...l)}));continue}let n=r.getAsFile();t.push(fn(n).then(a=>{a||i.push(n)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(o=>{r.getAsString(n=>{i.push(n),o()})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},sr=["focus"],_n=100,Ki=new Map;function bn(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Yi(s){let i=0,t=document.body,e=new Set,r=m=>e.add(m),o=z.INACTIVE,n=m=>{s.shouldIgnore()&&m!==z.INACTIVE||(o!==m&&e.forEach(b=>b(m)),o=m)},a=()=>i>0;r(m=>s.onChange(m));let l=()=>{i=0,n(z.INACTIVE)},u=()=>{i+=1,o===z.INACTIVE&&n(z.ACTIVE)},h=()=>{i-=1,a()||n(z.INACTIVE)},d=m=>{m.preventDefault(),i=0,n(z.INACTIVE)},p=m=>{a()||(i+=1),m.preventDefault();let b=[m.x,m.y],x=s.element.getBoundingClientRect(),A=Math.floor(bn(b,x)),w=A<_n,C=m.composedPath().includes(s.element);Ki.set(s.element,A);let H=Math.min(...Ki.values())===A;n(C&&H?z.OVER:w&&H?z.NEAR:z.ACTIVE)},f=async m=>{if(s.shouldIgnore())return;m.preventDefault();let b=await ir(m.dataTransfer);s.onItems(b),n(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",h),t.addEventListener("dragenter",u),t.addEventListener("dragover",p),s.element.addEventListener("drop",f),sr.forEach(m=>{window.addEventListener(m,l)}),()=>{Ki.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",h),t.removeEventListener("dragenter",u),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",f),sr.forEach(m=>{window.removeEventListener(m,l)})}}var pe=class extends v{constructor(){super(...arguments);c(this,"init$",{...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),o=window.getComputedStyle(this),n=o.visibility!=="hidden"&&o.display!=="none";return e&&n&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!e})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:typeof e=="string"})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:typeof e=="string"})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:typeof e=="string"})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Yi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:J.DROP_AREA});return}this.addFileFromObject(r,{source:J.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Yi({element:t,onChange:e=>{var o;let r=(o=Object.entries(z).find(([,n])=>n===e))==null?void 0:o[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var o;let r=(o=Object.entries(z).find(([,n])=>n===e))==null?void 0:o[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=U(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,o;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(o=this._destroyContentWrapperDropzone)==null||o.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};pe.template=`
{{text}}
`;pe.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var vn="src-type-",me=class extends v{constructor(){super(...arguments);c(this,"_registeredTypes",{});c(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:o=t,activity:n,onClick:a,activityParams:l={}}=e;this.applyL10nKey("src-type",`${vn}${r}`),this.$.iconName=o,this.onclick=u=>{(a?a(u):!!n)&&this.set$({"*currentActivityParams":l,"*currentActivity":n})}}};me.template=`
`;me.bindAttributes({type:null});var Zi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=U(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function rr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function or(s="#fff",i="rgba(0, 0, 0, .1)"){return rr(``)}function fe(s="hsl(209, 21%, 65%)",i=32,t=32){return rr(``)}function nr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,o=new Promise((n,a)=>{r.onload=()=>{let l=r.height/r.width;l>1?(t.width=i,t.height=i*l):(t.height=i,t.width=i/l),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(u=>{if(!u){a();return}let h=URL.createObjectURL(u);n(h)})},r.onerror=l=>{a(l)}});return r.src=URL.createObjectURL(s),o}var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),bt=class extends v{constructor(){super(...arguments);c(this,"pauseRender",!0);c(this,"_entrySubs",new Set);c(this,"_entry",null);c(this,"_isIntersecting",!1);c(this,"_debouncedGenerateThumb",G(this._generateThumbnail.bind(this),100));c(this,"_debouncedCalculateState",G(this._calculateState.bind(this),100));c(this,"_renderedOnce",!1);c(this,"init$",{...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);$.emit(new D({type:k.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}})}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,o=this.proxyUrl(S(At(this.cfg.cdnCname,this._entry.getValue("uuid")),P(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),n=t.getValue("thumbUrl");n!==o&&(t.setValue("thumbUrl",o),n!=null&&n.startsWith("blob:")&&URL.revokeObjectURL(n));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await nr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let o=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",fe(o))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",fe(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,o=>{this.isConnected&&e(o)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",o=>{this.$.progressValue=o}),this._subEntry("fileName",o=>{this.$.itemName=o||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",o=>{this.$.itemName=e.getValue("fileName")||o||this.l10n("file-no-name")}),this._subEntry("uuid",o=>{this._debouncedCalculateState(),o&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",o=>{this.$.thumbUrl=o?`url(${o})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{bt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),bt.activeInstances.add(this)}_handleState(t){var e,r;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&t===B.FINISHED&&((e=this._entry)==null?void 0:e.getValue("isImage")),errorText:((r=this._entry.getValue("uploadError"))==null?void 0:r.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),bt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var o,n,a;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(l=>!l.getValue("fileInfo"));$.emit(new D({type:k.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let l=new AbortController;t.setValue("abortController",l);let u=async()=>{let d=await this.getUploadClientOptions();return Bi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let f=p.value*100;t.setValue("uploadProgress",f)}this.$.progressUnknown=!p.isComputable},signal:l.signal})},h=await this.$["*uploadQueue"].add(u);t.setMultipleValues({fileInfo:h,isUploading:!1,fileName:h.originalFilename,fileSize:h.size,isImage:h.isImage,mimeType:(a=(n=(o=h.contentInfo)==null?void 0:o.mime)==null?void 0:n.mime)!=null?a:h.mimeType,uuid:h.uuid,cdnUrl:h.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(l){console.warn("Upload error",l),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),l instanceof R?l.isCancel||t.setValue("uploadError",l):t.setValue("uploadError",new Error("Unexpected error"))}}};bt.template=`
{{itemName}}{{errorText}}
`;bt.activeInstances=new Set;var Xe=class{constructor(){c(this,"caption","");c(this,"text","");c(this,"iconName","");c(this,"isError",!1)}},qe=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};qe.template=`
{{captionTxt}}
{{msgTxt}}
`;var Ge=class extends v{constructor(){super(...arguments);c(this,"couldBeUploadCollectionOwner",!0);c(this,"historyTracked",!0);c(this,"activityType",g.activities.UPLOAD_LIST);c(this,"init$",{...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));$.emit(new D({type:k.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}});c(this,"_debouncedHandleCollectionUpdate",G(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0))}_validateFilesCount(){var h,d;let t=!!this.cfg.multiple,e=t?(h=this.cfg.multipleMin)!=null?h:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,o=this.uploadCollection.size,n=e?or:!1;return{passed:!n&&!a,tooFew:n,tooMany:a,min:e,max:r,exact:r===o}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new Xe,o=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(o,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let f of t){let m=this.uploadCollection.read(f);m.getValue("fileInfo")&&!m.getValue("validationErrorMsg")&&(r.succeed+=1),m.getValue("isUploading")&&(r.uploading+=1),(m.getValue("validationErrorMsg")||m.getValue("uploadError"))&&(r.failed+=1),m.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:o,tooMany:n,exact:a}=this._validateFilesCount(),l=r.failed===0&&r.limitOverflow===0,u=!1,h=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&o?u=!0:(h=!0,d=r.total===r.succeed&&o&&l),this.set$({doneBtnVisible:h,doneBtnEnabled:d,uploadBtnVisible:u,addMoreBtnEnabled:r.total===0||!n&&!a,addMoreBtnVisible:!a||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let o=t[r];return this.l10n(`header-${r}`,{count:o})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};Ge.template=`{{headerText}}
`;var Ke=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.URL);c(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:J.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};Ke.template=`
`;var Ji=()=>typeof navigator.permissions!="undefined";var Ye=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.CAMERA);c(this,"_unsubPermissions",null);c(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Ji(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});c(this,"_onActivate",()=>{Ji()&&this._subscribePermissions(),this._capture()});c(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});c(this,"_handlePermissionsChange",()=>{this._capture()});c(this,"_setPermissionsState",G(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let o=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(o,{source:J.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,o)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${o+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};Ye.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var Qi=class extends v{};var Ze=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.DETAILS);c(this,"pauseRender",!0);c(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=fe(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(o=>{this._entrySubs.delete(o),o.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let o=le(this._file);o&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),o||this.showNonImageThumb()}let r=(o,n)=>{this._entrySubs.add(this.entry.subscribe(o,n))};r("fileName",o=>{this.$.fileName=o,this.$.onNameInput=()=>{let n=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:n}),this.entry.setValue("fileName",n)}}),r("fileSize",o=>{this.$.fileSize=Number.isFinite(o)?this.fileSizeFmt(o):this.l10n("file-size-unknown")}),r("uploadError",o=>{this.$.errorTxt=o==null?void 0:o.message}),r("externalUrl",o=>{o&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",o=>{let n=this.cfg.useCloudImageEditor&&o&&this.entry.getValue("isImage");if(o&&this.ref.filePreview.clear(),this.set$({cdnUrl:o,cloudEditBtnHidden:!n}),o&&this.entry.getValue("isImage")){let a=S(o,P("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(a))}})})}};Ze.template=`
{{fileSize}}
{{errorTxt}}
`;var ts=class{constructor(){c(this,"captionL10nStr","confirm-your-action");c(this,"messageL10Str","are-you-sure");c(this,"confirmL10nStr","yes");c(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},Je=class extends g{constructor(){super(...arguments);c(this,"activityType",g.activities.CONFIRMATION);c(this,"_defaults",new ts);c(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};Je.template=`{{activityCaption}}
{{messageTxt}}
`;var Qe=class extends v{constructor(){super(...arguments);c(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};Qe.template=``;var ti=class extends _{constructor(){super(...arguments);c(this,"_value",0);c(this,"_unknownMode",!1);c(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ti.template='
';var K="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var ge=class extends _{constructor(){super();c(this,"init$",{...this.init$,checkerboard:!1,src:K})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${or()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=K}};ge.template='';ge.bindAttributes({checkerboard:"checkerboard"});var ar="--cfg-ctx-name",I=class extends _{get cfgCssCtxName(){return this.getCssData(ar,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(ar,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function lr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function M(...s){let i=lr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function cr(s,...i){let t=lr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}function at(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var Y={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function yn(s,i){if(typeof i=="number")return Y[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Y[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Y[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var hr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function St(s){return je(...hr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yn(i,t)}).filter(i=>!!i))}var ei=je("format/auto","progressive/yes"),vt=([s])=>typeof s!="undefined"?Number(s):void 0,ur=()=>!0,Cn=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),xn=([s,i])=>({dimensions:U(s,"x").map(Number),coords:U(i).map(Number)}),wn={enhance:vt,brightness:vt,exposure:vt,gamma:vt,contrast:vt,saturation:vt,vibrance:vt,warmth:vt,filter:Cn,mirror:ur,flip:ur,rotate:vt,crop:xn};function dr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!hr.includes(e))continue;let o=wn[e],n=o(r);i[e]=n}return i}function pr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:K,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=K,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=P(St(i)),r=S(t,P(e,"preview")),o={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:o,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var mr=`
Network error
{{fileType}}
{{msg}}
`;var j={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},ii=[j.CROP,j.SLIDERS,j.FILTERS],fr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],gr=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],_r=["rotate","mirror","flip"],lt={brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}};var ct=class extends I{constructor(){super(...arguments);c(this,"init$",{...this.init$,...pr(this)});c(this,"_debouncedShowLoader",at(this._showLoader.bind(this),300))}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let o=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),n=new ResizeObserver(([a])=>{a.contentRect.width>0&&a.contentRect.height>0&&(e(),clearTimeout(o),n.disconnect())});n.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}if(this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==K&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||K)}),this.sub("*tabId",t=>{this.ref["img-el"].className=M("image",{image_hidden_to_cropper:t===j.CROP,image_hidden_effects:t!==j.CROP})}),this.$.cdnUrl){let t=Xs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=qs(this.$.cdnUrl),r=dr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{let e=this.$["*originalUrl"],r=P(St(t)),o=S(e,P(r,"preview")),n={originalUrl:e,cdnUrlModifiers:r,cdnUrl:o,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:n,bubbles:!0,composed:!0}))},!1);try{fetch(S(this.$["*originalUrl"],P("json"))).then(t=>t.json()).then(t=>{let{width:e,height:r}=t;this.$["*imageSize"]={width:e,height:r}})}catch(t){t&&console.error("Failed to load image info",t)}}};c(ct,"className","cloud-image-editor");ct.template=mr;ct.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl"});var _e=33.333333333333336,tt=24*2+34;function Nt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function et(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Nt(t,i),t}function br(s,i){let{x:t,y:e,width:r,height:o}=s,n=i.includes("w")?0:1,a=i.includes("n")?0:1,l=[-1,1][n],u=[-1,1][a],h=[t+n*r+1.5*l,e+a*o+1.5*u-24*u],d=[t+n*r+1.5*l,e+a*o+1.5*u],p=[t+n*r-24*l+1.5*l,e+a*o+1.5*u];return{d:`M ${h[0]} ${h[1]} L ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,center:d}}function vr(s,i){let{x:t,y:e,width:r,height:o}=s,n=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],l=[-1,1][n],u=[-1,1][a],h,d;["n","s"].includes(i)?(h=[t+n*r-34/2,e+a*o+1.5*u],d=[t+n*r+34/2,e+a*o+1.5*u]):(h=[t+n*r+1.5*l,e+a*o-34/2],d=[t+n*r+1.5*l,e+a*o+34/2]);let p=`M ${h[0]} ${h[1]} L ${d[0]} ${d[1]}`,f=[d[0]-(d[0]-h[0])/2,d[1]-(d[1]-h[1])/2];return{d:p,center:f}}function yr(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Cr(s,[i,t]){return{...s,x:s.x+i,y:s.y+t}}function si(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function xr(s,[i,t],e){let{x:r,y:o,width:n,height:a}=s;return e.includes("n")&&(o+=t,a-=t),e.includes("s")&&(a+=t),e.includes("w")&&(r+=i,n-=i),e.includes("e")&&(n+=i),{x:r,y:o,width:n,height:a}}function wr(s,i){let t=Math.max(s.x,i.x),e=Math.min(s.x+s.width,i.x+i.width),r=Math.max(s.y,i.y),o=Math.min(s.y+s.height,i.y+i.height);return{x:t,y:r,width:e-t,height:o-r}}function ri(s,[i,t],e){let{x:r,y:o,width:n,height:a}=s;if(e.includes("n")){let l=a;a=Math.max(t,a),o=o+l-a}if(e.includes("s")&&(a=Math.max(t,a)),e.includes("w")){let l=n;n=Math.max(i,n),r=r+l-n}return e.includes("e")&&(n=Math.max(i,n)),{x:r,y:o,width:n,height:a}}function Tr(s,[i,t]){return s.x<=i&&i<=s.x+s.width&&s.y<=t&&t<=s.y+s.height}var oi=class extends I{constructor(){super();c(this,"init$",{...this.init$,dragging:!1});this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(t){let e=this.$["*imageBox"];if(!e)return;if(t===""&&e.height<=tt&&e.width<=tt)return!0;let r=e.height<=tt&&(t.includes("n")||t.includes("s")),o=e.width<=tt&&(t.includes("e")||t.includes("w"));return r||o}_createBackdrop(){let t=this.$["*cropBox"];if(!t)return;let{x:e,y:r,width:o,height:n}=t,a=this.ref["svg-el"],l=et("mask",{id:"backdrop-mask"}),u=et("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=et("rect",{x:e,y:r,width:o,height:n,fill:"black"});l.appendChild(u),l.appendChild(h);let d=et("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});a.appendChild(d),a.appendChild(l),this._backdropMask=l,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask.style.display="block"}))}_updateBackdrop(){let t=this.$["*cropBox"];if(!t)return;let{x:e,y:r,width:o,height:n}=t;Nt(this._backdropMaskInner,{x:e,y:r,width:o,height:n})}_updateFrame(){let t=this.$["*cropBox"];if(!t)return;for(let r of Object.values(this._frameThumbs)){let{direction:o,pathNode:n,interactionNode:a,groupNode:l}=r,u=o==="",h=o.length===2;if(u){let{x:p,y:f,width:m,height:b}=t,x=[p+m/2,f+b/2];Nt(a,{r:Math.min(m,b)/3,cx:x[0],cy:x[1]})}else{let{d:p,center:f}=h?br(t,o):vr(t,o);Nt(a,{cx:f[0],cy:f[1]}),Nt(n,{d:p})}let d=this._shouldThumbBeDisabled(o);l.setAttribute("class",M("thumb",{"thumb--hidden":d,"thumb--visible":!d}))}let e=this._frameGuides;Nt(e,{x:t.x-1*.5,y:t.y-1*.5,width:t.width+1,height:t.height+1})}_createThumbs(){let t={};for(let e=0;e<3;e++)for(let r=0;r<3;r++){let o=`${["n","","s"][e]}${["w","","e"][r]}`,n=et("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let a=et("circle",{r:24+1.5,fill:"transparent"}),l=et("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(a),t[o]={direction:o,pathNode:l,interactionNode:a,groupNode:n},a.addEventListener("pointerdown",this._handlePointerDown.bind(this,o))}return t}_createGuides(){let t=et("svg"),e=et("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});t.appendChild(e);for(let r=1;r<=2;r++){let o=et("line",{x1:`${_e*r}%`,y1:"0%",x2:`${_e*r}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});t.appendChild(o)}for(let r=1;r<=2;r++){let o=et("line",{x1:"0%",y1:`${_e*r}%`,x2:"100%",y2:`${_e*r}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});t.appendChild(o)}return t.classList.add("guides","guides--semi-hidden"),t}_createFrame(){let t=this.ref["svg-el"],e=document.createDocumentFragment(),r=this._createGuides();e.appendChild(r);let o=this._createThumbs();for(let{groupNode:n}of Object.values(o))e.appendChild(n);t.appendChild(e),this._frameThumbs=o,this._frameGuides=r}_handlePointerDown(t,e){let r=this._frameThumbs[t];if(this._shouldThumbBeDisabled(t))return;let o=this.$["*cropBox"],{x:n,y:a}=this.ref["svg-el"].getBoundingClientRect(),l=e.x-n,u=e.y-a;this.$.dragging=!0,this._draggingThumb=r,this._dragStartPoint=[l,u],this._dragStartCrop={...o}}_handlePointerUp_(t){this._updateCursor(),this.$.dragging&&(t.stopPropagation(),t.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(t){if(!this.$.dragging)return;t.stopPropagation(),t.preventDefault();let e=this.ref["svg-el"],{x:r,y:o}=e.getBoundingClientRect(),n=t.x-r,a=t.y-o,l=n-this._dragStartPoint[0],u=a-this._dragStartPoint[1],{direction:h}=this._draggingThumb,d=this.$["*imageBox"],p=this._dragStartCrop;h===""?(p=Cr(p,[l,u]),p=si(p,d)):(p=xr(p,[l,u],h),p=wr(p,d));let f=[Math.min(d.width,tt),Math.min(d.height,tt)];if(p=ri(p,f,h),!Object.values(p).every(m=>Number.isFinite(m)&&m>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:p});return}this.$["*cropBox"]=p}_handleSvgPointerMove_(t){let e=Object.values(this._frameThumbs).find(r=>{if(this._shouldThumbBeDisabled(r.direction))return!1;let n=r.groupNode.getBoundingClientRect(),a={x:n.x,y:n.y,width:n.width,height:n.height};return Tr(a,[t.x,t.y])});this._hoverThumb=e,this._updateCursor()}_updateCursor(){let t=this._hoverThumb;this.ref["svg-el"].style.cursor=t?yr(t.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(t){Object.values(this._frameThumbs).map(({groupNode:e})=>e).forEach(e=>{e.setAttribute("class",M("thumb",{"thumb--hidden":!t,"thumb--visible":t}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",t=>{t&&(this._guidesHidden=t.height<=tt||t.width<=tt,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",t=>{this._frameGuides.setAttribute("class",M({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&t,"guides--semi-hidden":!this._guidesHidden&&!t}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};oi.template='';var yt=class extends I{constructor(){super(...arguments);c(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=M({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function En(s){let i=s+90;return i=i>=360?0:i,i}function An(s,i){return s==="rotate"?En(i):["mirror","flip"].includes(s)?!i:null}var Yt=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=An(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var be={FILTER:"filter",COLOR_OPERATION:"color_operation"},ut="original",ni=class extends I{constructor(){super(...arguments);c(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?be.FILTER:be.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ut?void 0:this.$.value,filter:this._filter===ut?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=lt[this._operation],[r,o]=t;this.$.min=r,this.$.max=o,this.$.zero=e;let n=this.$["*editorTransformations"][this._operation];if(this._controlType===be.FILTER){let a=o;if(n){let{name:l,amount:u}=n;a=l===this._filter?u:o}this.$.value=a,this.$.defaultValue=a}if(this._controlType===be.COLOR_OPERATION){let a=typeof n!="undefined"?n:e;this.$.value=a,this.$.defaultValue=a}}apply(){let t;this._controlType===be.FILTER?this._filter===ut?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ni.template=``;function ve(s){let i=new Image;return{promise:new Promise((r,o)=>{i.src=s,i.onload=r,i.onerror=o}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=K)}}}function ye(s){let i=[];for(let o of s){let n=ve(o);i.push(n)}let t=i.map(o=>o.image);return{promise:Promise.allSettled(i.map(o=>o.promise)),images:t,cancel:()=>{i.forEach(o=>{o.cancel()})}}}var Bt=class extends yt{constructor(){super(...arguments);c(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),o=e>=2?"lightest":"normal",n=100,a={...this.$["*editorTransformations"]};return a[this._operation]=this._filter!==ut?{name:this._filter,amount:n}:void 0,S(this._originalUrl,P(ei,St(a),`quality/${o}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let o=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"],{promise:a,cancel:l}=ve(o);this._cancelPreload=l,a.catch(u=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:u})}).finally(()=>{n.style.backgroundImage=`url(${o})`,n.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ut,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let o=this.ref["preview-el"];e?o.style.opacity="0":o.style.backgroundImage&&(o.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"];o.style.backgroundImage&&(o.style.backgroundImage="none",o.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Bt.template=`
`;var Zt=class extends yt{constructor(){super(...arguments);c(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=lt[this._operation],r=t[this._operation],o=typeof r!="undefined"?r!==e:!1;this.$.active=o})}};function Er(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Jt(s,i,t){let r=window.devicePixelRatio,o=Math.min(Math.ceil(i*r),3e3),n=r>=2?"lightest":"normal";return S(s,P(ei,St(t),`quality/${n}`,`stretch/off/-/resize/${o}x`))}function ai(s,i,t){return Math.min(Math.max(s,i),t)}function Ce({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function $n(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var li=class extends I{constructor(){super();c(this,"init$",{...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}});this._commitDebounced=at(this._commit.bind(this),300),this._handleResizeDebounced=at(this._handleResize.bind(this),10)}_handleResize(){this.isConnected&&(this.deactivate(),this.activate(this._imageSize,{fromViewer:!1}))}_syncTransformations(){let t=this.$["*editorTransformations"],e=Er(t,Object.keys(this.$["*operations"])),r={...this.$["*operations"],...e};this.$["*operations"]=r}_initCanvas(){let t=this.ref["canvas-el"],e=t.getContext("2d"),r=this.offsetWidth,o=this.offsetHeight,n=window.devicePixelRatio;t.style.width=`${r}px`,t.style.height=`${o}px`,t.width=r*n,t.height=o*n,e.scale(n,n),this._canvas=t,this._ctx=e}_alignImage(){if(!this._isActive||!this.$.image)return;let t=this.$.image,e=this.$["*padding"],r=this.$["*operations"],{rotate:o}=r,n={width:this.offsetWidth,height:this.offsetHeight},a=Ce({width:t.naturalWidth,height:t.naturalHeight},o);if(a.width>n.width-e*2||a.height>n.height-e*2){let l=a.width/a.height,u=n.width/n.height;if(l>u){let h=n.width-e*2,d=h/l,p=0+e,f=e+(n.height-e*2)/2-d/2;this.$["*imageBox"]={x:p,y:f,width:h,height:d}}else{let h=n.height-e*2,d=h*l,p=e+(n.width-e*2)/2-d/2,f=0+e;this.$["*imageBox"]={x:p,y:f,width:d,height:h}}}else{let{width:l,height:u}=a,h=e+(n.width-e*2)/2-l/2,d=e+(n.height-e*2)/2-u/2;this.$["*imageBox"]={x:h,y:d,width:l,height:u}}}_alignCrop(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,n=this.$["*editorTransformations"].crop;if(n){let{dimensions:[l,u],coords:[h,d]}=n,{width:p,x:f,y:m}=this.$["*imageBox"],{width:b}=Ce(this._imageSize,o),x=p/b;t={x:f+h*x,y:m+d*x,width:l*x,height:u*x}}else t={x:e.x,y:e.y,width:e.width,height:e.height};let a=[Math.min(e.width,tt),Math.min(e.height,tt)];t=ri(t,a,"se"),t=si(t,e),this.$["*cropBox"]=t}_drawImage(){let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:o,flip:n,rotate:a}=r,l=this._ctx,u=Ce({width:e.width,height:e.height},a);l.save(),l.translate(e.x+e.width/2,e.y+e.height/2),l.rotate(a*Math.PI*-1/180),l.scale(o?-1:1,n?-1:1),l.drawImage(t,-u.width/2,-u.height/2,u.width,u.height),l.restore()}_draw(){if(!this._isActive||!this.$.image)return;let t=this._canvas;this._ctx.clearRect(0,0,t.width,t.height),this._drawImage()}_animateIn({fromViewer:t}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=M({active_from_viewer:t,active_from_editor:!t,inactive_to_editor:!1})}))}_calculateDimensions(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a}=e,{width:l,height:u}=Ce(this._imageSize,o),{width:h,height:d}=t,p=n/l,f=a/u;return[ai(Math.round(h/p),1,l),ai(Math.round(d/f),1,u)]}_calculateCrop(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a,x:l,y:u}=e,{width:h,height:d}=Ce(this._imageSize,o),{x:p,y:f}=t,m=n/h,b=a/d,x=this._calculateDimensions(),A={dimensions:x,coords:[ai(Math.round((p-l)/m),0,h-x[0]),ai(Math.round((f-u)/b),0,d-x[1])]};if(!$n(A)){console.error("Cropper is trying to create invalid crop object",{payload:A});return}if(!(x[0]===h&&x[1]===d))return A}_commit(){if(!this.isConnected)return;let t=this.$["*operations"],{rotate:e,mirror:r,flip:o}=t,n=this._calculateCrop(),l={...this.$["*editorTransformations"],crop:n,rotate:e,mirror:r,flip:o};this.$["*editorTransformations"]=l}setValue(t,e){console.log(`Apply cropper operation [${t}=${e}]`),this.$["*operations"]={...this.$["*operations"],[t]:e},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(t){return this.$["*operations"][t]}async activate(t,{fromViewer:e}){if(!this._isActive){this._isActive=!0,this._imageSize=t,this.removeEventListener("transitionend",this._reset),this._initCanvas();try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw(),this._animateIn({fromViewer:e})}catch(r){console.error("Failed to activate cropper",{error:r})}}}deactivate(){this._isActive&&(this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=M({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}))}_transitionToCrop(){let t=this._calculateDimensions(),e=Math.min(this.offsetWidth,t[0])/this.$["*cropBox"].width,r=Math.min(this.offsetHeight,t[1])/this.$["*cropBox"].height,o=Math.min(e,r),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,a=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${o}) translate(${(this.offsetWidth/2-n)/o}px, ${(this.offsetHeight/2-a)/o}px)`,this.style.transformOrigin=`${n}px ${a}px`}_transitionToImage(){let t=this.$["*cropBox"].x+this.$["*cropBox"].width/2,e=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${t}px ${e}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(t,e){let r=this.offsetWidth;e={...e,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let o=this.proxyUrl(Jt(t,r,e)),{promise:n,cancel:a,image:l}=ve(o),u=this._handleImageLoading(o);return l.addEventListener("load",u,{once:!0}),l.addEventListener("error",u,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=a,n.then(()=>l).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(t){let e="crop",r=this.$["*loadingOperations"];return r.get(e)||r.set(e,new Map),r.get(e).get(t)||(r.set(e,r.get(e).set(t,!0)),this.$["*loadingOperations"]=r),()=>{var o;(o=r==null?void 0:r.get(e))!=null&&o.has(t)&&(r.get(e).delete(t),this.$["*loadingOperations"]=r)}}initCallback(){super.initCallback(),this._observer=new ResizeObserver(([t])=>{t.contentRect.width>0&&t.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeDebounced()}),this._observer.observe(this),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",t=>{this.$.image&&this._commitDebounced()}),setTimeout(()=>{this.sub("*networkProblems",t=>{t||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect()}};li.template=``;function ss(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function kn(s){return s.reduce((i,t,e)=>er<=i&&i<=o);return s.map(r=>{let o=Math.abs(e[0]-e[1]),n=Math.abs(i-e[0])/o;return e[0]===r?i>t?1:1-n:e[1]===r?i>=t?n:1:0})}function On(s,i){return s.map((t,e)=>to-n)}var rs=class extends I{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=at(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let o={...this._transformations};e&&(o[e]=t?{name:t,amount:r}:r);let n=this.offsetWidth;return this.proxyUrl(Jt(i,n,o))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(l=>l.value===e);if(r())return;let o=this._constructKeypoint(i,e),n=new Image;n.src=o.src;let a=this._handleImageLoading(o.src);n.addEventListener("load",a,{once:!0}),n.addEventListener("error",a,{once:!0}),o.image=n,n.classList.add("fader-image"),n.addEventListener("load",()=>{if(r())return;let l=this._keypoints,u=l.findIndex(d=>d.value>e),h=u{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=lt[i],r=this._keypoints.map(a=>a.value),o=In(r,t,e),n=On(r,e);for(let[a,l]of Object.entries(this._keypoints))l.opacity=o[a],l.zIndex=n[a];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(u=>u.src),{images:r,promise:o,cancel:n}=ye(e);r.forEach(u=>{let h=this._handleImageLoading(u.src);u.addEventListener("load",h),u.addEventListener("error",h)}),this._cancelLastImages=()=>{n(),this._cancelLastImages=void 0};let a=this._operation,l=this._filter;await o,this._isActive&&this._isSame(a,l)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((u,h)=>{let d=r[h];d.classList.add("fader-image"),u.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let n=Ar(e,r).map(l=>this._imageSrc({url:i,filter:t,operation:e,value:l})),{cancel:a}=ye(n);this._cancelBatchPreload=a}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=M({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=M({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:o}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=o,typeof e!="number"&&!r){let a=this._imageSrc({operation:t,value:e});this._setOriginalSrc(a),this._container&&this._container.remove();return}this._keypoints=Ar(t,e).map(a=>this._constructKeypoint(t,a)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=M({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Rn=1,ci=class extends I{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Rn?this.scrollLeft+=e:this.scrollLeft+=t})}};ci.template=" ";function Ln(s){return``}function Un(s){return`
`}var ui=class extends I{constructor(){super();c(this,"_updateInfoTooltip",at(()=>{var o,n;let t=this.$["*editorTransformations"],e="",r=!1;if(this.$["*tabId"]===j.FILTERS)if(r=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((n=t==null?void 0:t.filter)==null?void 0:n.amount)||100;e=this.l10n(this.$["*currentFilter"])+" "+a}else e=this.l10n(ut);else if(this.$["*tabId"]===j.SLIDERS&&this.$["*currentOperation"]){r=!0;let a=(t==null?void 0:t[this.$["*currentOperation"]])||lt[this.$["*currentOperation"]].zero;e=this.$["*currentOperation"]+" "+a}r&&(this.$["*operationTooltip"]=e),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",r)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ut,"*currentOperation":null,"*tabId":j.CROP,showLoader:!1,filters:gr,colorOperations:fr,cropOperations:_r,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":t=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":t=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":t=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":t=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=at(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===j.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=Zt.is&&new Zt;return e.operation=t,e}_createFilterControl(t){let e=Bt.is&&new Bt;return e.filter=t,e}_createToggleControl(t){let e=Yt.is&&new Yt;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===j.CROP?this.$.cropOperations.forEach(o=>{let n=this._createToggleControl(o);r.appendChild(n)}):t===j.FILTERS?[ut,...this.$.filters].forEach(o=>{let n=this._createFilterControl(o);r.appendChild(n)}):t===j.SLIDERS&&this.$.colorOperations.forEach(o=>{let n=this._createOperationControl(o);r.appendChild(n)}),r.childNodes.forEach((o,n)=>{n===r.childNodes.length-1&&o.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===j.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of ii){let o=r===t,n=this.ref[`tab-toggle-${r}`];n.active=o,o?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=o}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Jt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=ye([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",t=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,o]of r.entries())if(o){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this._updateInfoTooltip()}};ui.template=`
{{*operationTooltip}}
${ii.map(Un).join("")}
${ii.map(Ln).join("")}
`;var xe=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return M("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};xe.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});xe.template=`
{{text}}
`;var hi=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};hi.template=`
`;var di={transition:"transition",visible:"visible",hidden:"hidden"},pi=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=di.visible,this._hiddenStyle=di.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",cr(this,{[di.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(di.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};pi.template=" ";var mi=class extends _{constructor(){super();c(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${n}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${n}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),o=Math.ceil(r/2),n=Math.ceil(o/15)-2;if(this._stepsCount===n)return;let a=document.createDocumentFragment(),l=document.createElement("div"),u=document.createElement("div");l.className="minor-step",u.className="border-step",a.appendChild(u);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.CLOUD_IMG_EDIT);c(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new ct,e=this.$.cdnUrl;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),t.addEventListener("apply",r=>this.handleApply(r)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var Pn=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Sr=function(s,i="i"){let t=s.split("*").map(Pn);return new RegExp("^"+t.join(".+")+"$",i)};var Mn=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],o=Object.keys(r).reduce((n,a)=>{let l=r[a];return n+`${a}: ${l};`},"");return t+`${e}{${o}}`},"");function $r({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let o=`solid 1px ${r}`;return Mn({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":o},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":o},".list-table-body .list-items":{"border-bottom":o},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var $t={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in $t){let t=$t[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var kr=function(s,i,t){s in $t||($t[s]=[]),$t[s].push([i,t])},Ir=function(s,i){s in $t&&($t[s]=$t[s].filter(t=>t[0]!==i))};function Or(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var fi=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.EXTERNAL);c(this,"init$",{...this.init$,activityIcon:"",activityCaption:"",counter:0,onDone:()=>{this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}});c(this,"_iframe",null);c(this,"_inheritedUpdateCssData",this.updateCssData);c(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.$.counter=0,this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()})}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){console.log(t),this.$.counter=this.$.counter+1;let e=(()=>{if(t.alternatives){let n=U(this.cfg.externalSourcesPreferredTypes);for(let a of n){let l=Sr(a);for(let[u,h]of Object.entries(t.alternatives))if(l.test(u))return h}}return t.url})(),{filename:r}=t,{externalSourceType:o}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:o})}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:$r(t)})}remoteUrl(){var a,l;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,o={lang:((l=(a=this.getCssData("--l10n-locale-name"))==null?void 0:a.split("-"))==null?void 0:l[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},n=new URL(this.cfg.socialBaseUrl);return n.pathname=`/window3/${r}`,n.search=Or(o),n.toString()}mountIframe(){let t=se({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),kr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t}unmountIframe(){this._iframe&&Ir("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null}};fi.template=`
{{activityCaption}}
{{counter}}
`;var we=class extends _{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;U(i).forEach(e=>{let r=se({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};we.bindAttributes({"tab-list":null,default:null});we.template=`
`;var Qt=class extends v{constructor(){super(...arguments);c(this,"processInnerHtml",!0);c(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Qt.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let o=document.createElement("input");o.type="hidden",o.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,o.value=r,this._dynamicInputsContainer.appendChild(o)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(n=>n.uuid),r=await this.getUploadClientOptions(),o=await Rs(e,{...r});this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};Qt.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ns=class extends g{};var gi=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(o=>{e+=``}),this.$.selectHtml=e})}};gi.template=``;var q={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Rr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},st=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,src:"",ppIcon:q.PLAY,fsIcon:q.FS_ON,volIcon:q.VOL_ON,capIcon:q.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Rr.exitFullscreen():Rr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===q.CAP_OFF?(this.$.capIcon=q.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(st.is+":captions","1")):(this.$.capIcon=q.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(st.is+":captions"))}toggleSound(){this.$.volIcon===q.VOL_ON?(this.$.volIcon=q.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=q.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(st.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let o=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${o}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(st.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=q.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=q.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=q.FS_OFF:this.$.fsIcon=q.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let o="";r==null||r.sources.forEach(n=>{o+=``}),r.tracks&&(r.tracks.forEach(n=>{o+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=o,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(st.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};st.template=`
{{currentTime}} / {{totalTime}}
`;st.bindAttributes({video:"video",src:"src"});var Nn="css-src";function _i(s){return class extends s{constructor(){super(...arguments);c(this,"renderShadow",!0);c(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Nn);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Te=class extends _i(_){};var bi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};c(bi,"template",`Powered by Uploadcare`);var kt=class extends Te{constructor(){super(...arguments);c(this,"init$",Me(this));c(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var vi=class extends kt{};vi.template=``;var yi=class extends kt{constructor(){super(...arguments);c(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.sub(L("sourceList"),e=>{e!=="local"&&(this.$[L("sourceList")]="local")}),this.sub(L("confirmUpload"),e=>{e!==!1&&(this.$[L("confirmUpload")]=!1)})}};yi.template=``;var Ci=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};Ci.template=``;var as=class extends _i(ct){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function ls(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var cs="LR";async function Dn(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[cs]){t(window[cs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let o=window[cs];i&&ls(o),t(o)},document.head.appendChild(r)})}export{g as ActivityBlock,ns as ActivityHeader,zt as BaseComponent,_ as Block,Ye as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,ct as CloudImageEditorBlock,ze as Config,Je as ConfirmationDialog,bi as Copyright,oi as CropFrame,E as Data,Qt as DataOutput,pe as DropArea,Yt as EditorCropButtonControl,Bt as EditorFilterControl,li as EditorImageCropper,rs as EditorImageFader,Zt as EditorOperationControl,ci as EditorScroller,ni as EditorSlider,ui as EditorToolbar,fi as ExternalSource,bt as FileItem,ge as FilePreview,Ci as FileUploaderInline,yi as FileUploaderMinimal,vi as FileUploaderRegular,he as Icon,qi as Img,hi as LineLoaderUi,xe as LrBtnUi,qe as MessageBox,F as Modal,Ds as PACKAGE_NAME,Bs as PACKAGE_VERSION,pi as PresenceToggle,ti as ProgressBar,Qe as ProgressBarCommon,gi as Select,Te as ShadowWrapper,We as SimpleBtn,mi as SliderUi,me as SourceBtn,Zi as SourceList,Gi as StartFrom,we as Tabs,Qi as UploadCtxProvider,Ze as UploadDetails,Ge as UploadList,v as UploaderBlock,Ke as UrlSource,st as Video,Dn as connectBlocksFrom,ls as registerBlocks,_i as shadowed,_t as toKebabCase}; \ No newline at end of file +var Dr=Object.defineProperty;var Fr=(s,i,t)=>i in s?Dr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(Fr(s,typeof i!="symbol"?i+"":i,t),t),Ei=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var F=(s,i,t)=>(Ei(s,i,"read from private field"),t?t.call(s):i.get(s)),Ot=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},re=(s,i,t,e)=>(Ei(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var Se=(s,i,t)=>(Ei(s,i,"access private method"),t);var Vr=Object.defineProperty,Br=(s,i,t)=>i in s?Vr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,$i=(s,i,t)=>(Br(s,typeof i!="symbol"?i+"":i,t),t);function zr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=zr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var C=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),ps="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",jr=ps.length-1,oe=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Wr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function Xr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||us;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=us;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function qr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function Gr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Hr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):fs(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var ke="{{",ne="}}",Kr="skip-text";function Yr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(Kr))&&r.textContent.includes(ke)&&r.textContent.includes(ne)&&1}});for(;i=e.nextNode();)t.push(i);return t}var Zr=function(s,i){Yr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(ne);)e.textContent.startsWith(ke)?(n=e.textContent.indexOf(ne)+ne.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(ke),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(ke,"").replace(ne,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Jr=[Wr,Xr,qr,Gr,Zr],Ie="'",Bt='"',Qr=/\\([0-9a-fA-F]{1,6} ?)/g;function tn(s){return(s[0]===Bt||s[0]===Ie)&&(s[s.length-1]===Bt||s[s.length-1]===Ie)}function en(s){return(s[0]===Bt||s[0]===Ie)&&(s=s.slice(1)),(s[s.length-1]===Bt||s[s.length-1]===Ie)&&(s=s.slice(0,-1)),s}function sn(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ +`,"\\n"),i=sn(i),i=Bt+i+Bt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Vt=null,pt=null,vt=class extends HTMLElement{constructor(){super(),$i(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return vt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=oe.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=vt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=vt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=vt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=vt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=vt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=vt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])fs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Jr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);pt==null||pt.delete(this.updateCssData),pt!=null&&pt.size||(Vt==null||Vt.disconnect(),Vt=null,pt=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${C.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=rn(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){pt||(pt=new Set),pt.add(this.updateCssData),Vt||(Vt=new MutationObserver(s=>{s[0].type==="attributes"&&pt.forEach(i=>{i()})}),Vt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=vt;$i(zt,"template");var Ai=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Ai.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Ai.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Ai.appMap=Object.create(null);function nn(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function on(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function le(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&on(i,s.attributes),s.styles&&nn(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=le(t);i.appendChild(e)}),i}var ms="idb-store-ready",ln="symbiote-db",an="symbiote-idb-update_",cn=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return an+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=ln,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new cn(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};$i(gs,"_reg",Object.create(null));function S(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var hn="--uploadcare-blocks-window-height",Oe="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Si(){return typeof window[Oe]=="undefined"?!1:!!window[Oe]}function _s(){if(Si())return;let s=()=>{document.documentElement.style.setProperty(hn,`${window.innerHeight}px`),window[Oe]=!0},i=S(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[Oe]=!1,window.removeEventListener("resize",i)}}var un=s=>s,ki="{{",ys="}}",bs="plural:";function ae(s,i,t={}){var o;let{openToken:e=ki,closeToken:r=ys,transform:n=un}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(ki);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(ki,e)}return i}function Cs(s){return Object.prototype.toString.call(s)==="[object Object]"}var dn=/\W|_/g;function pn(s){return s.split(dn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ws(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>mt(t,{ignoreKeys:i})):s}function mt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ws(s,{ignoreKeys:i});if(!Cs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Cs(r)?r=mt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ws(r,{ignoreKeys:i})),t[pn(e)]=r}return t}var fn=s=>new Promise(i=>setTimeout(i,s));function Mi({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var mn={factor:2,time:100};function gn(s,i=mn){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>fn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var qt=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,qt.prototype),this.originalProgressEvent=t}},Re=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Ct=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,Ct.prototype)}},_n=500,Ts=({check:s,interval:i=_n,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Re(e,()=>{o&&clearTimeout(o),n(new Ct("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ct("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),T={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Pe="application/octet-stream",Es="original",xt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Re(r,()=>{u=!0,a.abort(),l(new Ct)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let A=$.split(": "),x=A.shift(),w=A.join(": ");x&&typeof x!="undefined"&&(m[x]=w)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new qt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function bn(s,...i){return s}var yn=({name:s})=>s?[s]:[],vn=bn,Cn=()=>new FormData,As=s=>!1,Me=s=>typeof Blob!="undefined"&&s instanceof Blob,Ne=s=>typeof File!="undefined"&&s instanceof File,De=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",ce=s=>Me(s)||Ne(s)||As()||De(s),wn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",xn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),Tn=s=>!!s&&typeof s=="object"&&"data"in s&&ce(s.data);function En(s,i,t){if(Tn(t)){let{name:e,contentType:r}=t,n=vn(t.data,e,r!=null?r:Pe),o=yn({name:e,contentType:r});s.push([i,n,...o])}else if(xn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else wn(t)&&t&&s.push([i,t.toString()])}function An(s){let i=[];for(let[t,e]of Object.entries(s))En(i,t,e);return i}function Ni(s){let i=Cn(),t=An(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var P=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}},$n=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=$n(t)),e.toString()},Sn="6.6.1",kn="UploadcareUploadClient",In=Sn;function Rt(s){return Mi({libraryName:kn,libraryVersion:In,...s})}var On="RequestThrottledError",xs=15e3,Ln=1e3;function Un(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return xs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:xs}function Tt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return gn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===On&&r{let i="";return(Me(s)||Ne(s)||De(s))&&(i=s.type),i||Pe},Ss=s=>{let i="";return Ne(s)&&s.name?i=s.name:Me(s)||As()?i="":De(s)&&s.name&&(i=s.name),i||Es};function Di(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Rn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=T.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:_}){return Tt(()=>xt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Ni({file:{data:s,name:t||Ss(s),contentType:e||$s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Di(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:$,headers:A,request:x})=>{let w=mt(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,x,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Li;(function(s){s.Token="token",s.FileInfo="file_info"})(Li||(Li={}));function Pn(s,{publicKey:i,baseURL:t=T.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:_}){return Tt(()=>xt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Di(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:$,headers:A,request:x})=>{let w=mt(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,x,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var q;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(q||(q={}));var Mn=s=>"status"in s&&s.status===q.Error;function Nn(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}={}){return Tt(()=>xt({method:"GET",headers:i?{"X-UC-User-Agent":Rt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=mt(JSON.parse(a));if("error"in d&&!Mn(d))throw new P(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Dn(s,{publicKey:i,baseURL:t=T.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:a,userAgent:c})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=mt(JSON.parse(p));if("error"in _)throw new P(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"GET",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Fn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=T.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:_}){return Tt(()=>xt({method:"POST",url:ft(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Ni({filename:e||Es,size:s,content_type:t||Pe,part_size:r,UPLOADCARE_STORE:Di(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:$,headers:A,request:x})=>{let w=mt(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,x,w,A);return w.parts=Object.keys(w.parts).map(W=>w.parts[W]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Vn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Pe}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Bn(s,{publicKey:i,baseURL:t=T.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},data:Ni({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Fi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return Ts({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}var wt=class{constructor(i,{baseCDN:t=T.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=ft(t,`${r}/`),l=n?ft(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},zn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:$})=>Rn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:A})=>Fi({file:A,publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new wt(A,{baseCDN:_})),jn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Hn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Re(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Wn=window.WebSocket,Ui=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Xn=(s,i)=>s==="success"?{status:q.Success,...i}:s==="progress"?{status:q.Progress,...i}:{status:q.Error,...i},Ri=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ui);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Wn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,Xn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Ii=null,Vi=s=>{if(!Ii){let i=typeof window=="undefined"?0:3e4;Ii=new Ri(s,i)}return Ii},qn=s=>{Vi(s).connect()};function Gn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return Ts({check:c=>Nn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case q.Error:return new P(u.error,u.errorCode);case q.Waiting:return!1;case q.Unknown:return new P(`Token "${s}" was not found.`);case q.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case q.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Kn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Vi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Re(t,()=>{a(),n(new Ct("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case q.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case q.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case q.Error:a(),n(new P(c.msg,c.error_code))}})}),Yn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:$=T.pusherKey,metadata:A})=>Promise.resolve(qn($)).then(()=>Pn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(x=>{let w=Vi($);return w==null||w.disconnect(),Promise.reject(x)}).then(x=>x.type===Li.FileInfo?x:Hn([({signal:w})=>Gn({token:x.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:w}),({signal:w})=>Kn({token:x.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(x=>{if(x instanceof P)throw x;return x}).then(x=>Fi({file:x.uuid,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(x=>new wt(x,{baseCDN:r})),Oi=new WeakMap,Zn=async s=>{if(Oi.has(s))return Oi.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Oi.set(s,i),i},Is=async s=>{if(Ne(s)||Me(s))return s.size;if(De(s))return(await Zn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Jn=(s,i=T.multipartMinFileSize)=>s>=i,Os=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!ce(s)&&t.test(s)},Ls=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!ce(s)&&t.test(s)},Qn=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},eo=async(s,i,t)=>e=>to(s,e,i,t),io=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Vn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),so=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:$=T.multipartChunkSize,maxConcurrentRequests:A=T.maxConcurrentRequests,baseCDN:x,metadata:w})=>{let W=e!=null?e:await Is(s),ht,It=(R,J)=>{if(!c)return;ht||(ht=Array(R).fill(0));let ut=X=>X.reduce((dt,Ti)=>dt+Ti,0);return X=>{X.isComputable&&(ht[J]=X.value,c({isComputable:!0,value:ut(ht)/R}))}};return _||(_=$s(s)),Fn(W,{publicKey:i,contentType:_,fileName:t||Ss(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:R,parts:J})=>{let ut=await eo(s,W,$);return Promise.all([R,Qn(A,J.map((X,dt)=>()=>io(ut(dt),X,{publicKey:i,contentType:_,onProgress:It(J.length,dt),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([R])=>Bn(R,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(R=>R.isReady?R:Fi({file:R.uuid,publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(R=>new wt(R,{baseCDN:x}))};async function Bi(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:$,maxConcurrentRequests:A,baseCDN:x=T.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:W,pusherKey:ht,metadata:It}){if(ce(s)){let R=await Is(s);return Jn(R,_)?so(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:R,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x,metadata:It}):zn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x,metadata:It})}if(Ls(s))return Yn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:x,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:W,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:ht,metadata:It});if(Os(s))return jn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x});throw new TypeError(`File uploading from "${s}" is not supported`)}var Pi=class{constructor(i,t){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},ro=s=>{for(let i of s)if(!ce(i))return!1;return!0},no=s=>{for(let i of s)if(!Os(i))return!1;return!0},oo=s=>{for(let i of s)if(!Ls(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=T.multipartChunkSize,baseCDN:$=T.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x,jsonpCallback:w}){if(!ro(s)&&!oo(s)&&!no(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let W,ht=!0,It=s.length,R=(J,ut)=>{if(!a)return;W||(W=Array(J).fill(0));let X=dt=>dt.reduce((Ti,Nr)=>Ti+Nr)/J;return dt=>{if(!dt.isComputable||!ht){ht=!1,a({isComputable:!1});return}W[ut]=dt.value,a({isComputable:!0,value:X(W)})}};return Promise.all(s.map((J,ut)=>Bi(J,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:R(It,ut),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:$,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x}))).then(J=>{let ut=J.map(X=>X.uuid);return Dn(ut,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(X=>new Pi(X,J)).then(X=>(a&&a({isComputable:!0,value:1}),X))})}var Lt,jt,Ut,Ht,Wt,Xt,Le,Ue=class{constructor(i){Ot(this,Xt);Ot(this,Lt,1);Ot(this,jt,[]);Ot(this,Ut,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);re(this,Lt,i)}add(i){return new Promise((t,e)=>{F(this,Ht).set(i,t),F(this,Wt).set(i,e),F(this,jt).push(i),Se(this,Xt,Le).call(this)})}get pending(){return F(this,jt).length}get running(){return F(this,Ut)}set concurrency(i){re(this,Lt,i),Se(this,Xt,Le).call(this)}get concurrency(){return F(this,Lt)}};Lt=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,Le=function(){let i=F(this,Lt)-F(this,Ut);for(let t=0;t{F(this,Ht).delete(e),F(this,Wt).delete(e),re(this,Ut,F(this,Ut)-1),Se(this,Xt,Le).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var zi=()=>({"*blocksRegistry":new Set}),ji=s=>({...zi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Fe=s=>({...ji(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Ue(1)});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var Q=s=>`*cfg/${s}`;var gt=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ps=new Set;function Ve(s){Ps.has(s)||(Ps.add(s),console.warn(s))}var Be=(s,i)=>new Intl.PluralRules(s).select(i);var Hi="lr-",b=class extends zt{constructor(){super();h(this,"allowCustomTemplate",!0);h(this,"init$",zi());h(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return ae(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Be(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setForCtxTarget(t,e,r){this.hasBlockInCtx(n=>n.constructor.StateConsumerScope===t)&&(this.$[e]=r)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Hi}${t}`,!0),Si()||(this._destroyInnerHeightTracker=_s()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?ae(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=Q(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Ve("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${gt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(Q(t));r.ctx.has(r.name)?this.sub(Q(t),e):(this.bindCssData(`--cfg-${gt(t)}`),this.sub(`--cfg-${gt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Hi)?t:Hi+t)}};h(b,"StateConsumerScope",null),h(b,"className","");var Wi=class extends b{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setForCtxTarget(Wi.StateConsumerScope,"*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}},B=Wi;h(B,"StateConsumerScope","modal");B.template=``;var Ms="active",he="___ACTIVITY_IS_ACTIVE___",st=class extends b{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",ji(this));h(this,"_debouncedHistoryFlush",S(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=st._activityRegistry[this.activityKey];this[he]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=st._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[he]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[he]?this._deactivate():this.activityType===t&&!this[he]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!st._activityRegistry[this.activityKey]}get isActivityActive(){return this[he]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;st._activityRegistry||(st._activityRegistry=Object.create(null)),st._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),st._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(st._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!1)}}},g=st;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ue=33.333333333333336,y=1,Xi=24,Ns=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function tt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Vs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Bs({rect:s,delta:[i,t],imageBox:e}){return Kt({...s,x:s.x+i,y:s.y+t},e)}function Kt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function lo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Yt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Zt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Et(s,i,t){return Math.min(Math.max(s,i),t)}var je=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var et=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs="blocks",qs="0.25.6";function Gs(s){return Mi({...s,libraryName:Xs,libraryVersion:qs})}var Ks=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},He=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ks(i)).join("/-/"),I=(...s)=>{let i=He(...s);return i?`-/${i}/`:""};function Ys(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Js(s){let i=Qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ks(n))}function Qs(s){let i=new URL(s),t=Ys(s),e=tr(t)?er(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function tr(s){return s.startsWith("http")}function er(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var k=(s,i,t)=>{let e=new URL(Qs(s));if(t=t||Ys(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),tr(t)){let r=er(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var M=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var de=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],qi=s=>s?s.filter(i=>typeof i=="string").map(i=>M(i)).flat():[],Gi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ir=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),pe=s=>{let i=s==null?void 0:s.type;return i?Gi(i,de):!1};var nt=1e3,Mt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),fe=s=>Math.ceil(s*100)/100,sr=(s,i=Mt.AUTO)=>{let t=i===Mt.AUTO;if(i===Mt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};h(O,"_timeoutStore",Object.create(null));var rr="[Typed State] Wrong property name: ",go="[Typed State] Wrong property type: ",We=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||oe.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(go+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Xe=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||oe.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new We(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var nr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var v=class extends g{constructor(){super(...arguments);h(this,"couldBeUploadCollectionOwner",!1);h(this,"isUploadCollectionOwner",!1);h(this,"init$",Fe(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",S(this._runValidators.bind(this),100));h(this,"_handleCollectionUpdate",t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,O.emit(new V({type:L.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&O.emit(new V({type:L.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{O.emit(new V({type:L.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{O.emit(new V({type:L.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{O.emit(new V({type:L.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){Ve("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Xe({typedSchema:nr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromObject(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:pe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:pe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=qi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?de:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=de.join(",")):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:et.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=M(this.cfg.sourceList)),t}initFlow(t=!1){var e,r;if((e=this.$["*uploadList"])!=null&&e.length&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let n=this.sourceList[0];n==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(n)?this.set$({"*currentActivityParams":{externalSourceType:n},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=n,this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0);O.emit(new V({type:L.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!1),O.emit(new V({type:L.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=qi([...e?de:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Gi(o,n),c=ir(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:sr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=je(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=I(`crop/${u.width}x${u.height}/${u.x},${u.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:k(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Gs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};e.push(a)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(L).forEach(s=>{let i=O.eName(s),t=S(e=>{if([L.UPLOAD_FINISH,L.REMOVE,L.CDN_MODIFICATION].includes(e.detail.type)){let n=E.getCtx(e.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let c=E.getCtx(a).store,u=c.fileInfo;if(u){let d={...u,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||u.cdnUrl};l.push(d)}}),O.emit(new V({type:L.DATA_OUTPUT,ctx:e.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var _o="https://ucarecdn.com",bo="https://upload.uploadcare.com",yo="https://social.uploadcare.com",me=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:_o,baseUrl:bo,socialBaseUrl:yo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var K=s=>String(s),ot=s=>Number(s),z=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,vo=s=>s==="auto"?s:z(s),Co={pubkey:K,multiple:z,multipleMin:ot,multipleMax:ot,confirmUpload:z,imgOnly:z,accept:K,externalSourcesPreferredTypes:K,store:vo,cameraMirror:z,sourceList:K,maxLocalFileSizeBytes:ot,thumbSize:ot,showEmptyList:z,useLocalImageEditor:z,useCloudImageEditor:z,removeCopyright:z,cropPreset:K,modalScrollLock:z,modalBackdropStrokes:z,sourceListWrap:z,remoteTabSessionKey:K,cdnCname:K,baseUrl:K,socialBaseUrl:K,secureSignature:K,secureExpire:K,secureDeliveryProxy:K,retryThrottledRequestMaxTimes:ot,multipartMinFileSize:ot,multipartChunkSize:ot,maxConcurrentRequests:ot,multipartMaxConcurrentRequests:ot,multipartMaxAttempts:ot,checkForUrlDuplicates:z,saveUrlForRecurrentUploads:z,groupOutput:z,userAgentIntegration:K},or=(s,i)=>{if(!(typeof i=="undefined"||i===null))return Co[s](i)};var qe=Object.keys(me),wo=["metadata"],xo=s=>wo.includes(s),Ki=qe.filter(s=>!xo(s)),To={...Object.fromEntries(Ki.map(s=>[gt(s),s])),...Object.fromEntries(Ki.map(s=>[s.toLowerCase(),s]))},Eo={...Object.fromEntries(qe.map(s=>[gt(s),Q(s)])),...Object.fromEntries(qe.map(s=>[s.toLowerCase(),Q(s)]))},Ge=class extends b{constructor(){super();h(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(me).map(([t,e])=>[Q(t),e]))}}initCallback(){super.initCallback();for(let t of qe){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,Ki.includes(t)){let o=[...new Set([gt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[Q(t)]!==n&&(typeof n=="undefined"||n===null?this.$[Q(t)]=me[t]:this.$[Q(t)]=n)},get:()=>this.$[Q(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=To[t],o=or(n,r),l=o!=null?o:me[n],a=this;a[n]=l}};Ge.bindAttributes(Eo);var ge=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ge.template=``;ge.bindAttributes({name:"name",size:"size"});var Ao="https://ucarecdn.com",Nt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Ao},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var lr=s=>[...new Set(s)];var _e="--lr-img-",ar="unresolved",Jt=2,Qt=3,cr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ur=Object.create(null),hr;for(let s in Nt)ur[_e+s]=((hr=Nt[s])==null?void 0:hr.default)||"";var Ke=class extends zt{constructor(){super(...arguments);h(this,"cssInit$",ur)}$$(t){return this.$[_e+t]}set$$(t){for(let e in t)this.$[_e+e]=t[e]}sub$$(t,e){this.sub(_e+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!cr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return I(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Nt.format.default}`,`quality/${this.$$("quality")||Nt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(cr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return k(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(k(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(k(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(k(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(k(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?ae(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(ar,""),this.img.onload=()=>{this.img.removeAttribute(ar)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Nt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?lr(M(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Jt+"x")}") ${n*Jt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Qt+"x")}") ${n*Qt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Jt))}") ${Jt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Qt))}") ${Qt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Jt+"x")+` ${e*Jt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Qt+"x")+` ${e*Qt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null)}static get observedAttributes(){return Object.keys(Nt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[_e+t]=r})}};var Yi=class extends Ke{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var Ye=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};Ye.template=``;var Zi=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function $o(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function So(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push(c),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function dr(s){let i=[],t=[];for(let e=0;e{i.push(...a)}));continue}let o=r.getAsFile();t.push($o(o).then(l=>{l||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}var j={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},pr=["focus"],ko=100,Ji=new Map;function Io(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Qi(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=j.INACTIVE,o=f=>{s.shouldIgnore()&&f!==j.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(j.INACTIVE)},c=()=>{i+=1,n===j.INACTIVE&&o(j.ACTIVE)},u=()=>{i-=1,l()||o(j.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(j.INACTIVE)},p=f=>{l()||(i+=1),f.preventDefault();let _=[f.x,f.y],$=s.element.getBoundingClientRect(),A=Math.floor(Io(_,$)),x=A{if(s.shouldIgnore())return;f.preventDefault();let _=await dr(f.dataTransfer);s.onItems(_),o(j.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),pr.forEach(f=>{window.addEventListener(f,a)}),()=>{Ji.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),pr.forEach(f=>{window.removeEventListener(f,a)})}}var be=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,state:j.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return e&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!e})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:typeof e=="string"})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:typeof e=="string"})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:typeof e=="string"})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Qi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:et.DROP_AREA});return}this.addFileFromObject(r,{source:et.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Qi({element:t,onChange:e=>{var n;let r=(n=Object.entries(j).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var n;let r=(n=Object.entries(j).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=M(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,n;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};be.template=`
{{text}}
`;be.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Oo="src-type-",ye=class extends v{constructor(){super(...arguments);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${Oo}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ye.template=`
`;ye.bindAttributes({type:null});var ts=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=M(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function fr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function mr(s="#fff",i="rgba(0, 0, 0, .1)"){return fr(``)}function ve(s="hsl(209, 21%, 65%)",i=32,t=32){return fr(``)}function gr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var H=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),_t=class extends v{constructor(){super();h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",S(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",S(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:H.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);O.emit(new V({type:L.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=H.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=H.FAILED:t.getValue("validationMultipleLimitMsg")?e=H.LIMIT_OVERFLOW:t.getValue("isUploading")?e=H.UPLOADING:t.getValue("fileInfo")&&(e=H.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(k(At(this.cfg.cdnCname,this._entry.getValue("uuid")),I(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await gr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ve(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ve(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{_t.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),_t.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===H.FAILED,isLimitOverflow:t===H.LIMIT_OVERFLOW,isUploading:t===H.UPLOADING,isFinished:t===H.FINISHED,progressVisible:t===H.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===H.FAILED||t===H.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===H.FINISHED&&(this.$.badgeIcon="badge-success"),t===H.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),_t.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));O.emit(new V({type:L.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=await this.getUploadClientOptions();return Bi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof P?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};_t.template=`
{{itemName}}{{errorText}}
`;_t.activeInstances=new Set;var Ze=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},Je=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Je.template=`
{{captionTxt}}
{{msgTxt}}
`;var Qe=class extends v{constructor(){super();h(this,"couldBeUploadCollectionOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",S(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));O.emit(new V({type:L.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new Ze,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};Qe.template=`{{headerText}}
`;var ti=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:et.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};ti.template=`
`;var es=()=>typeof navigator.permissions!="undefined";var ei=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:es(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{es()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",S(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:et.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ei.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var is=class extends v{};var ii=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ve(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=pe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=k(n,I("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ii.template=`
{{fileSize}}
{{errorTxt}}
`;var ss=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},si=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ss);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};si.template=`{{activityCaption}}
{{messageTxt}}
`;var ri=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};ri.template=``;var ni=class extends b{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ni.template='
';var Y="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var Ce=class extends b{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:Y})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${mr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Y}};Ce.template='';Ce.bindAttributes({checkerboard:"checkerboard"});var _r="--cfg-ctx-name",U=class extends b{get cfgCssCtxName(){return this.getCssData(_r,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(_r,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function br(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function N(...s){let i=br(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function yr(s,...i){let t=br(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var Z={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function Lo(s,i){if(typeof i=="number")return Z[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Z[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Z[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var Cr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return He(...Cr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return Lo(i,t)}).filter(i=>!!i))}var oi=He("format/auto","progressive/yes"),bt=([s])=>typeof s!="undefined"?Number(s):void 0,vr=()=>!0,Uo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Ro=([s,i])=>({dimensions:M(s,"x").map(Number),coords:M(i).map(Number)}),Po={enhance:bt,brightness:bt,exposure:bt,gamma:bt,contrast:bt,saturation:bt,vibrance:bt,warmth:bt,filter:Uo,mirror:vr,flip:vr,rotate:bt,crop:Ro};function wr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!Cr.includes(e))continue;let n=Po[e],o=n(r);i[e]=o}return i}function xr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Y,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"","presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Y,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=I($t(i)),r=k(t,I(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var Tr=`
Network error
{{fileType}}
{{msg}}
`;var D={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},li=[D.CROP,D.SLIDERS,D.FILTERS],Er=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],Ar=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],$r=["rotate","mirror","flip"],lt={brightness:{zero:Z.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Z.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Z.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Z.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Z.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Z.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Z.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Z.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Z.filter,range:[0,100],keypointsNumber:1}};var at=class extends U{constructor(){super();h(this,"_debouncedShowLoader",S(this._showLoader.bind(this),300));this.init$={...this.init$,...xr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===D.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Zs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Js(this.$.cdnUrl),r=wr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=k(this.$["*originalUrl"],I("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===D.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Y&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Y)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=je(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=N("image",{image_hidden_to_cropper:t===D.CROP,image_hidden_effects:t!==D.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=I($t(t)),n=k(e,I(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(at,"className","cloud-image-editor");at.template=Tr;at.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset"});var ai=class extends U{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=tt("mask",{id:"backdrop-mask"}),a=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=tt("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Pt(n,f)}else{let f=Et(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:$}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(Xi*Et(Math.min(d,p)/Xi/3,0,1),Ns);Pt(n,{x:$[0]-A,y:$[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",N("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=tt("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=tt("rect",{fill:"transparent"}),l=tt("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=tt("svg"),t=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=tt("line",{x1:`${ue*e}%`,y1:"0%",x2:`${ue*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=tt("line",{x1:"0%",y1:`${ue*e}%`,x2:"100%",y2:`${ue*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Bs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Kt(Zt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Vs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",N("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",N({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ai.template='';var yt=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=N({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function No(s){let i=s+90;return i=i>=360?0:i,i}function Do(s,i){return s==="rotate"?No(i):["mirror","flip"].includes(s)?!i:null}var te=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Do(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var we={FILTER:"filter",COLOR_OPERATION:"color_operation"},ct="original",ci=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?we.FILTER:we.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ct?void 0:this.$.value,filter:this._filter===ct?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=lt[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===we.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===we.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===we.FILTER?this._filter===ct?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ci.template=``;function xe(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=Y)}}}function Te(s){let i=[];for(let n of s){let o=xe(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Ft=class extends yt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ct?{name:this._filter,amount:o}:void 0,k(this._originalUrl,I(oi,$t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=xe(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ct,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Ft.template=`
`;var ee=class extends yt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=lt[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Sr=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function kr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function ie(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return k(s,I(oi,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Fo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var hi=class extends U{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=S(this._commit.bind(this),300),this._handleResizeThrottled=Sr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=kr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=Yt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Zt(l)}_alignCrop(){var c;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[u,d],coords:[p,m]}=n,{width:f}=Yt(this._imageSize,r),_=o/f;i=Kt(Zt({x:l+p*_,y:a+m*_,width:u*_,height:d*_}),this.$["*imageBox"])}if(!n||!Hs(i,t)){let u=(c=this.$["*cropPresetList"])==null?void 0:c[0],d=u?u.width/u.height:void 0,p=t.width/t.height,m=t.width,f=t.height;d&&(p>d?m=Math.min(t.height*d,t.width):f=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Kt(Zt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=Yt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=N({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=Yt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[Et(Math.round(c/d),1,l),Et(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=Yt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),$={dimensions:_,coords:[Et(Math.round((d-l)/m),0,c-_[0]),Et(Math.round((p-a)/f),0,u-_[1])]};if(!Fo($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(_[0]===c&&_[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=N({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(ie(i,e,t)),{promise:n,cancel:o,image:l}=xe(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};hi.template=``;function rs(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Vo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function zo(s,i){return s.map((t,e)=>tn-o)}var ns=class extends U{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=S(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(ie(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=lt[i],r=this._keypoints.map(l=>l.value),n=Bo(r,t,e),o=zo(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Te(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Ir(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=Te(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Ir(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=N({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var jo=1,ui=class extends U{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>jo?this.scrollLeft+=e:this.scrollLeft+=t})}};ui.template=" ";function Ho(s){return``}function Wo(s){return`
`}var di=class extends U{constructor(){super();h(this,"_updateInfoTooltip",S(()=>{var n,o;let t=this.$["*editorTransformations"],e="",r=!1;if(this.$["*tabId"]===D.FILTERS)if(r=!0,this.$["*currentFilter"]&&((n=t==null?void 0:t.filter)==null?void 0:n.name)===this.$["*currentFilter"]){let l=((o=t==null?void 0:t.filter)==null?void 0:o.amount)||100;e=this.l10n(this.$["*currentFilter"])+" "+l}else e=this.l10n(ct);else if(this.$["*tabId"]===D.SLIDERS&&this.$["*currentOperation"]){r=!0;let l=(t==null?void 0:t[this.$["*currentOperation"]])||lt[this.$["*currentOperation"]].zero;e=this.$["*currentOperation"]+" "+l}r&&(this.$["*operationTooltip"]=e),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",r)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ct,"*currentOperation":null,"*tabId":D.CROP,showLoader:!1,filters:Ar,colorOperations:Er,cropOperations:$r,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":t=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":t=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":t=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":t=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=S(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===D.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=ee.is&&new ee;return e.operation=t,e}_createFilterControl(t){let e=Ft.is&&new Ft;return e.filter=t,e}_createToggleControl(t){let e=te.is&&new te;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===D.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===D.FILTERS?[ct,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===D.SLIDERS&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),r.childNodes.forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===D.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of li){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ie(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Te([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",t=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this._updateInfoTooltip()}};di.template=`
{{*operationTooltip}}
${li.map(Wo).join("")}
${li.map(Ho).join("")}
`;var Ee=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return N("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Ee.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Ee.template=`
{{text}}
`;var pi=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};pi.template=`
`;var fi={transition:"transition",visible:"visible",hidden:"hidden"},mi=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=fi.visible,this._hiddenStyle=fi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",yr(this,{[fi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(fi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};mi.template=" ";var gi=class extends b{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);h(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new at,e=this.$.cdnUrl,r=this.cfg.cropPreset;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),t.addEventListener("apply",n=>this.handleApply(n)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var Xo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Or=function(s,i="i"){let t=s.split("*").map(Xo);return new RegExp("^"+t.join(".+")+"$",i)};var qo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Lr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return qo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var St={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in St){let t=St[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ur=function(s,i,t){s in St||(St[s]=[]),St[s].push([i,t])},Rr=function(s,i){s in St&&(St[s]=St[s].filter(t=>t[0]!==i))};function Pr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var _i=class extends v{constructor(){super();h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=M(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Or(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Lr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Pr(n),o.toString()}mountIframe(){let t=le({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ur("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Rr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};_i.template=`
{{activityCaption}}
{{counter}}
`;var Ae=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;M(i).forEach(e=>{let r=le({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};Ae.bindAttributes({"tab-list":null,default:null});Ae.template=`
`;var se=class extends v{constructor(){super(...arguments);h(this,"processInnerHtml",!0);h(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return se.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Us(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};se.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ls=class extends g{};var bi=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};bi.template=``;var G={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Mr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},it=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:G.PLAY,fsIcon:G.FS_ON,volIcon:G.VOL_ON,capIcon:G.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Mr.exitFullscreen():Mr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===G.CAP_OFF?(this.$.capIcon=G.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(it.is+":captions","1")):(this.$.capIcon=G.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(it.is+":captions"))}toggleSound(){this.$.volIcon===G.VOL_ON?(this.$.volIcon=G.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=G.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(it.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(it.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=G.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=G.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=G.FS_OFF:this.$.fsIcon=G.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(it.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};it.template=`
{{currentTime}} / {{totalTime}}
`;it.bindAttributes({video:"video",src:"src"});var Go="css-src";function yi(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Go);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var $e=class extends yi(b){};var vi=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(vi,"template",`Powered by Uploadcare`);var kt=class extends $e{constructor(){super(...arguments);h(this,"init$",Fe(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var Ci=class extends kt{};Ci.template=``;var wi=class extends kt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};wi.template=``;var xi=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};xi.template=``;var as=class extends yi(at){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Ko(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,zt as BaseComponent,b as Block,ei as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,at as CloudImageEditorBlock,Ge as Config,si as ConfirmationDialog,vi as Copyright,ai as CropFrame,E as Data,se as DataOutput,be as DropArea,te as EditorCropButtonControl,Ft as EditorFilterControl,hi as EditorImageCropper,ns as EditorImageFader,ee as EditorOperationControl,ui as EditorScroller,ci as EditorSlider,di as EditorToolbar,_i as ExternalSource,_t as FileItem,Ce as FilePreview,xi as FileUploaderInline,wi as FileUploaderMinimal,Ci as FileUploaderRegular,ge as Icon,Yi as Img,pi as LineLoaderUi,Ee as LrBtnUi,Je as MessageBox,B as Modal,Xs as PACKAGE_NAME,qs as PACKAGE_VERSION,mi as PresenceToggle,ni as ProgressBar,ri as ProgressBarCommon,bi as Select,$e as ShadowWrapper,Ye as SimpleBtn,gi as SliderUi,ye as SourceBtn,ts as SourceList,Zi as StartFrom,Ae as Tabs,is as UploadCtxProvider,ii as UploadDetails,Qe as UploadList,v as UploaderBlock,ti as UrlSource,it as Video,Ko as connectBlocksFrom,cs as registerBlocks,yi as shadowed,gt as toKebabCase}; \ No newline at end of file diff --git a/web/lr-cloud-image-editor.min.js b/web/lr-cloud-image-editor.min.js index 7e6da06d7..fc0816ce7 100644 --- a/web/lr-cloud-image-editor.min.js +++ b/web/lr-cloud-image-editor.min.js @@ -23,6 +23,6 @@ * SOFTWARE. * */ -var Mt=Object.defineProperty;var Dt=(r,i,e)=>i in r?Mt(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e;var f=(r,i,e)=>(Dt(r,typeof i!="symbol"?i+"":i,e),e);var je=r=>{if(typeof r!="string"||!r)return"";let i=r.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},le=(...r)=>r.filter(i=>typeof i=="string"&&i).map(i=>je(i)).join("/-/"),R=(...r)=>{let i=le(...r);return i?`-/${i}/`:""};function Ke(r){let i=new URL(r),e=i.pathname+i.search+i.hash,t=e.lastIndexOf("http"),s=e.lastIndexOf("/"),o="";return t>=0?o=e.slice(t):s>=0&&(o=e.slice(s+1)),o}function We(r){let i=new URL(r),{pathname:e}=i,t=e.indexOf("/"),s=e.indexOf("/",t+1);return e.substring(t+1,s)}function Ve(r){let i=Ge(r),e=new URL(i),t=e.pathname.indexOf("/-/");return t===-1?[]:e.pathname.substring(t).split("/-/").filter(Boolean).map(o=>je(o))}function Ge(r){let i=new URL(r),e=Ke(r),t=qe(e)?Ye(e).pathname:e;return i.pathname=i.pathname.replace(t,""),i.search="",i.hash="",i.toString()}function qe(r){return r.startsWith("http")}function Ye(r){let i=new URL(r);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var M=(r,i,e)=>{let t=new URL(Ge(r));if(e=e||Ke(r),t.pathname.startsWith("//")&&(t.pathname=t.pathname.replace("//","/")),qe(e)){let s=Ye(e);t.pathname=t.pathname+(i||"")+(s.pathname||""),t.search=s.search,t.hash=s.hash}else t.pathname=t.pathname+(i||"")+(e||"");return t.toString()},Re=(r,i)=>{let e=new URL(r);return e.pathname=i+"/",e.toString()};var I="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var Bt=Object.defineProperty,Ut=(r,i,e)=>i in r?Bt(r,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[i]=e,Ie=(r,i,e)=>(Ut(r,typeof i!="symbol"?i+"":i,e),e);function Ft(r){let i=e=>{var t;for(let s in e)((t=e[s])==null?void 0:t.constructor)===Object&&(e[s]=i(e[s]));return{...e}};return i(r)}var g=class{constructor(r){r.constructor===Object?this.store=Ft(r):(this._storeIsProxy=!0,this.store=r),this.callbackMap=Object.create(null)}static warn(r,i){console.warn(`Symbiote Data: cannot ${r}. Prop name: `+i)}read(r){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(g.warn("read",r),null):this.store[r]}has(r){return this._storeIsProxy?this.store[r]!==void 0:this.store.hasOwnProperty(r)}add(r,i,e=!1){!e&&Object.keys(this.store).includes(r)||(this.store[r]=i,this.notify(r))}pub(r,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(r)){g.warn("publish",r);return}this.store[r]=i,this.notify(r)}multiPub(r){for(let i in r)this.pub(i,r[i])}notify(r){this.callbackMap[r]&&this.callbackMap[r].forEach(i=>{i(this.store[r])})}sub(r,i,e=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(g.warn("subscribe",r),null):(this.callbackMap[r]||(this.callbackMap[r]=new Set),this.callbackMap[r].add(i),e&&i(this.store[r]),{remove:()=>{this.callbackMap[r].delete(i),this.callbackMap[r].size||delete this.callbackMap[r]},callback:i})}static registerCtx(r,i=Symbol()){let e=g.globalStore.get(i);return e?console.warn('State: context UID "'+i+'" already in use'):(e=new g(r),g.globalStore.set(i,e)),e}static deleteCtx(r){g.globalStore.delete(r)}static getCtx(r,i=!0){return g.globalStore.get(r)||(i&&console.warn('State: wrong context UID - "'+r+'"'),null)}};g.globalStore=new Map;var p=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),Je="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",zt=Je.length-1,Ht=class{static generate(r="XXXXXXXXX-XXX"){let i="";for(let e=0;e{ai&&e?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,e)=>i&&e?i.toUpperCase():i).join("")}function jt(r,i){[...r.querySelectorAll(`[${p.REPEAT_ATTR}]`)].forEach(e=>{let t=e.getAttribute(p.REPEAT_ITEM_TAG_ATTR),s;if(t&&(s=window.customElements.get(t)),!s){s=class extends i.BaseComponent{constructor(){super(),t||(this.style.display="contents")}};let n=e.innerHTML;s.template=n,s.reg(t)}for(;e.firstChild;)e.firstChild.remove();let o=e.getAttribute(p.REPEAT_ATTR);i.sub(o,n=>{if(!n){for(;e.firstChild;)e.firstChild.remove();return}let a=[...e.children],l,c=h=>{h.forEach((u,m)=>{if(a[m])if(a[m].set$)setTimeout(()=>{a[m].set$(u)});else for(let v in u)a[m][v]=u[v];else{l||(l=new DocumentFragment);let v=new s;Object.assign(v.init$,u),l.appendChild(v)}}),l&&e.appendChild(l);let d=a.slice(h.length,a.length);for(let u of d)u.remove()};if(n.constructor===Array)c(n);else if(n.constructor===Object){let h=[];for(let d in n){let u=n[d];Object.defineProperty(u,"_KEY_",{value:d,enumerable:!0}),h.push(u)}c(h)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),e.removeAttribute(p.REPEAT_ATTR),e.removeAttribute(p.REPEAT_ITEM_TAG_ATTR)})}var Ze="__default__";function Kt(r,i){if(i.shadowRoot)return;let e=[...r.querySelectorAll("slot")];if(!e.length)return;let t={};e.forEach(s=>{let o=s.getAttribute("name")||Ze;t[o]={slot:s,fr:document.createDocumentFragment()}}),i.initChildren.forEach(s=>{var o;let n=Ze;s instanceof Element&&s.hasAttribute("slot")&&(n=s.getAttribute("slot"),s.removeAttribute("slot")),(o=t[n])==null||o.fr.appendChild(s)}),Object.values(t).forEach(s=>{if(s.fr.childNodes.length)s.slot.parentNode.replaceChild(s.fr,s.slot);else if(s.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...s.slot.childNodes),s.slot.parentNode.replaceChild(o,s.slot)}else s.slot.remove()})}function Wt(r,i){[...r.querySelectorAll(`[${p.EL_REF_ATTR}]`)].forEach(e=>{let t=e.getAttribute(p.EL_REF_ATTR);i.ref[t]=e,e.removeAttribute(p.EL_REF_ATTR)})}function Vt(r,i){[...r.querySelectorAll(`[${p.BIND_ATTR}]`)].forEach(e=>{let s=e.getAttribute(p.BIND_ATTR).split(";");[...e.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=Xt(o.name.replace("-",""));s.push(n+":"+o.value),e.removeAttribute(o.name)}}),s.forEach(o=>{if(!o)return;let n=o.split(":").map(h=>h.trim()),a=n[0],l;a.indexOf(p.ATTR_BIND_PRFX)===0&&(l=!0,a=a.replace(p.ATTR_BIND_PRFX,""));let c=n[1].split(",").map(h=>h.trim());for(let h of c){let d;h.startsWith("!!")?(d="double",h=h.replace("!!","")):h.startsWith("!")&&(d="single",h=h.replace("!","")),i.sub(h,u=>{d==="double"?u=!!u:d==="single"&&(u=!u),l?(u==null?void 0:u.constructor)===Boolean?u?e.setAttribute(a,""):e.removeAttribute(a):e.setAttribute(a,u):et(e,a,u)||(e[p.SET_LATER_KEY]||(e[p.SET_LATER_KEY]=Object.create(null)),e[p.SET_LATER_KEY][a]=u)})}}),e.removeAttribute(p.BIND_ATTR)})}var he="{{",J="}}",Gt="skip-text";function qt(r){let i,e=[],t=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,{acceptNode:s=>{var o;return!((o=s.parentElement)!=null&&o.hasAttribute(Gt))&&s.textContent.includes(he)&&s.textContent.includes(J)&&1}});for(;i=t.nextNode();)e.push(i);return e}var Yt=function(r,i){qt(r).forEach(t=>{let s=[],o;for(;t.textContent.includes(J);)t.textContent.startsWith(he)?(o=t.textContent.indexOf(J)+J.length,t.splitText(o),s.push(t)):(o=t.textContent.indexOf(he),t.splitText(o)),t=t.nextSibling;s.forEach(n=>{let a=n.textContent.replace(he,"").replace(J,"");n.textContent="",i.sub(a,l=>{n.textContent=l})})})},Zt=[jt,Kt,Wt,Vt,Yt],ce="'",q='"',Qt=/\\([0-9a-fA-F]{1,6} ?)/g;function Jt(r){return(r[0]===q||r[0]===ce)&&(r[r.length-1]===q||r[r.length-1]===ce)}function ei(r){return(r[0]===q||r[0]===ce)&&(r=r.slice(1)),(r[r.length-1]===q||r[r.length-1]===ce)&&(r=r.slice(0,-1)),r}function ti(r){let i="",e="";for(var t=0;tString.fromCodePoint(parseInt(t.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=ti(i),i=q+i+q);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${r}`)}}var Qe=0,G=null,D=null,F=class extends HTMLElement{constructor(){super(),Ie(this,"updateCssData",()=>{var r;this.dropCssDataCache(),(r=this.__boundCssProps)==null||r.forEach(i=>{let e=this.getCssData(this.__extractCssName(i),!0);e!==null&&this.$[i]!==e&&(this.$[i]=e)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return F}initCallback(){}__initCallback(){var r;this.__initialized||(this.__initialized=!0,(r=this.initCallback)==null||r.call(this))}render(r,i=this.renderShadow){let e;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(p.USE_TPL);if(s){let o=this.getRootNode(),n=(o==null?void 0:o.querySelector(s))||document.querySelector(s);n?r=n.content.cloneNode(!0):console.warn(`Symbiote template "${s}" is not found...`)}}if(this.processInnerHtml)for(let s of this.tplProcessors)s(this,this);if(r||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(r==null?void 0:r.constructor)===DocumentFragment)e=r;else if((r==null?void 0:r.constructor)===String){let s=document.createElement("template");s.innerHTML=r,e=s.content.cloneNode(!0)}else this.constructor.__tpl&&(e=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(e,this)}let t=()=>{e&&(i&&this.shadowRoot.appendChild(e)||this.appendChild(e)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let s=document.createElement("link");s.rel="stylesheet",s.href=this.constructor.__shadowStylesUrl,s.onload=t,this.shadowRoot.prepend(s)}else t()}addTemplateProcessor(r){this.tplProcessors.add(r)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Ht.generate(),this.style.setProperty(p.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(p.CSS_CTX_PROP,!0)}get ctxName(){var r;let i=((r=this.getAttribute(p.CTX_NAME_ATTR))==null?void 0:r.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=g.registerCtx({},this)),this.__localCtx}get nodeCtx(){return g.getCtx(this.ctxName,!1)||g.registerCtx({},this.ctxName)}static __parseProp(r,i){let e,t;if(r.startsWith(p.EXT_DATA_CTX_PRFX))e=i.nodeCtx,t=r.replace(p.EXT_DATA_CTX_PRFX,"");else if(r.includes(p.NAMED_DATA_CTX_SPLTR)){let s=r.split(p.NAMED_DATA_CTX_SPLTR);e=g.getCtx(s[0]),t=s[1]}else e=i.localCtx,t=r;return{ctx:e,name:t}}sub(r,i,e=!0){let t=o=>{this.isConnected&&i(o)},s=F.__parseProp(r,this);s.ctx.has(s.name)?this.allSubs.add(s.ctx.sub(s.name,t,e)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,t,e))})}notify(r){let i=F.__parseProp(r,this);i.ctx.notify(i.name)}has(r){let i=F.__parseProp(r,this);return i.ctx.has(i.name)}add(r,i,e=!1){let t=F.__parseProp(r,this);t.ctx.add(t.name,i,e)}add$(r,i=!1){for(let e in r)this.add(e,r[e],i)}get $(){if(!this.__stateProxy){let r=Object.create(null);this.__stateProxy=new Proxy(r,{set:(i,e,t)=>{let s=F.__parseProp(e,this);return s.ctx.pub(s.name,t),!0},get:(i,e)=>{let t=F.__parseProp(e,this);return t.ctx.read(t.name)}})}return this.__stateProxy}set$(r,i=!1){for(let e in r){let t=r[e];i||![String,Number,Boolean].includes(t==null?void 0:t.constructor)?this.$[e]=t:this.$[e]!==t&&(this.$[e]=t)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(p.CTX_OWNER_ATTR)&&this.getAttribute(p.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let r=this.constructor.__attrDesc;if(r)for(let i of Object.values(r))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(p.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(p.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(p.NAMED_DATA_CTX_SPLTR)){let e=i.split(p.NAMED_DATA_CTX_SPLTR),t=e[0].trim(),s=e[1].trim();if(t&&s){let o=g.getCtx(t,!1);o||(o=g.registerCtx({},t)),o.add(s,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var r;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(r=this.getAttribute(p.CTX_NAME_ATTR))==null?void 0:r.trim();if(i&&this.style.setProperty(p.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[p.SET_LATER_KEY]){for(let e in this[p.SET_LATER_KEY])et(this,e,this[p.SET_LATER_KEY][e]);delete this[p.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let e of Zt)this.addTemplateProcessor(e);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let e=this.getRootNode();if(!e)return;if(e==null?void 0:e.querySelector(`link[${p.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(p.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},e.nodeType===Node.DOCUMENT_NODE?e.head.appendChild(s):e.prepend(s)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let r of this.allSubs)r.remove(),this.allSubs.delete(r);for(let r of this.tplProcessors)this.tplProcessors.delete(r);D==null||D.delete(this.updateCssData),D!=null&&D.size||(G==null||G.disconnect(),G=null,D=null)},100)))}static reg(r,i=!1){r||(Qe++,r=`${p.AUTO_TAG_PRFX}-${Qe}`),this.__tag=r;let e=window.customElements.get(r);if(e){!i&&e!==this&&console.warn([`Element with tag name "${r}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` -`));return}window.customElements.define(r,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(r){this.observedAttributes=Object.keys(r),this.__attrDesc=r}attributeChangedCallback(r,i,e){var t;if(i===e)return;let s=(t=this.constructor.__attrDesc)==null?void 0:t[r];s?this.__dataCtxInitialized?this.$[s]=e:this.init$[s]=e:this[r]=e}getCssData(r,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(r)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let e=this.__computedStyle.getPropertyValue(r).trim();try{this.__cssDataCache[r]=ii(e)}catch{!i&&console.warn(`CSS Data error: ${r}`),this.__cssDataCache[r]=null}}return this.__cssDataCache[r]}__extractCssName(r){return r.split("--").map((i,e)=>e===0?"":i).join("--")}__initStyleAttrObserver(){D||(D=new Set),D.add(this.updateCssData),G||(G=new MutationObserver(r=>{r[0].type==="attributes"&&D.forEach(i=>{i()})}),G.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(r,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(r);let e=this.getCssData(this.__extractCssName(r),!0);e===null&&(e=i),this.add(r,e),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(r,i,e){let t="__"+r;this[t]=this[r],Object.defineProperty(this,r,{set:s=>{this[t]=s,e?window.setTimeout(()=>{i==null||i(s)}):i==null||i(s)},get:()=>this[t]}),this[r]=this[t]}static set shadowStyles(r){let i=new Blob([r],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(r){if(!this.__rootStylesLink){let i=new Blob([r],{type:"text/css"}),e=URL.createObjectURL(i),t=document.createElement("link");t.href=e,t.rel="stylesheet",this.__rootStylesLink=t}}},Pe=F;Ie(Pe,"template");var Oe=class{static _print(r){console.warn(r)}static setDefaultTitle(r){this.defaultTitle=r}static setRoutingMap(r){Object.assign(this.appMap,r);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(r){this.__routingEventName=r}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let r={route:null,options:{}};return window.location.search.split(this.separator).forEach(e=>{if(e.includes("?"))r.route=e.replace("?","");else if(e.includes("=")){let t=e.split("=");r.options[t[0]]=decodeURI(t[1])}else r.options[e]=!0}),r}static notify(){let r=this.readAddressBar(),i=this.appMap[r.route];if(i&&i.title&&(document.title=i.title),r.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${r.route}" not found...`);return}let e=new CustomEvent(Oe.routingEventName,{detail:{route:r.route,options:Object.assign(i||{},r.options)}});window.dispatchEvent(e)}static reflect(r,i={}){let e=this.appMap[r];if(!e){this._print("Wrong route: "+r);return}let t="?"+r;for(let o in i)i[o]===!0?t+=this.separator+o:t+=this.separator+o+`=${i[o]}`;let s=e.title||this.defaultTitle||"";window.history.pushState(null,s,t),document.title=s}static applyRoute(r,i={}){this.reflect(r,i),this.notify()}static setSeparator(r){this._separator=r}static get separator(){return this._separator||"&"}static createRouterData(r,i){this.setRoutingMap(i);let e=g.registerCtx({route:null,options:null,title:null},r);return window.addEventListener(this.routingEventName,t=>{var s;e.multiPub({route:t.detail.route,options:t.detail.options,title:((s=t.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),Oe.notify(),this.initPopstateListener(),e}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Oe.appMap=Object.create(null);var tt="idb-store-ready",ri="symbiote-db",si="symbiote-idb-update_",oi=class{_notifyWhenReady(r=null){window.dispatchEvent(new CustomEvent(tt,{detail:{dbName:this.name,storeName:this.storeName,event:r}}))}get _updEventName(){return si+this.name}_getUpdateEvent(r){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:r}})}_notifySubscribers(r){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,r),window.dispatchEvent(this._getUpdateEvent(r))}constructor(r,i){this.name=r,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=e=>{this.db=e.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=t=>{this._notifyWhenReady(t)}},this.request.onsuccess=e=>{this.db=e.target.result,this._notifyWhenReady(e)},this.request.onerror=e=>{console.error(e)},this._subscriptionsMap={},this._updateHandler=e=>{e.key===this.name&&this._subscriptionsMap[e.newValue]&&this._subscriptionsMap[e.newValue].forEach(async s=>{s(await this.read(e.newValue))})},this._localUpdateHandler=e=>{this._updateHandler(e.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(r){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(r);return new Promise((t,s)=>{e.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?t(o.target.result._value):(t(null),console.warn(`IDB: cannot read "${r}"`))},e.onerror=o=>{s(o)}})}write(r,i,e=!1){let t={_key:r,_value:i},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(t);return new Promise((n,a)=>{o.onsuccess=l=>{e||this._notifySubscribers(r),n(l.target.result)},o.onerror=l=>{a(l)}})}delete(r,i=!1){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(r);return new Promise((s,o)=>{t.onsuccess=n=>{i||this._notifySubscribers(r),s(n)},t.onerror=n=>{o(n)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((e,t)=>{i.onsuccess=s=>{let o=s.target.result;e(o.map(n=>n._value))},i.onerror=s=>{t(s)}})}subscribe(r,i){this._subscriptionsMap[r]||(this._subscriptionsMap[r]=new Set);let e=this._subscriptionsMap[r];return e.add(i),{remove:()=>{e.delete(i),e.size||delete this._subscriptionsMap[r]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,it.clear(this.name)}},it=class{static get readyEventName(){return tt}static open(r=ri,i="store"){let e=r+"/"+i;return this._reg[e]||(this._reg[e]=new oi(r,i)),this._reg[e]}static clear(r){window.indexedDB.deleteDatabase(r);for(let i in this._reg)i.split("/")[0]===r&&delete this._reg[i]}};Ie(it,"_reg",Object.create(null));function rt(r,i){let e,t=(...s)=>{clearTimeout(e),e=setTimeout(()=>r(...s),i)};return t.cancel=()=>{clearTimeout(e)},t}var ni="--uploadcare-blocks-window-height",de="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ke(){return typeof window[de]=="undefined"?!1:!!window[de]}function st(){if(ke())return;let r=()=>{document.documentElement.style.setProperty(ni,`${window.innerHeight}px`),window[de]=!0},i=rt(r,100);return window.addEventListener("resize",i,{passive:!0}),r(),()=>{window[de]=!1,window.removeEventListener("resize",i)}}var ai=r=>r,Le="{{",nt="}}",ot="plural:";function Ne(r,i,e={}){var n;let{openToken:t=Le,closeToken:s=nt,transform:o=ai}=e;for(let a in i){let l=(n=i[a])==null?void 0:n.toString();r=r.replaceAll(t+a+s,typeof l=="string"?o(l):l)}return r}function at(r){let i=[],e=r.indexOf(Le);for(;e!==-1;){let t=r.indexOf(nt,e),s=r.substring(e+2,t);if(s.startsWith(ot)){let o=r.substring(e+2,t).replace(ot,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));i.push({variable:s,pluralKey:n,countVariable:a})}e=r.indexOf(Le,t)}return i}var lt=()=>({"*blocksRegistry":new Set});function ht(r,i){[...r.querySelectorAll("[l10n]")].forEach(e=>{let t=e.getAttribute("l10n"),s="textContent";if(t.includes(":")){let n=t.split(":");s=n[0],t=n[1]}let o="l10n:"+t;i.__l10nKeys.push(o),i.add(o,t),i.sub(o,n=>{e[s]=i.l10n(n)}),e.removeAttribute("l10n")})}var E=r=>`*cfg/${r}`;var z=r=>{var i;return(i=r.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(e=>e.toLowerCase()).join("-")};var ct=new Set;function dt(r){ct.has(r)||(ct.add(r),console.warn(r))}var ut=(r,i)=>new Intl.PluralRules(r).select(i);var Me="lr-",_=class extends Pe{constructor(){super();f(this,"allowCustomTemplate",!0);f(this,"init$",lt());f(this,"updateCtxCssData",()=>{let e=this.$["*blocksRegistry"];for(let t of e)t.isConnected&&t.updateCssData()});this.activityType=null,this.addTemplateProcessor(ht),this.__l10nKeys=[]}l10n(e,t={}){if(!e)return"";let s=this.getCssData("--l10n-"+e,!0)||e,o=at(s);for(let a of o)t[a.variable]=this.pluralize(a.pluralKey,Number(t[a.countVariable]));return Ne(s,t)}pluralize(e,t){let s=this.l10n("locale-name")||"en-US",o=ut(s,t);return this.l10n(`${e}__${o}`)}applyL10nKey(e,t){let s="l10n:"+e;this.$[s]=t,this.__l10nKeys.push(e)}hasBlockInCtx(e){let t=this.$["*blocksRegistry"];for(let s of t)if(e(s))return!0;return!1}setForCtxTarget(e,t,s){this.hasBlockInCtx(o=>o.constructor.StateConsumerScope===e)&&(this.$[t]=s)}setActivity(e){if(this.hasBlockInCtx(t=>t.activityType===e)){this.$["*currentActivity"]=e;return}console.warn(`Activity type "${e}" not found in the context`)}connectedCallback(){let e=this.constructor.className;e&&this.classList.toggle(`${Me}${e}`,!0),ke()||(this._destroyInnerHeightTracker=st()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._destroyInnerHeightTracker)==null||e.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(e,t=2){let s=["B","KB","MB","GB","TB"],o=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(e===0)return`0 ${o(s[0])}`;let n=1024,a=t<0?0:t,l=Math.floor(Math.log(e)/Math.log(n));return parseFloat((e/n**l).toFixed(a))+" "+o(s[l])}proxyUrl(e){let t=this.cfg.secureDeliveryProxy;return t?Ne(t,{previewUrl:e},{transform:s=>window.encodeURIComponent(s)}):e}parseCfgProp(e){return{ctx:this.nodeCtx,name:e.replace("*","")}}get cfg(){if(!this.__cfgProxy){let e=Object.create(null);this.__cfgProxy=new Proxy(e,{get:(t,s)=>{let o=E(s),n=this.parseCfgProp(o);return n.ctx.has(n.name)?n.ctx.read(n.name):(dt("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${z(s)}`))}})}return this.__cfgProxy}subConfigValue(e,t){let s=this.parseCfgProp(E(e));s.ctx.has(s.name)?this.sub(E(e),t):(this.bindCssData(`--cfg-${z(e)}`),this.sub(`--cfg-${z(e)}`,t))}static reg(e){if(!e){super.reg();return}super.reg(e.startsWith(Me)?e:Me+e)}};f(_,"StateConsumerScope",null),f(_,"className","");var pt="--cfg-ctx-name",b=class extends _{get cfgCssCtxName(){return this.getCssData(pt,!0)}get cfgCtxName(){var e;let i=((e=this.getAttribute("ctx-name"))==null?void 0:e.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let e=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();e&&this.style.setProperty(pt,`'${e}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:g.getCtx(this.cfgCtxName)}}};function ft(...r){return r.reduce((i,e)=>{if(typeof e=="string")return i[e]=!0,i;for(let t of Object.keys(e))i[t]=e[t];return i},{})}function x(...r){let i=ft(...r);return Object.keys(i).reduce((e,t)=>(i[t]&&e.push(t),e),[]).join(" ")}function mt(r,...i){let e=ft(...i);for(let t of Object.keys(e))r.classList.toggle(t,e[t])}function P(r,i){let e,t=(...s)=>{clearTimeout(e),e=setTimeout(()=>r(...s),i)};return t.cancel=()=>{clearTimeout(e)},t}var De=(r,i=",")=>r.trim().split(i).map(e=>e.trim()).filter(e=>e.length>0);var T={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function li(r,i){if(typeof i=="number")return T[r]!==i?`${r}/${i}`:"";if(typeof i=="boolean")return i&&T[r]!==i?`${r}`:"";if(r==="filter"){if(!i||T[r]===i.amount)return"";let{name:e,amount:t}=i;return`${r}/${e}/${t}`}if(r==="crop"){if(!i)return"";let{dimensions:e,coords:t}=i;return`${r}/${e.join("x")}/${t.join(",")}`}return""}var gt=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function H(r){return le(...gt.filter(i=>typeof r[i]!="undefined"&&r[i]!==null).map(i=>{let e=r[i];return li(i,e)}).filter(i=>!!i))}var ue=le("format/auto","progressive/yes"),B=([r])=>typeof r!="undefined"?Number(r):void 0,_t=()=>!0,hi=([r,i])=>({name:r,amount:typeof i!="undefined"?Number(i):100}),ci=([r,i])=>({dimensions:De(r,"x").map(Number),coords:De(i).map(Number)}),di={enhance:B,brightness:B,exposure:B,gamma:B,contrast:B,saturation:B,vibrance:B,warmth:B,filter:hi,mirror:_t,flip:_t,rotate:B,crop:ci};function bt(r){let i={};for(let e of r){let[t,...s]=e.split("/");if(!gt.includes(t))continue;let o=di[t],n=o(s);i[t]=n}return i}function vt(r){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:I,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=r.querySelectorAll("img");for(let e of i){let t=e.src;e.src=I,e.src=t}r.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let e=r.$["*originalUrl"],t=R(H(i)),s=M(e,R(t,"preview")),o={originalUrl:e,cdnUrlModifiers:t,cdnUrl:s,transformations:i};r.dispatchEvent(new CustomEvent("apply",{detail:o,bubbles:!0,composed:!0})),r.remove()},"*on.cancel":()=>{r.remove(),r.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var xt=`
Network error
{{fileType}}
{{msg}}
`;var w={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},pe=[w.CROP,w.SLIDERS,w.FILTERS],wt=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],yt=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],Ct=["rotate","mirror","flip"],k={brightness:{zero:T.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:T.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:T.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:T.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:T.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:T.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:T.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:T.enhance,range:[0,100],keypointsNumber:1},filter:{zero:T.filter,range:[0,100],keypointsNumber:1}};var X=class extends b{constructor(){super(...arguments);f(this,"init$",{...this.init$,...vt(this)});f(this,"_debouncedShowLoader",P(this._showLoader.bind(this),300))}get ctxName(){return this.autoCtxName}_showLoader(e){this.$.showLoader=e}_waitForSize(){return new Promise((t,s)=>{let o=setTimeout(()=>{s(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),n=new ResizeObserver(([a])=>{a.contentRect.width>0&&a.contentRect.height>0&&(t(),clearTimeout(o),n.disconnect())});n.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){try{await this._waitForSize()}catch(e){this.isConnected&&console.error(e.message);return}if(this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==I&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",e=>{let t=this.ref["img-el"];t.src!==e&&(this._imgLoading=!0,t.src=e||I)}),this.sub("*tabId",e=>{this.ref["img-el"].className=x("image",{image_hidden_to_cropper:e===w.CROP,image_hidden_effects:e!==w.CROP})}),this.$.cdnUrl){let e=We(this.$.cdnUrl);this.$["*originalUrl"]=Re(this.$.cdnUrl,e);let t=Ve(this.$.cdnUrl),s=bt(t);this.$["*editorTransformations"]=s}else if(this.$.uuid)this.$["*originalUrl"]=Re(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");this.classList.add("editor_ON"),this.sub("*networkProblems",e=>{this.$["presence.networkProblems"]=e,this.$["presence.modalCaption"]=!e}),this.sub("*editorTransformations",e=>{let t=this.$["*originalUrl"],s=R(H(e)),o=M(t,R(s,"preview")),n={originalUrl:t,cdnUrlModifiers:s,cdnUrl:o,transformations:e};this.dispatchEvent(new CustomEvent("change",{detail:n,bubbles:!0,composed:!0}))},!1);try{fetch(M(this.$["*originalUrl"],R("json"))).then(e=>e.json()).then(e=>{let{width:t,height:s}=e;this.$["*imageSize"]={width:t,height:s}})}catch(e){e&&console.error("Failed to load image info",e)}}};f(X,"className","cloud-image-editor");X.template=xt;X.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl"});var ee=33.333333333333336,$=24*2+34;function j(r,i){for(let e in i)r.setAttributeNS(null,e,i[e].toString())}function S(r,i={}){let e=document.createElementNS("http://www.w3.org/2000/svg",r);return j(e,i),e}function Tt(r,i){let{x:e,y:t,width:s,height:o}=r,n=i.includes("w")?0:1,a=i.includes("n")?0:1,l=[-1,1][n],c=[-1,1][a],h=[e+n*s+1.5*l,t+a*o+1.5*c-24*c],d=[e+n*s+1.5*l,t+a*o+1.5*c],u=[e+n*s-24*l+1.5*l,t+a*o+1.5*c];return{d:`M ${h[0]} ${h[1]} L ${d[0]} ${d[1]} L ${u[0]} ${u[1]}`,center:d}}function Et(r,i){let{x:e,y:t,width:s,height:o}=r,n=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],l=[-1,1][n],c=[-1,1][a],h,d;["n","s"].includes(i)?(h=[e+n*s-34/2,t+a*o+1.5*c],d=[e+n*s+34/2,t+a*o+1.5*c]):(h=[e+n*s+1.5*l,t+a*o-34/2],d=[e+n*s+1.5*l,t+a*o+34/2]);let u=`M ${h[0]} ${h[1]} L ${d[0]} ${d[1]}`,m=[d[0]-(d[0]-h[0])/2,d[1]-(d[1]-h[1])/2];return{d:u,center:m}}function $t(r){return r===""?"move":["e","w"].includes(r)?"ew-resize":["n","s"].includes(r)?"ns-resize":["nw","se"].includes(r)?"nwse-resize":"nesw-resize"}function St(r,[i,e]){return{...r,x:r.x+i,y:r.y+e}}function fe(r,i){let{x:e}=r,{y:t}=r;return r.xi.x+i.width&&(e=i.x+i.width-r.width),r.yi.y+i.height&&(t=i.y+i.height-r.height),{...r,x:e,y:t}}function At(r,[i,e],t){let{x:s,y:o,width:n,height:a}=r;return t.includes("n")&&(o+=e,a-=e),t.includes("s")&&(a+=e),t.includes("w")&&(s+=i,n-=i),t.includes("e")&&(n+=i),{x:s,y:o,width:n,height:a}}function Rt(r,i){let e=Math.max(r.x,i.x),t=Math.min(r.x+r.width,i.x+i.width),s=Math.max(r.y,i.y),o=Math.min(r.y+r.height,i.y+i.height);return{x:e,y:s,width:t-e,height:o-s}}function me(r,[i,e],t){let{x:s,y:o,width:n,height:a}=r;if(t.includes("n")){let l=a;a=Math.max(e,a),o=o+l-a}if(t.includes("s")&&(a=Math.max(e,a)),t.includes("w")){let l=n;n=Math.max(i,n),s=s+l-n}return t.includes("e")&&(n=Math.max(i,n)),{x:s,y:o,width:n,height:a}}function Ot(r,[i,e]){return r.x<=i&&i<=r.x+r.width&&r.y<=e&&e<=r.y+r.height}var _e=class extends b{constructor(){super();f(this,"init$",{...this.init$,dragging:!1});this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(e){let t=this.$["*imageBox"];if(!t)return;if(e===""&&t.height<=$&&t.width<=$)return!0;let s=t.height<=$&&(e.includes("n")||e.includes("s")),o=t.width<=$&&(e.includes("e")||e.includes("w"));return s||o}_createBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:t,y:s,width:o,height:n}=e,a=this.ref["svg-el"],l=S("mask",{id:"backdrop-mask"}),c=S("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=S("rect",{x:t,y:s,width:o,height:n,fill:"black"});l.appendChild(c),l.appendChild(h);let d=S("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});a.appendChild(d),a.appendChild(l),this._backdropMask=l,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask.style.display="block"}))}_updateBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:t,y:s,width:o,height:n}=e;j(this._backdropMaskInner,{x:t,y:s,width:o,height:n})}_updateFrame(){let e=this.$["*cropBox"];if(!e)return;for(let s of Object.values(this._frameThumbs)){let{direction:o,pathNode:n,interactionNode:a,groupNode:l}=s,c=o==="",h=o.length===2;if(c){let{x:u,y:m,width:v,height:V}=e,C=[u+v/2,m+V/2];j(a,{r:Math.min(v,V)/3,cx:C[0],cy:C[1]})}else{let{d:u,center:m}=h?Tt(e,o):Et(e,o);j(a,{cx:m[0],cy:m[1]}),j(n,{d:u})}let d=this._shouldThumbBeDisabled(o);l.setAttribute("class",x("thumb",{"thumb--hidden":d,"thumb--visible":!d}))}let t=this._frameGuides;j(t,{x:e.x-1*.5,y:e.y-1*.5,width:e.width+1,height:e.height+1})}_createThumbs(){let e={};for(let t=0;t<3;t++)for(let s=0;s<3;s++){let o=`${["n","","s"][t]}${["w","","e"][s]}`,n=S("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let a=S("circle",{r:24+1.5,fill:"transparent"}),l=S("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(a),e[o]={direction:o,pathNode:l,interactionNode:a,groupNode:n},a.addEventListener("pointerdown",this._handlePointerDown.bind(this,o))}return e}_createGuides(){let e=S("svg"),t=S("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});e.appendChild(t);for(let s=1;s<=2;s++){let o=S("line",{x1:`${ee*s}%`,y1:"0%",x2:`${ee*s}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});e.appendChild(o)}for(let s=1;s<=2;s++){let o=S("line",{x1:"0%",y1:`${ee*s}%`,x2:"100%",y2:`${ee*s}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});e.appendChild(o)}return e.classList.add("guides","guides--semi-hidden"),e}_createFrame(){let e=this.ref["svg-el"],t=document.createDocumentFragment(),s=this._createGuides();t.appendChild(s);let o=this._createThumbs();for(let{groupNode:n}of Object.values(o))t.appendChild(n);e.appendChild(t),this._frameThumbs=o,this._frameGuides=s}_handlePointerDown(e,t){let s=this._frameThumbs[e];if(this._shouldThumbBeDisabled(e))return;let o=this.$["*cropBox"],{x:n,y:a}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,c=t.y-a;this.$.dragging=!0,this._draggingThumb=s,this._dragStartPoint=[l,c],this._dragStartCrop={...o}}_handlePointerUp_(e){this._updateCursor(),this.$.dragging&&(e.stopPropagation(),e.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(e){if(!this.$.dragging)return;e.stopPropagation(),e.preventDefault();let t=this.ref["svg-el"],{x:s,y:o}=t.getBoundingClientRect(),n=e.x-s,a=e.y-o,l=n-this._dragStartPoint[0],c=a-this._dragStartPoint[1],{direction:h}=this._draggingThumb,d=this.$["*imageBox"],u=this._dragStartCrop;h===""?(u=St(u,[l,c]),u=fe(u,d)):(u=At(u,[l,c],h),u=Rt(u,d));let m=[Math.min(d.width,$),Math.min(d.height,$)];if(u=me(u,m,h),!Object.values(u).every(v=>Number.isFinite(v)&&v>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:u});return}this.$["*cropBox"]=u}_handleSvgPointerMove_(e){let t=Object.values(this._frameThumbs).find(s=>{if(this._shouldThumbBeDisabled(s.direction))return!1;let n=s.groupNode.getBoundingClientRect(),a={x:n.x,y:n.y,width:n.width,height:n.height};return Ot(a,[e.x,e.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let e=this._hoverThumb;this.ref["svg-el"].style.cursor=e?$t(e.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(e){Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",x("thumb",{"thumb--hidden":!e,"thumb--visible":e}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",e=>{e&&(this._guidesHidden=e.height<=$||e.width<=$,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",e=>{this._frameGuides.setAttribute("class",x({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&e,"guides--semi-hidden":!this._guidesHidden&&!e}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};_e.template='';var U=class extends b{constructor(){super(...arguments);f(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",e=>{this._titleEl&&(this._titleEl.style.display=e?"block":"none")}),this.sub("active",e=>{this.className=x({active:e,not_active:!e})}),this.sub("on.click",e=>{this.onclick=e})}};U.template=`
{{title}}
`;function pi(r){let i=r+90;return i=i>=360?0:i,i}function fi(r,i){return r==="rotate"?pi(i):["mirror","flip"].includes(r)?!i:null}var Y=class extends U{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let e=this.$["*cropperEl"].getValue(this._operation),t=fi(this._operation,e);this.$["*cropperEl"].setValue(this._operation,t)}}};var te={FILTER:"filter",COLOR_OPERATION:"color_operation"},L="original",ge=class extends b{constructor(){super(...arguments);f(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":e=>{this.$["*faderEl"].set(e),this.$.value=e}})}setOperation(e,t){this._controlType=e==="filter"?te.FILTER:te.COLOR_OPERATION,this._operation=e,this._iconName=e,this._title=e.toUpperCase(),this._filter=t,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===L?void 0:this.$.value,filter:this._filter===L?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:e,zero:t}=k[this._operation],[s,o]=e;this.$.min=s,this.$.max=o,this.$.zero=t;let n=this.$["*editorTransformations"][this._operation];if(this._controlType===te.FILTER){let a=o;if(n){let{name:l,amount:c}=n;a=l===this._filter?c:o}this.$.value=a,this.$.defaultValue=a}if(this._controlType===te.COLOR_OPERATION){let a=typeof n!="undefined"?n:t;this.$.value=a,this.$.defaultValue=a}}apply(){let e;this._controlType===te.FILTER?this._filter===L?e=null:e={name:this._filter,amount:this.$.value}:e=this.$.value;let t={...this.$["*editorTransformations"],[this._operation]:e};this.$["*editorTransformations"]=t}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",e=>{this._originalUrl=e}),this.sub("value",e=>{let t=`${this._filter||this._operation} ${e}`;this.$["*operationTooltip"]=t})}};ge.template=``;function ie(r){let i=new Image;return{promise:new Promise((s,o)=>{i.src=r,i.onload=s,i.onerror=o}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=I)}}}function re(r){let i=[];for(let o of r){let n=ie(o);i.push(n)}let e=i.map(o=>o.image);return{promise:Promise.allSettled(i.map(o=>o.promise)),images:e,cancel:()=>{i.forEach(o=>{o.cancel()})}}}var W=class extends U{constructor(){super(...arguments);f(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let e=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),t=window.devicePixelRatio,s=Math.ceil(t*e),o=t>=2?"lightest":"normal",n=100,a={...this.$["*editorTransformations"]};return a[this._operation]=this._filter!==L?{name:this._filter,amount:n}:void 0,M(this._originalUrl,R(ue,H(a),`quality/${o}`,`scale_crop/${s}x${s}/center`))}_observerCallback(e,t){if(e[0].isIntersecting){let o=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"],{promise:a,cancel:l}=ie(o);this._cancelPreload=l,a.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{n.style.backgroundImage=`url(${o})`,n.setAttribute("loaded",""),t.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",t=>{this._operation="filter",this._filter=t,this.$.isOriginal=t===L,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let e=this.$["*originalUrl"];this._originalUrl=e,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",t=>{this.$.active=t&&t===this._filter}),this.sub("isOriginal",t=>{this.$.iconSize=t?40:20}),this.sub("active",t=>{if(this.$.isOriginal)return;let s=this.ref["icon-el"];s.style.opacity=t?"1":"0";let o=this.ref["preview-el"];t?o.style.opacity="0":o.style.backgroundImage&&(o.style.opacity="1")}),this.sub("*networkProblems",t=>{if(!t){let s=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"];o.style.backgroundImage&&(o.style.backgroundImage="none",o.style.backgroundImage=`url(${s})`)}})}destroyCallback(){var e;super.destroyCallback(),(e=this._observer)==null||e.disconnect(),this._cancelPreload&&this._cancelPreload()}};W.template=`
`;var Z=class extends U{constructor(){super(...arguments);f(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",e=>{e&&(this._operation=e,this.$.icon=e,this.$.title=this.l10n(e))}),this.sub("*editorTransformations",e=>{if(!this._operation)return;let{zero:t}=k[this._operation],s=e[this._operation],o=typeof s!="undefined"?s!==t:!1;this.$.active=o})}};function It(r,i){let e={};for(let t of i){let s=r[t];(r.hasOwnProperty(t)||s!==void 0)&&(e[t]=s)}return e}function Q(r,i,e){let s=window.devicePixelRatio,o=Math.min(Math.ceil(i*s),3e3),n=s>=2?"lightest":"normal";return M(r,R(ue,H(e),`quality/${n}`,`stretch/off/-/resize/${o}x`))}function be(r,i,e){return Math.min(Math.max(r,i),e)}function se({width:r,height:i},e){let t=e/90%2!==0;return{width:t?i:r,height:t?r:i}}function _i(r){return r?[({dimensions:e,coords:t})=>[...e,...t].every(s=>Number.isInteger(s)&&Number.isFinite(s)),({dimensions:e,coords:t})=>e.every(s=>s>0)&&t.every(s=>s>=0)].every(e=>e(r)):!0}var ve=class extends b{constructor(){super();f(this,"init$",{...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}});this._commitDebounced=P(this._commit.bind(this),300),this._handleResizeDebounced=P(this._handleResize.bind(this),10)}_handleResize(){this.isConnected&&(this.deactivate(),this.activate(this._imageSize,{fromViewer:!1}))}_syncTransformations(){let e=this.$["*editorTransformations"],t=It(e,Object.keys(this.$["*operations"])),s={...this.$["*operations"],...t};this.$["*operations"]=s}_initCanvas(){let e=this.ref["canvas-el"],t=e.getContext("2d"),s=this.offsetWidth,o=this.offsetHeight,n=window.devicePixelRatio;e.style.width=`${s}px`,e.style.height=`${o}px`,e.width=s*n,e.height=o*n,t.scale(n,n),this._canvas=e,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let e=this.$.image,t=this.$["*padding"],s=this.$["*operations"],{rotate:o}=s,n={width:this.offsetWidth,height:this.offsetHeight},a=se({width:e.naturalWidth,height:e.naturalHeight},o);if(a.width>n.width-t*2||a.height>n.height-t*2){let l=a.width/a.height,c=n.width/n.height;if(l>c){let h=n.width-t*2,d=h/l,u=0+t,m=t+(n.height-t*2)/2-d/2;this.$["*imageBox"]={x:u,y:m,width:h,height:d}}else{let h=n.height-t*2,d=h*l,u=t+(n.width-t*2)/2-d/2,m=0+t;this.$["*imageBox"]={x:u,y:m,width:d,height:h}}}else{let{width:l,height:c}=a,h=t+(n.width-t*2)/2-l/2,d=t+(n.height-t*2)/2-c/2;this.$["*imageBox"]={x:h,y:d,width:l,height:c}}}_alignCrop(){let e=this.$["*cropBox"],t=this.$["*imageBox"],s=this.$["*operations"],{rotate:o}=s,n=this.$["*editorTransformations"].crop;if(n){let{dimensions:[l,c],coords:[h,d]}=n,{width:u,x:m,y:v}=this.$["*imageBox"],{width:V}=se(this._imageSize,o),C=u/V;e={x:m+h*C,y:v+d*C,width:l*C,height:c*C}}else e={x:t.x,y:t.y,width:t.width,height:t.height};let a=[Math.min(t.width,$),Math.min(t.height,$)];e=me(e,a,"se"),e=fe(e,t),this.$["*cropBox"]=e}_drawImage(){let e=this.$.image,t=this.$["*imageBox"],s=this.$["*operations"],{mirror:o,flip:n,rotate:a}=s,l=this._ctx,c=se({width:t.width,height:t.height},a);l.save(),l.translate(t.x+t.width/2,t.y+t.height/2),l.rotate(a*Math.PI*-1/180),l.scale(o?-1:1,n?-1:1),l.drawImage(e,-c.width/2,-c.height/2,c.width,c.height),l.restore()}_draw(){if(!this._isActive||!this.$.image)return;let e=this._canvas;this._ctx.clearRect(0,0,e.width,e.height),this._drawImage()}_animateIn({fromViewer:e}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=x({active_from_viewer:e,active_from_editor:!e,inactive_to_editor:!1})}))}_calculateDimensions(){let e=this.$["*cropBox"],t=this.$["*imageBox"],s=this.$["*operations"],{rotate:o}=s,{width:n,height:a}=t,{width:l,height:c}=se(this._imageSize,o),{width:h,height:d}=e,u=n/l,m=a/c;return[be(Math.round(h/u),1,l),be(Math.round(d/m),1,c)]}_calculateCrop(){let e=this.$["*cropBox"],t=this.$["*imageBox"],s=this.$["*operations"],{rotate:o}=s,{width:n,height:a,x:l,y:c}=t,{width:h,height:d}=se(this._imageSize,o),{x:u,y:m}=e,v=n/h,V=a/d,C=this._calculateDimensions(),Ae={dimensions:C,coords:[be(Math.round((u-l)/v),0,h-C[0]),be(Math.round((m-c)/V),0,d-C[1])]};if(!_i(Ae)){console.error("Cropper is trying to create invalid crop object",{payload:Ae});return}if(!(C[0]===h&&C[1]===d))return Ae}_commit(){if(!this.isConnected)return;let e=this.$["*operations"],{rotate:t,mirror:s,flip:o}=e,n=this._calculateCrop(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:s,flip:o};this.$["*editorTransformations"]=l}setValue(e,t){console.log(`Apply cropper operation [${e}=${t}]`),this.$["*operations"]={...this.$["*operations"],[e]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(e){return this.$["*operations"][e]}async activate(e,{fromViewer:t}){if(!this._isActive){this._isActive=!0,this._imageSize=e,this.removeEventListener("transitionend",this._reset),this._initCanvas();try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw(),this._animateIn({fromViewer:t})}catch(s){console.error("Failed to activate cropper",{error:s})}}}deactivate(){this._isActive&&(this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=x({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}))}_transitionToCrop(){let e=this._calculateDimensions(),t=Math.min(this.offsetWidth,e[0])/this.$["*cropBox"].width,s=Math.min(this.offsetHeight,e[1])/this.$["*cropBox"].height,o=Math.min(t,s),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,a=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${o}) translate(${(this.offsetWidth/2-n)/o}px, ${(this.offsetHeight/2-a)/o}px)`,this.style.transformOrigin=`${n}px ${a}px`}_transitionToImage(){let e=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${e}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(e,t){let s=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let o=this.proxyUrl(Q(e,s,t)),{promise:n,cancel:a,image:l}=ie(o),c=this._handleImageLoading(o);return l.addEventListener("load",c,{once:!0}),l.addEventListener("error",c,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=a,n.then(()=>l).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(e){let t="crop",s=this.$["*loadingOperations"];return s.get(t)||s.set(t,new Map),s.get(t).get(e)||(s.set(t,s.get(t).set(e,!0)),this.$["*loadingOperations"]=s),()=>{var o;(o=s==null?void 0:s.get(t))!=null&&o.has(e)&&(s.get(t).delete(e),this.$["*loadingOperations"]=s)}}initCallback(){super.initCallback(),this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeDebounced()}),this._observer.observe(this),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",e=>{this.$.image&&this._commitDebounced()}),setTimeout(()=>{this.sub("*networkProblems",e=>{e||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var e;super.destroyCallback(),(e=this._observer)==null||e.disconnect()}};ve.template=``;function Fe(r,i,e){let t=Array(e);e--;for(let s=e;s>=0;s--)t[s]=Math.ceil((s*i+(e-s)*r)/e);return t}function gi(r){return r.reduce((i,e,t)=>ts<=i&&i<=o);return r.map(s=>{let o=Math.abs(t[0]-t[1]),n=Math.abs(i-t[0])/o;return t[0]===s?i>e?1:1-n:t[1]===s?i>=e?n:1:0})}function vi(r,i){return r.map((e,t)=>eo-n)}var ze=class extends b{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=P(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let e=this._operation,t=this.$["*loadingOperations"];return t.get(e)||t.set(e,new Map),t.get(e).get(i)||(t.set(e,t.get(e).set(i,!0)),this.$["*loadingOperations"]=t),()=>{var s;(s=t==null?void 0:t.get(e))!=null&&s.has(i)&&(t.get(e).delete(i),this.$["*loadingOperations"]=t)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:e}=i;e&&(e.style.opacity=i.opacity.toString(),e.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:e=this._filter,operation:t,value:s}={}){let o={...this._transformations};t&&(o[t]=e?{name:e,amount:s}:s);let n=this.offsetWidth;return this.proxyUrl(Q(i,n,o))}_constructKeypoint(i,e){return{src:this._imageSrc({operation:i,value:e}),image:null,opacity:0,zIndex:0,value:e}}_isSame(i,e){return this._operation===i&&this._filter===e}_addKeypoint(i,e,t){let s=()=>!this._isSame(i,e)||this._value!==t||!!this._keypoints.find(l=>l.value===t);if(s())return;let o=this._constructKeypoint(i,t),n=new Image;n.src=o.src;let a=this._handleImageLoading(o.src);n.addEventListener("load",a,{once:!0}),n.addEventListener("error",a,{once:!0}),o.image=n,n.classList.add("fader-image"),n.addEventListener("load",()=>{if(s())return;let l=this._keypoints,c=l.findIndex(d=>d.value>t),h=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,e){this._operation=i,this._value=e;let{zero:t}=k[i],s=this._keypoints.map(a=>a.value),o=bi(s,e,t),n=vi(s,t);for(let[a,l]of Object.entries(this._keypoints))l.opacity=o[a],l.zIndex=n[a];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let e=document.createElement("div");i.appendChild(e);let t=this._keypoints.map(c=>c.src),{images:s,promise:o,cancel:n}=re(t);s.forEach(c=>{let h=this._handleImageLoading(c.src);c.addEventListener("load",h),c.addEventListener("error",h)}),this._cancelLastImages=()=>{n(),this._cancelLastImages=void 0};let a=this._operation,l=this._filter;await o,this._isActive&&this._isSame(a,l)&&(this._container&&this._container.remove(),this._container=e,this._keypoints.forEach((c,h)=>{let d=s[h];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let e=this._imageSrc(),t=this._handleImageLoading(e);this._previewImage.src=e,this._previewImage.addEventListener("load",t,{once:!0}),this._previewImage.addEventListener("error",t,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:e,operation:t,value:s}){this._cancelBatchPreload&&this._cancelBatchPreload();let n=Pt(t,s).map(l=>this._imageSrc({url:i,filter:e,operation:t,value:l})),{cancel:a}=re(n);this._cancelBatchPreload=a}_setOriginalSrc(i){let e=this._previewImage||this._createPreviewImage();if(!this.contains(e)&&this.appendChild(e),this._previewImage=e,e.src===i){e.style.opacity="1",e.style.transform="scale(1)",this.className=x({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}e.style.opacity="0";let t=this._handleImageLoading(i);e.addEventListener("error",t,{once:!0}),e.src=i,e.addEventListener("load",()=>{t(),e&&(e.style.opacity="1",e.style.transform="scale(1)",this.className=x({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),e.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:e,value:t,filter:s,fromViewer:o}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=e||"initial",this._value=t,this._filter=s,this._fromViewer=o,typeof t!="number"&&!s){let a=this._imageSrc({operation:e,value:t});this._setOriginalSrc(a),this._container&&this._container.remove();return}this._keypoints=Pt(e,t).map(a=>this._constructKeypoint(e,a)),this._update(e,t),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=x({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var xi=1,xe=class extends b{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:e,deltaX:t}=i;Math.abs(t)>xi?this.scrollLeft+=t:this.scrollLeft+=e})}};xe.template=" ";function wi(r){return``}function yi(r){return`
`}var we=class extends b{constructor(){super();f(this,"_updateInfoTooltip",P(()=>{var o,n;let e=this.$["*editorTransformations"],t="",s=!1;if(this.$["*tabId"]===w.FILTERS)if(s=!0,this.$["*currentFilter"]&&((o=e==null?void 0:e.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((n=e==null?void 0:e.filter)==null?void 0:n.amount)||100;t=this.l10n(this.$["*currentFilter"])+" "+a}else t=this.l10n(L);else if(this.$["*tabId"]===w.SLIDERS&&this.$["*currentOperation"]){s=!0;let a=(e==null?void 0:e[this.$["*currentOperation"]])||k[this.$["*currentOperation"]].zero;t=this.$["*currentOperation"]+" "+a}s&&(this.$["*operationTooltip"]=t),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",s)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":L,"*currentOperation":null,"*tabId":w.CROP,showLoader:!1,filters:yt,colorOperations:wt,cropOperations:Ct,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":e=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":e=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":e=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":e=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":e=>{let t=e.currentTarget.getAttribute("data-id");this._activateTab(t,{fromViewer:!1})}},this._debouncedShowLoader=P(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===w.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(e){let t=Z.is&&new Z;return t.operation=e,t}_createFilterControl(e){let t=W.is&&new W;return t.filter=e,t}_createToggleControl(e){let t=Y.is&&new Y;return t.operation=e,t}_renderControlsList(e){let t=this.ref[`controls-list-${e}`],s=document.createDocumentFragment();e===w.CROP?this.$.cropOperations.forEach(o=>{let n=this._createToggleControl(o);s.appendChild(n)}):e===w.FILTERS?[L,...this.$.filters].forEach(o=>{let n=this._createFilterControl(o);s.appendChild(n)}):e===w.SLIDERS&&this.$.colorOperations.forEach(o=>{let n=this._createOperationControl(o);s.appendChild(n)}),s.childNodes.forEach((o,n)=>{n===s.childNodes.length-1&&o.classList.add("controls-list_last-item")}),t.innerHTML="",t.appendChild(s)}_activateTab(e,{fromViewer:t}){this.$["*tabId"]=e,e===w.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:t})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:t}),this.$["*cropperEl"].deactivate());for(let s of pe){let o=s===e,n=this.ref[`tab-toggle-${s}`];n.active=o,o?(this._renderControlsList(e),this._syncTabIndicator()):this._unmountTabControls(s),this.$[`presence.tabContent.${s}`]=o}}_unmountTabControls(e){let t=this.ref[`controls-list-${e}`];t&&(t.innerHTML="")}_syncTabIndicator(){let e=this.ref[`tab-toggle-${this.$["*tabId"]}`],t=this.ref["tabs-indicator"];t.style.transform=`translateX(${e.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let e=this.$["*imgContainerEl"].offsetWidth,t=this.proxyUrl(Q(this.$["*originalUrl"],e,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:s}=re([t]);this._cancelPreload=()=>{s(),this._cancelPreload=void 0}}}_showLoader(e){this.$.showLoader=e}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",e=>{e&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",e=>{var s;let t=(s=e==null?void 0:e.filter)==null?void 0:s.name;this.$["*currentFilter"]!==t&&(this.$["*currentFilter"]=t)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",e=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",e=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(e)}),this.sub("*loadingOperations",e=>{let t=!1;for(let[,s]of e.entries()){if(t)break;for(let[,o]of s.entries())if(o){t=!0;break}}this._debouncedShowLoader(t)}),this.sub("*showSlider",e=>{this.$["presence.subToolbar"]=e,this.$["presence.mainToolbar"]=!e}),this._updateInfoTooltip()}};we.template=`
{{*operationTooltip}}
${pe.map(yi).join("")}
${pe.map(wi).join("")}
`;var oe=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return x("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};oe.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});oe.template=`
{{text}}
`;var ye=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),e=this.ref["line-el"];e.style.transition="transform 1s",e.style.opacity="1",e.style.transform=`translateX(${i}px)`,e.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};ye.template=`
`;var Ce={transition:"transition",visible:"visible",hidden:"hidden"},Te=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=Ce.visible,this._hiddenStyle=Ce.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",mt(this,{[Ce.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(Ce.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};Te.template=" ";var Ee=class extends _{constructor(){super();f(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e),this.$.onInput&&this.$.onInput(e)},"on.sliderChange":()=>{let e=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(e)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",t=>{this.$.disabled=t}),this.defineAccessor("min",t=>{this.$.min=t}),this.defineAccessor("max",t=>{this.$.max=t}),this.defineAccessor("defaultValue",t=>{this.$.defaultValue=t,this.ref["input-el"].value=t,this._updateValue(t)}),this.defineAccessor("zero",t=>{this._zero=t}),this.defineAccessor("onInput",t=>{t&&(this.$.onInput=t)}),this.defineAccessor("onChange",t=>{t&&(this.$.onChange=t)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t)},0),this.sub("disabled",t=>{let s=this.ref["input-el"];t?s.setAttribute("disabled","disabled"):s.removeAttribute("disabled")});let e=this.ref["input-el"];e.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),e.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(e){this._updateZeroDot(e);let{width:t}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(e-this.$.min)*(t-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${n}px)`})}_updateZeroDot(e){if(!this._zeroDotEl)return;e===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:t}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(t-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${n}px)`})}_updateSteps(){let t=this.ref["steps-el"],{width:s}=t.getBoundingClientRect(),o=Math.ceil(s/2),n=Math.ceil(o/15)-2;if(this._stepsCount===n)return;let a=document.createDocumentFragment(),l=document.createElement("div"),c=document.createElement("div");l.className="minor-step",c.className="border-step",a.appendChild(c);for(let d=0;d
`;var Ci="css-src";function He(r){return class extends r{constructor(){super(...arguments);f(this,"renderShadow",!0);f(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let e=this.getAttribute(Ci);if(e){this.attachShadow({mode:"open"});let t=document.createElement("link");t.rel="stylesheet",t.type="text/css",t.href=e,t.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(t)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var kt=class extends He(_){};var Lt=class extends He(X){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};var ne=class extends _{constructor(){super(...arguments);f(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",e=>{if(!e)return;let t=this.getCssData(`--icon-${e}`);t&&(this.$.path=t)}),this.sub("path",e=>{if(!e)return;e.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=e):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",e=>{this.$.viewBox=`0 0 ${e} ${e}`})}};ne.template=``;ne.bindAttributes({name:"name",size:"size"});function Ti(r){for(let i in r){let e=[...i].reduce((t,s)=>(s.toUpperCase()===s&&(s="-"+s.toLowerCase()),t+=s),"");e.startsWith("-")&&(e=e.replace("-","")),e.startsWith("lr-")||(e="lr-"+e),r[i].reg&&r[i].reg(e)}}var Ei="https://ucarecdn.com",$i="https://upload.uploadcare.com",Si="https://social.uploadcare.com",ae=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Ei,baseUrl:$i,socialBaseUrl:Si,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var A=r=>String(r),N=r=>Number(r),y=r=>typeof r=="boolean"?r:r==="true"||r===""?!0:r==="false"?!1:!!r,Ai=r=>r==="auto"?r:y(r),Ri={pubkey:A,multiple:y,multipleMin:N,multipleMax:N,confirmUpload:y,imgOnly:y,accept:A,externalSourcesPreferredTypes:A,store:Ai,cameraMirror:y,sourceList:A,maxLocalFileSizeBytes:N,thumbSize:N,showEmptyList:y,useLocalImageEditor:y,useCloudImageEditor:y,removeCopyright:y,modalScrollLock:y,modalBackdropStrokes:y,sourceListWrap:y,remoteTabSessionKey:A,cdnCname:A,baseUrl:A,socialBaseUrl:A,secureSignature:A,secureExpire:A,secureDeliveryProxy:A,retryThrottledRequestMaxTimes:N,multipartMinFileSize:N,multipartChunkSize:N,maxConcurrentRequests:N,multipartMaxConcurrentRequests:N,multipartMaxAttempts:N,checkForUrlDuplicates:y,saveUrlForRecurrentUploads:y,groupOutput:y,userAgentIntegration:A},Nt=(r,i)=>{if(!(typeof i=="undefined"||i===null))return Ri[r](i)};var $e=Object.keys(ae),Oi=["metadata"],Ii=r=>Oi.includes(r),Xe=$e.filter(r=>!Ii(r)),Pi={...Object.fromEntries(Xe.map(r=>[z(r),r])),...Object.fromEntries(Xe.map(r=>[r.toLowerCase(),r]))},ki={...Object.fromEntries($e.map(r=>[z(r),E(r)])),...Object.fromEntries($e.map(r=>[r.toLowerCase(),E(r)]))},Se=class extends _{constructor(){super(...arguments);f(this,"ctxOwner",!0);f(this,"init$",{...this.init$,...Object.fromEntries(Object.entries(ae).map(([e,t])=>[E(e),t]))})}initCallback(){super.initCallback();for(let e of $e){let t=this,s="__"+e;t[s]=t[e],Object.defineProperty(this,e,{set:o=>{if(t[s]=o,Xe.includes(e)){let n=[...new Set([z(e),e.toLowerCase()])];for(let a of n)typeof o=="undefined"||o===null?this.removeAttribute(a):this.setAttribute(a,o.toString())}this.$[E(e)]!==o&&(typeof o=="undefined"||o===null?this.$[E(e)]=ae[e]:this.$[E(e)]=o)},get:()=>this.$[E(e)]}),typeof t[e]!="undefined"&&t[e]!==null&&(t[e]=t[s])}}attributeChangedCallback(e,t,s){if(t===s)return;let o=Pi[e],n=Nt(o,s),a=n!=null?n:ae[o],l=this;l[o]=a}};Se.bindAttributes(ki);export{Lt as CloudImageEditor,X as CloudImageEditorBlock,Se as Config,_e as CropFrame,Y as EditorCropButtonControl,W as EditorFilterControl,ve as EditorImageCropper,ze as EditorImageFader,Z as EditorOperationControl,xe as EditorScroller,ge as EditorSlider,we as EditorToolbar,ne as Icon,ye as LineLoaderUi,oe as LrBtnUi,Te as PresenceToggle,Ee as SliderUi,Ti as registerBlocks}; \ No newline at end of file +var Fe=Object.defineProperty;var ze=(r,e,t)=>e in r?Fe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var m=(r,e,t)=>(ze(r,typeof e!="symbol"?e+"":e,t),t);var Wt=r=>{if(typeof r!="string"||!r)return"";let e=r.trim();return e.startsWith("-/")?e=e.slice(2):e.startsWith("/")&&(e=e.slice(1)),e.endsWith("/")&&(e=e.slice(0,e.length-1)),e},pt=(...r)=>r.filter(e=>typeof e=="string"&&e).map(e=>Wt(e)).join("/-/"),I=(...r)=>{let e=pt(...r);return e?`-/${e}/`:""};function Kt(r){let e=new URL(r),t=e.pathname+e.search+e.hash,i=t.lastIndexOf("http"),s=t.lastIndexOf("/"),o="";return i>=0?o=t.slice(i):s>=0&&(o=t.slice(s+1)),o}function Vt(r){let e=new URL(r),{pathname:t}=e,i=t.indexOf("/"),s=t.indexOf("/",i+1);return t.substring(i+1,s)}function Gt(r){let e=qt(r),t=new URL(e),i=t.pathname.indexOf("/-/");return i===-1?[]:t.pathname.substring(i).split("/-/").filter(Boolean).map(o=>Wt(o))}function qt(r){let e=new URL(r),t=Kt(r),i=Yt(t)?Zt(t).pathname:t;return e.pathname=e.pathname.replace(i,""),e.search="",e.hash="",e.toString()}function Yt(r){return r.startsWith("http")}function Zt(r){let e=new URL(r);return{pathname:e.origin+e.pathname||"",search:e.search||"",hash:e.hash||""}}var M=(r,e,t)=>{let i=new URL(qt(r));if(t=t||Kt(r),i.pathname.startsWith("//")&&(i.pathname=i.pathname.replace("//","/")),Yt(t)){let s=Zt(t);i.pathname=i.pathname+(e||"")+(s.pathname||""),i.search=s.search,i.hash=s.hash}else i.pathname=i.pathname+(e||"")+(t||"");return i.toString()},Pt=(r,e)=>{let t=new URL(r);return t.pathname=e+"/",t.toString()};var P="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";function O(r,e){let t,i=(...s)=>{clearTimeout(t),t=setTimeout(()=>r(...s),e)};return i.cancel=()=>{clearTimeout(t)},i}var He=Object.defineProperty,Xe=(r,e,t)=>e in r?He(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Rt=(r,e,t)=>(Xe(r,typeof e!="symbol"?e+"":e,t),t);function je(r){let e=t=>{var i;for(let s in t)((i=t[s])==null?void 0:i.constructor)===Object&&(t[s]=e(t[s]));return{...t}};return e(r)}var y=class{constructor(r){r.constructor===Object?this.store=je(r):(this._storeIsProxy=!0,this.store=r),this.callbackMap=Object.create(null)}static warn(r,e){console.warn(`Symbiote Data: cannot ${r}. Prop name: `+e)}read(r){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(y.warn("read",r),null):this.store[r]}has(r){return this._storeIsProxy?this.store[r]!==void 0:this.store.hasOwnProperty(r)}add(r,e,t=!1){!t&&Object.keys(this.store).includes(r)||(this.store[r]=e,this.notify(r))}pub(r,e){if(!this._storeIsProxy&&!this.store.hasOwnProperty(r)){y.warn("publish",r);return}this.store[r]=e,this.notify(r)}multiPub(r){for(let e in r)this.pub(e,r[e])}notify(r){this.callbackMap[r]&&this.callbackMap[r].forEach(e=>{e(this.store[r])})}sub(r,e,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(r)?(y.warn("subscribe",r),null):(this.callbackMap[r]||(this.callbackMap[r]=new Set),this.callbackMap[r].add(e),t&&e(this.store[r]),{remove:()=>{this.callbackMap[r].delete(e),this.callbackMap[r].size||delete this.callbackMap[r]},callback:e})}static registerCtx(r,e=Symbol()){let t=y.globalStore.get(e);return t?console.warn('State: context UID "'+e+'" already in use'):(t=new y(r),y.globalStore.set(e,t)),t}static deleteCtx(r){y.globalStore.delete(r)}static getCtx(r,e=!0){return y.globalStore.get(r)||(e&&console.warn('State: wrong context UID - "'+r+'"'),null)}};y.globalStore=new Map;var f=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),te="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Be=te.length-1,We=class{static generate(r="XXXXXXXXX-XXX"){let e="";for(let t=0;t{le&&t?e[0].toUpperCase()+e.slice(1):e).join("").split("_").map((e,t)=>e&&t?e.toUpperCase():e).join("")}function Ve(r,e){[...r.querySelectorAll(`[${f.REPEAT_ATTR}]`)].forEach(t=>{let i=t.getAttribute(f.REPEAT_ITEM_TAG_ATTR),s;if(i&&(s=window.customElements.get(i)),!s){s=class extends e.BaseComponent{constructor(){super(),i||(this.style.display="contents")}};let n=t.innerHTML;s.template=n,s.reg(i)}for(;t.firstChild;)t.firstChild.remove();let o=t.getAttribute(f.REPEAT_ATTR);e.sub(o,n=>{if(!n){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,h=c=>{c.forEach((u,_)=>{if(l[_])if(l[_].set$)setTimeout(()=>{l[_].set$(u)});else for(let g in u)l[_][g]=u[g];else{a||(a=new DocumentFragment);let g=new s;Object.assign(g.init$,u),a.appendChild(g)}}),a&&t.appendChild(a);let d=l.slice(c.length,l.length);for(let u of d)u.remove()};if(n.constructor===Array)h(n);else if(n.constructor===Object){let c=[];for(let d in n){let u=n[d];Object.defineProperty(u,"_KEY_",{value:d,enumerable:!0}),c.push(u)}h(c)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),t.removeAttribute(f.REPEAT_ATTR),t.removeAttribute(f.REPEAT_ITEM_TAG_ATTR)})}var Qt="__default__";function Ge(r,e){if(e.shadowRoot)return;let t=[...r.querySelectorAll("slot")];if(!t.length)return;let i={};t.forEach(s=>{let o=s.getAttribute("name")||Qt;i[o]={slot:s,fr:document.createDocumentFragment()}}),e.initChildren.forEach(s=>{var o;let n=Qt;s instanceof Element&&s.hasAttribute("slot")&&(n=s.getAttribute("slot"),s.removeAttribute("slot")),(o=i[n])==null||o.fr.appendChild(s)}),Object.values(i).forEach(s=>{if(s.fr.childNodes.length)s.slot.parentNode.replaceChild(s.fr,s.slot);else if(s.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...s.slot.childNodes),s.slot.parentNode.replaceChild(o,s.slot)}else s.slot.remove()})}function qe(r,e){[...r.querySelectorAll(`[${f.EL_REF_ATTR}]`)].forEach(t=>{let i=t.getAttribute(f.EL_REF_ATTR);e.ref[i]=t,t.removeAttribute(f.EL_REF_ATTR)})}function Ye(r,e){[...r.querySelectorAll(`[${f.BIND_ATTR}]`)].forEach(t=>{let s=t.getAttribute(f.BIND_ATTR).split(";");[...t.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=Ke(o.name.replace("-",""));s.push(n+":"+o.value),t.removeAttribute(o.name)}}),s.forEach(o=>{if(!o)return;let n=o.split(":").map(c=>c.trim()),l=n[0],a;l.indexOf(f.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(f.ATTR_BIND_PRFX,""));let h=n[1].split(",").map(c=>c.trim());for(let c of h){let d;c.startsWith("!!")?(d="double",c=c.replace("!!","")):c.startsWith("!")&&(d="single",c=c.replace("!","")),e.sub(c,u=>{d==="double"?u=!!u:d==="single"&&(u=!u),a?(u==null?void 0:u.constructor)===Boolean?u?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,u):ee(t,l,u)||(t[f.SET_LATER_KEY]||(t[f.SET_LATER_KEY]=Object.create(null)),t[f.SET_LATER_KEY][l]=u)})}}),t.removeAttribute(f.BIND_ATTR)})}var ft="{{",st="}}",Ze="skip-text";function Qe(r){let e,t=[],i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,{acceptNode:s=>{var o;return!((o=s.parentElement)!=null&&o.hasAttribute(Ze))&&s.textContent.includes(ft)&&s.textContent.includes(st)&&1}});for(;e=i.nextNode();)t.push(e);return t}var Je=function(r,e){Qe(r).forEach(i=>{let s=[],o;for(;i.textContent.includes(st);)i.textContent.startsWith(ft)?(o=i.textContent.indexOf(st)+st.length,i.splitText(o),s.push(i)):(o=i.textContent.indexOf(ft),i.splitText(o)),i=i.nextSibling;s.forEach(n=>{let l=n.textContent.replace(ft,"").replace(st,"");n.textContent="",e.sub(l,a=>{n.textContent=a})})})},ti=[Ve,Ge,qe,Ye,Je],mt="'",Y='"',ei=/\\([0-9a-fA-F]{1,6} ?)/g;function ii(r){return(r[0]===Y||r[0]===mt)&&(r[r.length-1]===Y||r[r.length-1]===mt)}function ri(r){return(r[0]===Y||r[0]===mt)&&(r=r.slice(1)),(r[r.length-1]===Y||r[r.length-1]===mt)&&(r=r.slice(0,-1)),r}function si(r){let e="",t="";for(var i=0;iString.fromCodePoint(parseInt(i.trim(),16))),e=e.replaceAll(`\\ +`,"\\n"),e=si(e),e=Y+e+Y);try{return JSON.parse(e)}catch{throw new Error(`Failed to parse CSS property value: ${e}. Original input: ${r}`)}}var Jt=0,q=null,D=null,z=class extends HTMLElement{constructor(){super(),Rt(this,"updateCssData",()=>{var r;this.dropCssDataCache(),(r=this.__boundCssProps)==null||r.forEach(e=>{let t=this.getCssData(this.__extractCssName(e),!0);t!==null&&this.$[e]!==t&&(this.$[e]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return z}initCallback(){}__initCallback(){var r;this.__initialized||(this.__initialized=!0,(r=this.initCallback)==null||r.call(this))}render(r,e=this.renderShadow){let t;if((e||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let s=this.getAttribute(f.USE_TPL);if(s){let o=this.getRootNode(),n=(o==null?void 0:o.querySelector(s))||document.querySelector(s);n?r=n.content.cloneNode(!0):console.warn(`Symbiote template "${s}" is not found...`)}}if(this.processInnerHtml)for(let s of this.tplProcessors)s(this,this);if(r||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(r==null?void 0:r.constructor)===DocumentFragment)t=r;else if((r==null?void 0:r.constructor)===String){let s=document.createElement("template");s.innerHTML=r,t=s.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let s of this.tplProcessors)s(t,this)}let i=()=>{t&&(e&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){e=!0;let s=document.createElement("link");s.rel="stylesheet",s.href=this.constructor.__shadowStylesUrl,s.onload=i,this.shadowRoot.prepend(s)}else i()}addTemplateProcessor(r){this.tplProcessors.add(r)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=We.generate(),this.style.setProperty(f.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(f.CSS_CTX_PROP,!0)}get ctxName(){var r;let e=((r=this.getAttribute(f.CTX_NAME_ATTR))==null?void 0:r.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=e,e}get localCtx(){return this.__localCtx||(this.__localCtx=y.registerCtx({},this)),this.__localCtx}get nodeCtx(){return y.getCtx(this.ctxName,!1)||y.registerCtx({},this.ctxName)}static __parseProp(r,e){let t,i;if(r.startsWith(f.EXT_DATA_CTX_PRFX))t=e.nodeCtx,i=r.replace(f.EXT_DATA_CTX_PRFX,"");else if(r.includes(f.NAMED_DATA_CTX_SPLTR)){let s=r.split(f.NAMED_DATA_CTX_SPLTR);t=y.getCtx(s[0]),i=s[1]}else t=e.localCtx,i=r;return{ctx:t,name:i}}sub(r,e,t=!0){let i=o=>{this.isConnected&&e(o)},s=z.__parseProp(r,this);s.ctx.has(s.name)?this.allSubs.add(s.ctx.sub(s.name,i,t)):window.setTimeout(()=>{this.allSubs.add(s.ctx.sub(s.name,i,t))})}notify(r){let e=z.__parseProp(r,this);e.ctx.notify(e.name)}has(r){let e=z.__parseProp(r,this);return e.ctx.has(e.name)}add(r,e,t=!1){let i=z.__parseProp(r,this);i.ctx.add(i.name,e,t)}add$(r,e=!1){for(let t in r)this.add(t,r[t],e)}get $(){if(!this.__stateProxy){let r=Object.create(null);this.__stateProxy=new Proxy(r,{set:(e,t,i)=>{let s=z.__parseProp(t,this);return s.ctx.pub(s.name,i),!0},get:(e,t)=>{let i=z.__parseProp(t,this);return i.ctx.read(i.name)}})}return this.__stateProxy}set$(r,e=!1){for(let t in r){let i=r[t];e||![String,Number,Boolean].includes(i==null?void 0:i.constructor)?this.$[t]=i:this.$[t]!==i&&(this.$[t]=i)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(f.CTX_OWNER_ATTR)&&this.getAttribute(f.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let r=this.constructor.__attrDesc;if(r)for(let e of Object.values(r))Object.keys(this.init$).includes(e)||(this.init$[e]="");for(let e in this.init$)if(e.startsWith(f.EXT_DATA_CTX_PRFX))this.nodeCtx.add(e.replace(f.EXT_DATA_CTX_PRFX,""),this.init$[e],this.__ctxOwner);else if(e.includes(f.NAMED_DATA_CTX_SPLTR)){let t=e.split(f.NAMED_DATA_CTX_SPLTR),i=t[0].trim(),s=t[1].trim();if(i&&s){let o=y.getCtx(i,!1);o||(o=y.registerCtx({},i)),o.add(s,this.init$[e])}}else this.localCtx.add(e,this.init$[e]);for(let e in this.cssInit$)this.bindCssData(e,this.cssInit$[e]);this.__dataCtxInitialized=!0}connectedCallback(){var r;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let e=(r=this.getAttribute(f.CTX_NAME_ATTR))==null?void 0:r.trim();if(e&&this.style.setProperty(f.CSS_CTX_PROP,`'${e}'`),this.__initDataCtx(),this[f.SET_LATER_KEY]){for(let t in this[f.SET_LATER_KEY])ee(this,t,this[f.SET_LATER_KEY][t]);delete this[f.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of ti)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${f.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let s=this.constructor.__rootStylesLink.cloneNode(!0);s.setAttribute(f.ROOT_STYLE_ATTR_NAME,this.constructor.is),s.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(s):t.prepend(s)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let r of this.allSubs)r.remove(),this.allSubs.delete(r);for(let r of this.tplProcessors)this.tplProcessors.delete(r);D==null||D.delete(this.updateCssData),D!=null&&D.size||(q==null||q.disconnect(),q=null,D=null)},100)))}static reg(r,e=!1){r||(Jt++,r=`${f.AUTO_TAG_PRFX}-${Jt}`),this.__tag=r;let t=window.customElements.get(r);if(t){!e&&t!==this&&console.warn([`Element with tag name "${r}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` +`));return}window.customElements.define(r,e?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(r){this.observedAttributes=Object.keys(r),this.__attrDesc=r}attributeChangedCallback(r,e,t){var i;if(e===t)return;let s=(i=this.constructor.__attrDesc)==null?void 0:i[r];s?this.__dataCtxInitialized?this.$[s]=t:this.init$[s]=t:this[r]=t}getCssData(r,e=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(r)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(r).trim();try{this.__cssDataCache[r]=oi(t)}catch{!e&&console.warn(`CSS Data error: ${r}`),this.__cssDataCache[r]=null}}return this.__cssDataCache[r]}__extractCssName(r){return r.split("--").map((e,t)=>t===0?"":e).join("--")}__initStyleAttrObserver(){D||(D=new Set),D.add(this.updateCssData),q||(q=new MutationObserver(r=>{r[0].type==="attributes"&&D.forEach(e=>{e()})}),q.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(r,e=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(r);let t=this.getCssData(this.__extractCssName(r),!0);t===null&&(t=e),this.add(r,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(r,e,t){let i="__"+r;this[i]=this[r],Object.defineProperty(this,r,{set:s=>{this[i]=s,t?window.setTimeout(()=>{e==null||e(s)}):e==null||e(s)},get:()=>this[i]}),this[r]=this[i]}static set shadowStyles(r){let e=new Blob([r],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(e)}static set rootStyles(r){if(!this.__rootStylesLink){let e=new Blob([r],{type:"text/css"}),t=URL.createObjectURL(e),i=document.createElement("link");i.href=t,i.rel="stylesheet",this.__rootStylesLink=i}}},Nt=z;Rt(Nt,"template");var kt=class{static _print(r){console.warn(r)}static setDefaultTitle(r){this.defaultTitle=r}static setRoutingMap(r){Object.assign(this.appMap,r);for(let e in this.appMap)!this.defaultRoute&&this.appMap[e].default===!0?this.defaultRoute=e:!this.errorRoute&&this.appMap[e].error===!0&&(this.errorRoute=e)}static set routingEventName(r){this.__routingEventName=r}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let r={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))r.route=t.replace("?","");else if(t.includes("=")){let i=t.split("=");r.options[i[0]]=decodeURI(i[1])}else r.options[t]=!0}),r}static notify(){let r=this.readAddressBar(),e=this.appMap[r.route];if(e&&e.title&&(document.title=e.title),r.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!e&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!e&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!e){this._print(`Route "${r.route}" not found...`);return}let t=new CustomEvent(kt.routingEventName,{detail:{route:r.route,options:Object.assign(e||{},r.options)}});window.dispatchEvent(t)}static reflect(r,e={}){let t=this.appMap[r];if(!t){this._print("Wrong route: "+r);return}let i="?"+r;for(let o in e)e[o]===!0?i+=this.separator+o:i+=this.separator+o+`=${e[o]}`;let s=t.title||this.defaultTitle||"";window.history.pushState(null,s,i),document.title=s}static applyRoute(r,e={}){this.reflect(r,e),this.notify()}static setSeparator(r){this._separator=r}static get separator(){return this._separator||"&"}static createRouterData(r,e){this.setRoutingMap(e);let t=y.registerCtx({route:null,options:null,title:null},r);return window.addEventListener(this.routingEventName,i=>{var s;t.multiPub({route:i.detail.route,options:i.detail.options,title:((s=i.detail.options)==null?void 0:s.title)||this.defaultTitle||""})}),kt.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};kt.appMap=Object.create(null);var ie="idb-store-ready",ni="symbiote-db",li="symbiote-idb-update_",ai=class{_notifyWhenReady(r=null){window.dispatchEvent(new CustomEvent(ie,{detail:{dbName:this.name,storeName:this.storeName,event:r}}))}get _updEventName(){return li+this.name}_getUpdateEvent(r){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:r}})}_notifySubscribers(r){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,r),window.dispatchEvent(this._getUpdateEvent(r))}constructor(r,e){this.name=r,this.storeName=e,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(e,{keyPath:"_key"}),this.objStore.transaction.oncomplete=i=>{this._notifyWhenReady(i)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async s=>{s(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(r){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(r);return new Promise((i,s)=>{t.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?i(o.target.result._value):(i(null),console.warn(`IDB: cannot read "${r}"`))},t.onerror=o=>{s(o)}})}write(r,e,t=!1){let i={_key:r,_value:e},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(i);return new Promise((n,l)=>{o.onsuccess=a=>{t||this._notifySubscribers(r),n(a.target.result)},o.onerror=a=>{l(a)}})}delete(r,e=!1){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(r);return new Promise((s,o)=>{i.onsuccess=n=>{e||this._notifySubscribers(r),s(n)},i.onerror=n=>{o(n)}})}getAll(){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,i)=>{e.onsuccess=s=>{let o=s.target.result;t(o.map(n=>n._value))},e.onerror=s=>{i(s)}})}subscribe(r,e){this._subscriptionsMap[r]||(this._subscriptionsMap[r]=new Set);let t=this._subscriptionsMap[r];return t.add(e),{remove:()=>{t.delete(e),t.size||delete this._subscriptionsMap[r]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,re.clear(this.name)}},re=class{static get readyEventName(){return ie}static open(r=ni,e="store"){let t=r+"/"+e;return this._reg[t]||(this._reg[t]=new ai(r,e)),this._reg[t]}static clear(r){window.indexedDB.deleteDatabase(r);for(let e in this._reg)e.split("/")[0]===r&&delete this._reg[e]}};Rt(re,"_reg",Object.create(null));var hi="--uploadcare-blocks-window-height",_t="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Lt(){return typeof window[_t]=="undefined"?!1:!!window[_t]}function se(){if(Lt())return;let r=()=>{document.documentElement.style.setProperty(hi,`${window.innerHeight}px`),window[_t]=!0},e=O(r,100);return window.addEventListener("resize",e,{passive:!0}),r(),()=>{window[_t]=!1,window.removeEventListener("resize",e)}}var ci=r=>r,Mt="{{",ne="}}",oe="plural:";function Dt(r,e,t={}){var n;let{openToken:i=Mt,closeToken:s=ne,transform:o=ci}=t;for(let l in e){let a=(n=e[l])==null?void 0:n.toString();r=r.replaceAll(i+l+s,typeof a=="string"?o(a):a)}return r}function le(r){let e=[],t=r.indexOf(Mt);for(;t!==-1;){let i=r.indexOf(ne,t),s=r.substring(t+2,i);if(s.startsWith(oe)){let o=r.substring(t+2,i).replace(oe,""),n=o.substring(0,o.indexOf("(")),l=o.substring(o.indexOf("(")+1,o.indexOf(")"));e.push({variable:s,pluralKey:n,countVariable:l})}t=r.indexOf(Mt,i)}return e}var ae=()=>({"*blocksRegistry":new Set});function he(r,e){[...r.querySelectorAll("[l10n]")].forEach(t=>{let i=t.getAttribute("l10n"),s="textContent";if(i.includes(":")){let n=i.split(":");s=n[0],i=n[1]}let o="l10n:"+i;e.__l10nKeys.push(o),e.add(o,i),e.sub(o,n=>{t[s]=e.l10n(n)}),t.removeAttribute("l10n")})}var S=r=>`*cfg/${r}`;var H=r=>{var e;return(e=r.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:e.map(t=>t.toLowerCase()).join("-")};var ce=new Set;function de(r){ce.has(r)||(ce.add(r),console.warn(r))}var ue=(r,e)=>new Intl.PluralRules(r).select(e);var Ut="lr-",b=class extends Nt{constructor(){super();m(this,"allowCustomTemplate",!0);m(this,"init$",ae());m(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let i of t)i.isConnected&&i.updateCssData()});this.activityType=null,this.addTemplateProcessor(he),this.__l10nKeys=[]}l10n(t,i={}){if(!t)return"";let s=this.getCssData("--l10n-"+t,!0)||t,o=le(s);for(let l of o)i[l.variable]=this.pluralize(l.pluralKey,Number(i[l.countVariable]));return Dt(s,i)}pluralize(t,i){let s=this.l10n("locale-name")||"en-US",o=ue(s,i);return this.l10n(`${t}__${o}`)}applyL10nKey(t,i){let s="l10n:"+t;this.$[s]=i,this.__l10nKeys.push(t)}hasBlockInCtx(t){let i=this.$["*blocksRegistry"];for(let s of i)if(t(s))return!0;return!1}setForCtxTarget(t,i,s){this.hasBlockInCtx(o=>o.constructor.StateConsumerScope===t)&&(this.$[i]=s)}setActivity(t){if(this.hasBlockInCtx(i=>i.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Ut}${t}`,!0),Lt()||(this._destroyInnerHeightTracker=se()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,i=2){let s=["B","KB","MB","GB","TB"],o=h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h;if(t===0)return`0 ${o(s[0])}`;let n=1024,l=i<0?0:i,a=Math.floor(Math.log(t)/Math.log(n));return parseFloat((t/n**a).toFixed(l))+" "+o(s[a])}proxyUrl(t){let i=this.cfg.secureDeliveryProxy;return i?Dt(i,{previewUrl:t},{transform:s=>window.encodeURIComponent(s)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(i,s)=>{let o=S(s),n=this.parseCfgProp(o);return n.ctx.has(n.name)?n.ctx.read(n.name):(de("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${H(s)}`))}})}return this.__cfgProxy}subConfigValue(t,i){let s=this.parseCfgProp(S(t));s.ctx.has(s.name)?this.sub(S(t),i):(this.bindCssData(`--cfg-${H(t)}`),this.sub(`--cfg-${H(t)}`,i))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Ut)?t:Ut+t)}};m(b,"StateConsumerScope",null),m(b,"className","");var pe="--cfg-ctx-name",v=class extends b{get cfgCssCtxName(){return this.getCssData(pe,!0)}get cfgCtxName(){var t;let e=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=e,e}connectedCallback(){var e;if(!this.connectedOnce){let t=(e=this.getAttribute("ctx-name"))==null?void 0:e.trim();t&&this.style.setProperty(pe,`'${t}'`)}super.connectedCallback()}parseCfgProp(e){return{...super.parseCfgProp(e),ctx:y.getCtx(this.cfgCtxName)}}};function fe(...r){return r.reduce((e,t)=>{if(typeof t=="string")return e[t]=!0,e;for(let i of Object.keys(t))e[i]=t[i];return e},{})}function w(...r){let e=fe(...r);return Object.keys(e).reduce((t,i)=>(e[i]&&t.push(i),t),[]).join(" ")}function me(r,...e){let t=fe(...e);for(let i of Object.keys(t))r.classList.toggle(i,t[i])}var _e=r=>{if(!r)return[];let[e,t]=r.split(":").map(Number);if(!Number.isFinite(e)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${r}`);return}return[{type:"aspect-ratio",width:e,height:t}]};var Ft=(r,e=",")=>r.trim().split(e).map(t=>t.trim()).filter(t=>t.length>0);var E={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function di(r,e){if(typeof e=="number")return E[r]!==e?`${r}/${e}`:"";if(typeof e=="boolean")return e&&E[r]!==e?`${r}`:"";if(r==="filter"){if(!e||E[r]===e.amount)return"";let{name:t,amount:i}=e;return`${r}/${t}/${i}`}if(r==="crop"){if(!e)return"";let{dimensions:t,coords:i}=e;return`${r}/${t.join("x")}/${i.join(",")}`}return""}var be=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function X(r){return pt(...be.filter(e=>typeof r[e]!="undefined"&&r[e]!==null).map(e=>{let t=r[e];return di(e,t)}).filter(e=>!!e))}var gt=pt("format/auto","progressive/yes"),U=([r])=>typeof r!="undefined"?Number(r):void 0,ge=()=>!0,ui=([r,e])=>({name:r,amount:typeof e!="undefined"?Number(e):100}),pi=([r,e])=>({dimensions:Ft(r,"x").map(Number),coords:Ft(e).map(Number)}),fi={enhance:U,brightness:U,exposure:U,gamma:U,contrast:U,saturation:U,vibrance:U,warmth:U,filter:ui,mirror:ge,flip:ge,rotate:U,crop:pi};function ye(r){let e={};for(let t of r){let[i,...s]=t.split("/");if(!be.includes(i))continue;let o=fi[i],n=o(s);e[i]=n}return e}function ve(r){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:P,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"","presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let e=r.querySelectorAll("img");for(let t of e){let i=t.src;t.src=P,t.src=i}r.$["*networkProblems"]=!1},"*on.apply":e=>{if(!e)return;let t=r.$["*originalUrl"],i=I(X(e)),s=M(t,I(i,"preview")),o={originalUrl:t,cdnUrlModifiers:i,cdnUrl:s,transformations:e};r.dispatchEvent(new CustomEvent("apply",{detail:o,bubbles:!0,composed:!0})),r.remove()},"*on.cancel":()=>{r.remove(),r.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var we=`
Network error
{{fileType}}
{{msg}}
`;var C={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},bt=[C.CROP,C.SLIDERS,C.FILTERS],Ce=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],xe=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],Te=["rotate","mirror","flip"],k={brightness:{zero:E.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:E.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:E.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:E.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:E.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:E.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:E.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:E.enhance,range:[0,100],keypointsNumber:1},filter:{zero:E.filter,range:[0,100],keypointsNumber:1}};var j=class extends v{constructor(){super();m(this,"_debouncedShowLoader",O(this._showLoader.bind(this),300));this.init$={...this.init$,...ve(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((i,s)=>{let o=setTimeout(()=>{s(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),n=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(i(),clearTimeout(o),n.disconnect())});n.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===C.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Vt(this.$.cdnUrl);this.$["*originalUrl"]=Pt(this.$.cdnUrl,t);let i=Gt(this.$.cdnUrl),s=ye(i);this.$["*editorTransformations"]=s}else if(this.$.uuid)this.$["*originalUrl"]=Pt(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=M(this.$["*originalUrl"],I("json")),i=await fetch(t).then(n=>n.json()),{width:s,height:o}=i;this.$["*imageSize"]={width:s,height:o},this.$["*tabId"]===C.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==P&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let i=this.ref["img-el"];i.src!==t&&(this._imgLoading=!0,i.src=t||P)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=_e(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=w("image",{image_hidden_to_cropper:t===C.CROP,image_hidden_effects:t!==C.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let i=this.$["*originalUrl"],s=I(X(t)),o=M(i,I(s,"preview")),n={originalUrl:i,cdnUrlModifiers:s,cdnUrl:o,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:n,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};m(j,"className","cloud-image-editor");j.template=we;j.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset"});var ot=33.333333333333336,p=1,zt=24,Ee=6;function W(r,e){for(let t in e)r.setAttributeNS(null,t,e[t].toString())}function A(r,e={}){let t=document.createElementNS("http://www.w3.org/2000/svg",r);return W(t,e),t}function $e(r,e,t){let{x:i,y:s,width:o,height:n}=r,l=e.includes("w")?0:1,a=e.includes("n")?0:1,h=[-1,1][l],c=[-1,1][a],d=[i+l*o+1.5*h,s+a*n+1.5*c-24*t*c],u=[i+l*o+1.5*h,s+a*n+1.5*c],_=[i+l*o-24*t*h+1.5*h,s+a*n+1.5*c];return{d:`M ${d[0]} ${d[1]} L ${u[0]} ${u[1]} L ${_[0]} ${_[1]}`,center:u}}function Se(r,e,t){let{x:i,y:s,width:o,height:n}=r,l=["n","s"].includes(e)?.5:{w:0,e:1}[e],a=["w","e"].includes(e)?.5:{n:0,s:1}[e],h=[-1,1][l],c=[-1,1][a],d,u;["n","s"].includes(e)?(d=[i+l*o-34*t/2,s+a*n+1.5*c],u=[i+l*o+34*t/2,s+a*n+1.5*c]):(d=[i+l*o+1.5*h,s+a*n-34*t/2],u=[i+l*o+1.5*h,s+a*n+34*t/2]);let _=`M ${d[0]} ${d[1]} L ${u[0]} ${u[1]}`,g=[u[0]-(u[0]-d[0])/2,u[1]-(u[1]-d[1])/2];return{d:_,center:g}}function Ae(r){return r===""?"move":["e","w"].includes(r)?"ew-resize":["n","s"].includes(r)?"ns-resize":["nw","se"].includes(r)?"nwse-resize":"nesw-resize"}function Ie({rect:r,delta:[e,t],imageBox:i}){return Q({...r,x:r.x+e,y:r.y+t},i)}function Q(r,e){let{x:t}=r,{y:i}=r;return r.xe.x+e.width&&(t=e.x+e.width-r.width),r.ye.y+e.height&&(i=e.y+e.height-r.height),{...r,x:t,y:i}}function mi({rect:r,delta:e,aspectRatio:t,imageBox:i}){let[,s]=e,{y:o,width:n,height:l}=r;o+=s,l-=s,t&&(n=l*t);let a=r.x+r.width/2-n/2;return o<=i.y&&(o=i.y,l=r.y+r.height-o,t&&(n=l*t,a=r.x+r.width/2-n/2)),a<=i.x&&(a=i.x,o=r.y+r.height-l),a+n>=i.x+i.width&&(a=Math.max(i.x,i.x+i.width-n),n=i.x+i.width-a,t&&(l=n/t),o=r.y+r.height-l),l=i.y+i.height&&(a=Math.max(i.y,i.y+i.height-l),l=i.y+i.height-a,t&&(n=l*t),o=r.x+r.width-n),l=i.y+i.height&&(l=i.y+i.height-o,t&&(n=l*t),a=r.x+r.width/2-n/2),a<=i.x&&(a=i.x,o=r.y),a+n>=i.x+i.width&&(a=Math.max(i.x,i.x+i.width-n),n=i.x+i.width-a,t&&(l=n/t),o=r.y),l=i.x+i.width&&(n=i.x+i.width-o,t&&(l=n/t),a=r.y+r.height/2-l/2),a<=i.y&&(a=i.y,o=r.x),a+l>=i.y+i.height&&(a=Math.max(i.y,i.y+i.height-l),l=i.y+i.height-a,t&&(n=l*t),o=r.x),lt?(o=a/t-h,h+=o,l-=o,l<=i.y&&(h=h-(i.y-l),a=h*t,n=r.x+r.width-a,l=i.y)):t&&(s=h*t-a,a=a+s,n-=s,n<=i.x&&(a=a-(i.x-n),h=a/t,n=i.x,l=r.y+r.height-h)),hi.x+i.width&&(s=i.x+i.width-n-a),l+ot?(o=a/t-h,h+=o,l-=o,l<=i.y&&(h=h-(i.y-l),a=h*t,n=r.x,l=i.y)):t&&(s=h*t-a,a+=s,n+a>=i.x+i.width&&(a=i.x+i.width-n,h=a/t,n=i.x+i.width-a,l=r.y+r.height-h)),hi.y+i.height&&(o=i.y+i.height-l-h),n+=s,a-=s,h+=o,t&&Math.abs(a/h)>t?(o=a/t-h,h+=o,l+h>=i.y+i.height&&(h=i.y+i.height-l,a=h*t,n=r.x+r.width-a,l=i.y+i.height-h)):t&&(s=h*t-a,a+=s,n-=s,n<=i.x&&(a=a-(i.x-n),h=a/t,n=i.x,l=r.y)),hi.x+i.width&&(s=i.x+i.width-n-a),l+h+o>i.y+i.height&&(o=i.y+i.height-l-h),a+=s,h+=o,t&&Math.abs(a/h)>t?(o=a/t-h,h+=o,l+h>=i.y+i.height&&(h=i.y+i.height-l,a=h*t,n=r.x,l=i.y+i.height-h)):t&&(s=h*t-a,a+=s,n+a>=i.x+i.width&&(a=i.x+i.width-n,h=a/t,n=i.x+i.width-a,l=r.y)),h=e.x&&r.y>=e.y&&r.x+r.width<=e.x+e.width&&r.y+r.height<=e.y+e.height}function J({width:r,height:e},t){let i=t/90%2!==0;return{width:i?e:r,height:i?r:e}}function tt(r){return{x:Math.round(r.x),y:Math.round(r.y),width:Math.round(r.width),height:Math.round(r.height)}}function B(r,e,t){return Math.min(Math.max(r,e),t)}var vt=class extends v{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(e){let t=this.$["*imageBox"];if(!t)return;if(e===""&&t.height<=p&&t.width<=p)return!0;let i=t.height<=p&&(e.includes("n")||e.includes("s")),s=t.width<=p&&(e.includes("e")||e.includes("w"));return i||s}_createBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:t,y:i,width:s,height:o}=e,n=this.ref["svg-el"],l=A("mask",{id:"backdrop-mask"}),a=A("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=A("rect",{x:t,y:i,width:s,height:o,fill:"black"});l.appendChild(a),l.appendChild(h);let c=A("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});n.appendChild(c),n.appendChild(l),this._backdropMask=l,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let e=this.$["*cropBox"];if(!e)return;let{x:t,y:i,width:s,height:o}=e;this._backdropMaskInner&&W(this._backdropMaskInner,{x:t,y:i,width:s,height:o})}_updateFrame(){let e=this.$["*cropBox"];if(!(!e||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:i,pathNode:s,interactionNode:o,groupNode:n}=t,l=i==="",a=i.length===2,{x:h,y:c,width:d,height:u}=e;if(l){let g={x:h+d/3,y:c+u/3,width:d/3,height:u/3};W(o,g)}else{let g=B(Math.min(d,u)/(24*2+34)/2,0,1),{d:T,center:G}=a?$e(e,i,g):Se(e,i,g),ut=Math.max(zt*B(Math.min(d,u)/zt/3,0,1),Ee);W(o,{x:G[0]-ut,y:G[1]-ut,width:ut*2,height:ut*2}),W(s,{d:T})}let _=this._shouldThumbBeDisabled(i);n.setAttribute("class",w("thumb",{"thumb--hidden":_,"thumb--visible":!_}))}W(this._frameGuides,{x:e.x-1*.5,y:e.y-1*.5,width:e.width+1,height:e.height+1})}}_createThumbs(){let e={};for(let t=0;t<3;t++)for(let i=0;i<3;i++){let s=`${["n","","s"][t]}${["w","","e"][i]}`,o=A("g");o.classList.add("thumb"),o.setAttribute("with-effects","");let n=A("rect",{fill:"transparent"}),l=A("path",{stroke:"currentColor",fill:"none","stroke-width":3});o.appendChild(l),o.appendChild(n),e[s]={direction:s,pathNode:l,interactionNode:n,groupNode:o},n.addEventListener("pointerdown",this._handlePointerDown.bind(this,s))}return e}_createGuides(){let e=A("svg"),t=A("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});e.appendChild(t);for(let i=1;i<=2;i++){let s=A("line",{x1:`${ot*i}%`,y1:"0%",x2:`${ot*i}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});e.appendChild(s)}for(let i=1;i<=2;i++){let s=A("line",{x1:"0%",y1:`${ot*i}%`,x2:"100%",y2:`${ot*i}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});e.appendChild(s)}return e.classList.add("guides","guides--semi-hidden"),e}_createFrame(){let e=this.ref["svg-el"],t=document.createDocumentFragment(),i=this._createGuides();t.appendChild(i);let s=this._createThumbs();for(let{groupNode:o}of Object.values(s))t.appendChild(o);e.appendChild(t),this._frameThumbs=s,this._frameGuides=i}_handlePointerDown(e,t){if(!this._frameThumbs)return;let i=this._frameThumbs[e];if(this._shouldThumbBeDisabled(e))return;let s=this.$["*cropBox"],{x:o,y:n}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-o,a=t.y-n;this.$.dragging=!0,this._draggingThumb=i,this._dragStartPoint=[l,a],this._dragStartCrop={...s}}_handlePointerUp_(e){this._updateCursor(),this.$.dragging&&(e.stopPropagation(),e.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(e){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;e.stopPropagation(),e.preventDefault();let t=this.ref["svg-el"],{x:i,y:s}=t.getBoundingClientRect(),o=e.x-i,n=e.y-s,l=o-this._dragStartPoint[0],a=n-this._dragStartPoint[1],{direction:h}=this._draggingThumb,c=this._calcCropBox(h,[l,a]);c&&(this.$["*cropBox"]=c)}_calcCropBox(e,t){var h,c;let[i,s]=t,o=this.$["*imageBox"],n=(h=this._dragStartCrop)!=null?h:this.$["*cropBox"],l=(c=this.$["*cropPresetList"])==null?void 0:c[0],a=l?l.width/l.height:void 0;if(e===""?n=Ie({rect:n,delta:[i,s],imageBox:o}):n=Oe({rect:n,delta:[i,s],direction:e,aspectRatio:a,imageBox:o}),!Object.values(n).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:n});return}return Q(tt(n),this.$["*imageBox"])}_handleSvgPointerMove_(e){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(i=>{if(this._shouldThumbBeDisabled(i.direction))return!1;let o=i.interactionNode.getBoundingClientRect(),n={x:o.x,y:o.y,width:o.width,height:o.height};return Pe(n,[e.x,e.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let e=this._hoverThumb;this.ref["svg-el"].style.cursor=e?Ae(e.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(e){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",w("thumb",{"thumb--hidden":!e,"thumb--visible":e}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",e=>{e&&(this._guidesHidden=e.height<=p||e.width<=p,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",e=>{this._frameGuides&&this._frameGuides.setAttribute("class",w({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&e,"guides--semi-hidden":!this._guidesHidden&&!e}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};vt.template='';var F=class extends v{constructor(){super(...arguments);m(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=w({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};F.template=`
{{title}}
`;function Ti(r){let e=r+90;return e=e>=360?0:e,e}function Ei(r,e){return r==="rotate"?Ti(e):["mirror","flip"].includes(r)?!e:null}var et=class extends F{initCallback(){super.initCallback(),this.defineAccessor("operation",e=>{e&&(this._operation=e,this.$.icon=e)}),this.$["on.click"]=e=>{let t=this.$["*cropperEl"].getValue(this._operation),i=Ei(this._operation,t);this.$["*cropperEl"].setValue(this._operation,i)}}};var nt={FILTER:"filter",COLOR_OPERATION:"color_operation"},N="original",wt=class extends v{constructor(){super(...arguments);m(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,i){this._controlType=t==="filter"?nt.FILTER:nt.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=i,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===N?void 0:this.$.value,filter:this._filter===N?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:i}=k[this._operation],[s,o]=t;this.$.min=s,this.$.max=o,this.$.zero=i;let n=this.$["*editorTransformations"][this._operation];if(this._controlType===nt.FILTER){let l=o;if(n){let{name:a,amount:h}=n;l=a===this._filter?h:o}this.$.value=l,this.$.defaultValue=l}if(this._controlType===nt.COLOR_OPERATION){let l=typeof n!="undefined"?n:i;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===nt.FILTER?this._filter===N?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let i={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=i}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let i=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=i})}};wt.template=``;function lt(r){let e=new Image;return{promise:new Promise((s,o)=>{e.src=r,e.onload=s,e.onerror=o}),image:e,cancel:()=>{e.naturalWidth===0&&(e.src=P)}}}function at(r){let e=[];for(let o of r){let n=lt(o);e.push(n)}let t=e.map(o=>o.image);return{promise:Promise.allSettled(e.map(o=>o.promise)),images:t,cancel:()=>{e.forEach(o=>{o.cancel()})}}}var V=class extends F{constructor(){super(...arguments);m(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),i=window.devicePixelRatio,s=Math.ceil(i*t),o=i>=2?"lightest":"normal",n=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==N?{name:this._filter,amount:n}:void 0,M(this._originalUrl,I(gt,X(l),`quality/${o}`,`scale_crop/${s}x${s}/center`))}_observerCallback(t,i){if(t[0].isIntersecting){let o=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"],{promise:l,cancel:a}=lt(o);this._cancelPreload=a,l.catch(h=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:h})}).finally(()=>{n.style.backgroundImage=`url(${o})`,n.setAttribute("loaded",""),i.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=i=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",i=>{this._operation="filter",this._filter=i,this.$.isOriginal=i===N,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",i=>{this.$.active=i&&i===this._filter}),this.sub("isOriginal",i=>{this.$.iconSize=i?40:20}),this.sub("active",i=>{if(this.$.isOriginal)return;let s=this.ref["icon-el"];s.style.opacity=i?"1":"0";let o=this.ref["preview-el"];i?o.style.opacity="0":o.style.backgroundImage&&(o.style.opacity="1")}),this.sub("*networkProblems",i=>{if(!i){let s=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"];o.style.backgroundImage&&(o.style.backgroundImage="none",o.style.backgroundImage=`url(${s})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};V.template=`
`;var it=class extends F{constructor(){super(...arguments);m(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:i}=k[this._operation],s=t[this._operation],o=typeof s!="undefined"?s!==i:!1;this.$.active=o})}};var Re=(r,e)=>{let t,i,s;return(...o)=>{t?(clearTimeout(i),i=setTimeout(()=>{Date.now()-s>=e&&(r(...o),s=Date.now())},Math.max(e-(Date.now()-s),0))):(r(...o),s=Date.now(),t=!0)}};function Ne(r,e){let t={};for(let i of e){let s=r[i];(r.hasOwnProperty(i)||s!==void 0)&&(t[i]=s)}return t}function rt(r,e,t){let s=window.devicePixelRatio,o=Math.min(Math.ceil(e*s),3e3),n=s>=2?"lightest":"normal";return M(r,I(gt,X(t),`quality/${n}`,`stretch/off/-/resize/${o}x`))}function $i(r){return r?[({dimensions:t,coords:i})=>[...t,...i].every(s=>Number.isInteger(s)&&Number.isFinite(s)),({dimensions:t,coords:i})=>t.every(s=>s>0)&&i.every(s=>s>=0)].every(t=>t(r)):!0}var Ct=class extends v{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=O(this._commit.bind(this),300),this._handleResizeThrottled=Re(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let e=this.$["*editorTransformations"],t=Ne(e,Object.keys(this.$["*operations"])),i={...this.$["*operations"],...t};this.$["*operations"]=i}_initCanvas(){let e=this.ref["canvas-el"],t=e.getContext("2d"),i=this.offsetWidth,s=this.offsetHeight,o=window.devicePixelRatio;e.style.width=`${i}px`,e.style.height=`${s}px`,e.width=i*o,e.height=s*o,t==null||t.scale(o,o),this._canvas=e,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let e=this.$.image,t=this.$["*padding"],i=this.$["*operations"],{rotate:s}=i,o={width:this.offsetWidth,height:this.offsetHeight},n=J({width:e.naturalWidth,height:e.naturalHeight},s),l;if(n.width>o.width-t*2||n.height>o.height-t*2){let a=n.width/n.height,h=o.width/o.height;if(a>h){let c=o.width-t*2,d=c/a,u=0+t,_=t+(o.height-t*2)/2-d/2;l={x:u,y:_,width:c,height:d}}else{let c=o.height-t*2,d=c*a,u=t+(o.width-t*2)/2-d/2,_=0+t;l={x:u,y:_,width:d,height:c}}}else{let{width:a,height:h}=n,c=t+(o.width-t*2)/2-a/2,d=t+(o.height-t*2)/2-h/2;l={x:c,y:d,width:a,height:h}}this.$["*imageBox"]=tt(l)}_alignCrop(){var h;let e=this.$["*cropBox"],t=this.$["*imageBox"],i=this.$["*operations"],{rotate:s}=i,o=this.$["*editorTransformations"].crop,{width:n,x:l,y:a}=this.$["*imageBox"];if(o){let{dimensions:[c,d],coords:[u,_]}=o,{width:g}=J(this._imageSize,s),T=n/g;e=Q(tt({x:l+u*T,y:a+_*T,width:c*T,height:d*T}),this.$["*imageBox"])}if(!o||!ke(e,t)){let c=(h=this.$["*cropPresetList"])==null?void 0:h[0],d=c?c.width/c.height:void 0,u=t.width/t.height,_=t.width,g=t.height;d&&(u>d?_=Math.min(t.height*d,t.width):g=Math.min(t.width/d,t.height)),e={x:t.x+t.width/2-_/2,y:t.y+t.height/2-g/2,width:_,height:g}}this.$["*cropBox"]=Q(tt(e),this.$["*imageBox"])}_drawImage(){let e=this._ctx;if(!e)return;let t=this.$.image,i=this.$["*imageBox"],s=this.$["*operations"],{mirror:o,flip:n,rotate:l}=s,a=J({width:i.width,height:i.height},l);e.save(),e.translate(i.x+i.width/2,i.y+i.height/2),e.rotate(l*Math.PI*-1/180),e.scale(o?-1:1,n?-1:1),e.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),e.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let e=this._canvas;this._ctx.clearRect(0,0,e.width,e.height),this._drawImage()}_animateIn({fromViewer:e}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=w({active_from_viewer:e,active_from_editor:!e,inactive_to_editor:!1})}))}_getCropDimensions(){let e=this.$["*cropBox"],t=this.$["*imageBox"],i=this.$["*operations"],{rotate:s}=i,{width:o,height:n}=t,{width:l,height:a}=J(this._imageSize,s),{width:h,height:c}=e,d=o/l,u=n/a;return[B(Math.round(h/d),1,l),B(Math.round(c/u),1,a)]}_getCropTransformation(){let e=this.$["*cropBox"],t=this.$["*imageBox"],i=this.$["*operations"],{rotate:s}=i,{width:o,height:n,x:l,y:a}=t,{width:h,height:c}=J(this._imageSize,s),{x:d,y:u}=e,_=o/h,g=n/c,T=this._getCropDimensions(),G={dimensions:T,coords:[B(Math.round((d-l)/_),0,h-T[0]),B(Math.round((u-a)/g),0,c-T[1])]};if(!$i(G)){console.error("Cropper is trying to create invalid crop object",{payload:G});return}if(!(T[0]===h&&T[1]===c))return G}_commit(){if(!this.isConnected)return;let e=this.$["*operations"],{rotate:t,mirror:i,flip:s}=e,o=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:o,rotate:t,mirror:i,flip:s};this.$["*editorTransformations"]=l}setValue(e,t){console.log(`Apply cropper operation [${e}=${t}]`),this.$["*operations"]={...this.$["*operations"],[e]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(e){return this.$["*operations"][e]}async activate(e,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=e,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(i){console.error("Failed to activate cropper",{error:i})}this._observer=new ResizeObserver(([i])=>{i.contentRect.width>0&&i.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:e=!1}={}){var t;this._isActive&&(!e&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=w({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let e=this._getCropDimensions(),t=Math.min(this.offsetWidth,e[0])/this.$["*cropBox"].width,i=Math.min(this.offsetHeight,e[1])/this.$["*cropBox"].height,s=Math.min(t,i),o=this.$["*cropBox"].x+this.$["*cropBox"].width/2,n=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${s}) translate(${(this.offsetWidth/2-o)/s}px, ${(this.offsetHeight/2-n)/s}px)`,this.style.transformOrigin=`${o}px ${n}px`}_transitionToImage(){let e=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${e}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(e,t){let i=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let s=this.proxyUrl(rt(e,i,t)),{promise:o,cancel:n,image:l}=lt(s),a=this._handleImageLoading(s);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=n,o.then(()=>l).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(e){let t="crop",i=this.$["*loadingOperations"];return i.get(t)||i.set(t,new Map),i.get(t).get(e)||(i.set(t,i.get(t).set(e,!0)),this.$["*loadingOperations"]=i),()=>{var s;(s=i==null?void 0:i.get(t))!=null&&s.has(e)&&(i.get(t).delete(e),this.$["*loadingOperations"]=i)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",e=>{e||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var e;super.destroyCallback(),(e=this._observer)==null||e.disconnect()}};Ct.template=``;function Ht(r,e,t){let i=Array(t);t--;for(let s=t;s>=0;s--)i[s]=Math.ceil((s*e+(t-s)*r)/t);return i}function Si(r){return r.reduce((e,t,i)=>is<=e&&e<=o);return r.map(s=>{let o=Math.abs(i[0]-i[1]),n=Math.abs(e-i[0])/o;return i[0]===s?e>t?1:1-n:i[1]===s?e>=t?n:1:0})}function Ii(r,e){return r.map((t,i)=>to-n)}var Xt=class extends v{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=O(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(e){let t=this._operation,i=this.$["*loadingOperations"];return i.get(t)||i.set(t,new Map),i.get(t).get(e)||(i.set(t,i.get(t).set(e,!0)),this.$["*loadingOperations"]=i),()=>{var s;(s=i==null?void 0:i.get(t))!=null&&s.has(e)&&(i.get(t).delete(e),this.$["*loadingOperations"]=i)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let e of this._keypoints){let{image:t}=e;t&&(t.style.opacity=e.opacity.toString(),t.style.zIndex=e.zIndex.toString())}})}_imageSrc({url:e=this._url,filter:t=this._filter,operation:i,value:s}={}){let o={...this._transformations};i&&(o[i]=t?{name:t,amount:s}:s);let n=this.offsetWidth;return this.proxyUrl(rt(e,n,o))}_constructKeypoint(e,t){return{src:this._imageSrc({operation:e,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(e,t){return this._operation===e&&this._filter===t}_addKeypoint(e,t,i){let s=()=>!this._isSame(e,t)||this._value!==i||!!this._keypoints.find(a=>a.value===i);if(s())return;let o=this._constructKeypoint(e,i),n=new Image;n.src=o.src;let l=this._handleImageLoading(o.src);n.addEventListener("load",l,{once:!0}),n.addEventListener("error",l,{once:!0}),o.image=n,n.classList.add("fader-image"),n.addEventListener("load",()=>{if(s())return;let a=this._keypoints,h=a.findIndex(d=>d.value>i),c=h{this.$["*networkProblems"]=!0},{once:!0})}set(e){e=typeof e=="string"?parseInt(e,10):e,this._update(this._operation,e),this._addKeypointDebounced(this._operation,this._filter,e)}_update(e,t){this._operation=e,this._value=t;let{zero:i}=k[e],s=this._keypoints.map(l=>l.value),o=Ai(s,t,i),n=Ii(s,i);for(let[l,a]of Object.entries(this._keypoints))a.opacity=o[l],a.zIndex=n[l];this._flush()}_createPreviewImage(){let e=new Image;return e.classList.add("fader-image","fader-image--preview"),e.style.opacity="0",e}async _initNodes(){let e=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&e.appendChild(this._previewImage);let t=document.createElement("div");e.appendChild(t);let i=this._keypoints.map(h=>h.src),{images:s,promise:o,cancel:n}=at(i);s.forEach(h=>{let c=this._handleImageLoading(h.src);h.addEventListener("load",c),h.addEventListener("error",c)}),this._cancelLastImages=()=>{n(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await o,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((h,c)=>{let d=s[c];d.classList.add("fader-image"),h.image=d,this._container.appendChild(d)}),this.appendChild(e),this._flush())}setTransformations(e){if(this._transformations=e,this._previewImage){let t=this._imageSrc(),i=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",i,{once:!0}),this._previewImage.addEventListener("error",i,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:e,filter:t,operation:i,value:s}){this._cancelBatchPreload&&this._cancelBatchPreload();let n=Le(i,s).map(a=>this._imageSrc({url:e,filter:t,operation:i,value:a})),{cancel:l}=at(n);this._cancelBatchPreload=l}_setOriginalSrc(e){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===e){t.style.opacity="1",t.style.transform="scale(1)",this.className=w({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let i=this._handleImageLoading(e);t.addEventListener("error",i,{once:!0}),t.src=e,t.addEventListener("load",()=>{i(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=w({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:e,operation:t,value:i,filter:s,fromViewer:o}){if(this._isActive=!0,this._hidden=!1,this._url=e,this._operation=t||"initial",this._value=i,this._filter=s,this._fromViewer=o,typeof i!="number"&&!s){let l=this._imageSrc({operation:t,value:i});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Le(t,i).map(l=>this._constructKeypoint(t,l)),this._update(t,i),this._initNodes()}deactivate({hide:e=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),e&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=w({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Oi=1,xt=class extends v{initCallback(){super.initCallback(),this.addEventListener("wheel",e=>{e.preventDefault();let{deltaY:t,deltaX:i}=e;Math.abs(i)>Oi?this.scrollLeft+=i:this.scrollLeft+=t})}};xt.template=" ";function Pi(r){return``}function ki(r){return`
`}var Tt=class extends v{constructor(){super();m(this,"_updateInfoTooltip",O(()=>{var o,n;let t=this.$["*editorTransformations"],i="",s=!1;if(this.$["*tabId"]===C.FILTERS)if(s=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let l=((n=t==null?void 0:t.filter)==null?void 0:n.amount)||100;i=this.l10n(this.$["*currentFilter"])+" "+l}else i=this.l10n(N);else if(this.$["*tabId"]===C.SLIDERS&&this.$["*currentOperation"]){s=!0;let l=(t==null?void 0:t[this.$["*currentOperation"]])||k[this.$["*currentOperation"]].zero;i=this.$["*currentOperation"]+" "+l}s&&(this.$["*operationTooltip"]=i),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",s)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":N,"*currentOperation":null,"*tabId":C.CROP,showLoader:!1,filters:xe,colorOperations:Ce,cropOperations:Te,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":t=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":t=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":t=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":t=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let i=t.currentTarget.getAttribute("data-id");this._activateTab(i,{fromViewer:!1})}},this._debouncedShowLoader=O(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===C.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let i=it.is&&new it;return i.operation=t,i}_createFilterControl(t){let i=V.is&&new V;return i.filter=t,i}_createToggleControl(t){let i=et.is&&new et;return i.operation=t,i}_renderControlsList(t){let i=this.ref[`controls-list-${t}`],s=document.createDocumentFragment();t===C.CROP?this.$.cropOperations.forEach(o=>{let n=this._createToggleControl(o);s.appendChild(n)}):t===C.FILTERS?[N,...this.$.filters].forEach(o=>{let n=this._createFilterControl(o);s.appendChild(n)}):t===C.SLIDERS&&this.$.colorOperations.forEach(o=>{let n=this._createOperationControl(o);s.appendChild(n)}),s.childNodes.forEach((o,n)=>{n===s.childNodes.length-1&&o.classList.add("controls-list_last-item")}),i.innerHTML="",i.appendChild(s)}_activateTab(t,{fromViewer:i}){this.$["*tabId"]=t,t===C.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:i})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:i}),this.$["*cropperEl"].deactivate());for(let s of bt){let o=s===t,n=this.ref[`tab-toggle-${s}`];n.active=o,o?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(s),this.$[`presence.tabContent.${s}`]=o}}_unmountTabControls(t){let i=this.ref[`controls-list-${t}`];i&&(i.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],i=this.ref["tabs-indicator"];i.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,i=this.proxyUrl(rt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:s}=at([i]);this._cancelPreload=()=>{s(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var s;let i=(s=t==null?void 0:t.filter)==null?void 0:s.name;this.$["*currentFilter"]!==i&&(this.$["*currentFilter"]=i)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",t=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let i=!1;for(let[,s]of t.entries()){if(i)break;for(let[,o]of s.entries())if(o){i=!0;break}}this._debouncedShowLoader(i)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this._updateInfoTooltip()}};Tt.template=`
{{*operationTooltip}}
${bt.map(ki).join("")}
${bt.map(Pi).join("")}
`;var ht=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",e=>{e?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return w("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",e=>{this._iconSingle=!this.$.text,this._iconHidden=!e,this.$.iconCss=this._iconCss()}),this.sub("theme",e=>{e!=="custom"&&(this.className=e)}),this.sub("text",e=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(e){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};ht.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});ht.template=`
{{text}}
`;var Et=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let e=this.ref["line-el"];e.style.transition="initial",e.style.opacity="0",e.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",e=>{typeof e=="boolean"&&(e?this._start():this._stop())})}_start(){this._active=!0;let{width:e}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${e}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};Et.template=`
`;var $t={transition:"transition",visible:"visible",hidden:"hidden"},St=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=$t.visible,this._hiddenStyle=$t.hidden,this._externalTransitions=!1,this.defineAccessor("styles",e=>{e&&(this._externalTransitions=!0,this._visibleStyle=e.visible,this._hiddenStyle=e.hidden)}),this.defineAccessor("visible",e=>{typeof e=="boolean"&&(this._visible=e,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",me(this,{[$t.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add($t.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};St.template=" ";var At=class extends b{constructor(){super();m(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",i=>{this.$.disabled=i}),this.defineAccessor("min",i=>{this.$.min=i}),this.defineAccessor("max",i=>{this.$.max=i}),this.defineAccessor("defaultValue",i=>{this.$.defaultValue=i,this.ref["input-el"].value=i,this._updateValue(i)}),this.defineAccessor("zero",i=>{this._zero=i}),this.defineAccessor("onInput",i=>{i&&(this.$.onInput=i)}),this.defineAccessor("onChange",i=>{i&&(this.$.onChange=i)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let i=parseInt(this.ref["input-el"].value,10);this._updateValue(i)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let i=parseInt(this.ref["input-el"].value,10);this._updateValue(i)},0),this.sub("disabled",i=>{let s=this.ref["input-el"];i?s.setAttribute("disabled","disabled"):s.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:i}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(t-this.$.min)*(i-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${n}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:i}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(i-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${n}px)`})}_updateSteps(){let i=this.ref["steps-el"],{width:s}=i.getBoundingClientRect(),o=Math.ceil(s/2),n=Math.ceil(o/15)-2;if(this._stepsCount===n)return;let l=document.createDocumentFragment(),a=document.createElement("div"),h=document.createElement("div");a.className="minor-step",h.className="border-step",l.appendChild(h);for(let d=0;d
`;var Ri="css-src";function jt(r){return class extends r{constructor(){super(...arguments);m(this,"renderShadow",!0);m(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Ri);if(t){this.attachShadow({mode:"open"});let i=document.createElement("link");i.rel="stylesheet",i.type="text/css",i.href=t,i.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(i)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Me=class extends jt(b){};var De=class extends jt(j){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};var ct=class extends b{constructor(){super(...arguments);m(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let i=this.getCssData(`--icon-${t}`);i&&(this.$.path=i)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ct.template=``;ct.bindAttributes({name:"name",size:"size"});function Ni(r){for(let e in r){let t=[...e].reduce((i,s)=>(s.toUpperCase()===s&&(s="-"+s.toLowerCase()),i+=s),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),r[e].reg&&r[e].reg(t)}}var Li="https://ucarecdn.com",Mi="https://upload.uploadcare.com",Di="https://social.uploadcare.com",dt=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:Li,baseUrl:Mi,socialBaseUrl:Di,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var $=r=>String(r),L=r=>Number(r),x=r=>typeof r=="boolean"?r:r==="true"||r===""?!0:r==="false"?!1:!!r,Ui=r=>r==="auto"?r:x(r),Fi={pubkey:$,multiple:x,multipleMin:L,multipleMax:L,confirmUpload:x,imgOnly:x,accept:$,externalSourcesPreferredTypes:$,store:Ui,cameraMirror:x,sourceList:$,maxLocalFileSizeBytes:L,thumbSize:L,showEmptyList:x,useLocalImageEditor:x,useCloudImageEditor:x,removeCopyright:x,cropPreset:$,modalScrollLock:x,modalBackdropStrokes:x,sourceListWrap:x,remoteTabSessionKey:$,cdnCname:$,baseUrl:$,socialBaseUrl:$,secureSignature:$,secureExpire:$,secureDeliveryProxy:$,retryThrottledRequestMaxTimes:L,multipartMinFileSize:L,multipartChunkSize:L,maxConcurrentRequests:L,multipartMaxConcurrentRequests:L,multipartMaxAttempts:L,checkForUrlDuplicates:x,saveUrlForRecurrentUploads:x,groupOutput:x,userAgentIntegration:$},Ue=(r,e)=>{if(!(typeof e=="undefined"||e===null))return Fi[r](e)};var It=Object.keys(dt),zi=["metadata"],Hi=r=>zi.includes(r),Bt=It.filter(r=>!Hi(r)),Xi={...Object.fromEntries(Bt.map(r=>[H(r),r])),...Object.fromEntries(Bt.map(r=>[r.toLowerCase(),r]))},ji={...Object.fromEntries(It.map(r=>[H(r),S(r)])),...Object.fromEntries(It.map(r=>[r.toLowerCase(),S(r)]))},Ot=class extends b{constructor(){super();m(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(dt).map(([t,i])=>[S(t),i]))}}initCallback(){super.initCallback();for(let t of It){let i=this,s="__"+t;i[s]=i[t],Object.defineProperty(this,t,{set:o=>{if(i[s]=o,Bt.includes(t)){let n=[...new Set([H(t),t.toLowerCase()])];for(let l of n)typeof o=="undefined"||o===null?this.removeAttribute(l):this.setAttribute(l,o.toString())}this.$[S(t)]!==o&&(typeof o=="undefined"||o===null?this.$[S(t)]=dt[t]:this.$[S(t)]=o)},get:()=>this.$[S(t)]}),typeof i[t]!="undefined"&&i[t]!==null&&(i[t]=i[s])}}attributeChangedCallback(t,i,s){if(i===s)return;let o=Xi[t],n=Ue(o,s),l=n!=null?n:dt[o],a=this;a[o]=l}};Ot.bindAttributes(ji);export{De as CloudImageEditor,j as CloudImageEditorBlock,Ot as Config,vt as CropFrame,et as EditorCropButtonControl,V as EditorFilterControl,Ct as EditorImageCropper,Xt as EditorImageFader,it as EditorOperationControl,xt as EditorScroller,wt as EditorSlider,Tt as EditorToolbar,ct as Icon,Et as LineLoaderUi,ht as LrBtnUi,St as PresenceToggle,At as SliderUi,Ni as registerBlocks}; \ No newline at end of file diff --git a/web/lr-file-uploader-inline.min.js b/web/lr-file-uploader-inline.min.js index e46c306df..077d09a06 100644 --- a/web/lr-file-uploader-inline.min.js +++ b/web/lr-file-uploader-inline.min.js @@ -23,5 +23,5 @@ * SOFTWARE. * */ -var Ur=Object.defineProperty;var Pr=(s,i,t)=>i in s?Ur(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var c=(s,i,t)=>(Pr(s,typeof i!="symbol"?i+"":i,t),t),wi=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var N=(s,i,t)=>(wi(s,i,"read from private field"),t?t.call(s):i.get(s)),Ot=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},te=(s,i,t,e)=>(wi(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var Ee=(s,i,t)=>(wi(s,i,"access private method"),t);var Mr=Object.defineProperty,Nr=(s,i,t)=>i in s?Mr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,Ei=(s,i,t)=>(Nr(s,typeof i!="symbol"?i+"":i,t),t);function Dr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=Dr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var y=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),ds="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Br=ds.length-1,ie=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{ai&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Vr(s,i){[...s.querySelectorAll(`[${y.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(y.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let n=t.innerHTML;r.template=n,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let o=t.getAttribute(y.REPEAT_ATTR);i.sub(o,n=>{if(!n){for(;t.firstChild;)t.firstChild.remove();return}let a=[...t.children],l,u=h=>{h.forEach((p,f)=>{if(a[f])if(a[f].set$)setTimeout(()=>{a[f].set$(p)});else for(let m in p)a[f][m]=p[m];else{l||(l=new DocumentFragment);let m=new r;Object.assign(m.init$,p),l.appendChild(m)}}),l&&t.appendChild(l);let d=a.slice(h.length,a.length);for(let p of d)p.remove()};if(n.constructor===Array)u(n);else if(n.constructor===Object){let h=[];for(let d in n){let p=n[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),h.push(p)}u(h)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),t.removeAttribute(y.REPEAT_ATTR),t.removeAttribute(y.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function zr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let o=r.getAttribute("name")||us;e[o]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var o;let n=us;r instanceof Element&&r.hasAttribute("slot")&&(n=r.getAttribute("slot"),r.removeAttribute("slot")),(o=e[n])==null||o.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(o,r.slot)}else r.slot.remove()})}function jr(s,i){[...s.querySelectorAll(`[${y.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(y.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(y.EL_REF_ATTR)})}function Hr(s,i){[...s.querySelectorAll(`[${y.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(y.BIND_ATTR).split(";");[...t.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=Fr(o.name.replace("-",""));r.push(n+":"+o.value),t.removeAttribute(o.name)}}),r.forEach(o=>{if(!o)return;let n=o.split(":").map(h=>h.trim()),a=n[0],l;a.indexOf(y.ATTR_BIND_PRFX)===0&&(l=!0,a=a.replace(y.ATTR_BIND_PRFX,""));let u=n[1].split(",").map(h=>h.trim());for(let h of u){let d;h.startsWith("!!")?(d="double",h=h.replace("!!","")):h.startsWith("!")&&(d="single",h=h.replace("!","")),i.sub(h,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),l?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(a,""):t.removeAttribute(a):t.setAttribute(a,p):ps(t,a,p)||(t[y.SET_LATER_KEY]||(t[y.SET_LATER_KEY]=Object.create(null)),t[y.SET_LATER_KEY][a]=p)})}}),t.removeAttribute(y.BIND_ATTR)})}var Ae="{{",ee="}}",Wr="skip-text";function Xr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var o;return!((o=r.parentElement)!=null&&o.hasAttribute(Wr))&&r.textContent.includes(Ae)&&r.textContent.includes(ee)&&1}});for(;i=e.nextNode();)t.push(i);return t}var qr=function(s,i){Xr(s).forEach(e=>{let r=[],o;for(;e.textContent.includes(ee);)e.textContent.startsWith(Ae)?(o=e.textContent.indexOf(ee)+ee.length,e.splitText(o),r.push(e)):(o=e.textContent.indexOf(Ae),e.splitText(o)),e=e.nextSibling;r.forEach(n=>{let a=n.textContent.replace(Ae,"").replace(ee,"");n.textContent="",i.sub(a,l=>{n.textContent=l})})})},Gr=[Vr,zr,jr,Hr,qr],Se="'",Vt='"',Kr=/\\([0-9a-fA-F]{1,6} ?)/g;function Yr(s){return(s[0]===Vt||s[0]===Se)&&(s[s.length-1]===Vt||s[s.length-1]===Se)}function Zr(s){return(s[0]===Vt||s[0]===Se)&&(s=s.slice(1)),(s[s.length-1]===Vt||s[s.length-1]===Se)&&(s=s.slice(0,-1)),s}function Jr(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=Jr(i),i=Vt+i+Vt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var hs=0,Ft=null,mt=null,Ct=class extends HTMLElement{constructor(){super(),Ei(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return Ct}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(y.USE_TPL);if(r){let o=this.getRootNode(),n=(o==null?void 0:o.querySelector(r))||document.querySelector(r);n?s=n.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ie.generate(),this.style.setProperty(y.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(y.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(y.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(y.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(y.EXT_DATA_CTX_PRFX,"");else if(s.includes(y.NAMED_DATA_CTX_SPLTR)){let r=s.split(y.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=o=>{this.isConnected&&i(o)},r=Ct.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=Ct.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=Ct.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=Ct.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=Ct.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=Ct.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(y.CTX_OWNER_ATTR)&&this.getAttribute(y.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(y.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(y.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(y.NAMED_DATA_CTX_SPLTR)){let t=i.split(y.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let o=E.getCtx(e,!1);o||(o=E.registerCtx({},e)),o.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(y.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(y.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[y.SET_LATER_KEY]){for(let t in this[y.SET_LATER_KEY])ps(this,t,this[y.SET_LATER_KEY][t]);delete this[y.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Gr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${y.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(y.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);mt==null||mt.delete(this.updateCssData),mt!=null&&mt.size||(Ft==null||Ft.disconnect(),Ft=null,mt=null)},100)))}static reg(s,i=!1){s||(hs++,s=`${y.AUTO_TAG_PRFX}-${hs}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Qr(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){mt||(mt=new Set),mt.add(this.updateCssData),Ft||(Ft=new MutationObserver(s=>{s[0].type==="attributes"&&mt.forEach(i=>{i()})}),Ft.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=Ct;Ei(zt,"template");var Ti=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Ti.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let o in i)i[o]===!0?e+=this.separator+o:e+=this.separator+o+`=${i[o]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Ti.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Ti.appMap=Object.create(null);function to(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function eo(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function se(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&eo(i,s.attributes),s.styles&&to(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=se(t);i.appendChild(e)}),i}var ms="idb-store-ready",io="symbiote-db",so="symbiote-idb-update_",ro=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return so+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?e(o.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=o=>{r(o)}})}write(s,i,t=!1){let e={_key:s,_value:i},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((n,a)=>{o.onsuccess=l=>{t||this._notifySubscribers(s),n(l.target.result)},o.onerror=l=>{a(l)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,o)=>{e.onsuccess=n=>{i||this._notifySubscribers(s),r(n)},e.onerror=n=>{o(n)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let o=r.target.result;t(o.map(n=>n._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,fs.clear(this.name)}},fs=class{static get readyEventName(){return ms}static open(s=io,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new ro(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Ei(fs,"_reg",Object.create(null));function G(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var oo="--uploadcare-blocks-window-height",$e="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Ai(){return typeof window[$e]=="undefined"?!1:!!window[$e]}function gs(){if(Ai())return;let s=()=>{document.documentElement.style.setProperty(oo,`${window.innerHeight}px`),window[$e]=!0},i=G(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[$e]=!1,window.removeEventListener("resize",i)}}var no=s=>s,Si="{{",bs="}}",_s="plural:";function re(s,i,t={}){var n;let{openToken:e=Si,closeToken:r=bs,transform:o=no}=t;for(let a in i){let l=(n=i[a])==null?void 0:n.toString();s=s.replaceAll(e+a+r,typeof l=="string"?o(l):l)}return s}function vs(s){let i=[],t=s.indexOf(Si);for(;t!==-1;){let e=s.indexOf(bs,t),r=s.substring(t+2,e);if(r.startsWith(_s)){let o=s.substring(t+2,e).replace(_s,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));i.push({variable:r,pluralKey:n,countVariable:a})}t=s.indexOf(Si,e)}return i}function ys(s){return Object.prototype.toString.call(s)==="[object Object]"}var ao=/\W|_/g;function lo(s){return s.split(ao).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Cs(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>gt(t,{ignoreKeys:i})):s}function gt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return Cs(s,{ignoreKeys:i});if(!ys(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ys(r)?r=gt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=Cs(r,{ignoreKeys:i})),t[lo(e)]=r}return t}var co=s=>new Promise(i=>setTimeout(i,s));function Ui({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let o="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:o,integration:r});let n=[s,i,e].filter(Boolean).join("/"),a=[o,r].filter(Boolean).join("; ");return`${n} (${a})`}var uo={factor:2,time:100};function ho(s,i=uo){let t=0;function e(r){let o=Math.round(i.time*i.factor**t);return r({attempt:t,retry:a=>co(a!=null?a:o).then(()=>(t+=1,e(r)))})}return e(s)}var qt=class extends Error{constructor(t){super();c(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,qt.prototype),this.originalProgressEvent=t}},Oe=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},xt=class extends Error{constructor(t="Request canceled"){super(t);c(this,"isCancel",!0);Object.setPrototypeOf(this,xt.prototype)}},po=500,ws=({check:s,interval:i=po,timeout:t,signal:e})=>new Promise((r,o)=>{let n,a;Oe(e,()=>{n&&clearTimeout(n),o(new xt("Poll cancelled"))}),t&&(a=setTimeout(()=>{n&&clearTimeout(n),o(new xt("Timed out"))},t));let l=()=>{try{Promise.resolve(s(e)).then(u=>{u?(a&&clearTimeout(a),r(u)):n=setTimeout(l,i)}).catch(u=>{a&&clearTimeout(a),o(u)})}catch(u){a&&clearTimeout(a),o(u)}};n=setTimeout(l,0)}),T={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Re="application/octet-stream",Ts="original",Tt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:o})=>new Promise((n,a)=>{let l=new XMLHttpRequest,u=(s==null?void 0:s.toUpperCase())||"GET",h=!1;l.open(u,i,!0),e&&Object.entries(e).forEach(d=>{let[p,f]=d;typeof f!="undefined"&&!Array.isArray(f)&&l.setRequestHeader(p,f)}),l.responseType="text",Oe(r,()=>{h=!0,l.abort(),a(new xt)}),l.onload=()=>{if(l.status!=200)a(new Error(`Error ${l.status}: ${l.statusText}`));else{let d={method:u,url:i,data:t,headers:e||void 0,signal:r,onProgress:o},p=l.getAllResponseHeaders().trim().split(/[\r\n]+/),f={};p.forEach(function(x){let A=x.split(": "),w=A.shift(),C=A.join(": ");w&&typeof w!="undefined"&&(f[w]=C)});let m=l.response,b=l.status;n({request:d,data:m,headers:f,status:b})}},l.onerror=d=>{h||a(new qt(d))},o&&typeof o=="function"&&(l.upload.onprogress=d=>{d.lengthComputable?o({isComputable:!0,value:d.loaded/d.total}):o({isComputable:!1})}),t?l.send(t):l.send()});function mo(s,...i){return s}var fo=({name:s})=>s?[s]:[],go=mo,_o=()=>new FormData,Es=s=>!1,Le=s=>typeof Blob!="undefined"&&s instanceof Blob,Ue=s=>typeof File!="undefined"&&s instanceof File,Pe=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",oe=s=>Le(s)||Ue(s)||Es()||Pe(s),bo=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",vo=s=>!!s&&typeof s=="object"&&!Array.isArray(s),yo=s=>!!s&&typeof s=="object"&&"data"in s&&oe(s.data);function Co(s,i,t){if(yo(t)){let{name:e,contentType:r}=t,o=go(t.data,e,r!=null?r:Re),n=fo({name:e,contentType:r});s.push([i,o,...n])}else if(vo(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else bo(t)&&t&&s.push([i,t.toString()])}function xo(s){let i=[];for(let[t,e]of Object.entries(s))Co(i,t,e);return i}function Pi(s){let i=_o(),t=xo(s);for(let e of t){let[r,o,...n]=e;i.append(r,o,...n)}return i}var R=class extends Error{constructor(t,e,r,o,n){super();c(this,"isCancel");c(this,"code");c(this,"request");c(this,"response");c(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=o,this.headers=n,Object.setPrototypeOf(this,R.prototype)}},wo=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var o;return(o=r[1])!=null?o:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=wo(t)),e.toString()},To="6.6.1",Eo="UploadcareUploadClient",Ao=To;function Ut(s){return Ui({libraryName:Eo,libraryVersion:Ao,...s})}var So="RequestThrottledError",xs=15e3,$o=1e3;function ko(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return xs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:xs}function Et(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return ho(({attempt:r,retry:o})=>s().catch(n=>{if("response"in n&&(n==null?void 0:n.code)===So&&r{let i="";return(Le(s)||Ue(s)||Pe(s))&&(i=s.type),i||Re},Ss=s=>{let i="";return Ue(s)&&s.name?i=s.name:Le(s)||Es()?i="":Pe(s)&&s.name&&(i=s.name),i||Ts};function Mi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Io(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=T.baseURL,secureSignature:o,secureExpire:n,store:a,signal:l,onProgress:u,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=T.retryNetworkErrorMaxTimes,metadata:b}){return Et(()=>Tt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:d,userAgent:p})},data:Pi({file:{data:s,name:t||Ss(s),contentType:e||As(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Mi(a),signature:o,expire:n,source:h,metadata:b}),signal:l,onProgress:u}).then(({data:x,headers:A,request:w})=>{let C=gt(JSON.parse(x));if("error"in C)throw new R(C.error.content,C.error.errorCode,w,C,A);return C}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var Ii;(function(s){s.Token="token",s.FileInfo="file_info"})(Ii||(Ii={}));function Oo(s,{publicKey:i,baseURL:t=T.baseURL,store:e,fileName:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,source:u="url",signal:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=T.retryNetworkErrorMaxTimes,metadata:b}){return Et(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Mi(e),filename:r,check_URL_duplicates:o?1:void 0,save_URL_duplicates:n?1:void 0,signature:a,expire:l,source:u,metadata:b}),signal:h}).then(({data:x,headers:A,request:w})=>{let C=gt(JSON.parse(x));if("error"in C)throw new R(C.error.content,C.error.errorCode,w,C,A);return C}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var X;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(X||(X={}));var Ro=s=>"status"in s&&s.status===X.Error;function Lo(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}={}){return Et(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Ut({publicKey:i,integration:r,userAgent:o})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:l,headers:u,request:h})=>{let d=gt(JSON.parse(l));if("error"in d&&!Ro(d))throw new R(d.error.content,void 0,h,d,u);return d}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:n})}function Uo(s,{publicKey:i,baseURL:t=T.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:o,signal:n,source:a,integration:l,userAgent:u,retryThrottledRequestMaxTimes:h=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:l,userAgent:u})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:o,source:a}),signal:n}).then(({data:p,headers:f,request:m})=>{let b=gt(JSON.parse(p));if("error"in b)throw new R(b.error.content,b.error.errorCode,m,b,f);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function $s(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,source:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:o,userAgent:n})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:u,headers:h,request:d})=>{let p=gt(JSON.parse(u));if("error"in p)throw new R(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function Po(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=T.multipartChunkSize,baseURL:o="",secureSignature:n,secureExpire:a,store:l,signal:u,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=T.retryNetworkErrorMaxTimes,metadata:b}){return Et(()=>Tt({method:"POST",url:ft(o,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:d,userAgent:p})},data:Pi({filename:e||Ts,size:s,content_type:t||Re,part_size:r,UPLOADCARE_STORE:Mi(l),UPLOADCARE_PUB_KEY:i,signature:n,expire:a,source:h,metadata:b}),signal:u}).then(({data:x,headers:A,request:w})=>{let C=gt(JSON.parse(x));if("error"in C)throw new R(C.error.content,C.error.errorCode,w,C,A);return C.parts=Object.keys(C.parts).map(H=>C.parts[H]),C}),{retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})}function Mo(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:o=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:n=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Re}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n})}function No(s,{publicKey:i,baseURL:t=T.baseURL,source:e="local",signal:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:o,userAgent:n})},data:Pi({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:u,headers:h,request:d})=>{let p=gt(JSON.parse(u));if("error"in p)throw new R(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function Ni({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a,signal:l,onProgress:u}){return ws({check:h=>$s(s,{publicKey:i,baseURL:t,signal:h,source:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a}).then(d=>d.isReady?d:(u&&u({isComputable:!0,value:1}),!1)),signal:l})}var wt=class{constructor(i,{baseCDN:t=T.baseCDN,fileName:e}={}){c(this,"uuid");c(this,"name",null);c(this,"size",null);c(this,"isStored",null);c(this,"isImage",null);c(this,"mimeType",null);c(this,"cdnUrl",null);c(this,"s3Url",null);c(this,"originalFilename",null);c(this,"imageInfo",null);c(this,"videoInfo",null);c(this,"contentInfo",null);c(this,"metadata",null);c(this,"s3Bucket",null);let{uuid:r,s3Bucket:o}=i,n=ft(t,`${r}/`),a=o?ft(`https://${o}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=n,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=o||null,this.s3Url=a}},Do=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:n,contentType:a,signal:l,onProgress:u,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:x})=>Io(s,{publicKey:i,fileName:t,contentType:a,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:l,onProgress:u,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,metadata:x}).then(({file:A})=>Ni({file:A,publicKey:i,baseURL:e,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,onProgress:u,signal:l})).then(A=>new wt(A,{baseCDN:b})),Bo=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:o,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:u,retryNetworkErrorMaxTimes:h,baseCDN:d})=>$s(s,{publicKey:i,baseURL:e,signal:r,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:u,retryNetworkErrorMaxTimes:h}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(o&&o({isComputable:!0,value:1}),p)),Fo=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),o=n=>()=>{e=n,r.forEach((a,l)=>l!==n&&a.abort())};return Oe(i,()=>{r.forEach(n=>n.abort())}),Promise.all(s.map((n,a)=>{let l=o(a);return Promise.resolve().then(()=>n({stopRace:l,signal:r[a].signal})).then(u=>(l(),u)).catch(u=>(t=u,null))})).then(n=>{if(e===null)throw t;return n[e]})},Vo=window.WebSocket,Oi=class{constructor(){c(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},zo=(s,i)=>s==="success"?{status:X.Success,...i}:s==="progress"?{status:X.Progress,...i}:{status:X.Error,...i},Ri=class{constructor(i,t=3e4){c(this,"key");c(this,"disconnectTime");c(this,"ws");c(this,"queue",[]);c(this,"isConnected",!1);c(this,"subscribers",0);c(this,"emmitter",new Oi);c(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Vo(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,zo(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},$i=null,Di=s=>{if(!$i){let i=typeof window=="undefined"?0:3e4;$i=new Ri(s,i)}return $i},jo=s=>{Di(s).connect()};function Ho({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,onProgress:a,signal:l}){return ws({check:u=>Lo(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,signal:u}).then(h=>{switch(h.status){case X.Error:return new R(h.error,h.errorCode);case X.Waiting:return!1;case X.Unknown:return new R(`Token "${s}" was not found.`);case X.Progress:return a&&(h.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:h.done/h.total})),!1;case X.Success:return a&&a({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:l})}var Wo=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,o)=>{let n=Di(i),a=n.onError(o),l=()=>{a(),n.unsubscribe(s)};Oe(t,()=>{l(),o(new xt("pusher cancelled"))}),n.subscribe(s,u=>{switch(u.status){case X.Progress:{e&&(u.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:u.done/u.total}));break}case X.Success:{l(),e&&e({isComputable:!0,value:u.done/u.total}),r(u);break}case X.Error:l(),o(new R(u.msg,u.error_code))}})}),Xo=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:u,signal:h,onProgress:d,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,pusherKey:x=T.pusherKey,metadata:A})=>Promise.resolve(jo(x)).then(()=>Oo(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:u,signal:h,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,metadata:A})).catch(w=>{let C=Di(x);return C==null||C.disconnect(),Promise.reject(w)}).then(w=>w.type===Ii.FileInfo?w:Fo([({signal:C})=>Ho({token:w.token,publicKey:i,baseURL:e,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:C}),({signal:C})=>Wo({token:w.token,pusherKey:x,signal:C,onProgress:d})],{signal:h})).then(w=>{if(w instanceof R)throw w;return w}).then(w=>Ni({file:w.uuid,publicKey:i,baseURL:e,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:h})).then(w=>new wt(w,{baseCDN:r})),ki=new WeakMap,qo=async s=>{if(ki.has(s))return ki.get(s);let i=await fetch(s.uri).then(t=>t.blob());return ki.set(s,i),i},ks=async s=>{if(Ue(s)||Le(s))return s.size;if(Pe(s))return(await qo(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Go=(s,i=T.multipartMinFileSize)=>s>=i,Is=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!oe(s)&&t.test(s)},Os=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!oe(s)&&t.test(s)},Ko=(s,i)=>new Promise((t,e)=>{let r=[],o=!1,n=i.length,a=[...i],l=()=>{let u=i.length-a.length,h=a.shift();h&&h().then(d=>{o||(r[u]=d,n-=1,n?l():t(r))}).catch(d=>{o=!0,e(d)})};for(let u=0;u{let r=e*i,o=Math.min(r+e,t);return s.slice(r,o)},Zo=async(s,i,t)=>e=>Yo(s,e,i,t),Jo=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:o,integration:n,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})=>Mo(s,i,{publicKey:t,contentType:e,onProgress:r,signal:o,integration:n,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l}),Qo=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:o,secureExpire:n,store:a,signal:l,onProgress:u,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:b,multipartChunkSize:x=T.multipartChunkSize,maxConcurrentRequests:A=T.maxConcurrentRequests,baseCDN:w,metadata:C})=>{let H=e!=null?e:await ks(s),ht,It=(O,Z)=>{if(!u)return;ht||(ht=Array(O).fill(0));let dt=W=>W.reduce((pt,xi)=>pt+xi,0);return W=>{W.isComputable&&(ht[Z]=W.value,u({isComputable:!0,value:dt(ht)/O}))}};return b||(b=As(s)),Po(H,{publicKey:i,contentType:b,fileName:t||Ss(s),baseURL:r,secureSignature:o,secureExpire:n,store:a,signal:l,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,metadata:C}).then(async({uuid:O,parts:Z})=>{let dt=await Zo(s,H,x);return Promise.all([O,Ko(A,Z.map((W,pt)=>()=>Jo(dt(pt),W,{publicKey:i,contentType:b,onProgress:It(Z.length,pt),signal:l,integration:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})))])}).then(([O])=>No(O,{publicKey:i,baseURL:r,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})).then(O=>O.isReady?O:Ni({file:O.uuid,publicKey:i,baseURL:r,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,onProgress:u,signal:l})).then(O=>new wt(O,{baseCDN:w}))};async function Bi(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,contentType:m,multipartMinFileSize:b,multipartChunkSize:x,maxConcurrentRequests:A,baseCDN:w=T.baseCDN,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:H,pusherKey:ht,metadata:It}){if(oe(s)){let O=await ks(s);return Go(O,b)?Qo(s,{publicKey:i,contentType:m,multipartChunkSize:x,fileSize:O,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,baseCDN:w,metadata:It}):Do(s,{publicKey:i,fileName:t,contentType:m,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,baseCDN:w,metadata:It})}if(Os(s))return Xo(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:w,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:H,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,pusherKey:ht,metadata:It});if(Is(s))return Bo(s,{publicKey:i,fileName:t,baseURL:e,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,baseCDN:w});throw new TypeError(`File uploading from "${s}" is not supported`)}var Li=class{constructor(i,t){c(this,"uuid");c(this,"filesCount");c(this,"totalSize");c(this,"isStored");c(this,"isImage");c(this,"cdnUrl");c(this,"files");c(this,"createdAt");c(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},tn=s=>{for(let i of s)if(!oe(i))return!1;return!0},en=s=>{for(let i of s)if(!Is(i))return!1;return!0},sn=s=>{for(let i of s)if(!Os(i))return!1;return!0};function Rs(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,contentType:m,multipartChunkSize:b=T.multipartChunkSize,baseCDN:x=T.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:w,jsonpCallback:C}){if(!tn(s)&&!sn(s)&&!en(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let H,ht=!0,It=s.length,O=(Z,dt)=>{if(!l)return;H||(H=Array(Z).fill(0));let W=pt=>pt.reduce((xi,Lr)=>xi+Lr)/Z;return pt=>{if(!pt.isComputable||!ht){ht=!1,l({isComputable:!1});return}H[dt]=pt.value,l({isComputable:!0,value:W(H)})}};return Promise.all(s.map((Z,dt)=>Bi(Z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:O(It,dt),source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,contentType:m,multipartChunkSize:b,baseCDN:x,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:w}))).then(Z=>{let dt=Z.map(W=>W.uuid);return Uo(dt,{publicKey:i,baseURL:e,jsonpCallback:C,secureSignature:r,secureExpire:o,signal:a,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f}).then(W=>new Li(W,Z)).then(W=>(l&&l({isComputable:!0,value:1}),W))})}var Rt,jt,Lt,Ht,Wt,Xt,ke,Ie=class{constructor(i){Ot(this,Xt);Ot(this,Rt,1);Ot(this,jt,[]);Ot(this,Lt,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);te(this,Rt,i)}add(i){return new Promise((t,e)=>{N(this,Ht).set(i,t),N(this,Wt).set(i,e),N(this,jt).push(i),Ee(this,Xt,ke).call(this)})}get pending(){return N(this,jt).length}get running(){return N(this,Lt)}set concurrency(i){te(this,Rt,i),Ee(this,Xt,ke).call(this)}get concurrency(){return N(this,Rt)}};Rt=new WeakMap,jt=new WeakMap,Lt=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,ke=function(){let i=N(this,Rt)-N(this,Lt);for(let t=0;t{N(this,Ht).delete(e),N(this,Wt).delete(e),te(this,Lt,N(this,Lt)-1),Ee(this,Xt,ke).call(this)}).then(n=>r(n)).catch(n=>o(n))}};var Fi=()=>({"*blocksRegistry":new Set}),Vi=s=>({...Fi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Me=s=>({...Vi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Ie(1)});function Ls(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let n=e.split(":");r=n[0],e=n[1]}let o="l10n:"+e;i.__l10nKeys.push(o),i.add(o,e),i.sub(o,n=>{t[r]=i.l10n(n)}),t.removeAttribute("l10n")})}var L=s=>`*cfg/${s}`;var _t=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Us=new Set;function Ne(s){Us.has(s)||(Us.add(s),console.warn(s))}var De=(s,i)=>new Intl.PluralRules(s).select(i);var zi="lr-",_=class extends zt{constructor(){super();c(this,"allowCustomTemplate",!0);c(this,"init$",Fi());c(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Ls),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,o=vs(r);for(let a of o)e[a.variable]=this.pluralize(a.pluralKey,Number(e[a.countVariable]));return re(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",o=De(r,e);return this.l10n(`${t}__${o}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setForCtxTarget(t,e,r){this.hasBlockInCtx(o=>o.constructor.StateConsumerScope===t)&&(this.$[e]=r)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${zi}${t}`,!0),Ai()||(this._destroyInnerHeightTracker=gs()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],o=u=>this.getCssData("--l10n-unit-"+u.toLowerCase(),!0)||u;if(t===0)return`0 ${o(r[0])}`;let n=1024,a=e<0?0:e,l=Math.floor(Math.log(t)/Math.log(n));return parseFloat((t/n**l).toFixed(a))+" "+o(r[l])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?re(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let o=L(r),n=this.parseCfgProp(o);return n.ctx.has(n.name)?n.ctx.read(n.name):(Ne("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${_t(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(L(t));r.ctx.has(r.name)?this.sub(L(t),e):(this.bindCssData(`--cfg-${_t(t)}`),this.sub(`--cfg-${_t(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(zi)?t:zi+t)}};c(_,"StateConsumerScope",null),c(_,"className","");var ji=class extends _{constructor(){super(...arguments);c(this,"_handleBackdropClick",()=>{this._closeDialog()});c(this,"_closeDialog",()=>{this.setForCtxTarget(ji.StateConsumerScope,"*modalActive",!1)});c(this,"_handleDialogClose",()=>{this._closeDialog()});c(this,"_handleDialogClick",t=>{t.target===this.ref.dialog&&this._closeDialog()});c(this,"init$",{...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose})}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("click",this._handleDialogClick);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogClick)}},F=ji;c(F,"StateConsumerScope","modal");F.template=``;var Ps="active",ne="___ACTIVITY_IS_ACTIVE___",rt=class extends _{constructor(){super(...arguments);c(this,"historyTracked",!1);c(this,"init$",Vi(this));c(this,"_debouncedHistoryFlush",G(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=rt._activityRegistry[this.activityKey];this[ne]=!1,this.removeAttribute(Ps),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=rt._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[ne]=!0,this.setAttribute(Ps,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[ne]?this._deactivate():this.activityType===t&&!this[ne]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!rt._activityRegistry[this.activityKey]}get isActivityActive(){return this[ne]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:o}=e;rt._activityRegistry||(rt._activityRegistry=Object.create(null)),rt._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:o}}unregisterActivity(){this.isActivityActive&&this._deactivate(),rt._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(rt._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!1)}}},g=rt;c(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var U=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var ae=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Hi=s=>s?s.filter(i=>typeof i=="string").map(i=>U(i)).flat():[],Wi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),Ms=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),le=s=>{let i=s==null?void 0:s.type;return i?Wi(i,ae):!1};var Ns=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var Ds="blocks",Bs="0.25.6";function Fs(s){return Ui({...s,libraryName:Ds,libraryVersion:Bs})}var Vs="[Typed State] Wrong property name: ",rn="[Typed State] Wrong property type: ",Be=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||ie.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Vs+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(rn+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Vs+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Fe=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||ie.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(o=>{o({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Be(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var k={UPLOAD_START:"UPLOAD_START",REMOVE:"REMOVE",UPLOAD_PROGRESS:"UPLOAD_PROGRESS",UPLOAD_FINISH:"UPLOAD_FINISH",UPLOAD_ERROR:"UPLOAD_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",CDN_MODIFICATION:"CLOUD_MODIFICATION",DATA_OUTPUT:"DATA_OUTPUT",DONE_FLOW:"DONE_FLOW",INIT_FLOW:"INIT_FLOW"},D=class{constructor(i){this.ctx=i.ctx,this.type=i.type,this.data=i.data}},$=class{static eName(i){return"LR_"+i}static emit(i,t=window,e=!0){let r=()=>{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let o=i.type+i.ctx;this._timeoutStore[o]&&window.clearTimeout(this._timeoutStore[o]),this._timeoutStore[o]=window.setTimeout(()=>{r(),delete this._timeoutStore[o]},20)}};c($,"_timeoutStore",Object.create(null));var J=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var ot=1e3,Pt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ce=s=>Math.ceil(s*100)/100,zs=(s,i=Pt.AUTO)=>{let t=i===Pt.AUTO;if(i===Pt.BYTE||t&&s{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(o=>[...o]).flat())].map(o=>e.read(o)).filter(Boolean);for(let o of r)this._runValidatorsForEntry(o);if(t.uploadProgress){let o=0,n=e.findItems(l=>!l.getValue("uploadError"));n.forEach(l=>{o+=e.readProp(l,"uploadProgress")});let a=Math.round(o/n.length);this.$["*commonProgress"]=a,$.emit(new D({type:k.UPLOAD_PROGRESS,ctx:this.ctxName,data:a}),void 0,a===100)}if(t.fileInfo){let o=e.findItems(a=>!!a.getValue("fileInfo")),n=e.findItems(a=>!!a.getValue("uploadError")||!!a.getValue("validationErrorMsg"));if(e.size-n.length===o.length){let a=this.getOutputData(l=>!!l.getValue("fileInfo")&&!l.getValue("silentUpload"));a.length>0&&$.emit(new D({type:k.UPLOAD_FINISH,ctx:this.ctxName,data:a}))}}t.uploadError&&e.findItems(n=>!!n.getValue("uploadError")).forEach(n=>{$.emit(new D({type:k.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(n,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(n=>!!n.getValue("validationErrorMsg")).forEach(n=>{$.emit(new D({type:k.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(n,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(n=>!!n.getValue("cdnUrlModifiers")).forEach(n=>{$.emit(new D({type:k.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(n).store}),void 0,!1)})})}setUploadMetadata(t){Ne("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Fe({typedSchema:Ns,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,o)=>{var n;this._runValidators();for(let a of o)(n=a==null?void 0:a.getValue("abortController"))==null||n.abort(),a==null||a.setValue("abortController",null),URL.revokeObjectURL(a==null?void 0:a.getValue("thumbUrl"));this.$["*uploadList"]=e.map(a=>({uid:a}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:o!=null?o:J.API})}addFileFromUuid(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:o!=null?o:J.API})}addFileFromObject(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({file:t,isImage:le(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:o!=null?o:J.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:le(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Hi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?ae:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=ae.join(",")):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(o=>this.addFileFromObject(o,{source:J.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=U(this.cfg.sourceList)),t}initFlow(t=!1){var e,r;if((e=this.$["*uploadList"])!=null&&e.length&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let o=this.sourceList[0];o==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(o)?this.set$({"*currentActivityParams":{externalSourceType:o},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=o,this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0);$.emit(new D({type:k.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!1),$.emit(new D({type:k.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,o=Hi([...e?ae:[],r]);if(!o.length)return;let n=t.getValue("mimeType"),a=t.getValue("fileName");if(!n||!a)return;let l=Wi(n,o),u=Ms(a,o);if(!l&&!u)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:zs(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),o=this.cfg.multiple?this.cfg.multipleMax:1;if(o&&r>=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Fs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(o=>{let n=E.getCtx(o).store,a=n.fileInfo||{name:n.fileName,fileSize:n.fileSize,isImage:n.isImage,mimeType:n.mimeType},l={...a,cdnUrlModifiers:n.cdnUrlModifiers,cdnUrl:n.cdnUrl||a.cdnUrl};e.push(l)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(k).forEach(s=>{let i=$.eName(s);window.addEventListener(i,t=>{if([k.UPLOAD_FINISH,k.REMOVE,k.CDN_MODIFICATION].includes(t.detail.type)){let r=E.getCtx(t.detail.ctx),o=r.read("uploadCollection"),n=[];o.items().forEach(a=>{let l=E.getCtx(a).store,u=l.fileInfo;if(u){let h={...u,cdnUrlModifiers:l.cdnUrlModifiers,cdnUrl:l.cdnUrl||u.cdnUrl};n.push(h)}}),$.emit(new D({type:k.DATA_OUTPUT,ctx:t.detail.ctx,data:n})),r.pub("outputData",n)}})});var on="https://ucarecdn.com",nn="https://upload.uploadcare.com",an="https://social.uploadcare.com",ue=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:on,baseUrl:nn,socialBaseUrl:an,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var Q=s=>String(s),nt=s=>Number(s),V=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,ln=s=>s==="auto"?s:V(s),cn={pubkey:Q,multiple:V,multipleMin:nt,multipleMax:nt,confirmUpload:V,imgOnly:V,accept:Q,externalSourcesPreferredTypes:Q,store:ln,cameraMirror:V,sourceList:Q,maxLocalFileSizeBytes:nt,thumbSize:nt,showEmptyList:V,useLocalImageEditor:V,useCloudImageEditor:V,removeCopyright:V,modalScrollLock:V,modalBackdropStrokes:V,sourceListWrap:V,remoteTabSessionKey:Q,cdnCname:Q,baseUrl:Q,socialBaseUrl:Q,secureSignature:Q,secureExpire:Q,secureDeliveryProxy:Q,retryThrottledRequestMaxTimes:nt,multipartMinFileSize:nt,multipartChunkSize:nt,maxConcurrentRequests:nt,multipartMaxConcurrentRequests:nt,multipartMaxAttempts:nt,checkForUrlDuplicates:V,saveUrlForRecurrentUploads:V,groupOutput:V,userAgentIntegration:Q},js=(s,i)=>{if(!(typeof i=="undefined"||i===null))return cn[s](i)};var Ve=Object.keys(ue),un=["metadata"],hn=s=>un.includes(s),Xi=Ve.filter(s=>!hn(s)),dn={...Object.fromEntries(Xi.map(s=>[_t(s),s])),...Object.fromEntries(Xi.map(s=>[s.toLowerCase(),s]))},pn={...Object.fromEntries(Ve.map(s=>[_t(s),L(s)])),...Object.fromEntries(Ve.map(s=>[s.toLowerCase(),L(s)]))},ze=class extends _{constructor(){super(...arguments);c(this,"ctxOwner",!0);c(this,"init$",{...this.init$,...Object.fromEntries(Object.entries(ue).map(([t,e])=>[L(t),e]))})}initCallback(){super.initCallback();for(let t of Ve){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:o=>{if(e[r]=o,Xi.includes(t)){let n=[...new Set([_t(t),t.toLowerCase()])];for(let a of n)typeof o=="undefined"||o===null?this.removeAttribute(a):this.setAttribute(a,o.toString())}this.$[L(t)]!==o&&(typeof o=="undefined"||o===null?this.$[L(t)]=ue[t]:this.$[L(t)]=o)},get:()=>this.$[L(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let o=dn[t],n=js(o,r),a=n!=null?n:ue[o],l=this;l[o]=a}};ze.bindAttributes(pn);var he=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};he.template=``;he.bindAttributes({name:"name",size:"size"});var Hs=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},je=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Hs(i)).join("/-/"),P=(...s)=>{let i=je(...s);return i?`-/${i}/`:""};function Ws(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),o="";return e>=0?o=t.slice(e):r>=0&&(o=t.slice(r+1)),o}function Xs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function qs(s){let i=Gs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(o=>Hs(o))}function Gs(s){let i=new URL(s),t=Ws(s),e=Ks(t)?Ys(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function Ks(s){return s.startsWith("http")}function Ys(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var S=(s,i,t)=>{let e=new URL(Gs(s));if(t=t||Ws(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Ks(t)){let r=Ys(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var mn="https://ucarecdn.com",Mt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:mn},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var Zs=s=>[...new Set(s)];var de="--lr-img-",Js="unresolved",Gt=2,Kt=3,Qs=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),er=Object.create(null),tr;for(let s in Mt)er[de+s]=((tr=Mt[s])==null?void 0:tr.default)||"";var He=class extends zt{constructor(){super(...arguments);c(this,"cssInit$",er)}$$(t){return this.$[de+t]}set$$(t){for(let e in t)this.$[de+e]=t[e]}sub$$(t,e){this.sub(de+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!Qs&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return P(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Mt.format.default}`,`quality/${this.$$("quality")||Mt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(Qs&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return S(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(S(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(S(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(S(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(S(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?re(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let o=t.getBoundingClientRect(),n=e*Math.round(o.width),a=r?"":e*Math.round(o.height);return n||a?`${n||""}x${a||""}`:null}_setupEventProxy(t){let e=o=>{o.stopPropagation();let n=new Event(o.type,o);this.dispatchEvent(n)},r=["load","error"];for(let o of r)t.addEventListener(o,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(Js,""),this.img.onload=()=>{this.img.removeAttribute(Js)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Mt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?Zs(U(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(o=>{e.add(`url("${this._getUrlBase(o+"x")}") ${o}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(o*Gt+"x")}") ${o*Gt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(o*Kt+"x")}") ${o*Kt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Gt))}") ${Gt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Kt))}") ${Kt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Gt+"x")+` ${e*Gt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Kt+"x")+` ${e*Kt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(o=>{o.forEach(n=>{n.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null)}static get observedAttributes(){return Object.keys(Mt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[de+t]=r})}};var qi=class extends He{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var We=class extends v{constructor(){super(...arguments);c(this,"init$",{...this.init$,"*simpleButtonText":"",onClick:()=>{this.initFlow()}})}initCallback(){super.initCallback(),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};We.template=``;var Gi=class extends g{constructor(){super(...arguments);c(this,"historyTracked",!0);c(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function fn(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function gn(s,i){return new Promise(t=>{let e=0,r=[],o=a=>{a||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),a.isFile?(e++,a.file(l=>{e--;let u=new File([l],l.name,{type:l.type||i});r.push(u),e===0&&t(r)})):a.isDirectory&&n(a.createReader())},n=a=>{e++,a.readEntries(l=>{e--;for(let u of l)o(u);e===0&&t(r)})};o(s)})}function ir(s){let i=[],t=[];for(let e=0;e{i.push(...l)}));continue}let n=r.getAsFile();t.push(fn(n).then(a=>{a||i.push(n)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(o=>{r.getAsString(n=>{i.push(n),o()})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},sr=["focus"],_n=100,Ki=new Map;function bn(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Yi(s){let i=0,t=document.body,e=new Set,r=m=>e.add(m),o=z.INACTIVE,n=m=>{s.shouldIgnore()&&m!==z.INACTIVE||(o!==m&&e.forEach(b=>b(m)),o=m)},a=()=>i>0;r(m=>s.onChange(m));let l=()=>{i=0,n(z.INACTIVE)},u=()=>{i+=1,o===z.INACTIVE&&n(z.ACTIVE)},h=()=>{i-=1,a()||n(z.INACTIVE)},d=m=>{m.preventDefault(),i=0,n(z.INACTIVE)},p=m=>{a()||(i+=1),m.preventDefault();let b=[m.x,m.y],x=s.element.getBoundingClientRect(),A=Math.floor(bn(b,x)),w=A<_n,C=m.composedPath().includes(s.element);Ki.set(s.element,A);let H=Math.min(...Ki.values())===A;n(C&&H?z.OVER:w&&H?z.NEAR:z.ACTIVE)},f=async m=>{if(s.shouldIgnore())return;m.preventDefault();let b=await ir(m.dataTransfer);s.onItems(b),n(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",h),t.addEventListener("dragenter",u),t.addEventListener("dragover",p),s.element.addEventListener("drop",f),sr.forEach(m=>{window.addEventListener(m,l)}),()=>{Ki.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",h),t.removeEventListener("dragenter",u),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",f),sr.forEach(m=>{window.removeEventListener(m,l)})}}var pe=class extends v{constructor(){super(...arguments);c(this,"init$",{...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),o=window.getComputedStyle(this),n=o.visibility!=="hidden"&&o.display!=="none";return e&&n&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!e})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:typeof e=="string"})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:typeof e=="string"})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:typeof e=="string"})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Yi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:J.DROP_AREA});return}this.addFileFromObject(r,{source:J.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Yi({element:t,onChange:e=>{var o;let r=(o=Object.entries(z).find(([,n])=>n===e))==null?void 0:o[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var o;let r=(o=Object.entries(z).find(([,n])=>n===e))==null?void 0:o[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=U(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,o;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(o=this._destroyContentWrapperDropzone)==null||o.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};pe.template=`
{{text}}
`;pe.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var vn="src-type-",me=class extends v{constructor(){super(...arguments);c(this,"_registeredTypes",{});c(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:o=t,activity:n,onClick:a,activityParams:l={}}=e;this.applyL10nKey("src-type",`${vn}${r}`),this.$.iconName=o,this.onclick=u=>{(a?a(u):!!n)&&this.set$({"*currentActivityParams":l,"*currentActivity":n})}}};me.template=`
`;me.bindAttributes({type:null});var Zi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=U(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function rr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function or(s="#fff",i="rgba(0, 0, 0, .1)"){return rr(``)}function fe(s="hsl(209, 21%, 65%)",i=32,t=32){return rr(``)}function nr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,o=new Promise((n,a)=>{r.onload=()=>{let l=r.height/r.width;l>1?(t.width=i,t.height=i*l):(t.height=i,t.width=i/l),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(u=>{if(!u){a();return}let h=URL.createObjectURL(u);n(h)})},r.onerror=l=>{a(l)}});return r.src=URL.createObjectURL(s),o}var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),bt=class extends v{constructor(){super(...arguments);c(this,"pauseRender",!0);c(this,"_entrySubs",new Set);c(this,"_entry",null);c(this,"_isIntersecting",!1);c(this,"_debouncedGenerateThumb",G(this._generateThumbnail.bind(this),100));c(this,"_debouncedCalculateState",G(this._calculateState.bind(this),100));c(this,"_renderedOnce",!1);c(this,"init$",{...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);$.emit(new D({type:k.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}})}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,o=this.proxyUrl(S(At(this.cfg.cdnCname,this._entry.getValue("uuid")),P(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),n=t.getValue("thumbUrl");n!==o&&(t.setValue("thumbUrl",o),n!=null&&n.startsWith("blob:")&&URL.revokeObjectURL(n));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await nr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let o=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",fe(o))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",fe(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,o=>{this.isConnected&&e(o)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",o=>{this.$.progressValue=o}),this._subEntry("fileName",o=>{this.$.itemName=o||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",o=>{this.$.itemName=e.getValue("fileName")||o||this.l10n("file-no-name")}),this._subEntry("uuid",o=>{this._debouncedCalculateState(),o&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",o=>{this.$.thumbUrl=o?`url(${o})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{bt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),bt.activeInstances.add(this)}_handleState(t){var e,r;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&t===B.FINISHED&&((e=this._entry)==null?void 0:e.getValue("isImage")),errorText:((r=this._entry.getValue("uploadError"))==null?void 0:r.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),bt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var o,n,a;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(l=>!l.getValue("fileInfo"));$.emit(new D({type:k.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let l=new AbortController;t.setValue("abortController",l);let u=async()=>{let d=await this.getUploadClientOptions();return Bi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let f=p.value*100;t.setValue("uploadProgress",f)}this.$.progressUnknown=!p.isComputable},signal:l.signal})},h=await this.$["*uploadQueue"].add(u);t.setMultipleValues({fileInfo:h,isUploading:!1,fileName:h.originalFilename,fileSize:h.size,isImage:h.isImage,mimeType:(a=(n=(o=h.contentInfo)==null?void 0:o.mime)==null?void 0:n.mime)!=null?a:h.mimeType,uuid:h.uuid,cdnUrl:h.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(l){console.warn("Upload error",l),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),l instanceof R?l.isCancel||t.setValue("uploadError",l):t.setValue("uploadError",new Error("Unexpected error"))}}};bt.template=`
{{itemName}}{{errorText}}
`;bt.activeInstances=new Set;var Xe=class{constructor(){c(this,"caption","");c(this,"text","");c(this,"iconName","");c(this,"isError",!1)}},qe=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};qe.template=`
{{captionTxt}}
{{msgTxt}}
`;var Ge=class extends v{constructor(){super(...arguments);c(this,"couldBeUploadCollectionOwner",!0);c(this,"historyTracked",!0);c(this,"activityType",g.activities.UPLOAD_LIST);c(this,"init$",{...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));$.emit(new D({type:k.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}});c(this,"_debouncedHandleCollectionUpdate",G(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0))}_validateFilesCount(){var h,d;let t=!!this.cfg.multiple,e=t?(h=this.cfg.multipleMin)!=null?h:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,o=this.uploadCollection.size,n=e?or:!1;return{passed:!n&&!a,tooFew:n,tooMany:a,min:e,max:r,exact:r===o}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new Xe,o=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(o,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let f of t){let m=this.uploadCollection.read(f);m.getValue("fileInfo")&&!m.getValue("validationErrorMsg")&&(r.succeed+=1),m.getValue("isUploading")&&(r.uploading+=1),(m.getValue("validationErrorMsg")||m.getValue("uploadError"))&&(r.failed+=1),m.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:o,tooMany:n,exact:a}=this._validateFilesCount(),l=r.failed===0&&r.limitOverflow===0,u=!1,h=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&o?u=!0:(h=!0,d=r.total===r.succeed&&o&&l),this.set$({doneBtnVisible:h,doneBtnEnabled:d,uploadBtnVisible:u,addMoreBtnEnabled:r.total===0||!n&&!a,addMoreBtnVisible:!a||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let o=t[r];return this.l10n(`header-${r}`,{count:o})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};Ge.template=`{{headerText}}
`;var Ke=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.URL);c(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:J.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};Ke.template=`
`;var Ji=()=>typeof navigator.permissions!="undefined";var Ye=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.CAMERA);c(this,"_unsubPermissions",null);c(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Ji(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});c(this,"_onActivate",()=>{Ji()&&this._subscribePermissions(),this._capture()});c(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});c(this,"_handlePermissionsChange",()=>{this._capture()});c(this,"_setPermissionsState",G(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let o=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(o,{source:J.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,o)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${o+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};Ye.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var Qi=class extends v{};var Ze=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.DETAILS);c(this,"pauseRender",!0);c(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=fe(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(o=>{this._entrySubs.delete(o),o.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let o=le(this._file);o&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),o||this.showNonImageThumb()}let r=(o,n)=>{this._entrySubs.add(this.entry.subscribe(o,n))};r("fileName",o=>{this.$.fileName=o,this.$.onNameInput=()=>{let n=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:n}),this.entry.setValue("fileName",n)}}),r("fileSize",o=>{this.$.fileSize=Number.isFinite(o)?this.fileSizeFmt(o):this.l10n("file-size-unknown")}),r("uploadError",o=>{this.$.errorTxt=o==null?void 0:o.message}),r("externalUrl",o=>{o&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",o=>{let n=this.cfg.useCloudImageEditor&&o&&this.entry.getValue("isImage");if(o&&this.ref.filePreview.clear(),this.set$({cdnUrl:o,cloudEditBtnHidden:!n}),o&&this.entry.getValue("isImage")){let a=S(o,P("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(a))}})})}};Ze.template=`
{{fileSize}}
{{errorTxt}}
`;var ts=class{constructor(){c(this,"captionL10nStr","confirm-your-action");c(this,"messageL10Str","are-you-sure");c(this,"confirmL10nStr","yes");c(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},Je=class extends g{constructor(){super(...arguments);c(this,"activityType",g.activities.CONFIRMATION);c(this,"_defaults",new ts);c(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};Je.template=`{{activityCaption}}
{{messageTxt}}
`;var Qe=class extends v{constructor(){super(...arguments);c(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};Qe.template=``;var ti=class extends _{constructor(){super(...arguments);c(this,"_value",0);c(this,"_unknownMode",!1);c(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ti.template='
';var K="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var ge=class extends _{constructor(){super();c(this,"init$",{...this.init$,checkerboard:!1,src:K})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${or()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=K}};ge.template='';ge.bindAttributes({checkerboard:"checkerboard"});var ar="--cfg-ctx-name",I=class extends _{get cfgCssCtxName(){return this.getCssData(ar,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(ar,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function lr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function M(...s){let i=lr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function cr(s,...i){let t=lr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}function at(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var Y={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function yn(s,i){if(typeof i=="number")return Y[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Y[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Y[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var hr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function St(s){return je(...hr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yn(i,t)}).filter(i=>!!i))}var ei=je("format/auto","progressive/yes"),vt=([s])=>typeof s!="undefined"?Number(s):void 0,ur=()=>!0,Cn=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),xn=([s,i])=>({dimensions:U(s,"x").map(Number),coords:U(i).map(Number)}),wn={enhance:vt,brightness:vt,exposure:vt,gamma:vt,contrast:vt,saturation:vt,vibrance:vt,warmth:vt,filter:Cn,mirror:ur,flip:ur,rotate:vt,crop:xn};function dr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!hr.includes(e))continue;let o=wn[e],n=o(r);i[e]=n}return i}function pr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:K,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=K,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=P(St(i)),r=S(t,P(e,"preview")),o={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:o,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var mr=`
Network error
{{fileType}}
{{msg}}
`;var j={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},ii=[j.CROP,j.SLIDERS,j.FILTERS],fr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],gr=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],_r=["rotate","mirror","flip"],lt={brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}};var ct=class extends I{constructor(){super(...arguments);c(this,"init$",{...this.init$,...pr(this)});c(this,"_debouncedShowLoader",at(this._showLoader.bind(this),300))}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let o=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),n=new ResizeObserver(([a])=>{a.contentRect.width>0&&a.contentRect.height>0&&(e(),clearTimeout(o),n.disconnect())});n.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}if(this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==K&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||K)}),this.sub("*tabId",t=>{this.ref["img-el"].className=M("image",{image_hidden_to_cropper:t===j.CROP,image_hidden_effects:t!==j.CROP})}),this.$.cdnUrl){let t=Xs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=qs(this.$.cdnUrl),r=dr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{let e=this.$["*originalUrl"],r=P(St(t)),o=S(e,P(r,"preview")),n={originalUrl:e,cdnUrlModifiers:r,cdnUrl:o,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:n,bubbles:!0,composed:!0}))},!1);try{fetch(S(this.$["*originalUrl"],P("json"))).then(t=>t.json()).then(t=>{let{width:e,height:r}=t;this.$["*imageSize"]={width:e,height:r}})}catch(t){t&&console.error("Failed to load image info",t)}}};c(ct,"className","cloud-image-editor");ct.template=mr;ct.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl"});var _e=33.333333333333336,tt=24*2+34;function Nt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function et(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Nt(t,i),t}function br(s,i){let{x:t,y:e,width:r,height:o}=s,n=i.includes("w")?0:1,a=i.includes("n")?0:1,l=[-1,1][n],u=[-1,1][a],h=[t+n*r+1.5*l,e+a*o+1.5*u-24*u],d=[t+n*r+1.5*l,e+a*o+1.5*u],p=[t+n*r-24*l+1.5*l,e+a*o+1.5*u];return{d:`M ${h[0]} ${h[1]} L ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,center:d}}function vr(s,i){let{x:t,y:e,width:r,height:o}=s,n=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],l=[-1,1][n],u=[-1,1][a],h,d;["n","s"].includes(i)?(h=[t+n*r-34/2,e+a*o+1.5*u],d=[t+n*r+34/2,e+a*o+1.5*u]):(h=[t+n*r+1.5*l,e+a*o-34/2],d=[t+n*r+1.5*l,e+a*o+34/2]);let p=`M ${h[0]} ${h[1]} L ${d[0]} ${d[1]}`,f=[d[0]-(d[0]-h[0])/2,d[1]-(d[1]-h[1])/2];return{d:p,center:f}}function yr(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Cr(s,[i,t]){return{...s,x:s.x+i,y:s.y+t}}function si(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function xr(s,[i,t],e){let{x:r,y:o,width:n,height:a}=s;return e.includes("n")&&(o+=t,a-=t),e.includes("s")&&(a+=t),e.includes("w")&&(r+=i,n-=i),e.includes("e")&&(n+=i),{x:r,y:o,width:n,height:a}}function wr(s,i){let t=Math.max(s.x,i.x),e=Math.min(s.x+s.width,i.x+i.width),r=Math.max(s.y,i.y),o=Math.min(s.y+s.height,i.y+i.height);return{x:t,y:r,width:e-t,height:o-r}}function ri(s,[i,t],e){let{x:r,y:o,width:n,height:a}=s;if(e.includes("n")){let l=a;a=Math.max(t,a),o=o+l-a}if(e.includes("s")&&(a=Math.max(t,a)),e.includes("w")){let l=n;n=Math.max(i,n),r=r+l-n}return e.includes("e")&&(n=Math.max(i,n)),{x:r,y:o,width:n,height:a}}function Tr(s,[i,t]){return s.x<=i&&i<=s.x+s.width&&s.y<=t&&t<=s.y+s.height}var oi=class extends I{constructor(){super();c(this,"init$",{...this.init$,dragging:!1});this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(t){let e=this.$["*imageBox"];if(!e)return;if(t===""&&e.height<=tt&&e.width<=tt)return!0;let r=e.height<=tt&&(t.includes("n")||t.includes("s")),o=e.width<=tt&&(t.includes("e")||t.includes("w"));return r||o}_createBackdrop(){let t=this.$["*cropBox"];if(!t)return;let{x:e,y:r,width:o,height:n}=t,a=this.ref["svg-el"],l=et("mask",{id:"backdrop-mask"}),u=et("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=et("rect",{x:e,y:r,width:o,height:n,fill:"black"});l.appendChild(u),l.appendChild(h);let d=et("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});a.appendChild(d),a.appendChild(l),this._backdropMask=l,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask.style.display="block"}))}_updateBackdrop(){let t=this.$["*cropBox"];if(!t)return;let{x:e,y:r,width:o,height:n}=t;Nt(this._backdropMaskInner,{x:e,y:r,width:o,height:n})}_updateFrame(){let t=this.$["*cropBox"];if(!t)return;for(let r of Object.values(this._frameThumbs)){let{direction:o,pathNode:n,interactionNode:a,groupNode:l}=r,u=o==="",h=o.length===2;if(u){let{x:p,y:f,width:m,height:b}=t,x=[p+m/2,f+b/2];Nt(a,{r:Math.min(m,b)/3,cx:x[0],cy:x[1]})}else{let{d:p,center:f}=h?br(t,o):vr(t,o);Nt(a,{cx:f[0],cy:f[1]}),Nt(n,{d:p})}let d=this._shouldThumbBeDisabled(o);l.setAttribute("class",M("thumb",{"thumb--hidden":d,"thumb--visible":!d}))}let e=this._frameGuides;Nt(e,{x:t.x-1*.5,y:t.y-1*.5,width:t.width+1,height:t.height+1})}_createThumbs(){let t={};for(let e=0;e<3;e++)for(let r=0;r<3;r++){let o=`${["n","","s"][e]}${["w","","e"][r]}`,n=et("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let a=et("circle",{r:24+1.5,fill:"transparent"}),l=et("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(a),t[o]={direction:o,pathNode:l,interactionNode:a,groupNode:n},a.addEventListener("pointerdown",this._handlePointerDown.bind(this,o))}return t}_createGuides(){let t=et("svg"),e=et("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});t.appendChild(e);for(let r=1;r<=2;r++){let o=et("line",{x1:`${_e*r}%`,y1:"0%",x2:`${_e*r}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});t.appendChild(o)}for(let r=1;r<=2;r++){let o=et("line",{x1:"0%",y1:`${_e*r}%`,x2:"100%",y2:`${_e*r}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});t.appendChild(o)}return t.classList.add("guides","guides--semi-hidden"),t}_createFrame(){let t=this.ref["svg-el"],e=document.createDocumentFragment(),r=this._createGuides();e.appendChild(r);let o=this._createThumbs();for(let{groupNode:n}of Object.values(o))e.appendChild(n);t.appendChild(e),this._frameThumbs=o,this._frameGuides=r}_handlePointerDown(t,e){let r=this._frameThumbs[t];if(this._shouldThumbBeDisabled(t))return;let o=this.$["*cropBox"],{x:n,y:a}=this.ref["svg-el"].getBoundingClientRect(),l=e.x-n,u=e.y-a;this.$.dragging=!0,this._draggingThumb=r,this._dragStartPoint=[l,u],this._dragStartCrop={...o}}_handlePointerUp_(t){this._updateCursor(),this.$.dragging&&(t.stopPropagation(),t.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(t){if(!this.$.dragging)return;t.stopPropagation(),t.preventDefault();let e=this.ref["svg-el"],{x:r,y:o}=e.getBoundingClientRect(),n=t.x-r,a=t.y-o,l=n-this._dragStartPoint[0],u=a-this._dragStartPoint[1],{direction:h}=this._draggingThumb,d=this.$["*imageBox"],p=this._dragStartCrop;h===""?(p=Cr(p,[l,u]),p=si(p,d)):(p=xr(p,[l,u],h),p=wr(p,d));let f=[Math.min(d.width,tt),Math.min(d.height,tt)];if(p=ri(p,f,h),!Object.values(p).every(m=>Number.isFinite(m)&&m>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:p});return}this.$["*cropBox"]=p}_handleSvgPointerMove_(t){let e=Object.values(this._frameThumbs).find(r=>{if(this._shouldThumbBeDisabled(r.direction))return!1;let n=r.groupNode.getBoundingClientRect(),a={x:n.x,y:n.y,width:n.width,height:n.height};return Tr(a,[t.x,t.y])});this._hoverThumb=e,this._updateCursor()}_updateCursor(){let t=this._hoverThumb;this.ref["svg-el"].style.cursor=t?yr(t.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(t){Object.values(this._frameThumbs).map(({groupNode:e})=>e).forEach(e=>{e.setAttribute("class",M("thumb",{"thumb--hidden":!t,"thumb--visible":t}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",t=>{t&&(this._guidesHidden=t.height<=tt||t.width<=tt,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",t=>{this._frameGuides.setAttribute("class",M({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&t,"guides--semi-hidden":!this._guidesHidden&&!t}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};oi.template='';var yt=class extends I{constructor(){super(...arguments);c(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=M({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function En(s){let i=s+90;return i=i>=360?0:i,i}function An(s,i){return s==="rotate"?En(i):["mirror","flip"].includes(s)?!i:null}var Yt=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=An(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var be={FILTER:"filter",COLOR_OPERATION:"color_operation"},ut="original",ni=class extends I{constructor(){super(...arguments);c(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?be.FILTER:be.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ut?void 0:this.$.value,filter:this._filter===ut?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=lt[this._operation],[r,o]=t;this.$.min=r,this.$.max=o,this.$.zero=e;let n=this.$["*editorTransformations"][this._operation];if(this._controlType===be.FILTER){let a=o;if(n){let{name:l,amount:u}=n;a=l===this._filter?u:o}this.$.value=a,this.$.defaultValue=a}if(this._controlType===be.COLOR_OPERATION){let a=typeof n!="undefined"?n:e;this.$.value=a,this.$.defaultValue=a}}apply(){let t;this._controlType===be.FILTER?this._filter===ut?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ni.template=``;function ve(s){let i=new Image;return{promise:new Promise((r,o)=>{i.src=s,i.onload=r,i.onerror=o}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=K)}}}function ye(s){let i=[];for(let o of s){let n=ve(o);i.push(n)}let t=i.map(o=>o.image);return{promise:Promise.allSettled(i.map(o=>o.promise)),images:t,cancel:()=>{i.forEach(o=>{o.cancel()})}}}var Bt=class extends yt{constructor(){super(...arguments);c(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),o=e>=2?"lightest":"normal",n=100,a={...this.$["*editorTransformations"]};return a[this._operation]=this._filter!==ut?{name:this._filter,amount:n}:void 0,S(this._originalUrl,P(ei,St(a),`quality/${o}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let o=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"],{promise:a,cancel:l}=ve(o);this._cancelPreload=l,a.catch(u=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:u})}).finally(()=>{n.style.backgroundImage=`url(${o})`,n.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ut,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let o=this.ref["preview-el"];e?o.style.opacity="0":o.style.backgroundImage&&(o.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"];o.style.backgroundImage&&(o.style.backgroundImage="none",o.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Bt.template=`
`;var Zt=class extends yt{constructor(){super(...arguments);c(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=lt[this._operation],r=t[this._operation],o=typeof r!="undefined"?r!==e:!1;this.$.active=o})}};function Er(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Jt(s,i,t){let r=window.devicePixelRatio,o=Math.min(Math.ceil(i*r),3e3),n=r>=2?"lightest":"normal";return S(s,P(ei,St(t),`quality/${n}`,`stretch/off/-/resize/${o}x`))}function ai(s,i,t){return Math.min(Math.max(s,i),t)}function Ce({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function $n(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var li=class extends I{constructor(){super();c(this,"init$",{...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}});this._commitDebounced=at(this._commit.bind(this),300),this._handleResizeDebounced=at(this._handleResize.bind(this),10)}_handleResize(){this.isConnected&&(this.deactivate(),this.activate(this._imageSize,{fromViewer:!1}))}_syncTransformations(){let t=this.$["*editorTransformations"],e=Er(t,Object.keys(this.$["*operations"])),r={...this.$["*operations"],...e};this.$["*operations"]=r}_initCanvas(){let t=this.ref["canvas-el"],e=t.getContext("2d"),r=this.offsetWidth,o=this.offsetHeight,n=window.devicePixelRatio;t.style.width=`${r}px`,t.style.height=`${o}px`,t.width=r*n,t.height=o*n,e.scale(n,n),this._canvas=t,this._ctx=e}_alignImage(){if(!this._isActive||!this.$.image)return;let t=this.$.image,e=this.$["*padding"],r=this.$["*operations"],{rotate:o}=r,n={width:this.offsetWidth,height:this.offsetHeight},a=Ce({width:t.naturalWidth,height:t.naturalHeight},o);if(a.width>n.width-e*2||a.height>n.height-e*2){let l=a.width/a.height,u=n.width/n.height;if(l>u){let h=n.width-e*2,d=h/l,p=0+e,f=e+(n.height-e*2)/2-d/2;this.$["*imageBox"]={x:p,y:f,width:h,height:d}}else{let h=n.height-e*2,d=h*l,p=e+(n.width-e*2)/2-d/2,f=0+e;this.$["*imageBox"]={x:p,y:f,width:d,height:h}}}else{let{width:l,height:u}=a,h=e+(n.width-e*2)/2-l/2,d=e+(n.height-e*2)/2-u/2;this.$["*imageBox"]={x:h,y:d,width:l,height:u}}}_alignCrop(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,n=this.$["*editorTransformations"].crop;if(n){let{dimensions:[l,u],coords:[h,d]}=n,{width:p,x:f,y:m}=this.$["*imageBox"],{width:b}=Ce(this._imageSize,o),x=p/b;t={x:f+h*x,y:m+d*x,width:l*x,height:u*x}}else t={x:e.x,y:e.y,width:e.width,height:e.height};let a=[Math.min(e.width,tt),Math.min(e.height,tt)];t=ri(t,a,"se"),t=si(t,e),this.$["*cropBox"]=t}_drawImage(){let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:o,flip:n,rotate:a}=r,l=this._ctx,u=Ce({width:e.width,height:e.height},a);l.save(),l.translate(e.x+e.width/2,e.y+e.height/2),l.rotate(a*Math.PI*-1/180),l.scale(o?-1:1,n?-1:1),l.drawImage(t,-u.width/2,-u.height/2,u.width,u.height),l.restore()}_draw(){if(!this._isActive||!this.$.image)return;let t=this._canvas;this._ctx.clearRect(0,0,t.width,t.height),this._drawImage()}_animateIn({fromViewer:t}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=M({active_from_viewer:t,active_from_editor:!t,inactive_to_editor:!1})}))}_calculateDimensions(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a}=e,{width:l,height:u}=Ce(this._imageSize,o),{width:h,height:d}=t,p=n/l,f=a/u;return[ai(Math.round(h/p),1,l),ai(Math.round(d/f),1,u)]}_calculateCrop(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a,x:l,y:u}=e,{width:h,height:d}=Ce(this._imageSize,o),{x:p,y:f}=t,m=n/h,b=a/d,x=this._calculateDimensions(),A={dimensions:x,coords:[ai(Math.round((p-l)/m),0,h-x[0]),ai(Math.round((f-u)/b),0,d-x[1])]};if(!$n(A)){console.error("Cropper is trying to create invalid crop object",{payload:A});return}if(!(x[0]===h&&x[1]===d))return A}_commit(){if(!this.isConnected)return;let t=this.$["*operations"],{rotate:e,mirror:r,flip:o}=t,n=this._calculateCrop(),l={...this.$["*editorTransformations"],crop:n,rotate:e,mirror:r,flip:o};this.$["*editorTransformations"]=l}setValue(t,e){console.log(`Apply cropper operation [${t}=${e}]`),this.$["*operations"]={...this.$["*operations"],[t]:e},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(t){return this.$["*operations"][t]}async activate(t,{fromViewer:e}){if(!this._isActive){this._isActive=!0,this._imageSize=t,this.removeEventListener("transitionend",this._reset),this._initCanvas();try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw(),this._animateIn({fromViewer:e})}catch(r){console.error("Failed to activate cropper",{error:r})}}}deactivate(){this._isActive&&(this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=M({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}))}_transitionToCrop(){let t=this._calculateDimensions(),e=Math.min(this.offsetWidth,t[0])/this.$["*cropBox"].width,r=Math.min(this.offsetHeight,t[1])/this.$["*cropBox"].height,o=Math.min(e,r),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,a=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${o}) translate(${(this.offsetWidth/2-n)/o}px, ${(this.offsetHeight/2-a)/o}px)`,this.style.transformOrigin=`${n}px ${a}px`}_transitionToImage(){let t=this.$["*cropBox"].x+this.$["*cropBox"].width/2,e=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${t}px ${e}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(t,e){let r=this.offsetWidth;e={...e,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let o=this.proxyUrl(Jt(t,r,e)),{promise:n,cancel:a,image:l}=ve(o),u=this._handleImageLoading(o);return l.addEventListener("load",u,{once:!0}),l.addEventListener("error",u,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=a,n.then(()=>l).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(t){let e="crop",r=this.$["*loadingOperations"];return r.get(e)||r.set(e,new Map),r.get(e).get(t)||(r.set(e,r.get(e).set(t,!0)),this.$["*loadingOperations"]=r),()=>{var o;(o=r==null?void 0:r.get(e))!=null&&o.has(t)&&(r.get(e).delete(t),this.$["*loadingOperations"]=r)}}initCallback(){super.initCallback(),this._observer=new ResizeObserver(([t])=>{t.contentRect.width>0&&t.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeDebounced()}),this._observer.observe(this),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",t=>{this.$.image&&this._commitDebounced()}),setTimeout(()=>{this.sub("*networkProblems",t=>{t||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect()}};li.template=``;function ss(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function kn(s){return s.reduce((i,t,e)=>er<=i&&i<=o);return s.map(r=>{let o=Math.abs(e[0]-e[1]),n=Math.abs(i-e[0])/o;return e[0]===r?i>t?1:1-n:e[1]===r?i>=t?n:1:0})}function On(s,i){return s.map((t,e)=>to-n)}var rs=class extends I{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=at(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let o={...this._transformations};e&&(o[e]=t?{name:t,amount:r}:r);let n=this.offsetWidth;return this.proxyUrl(Jt(i,n,o))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(l=>l.value===e);if(r())return;let o=this._constructKeypoint(i,e),n=new Image;n.src=o.src;let a=this._handleImageLoading(o.src);n.addEventListener("load",a,{once:!0}),n.addEventListener("error",a,{once:!0}),o.image=n,n.classList.add("fader-image"),n.addEventListener("load",()=>{if(r())return;let l=this._keypoints,u=l.findIndex(d=>d.value>e),h=u{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=lt[i],r=this._keypoints.map(a=>a.value),o=In(r,t,e),n=On(r,e);for(let[a,l]of Object.entries(this._keypoints))l.opacity=o[a],l.zIndex=n[a];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(u=>u.src),{images:r,promise:o,cancel:n}=ye(e);r.forEach(u=>{let h=this._handleImageLoading(u.src);u.addEventListener("load",h),u.addEventListener("error",h)}),this._cancelLastImages=()=>{n(),this._cancelLastImages=void 0};let a=this._operation,l=this._filter;await o,this._isActive&&this._isSame(a,l)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((u,h)=>{let d=r[h];d.classList.add("fader-image"),u.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let n=Ar(e,r).map(l=>this._imageSrc({url:i,filter:t,operation:e,value:l})),{cancel:a}=ye(n);this._cancelBatchPreload=a}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=M({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=M({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:o}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=o,typeof e!="number"&&!r){let a=this._imageSrc({operation:t,value:e});this._setOriginalSrc(a),this._container&&this._container.remove();return}this._keypoints=Ar(t,e).map(a=>this._constructKeypoint(t,a)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=M({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Rn=1,ci=class extends I{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Rn?this.scrollLeft+=e:this.scrollLeft+=t})}};ci.template=" ";function Ln(s){return``}function Un(s){return`
`}var ui=class extends I{constructor(){super();c(this,"_updateInfoTooltip",at(()=>{var o,n;let t=this.$["*editorTransformations"],e="",r=!1;if(this.$["*tabId"]===j.FILTERS)if(r=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((n=t==null?void 0:t.filter)==null?void 0:n.amount)||100;e=this.l10n(this.$["*currentFilter"])+" "+a}else e=this.l10n(ut);else if(this.$["*tabId"]===j.SLIDERS&&this.$["*currentOperation"]){r=!0;let a=(t==null?void 0:t[this.$["*currentOperation"]])||lt[this.$["*currentOperation"]].zero;e=this.$["*currentOperation"]+" "+a}r&&(this.$["*operationTooltip"]=e),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",r)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ut,"*currentOperation":null,"*tabId":j.CROP,showLoader:!1,filters:gr,colorOperations:fr,cropOperations:_r,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":t=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":t=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":t=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":t=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=at(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===j.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=Zt.is&&new Zt;return e.operation=t,e}_createFilterControl(t){let e=Bt.is&&new Bt;return e.filter=t,e}_createToggleControl(t){let e=Yt.is&&new Yt;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===j.CROP?this.$.cropOperations.forEach(o=>{let n=this._createToggleControl(o);r.appendChild(n)}):t===j.FILTERS?[ut,...this.$.filters].forEach(o=>{let n=this._createFilterControl(o);r.appendChild(n)}):t===j.SLIDERS&&this.$.colorOperations.forEach(o=>{let n=this._createOperationControl(o);r.appendChild(n)}),r.childNodes.forEach((o,n)=>{n===r.childNodes.length-1&&o.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===j.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of ii){let o=r===t,n=this.ref[`tab-toggle-${r}`];n.active=o,o?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=o}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Jt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=ye([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",t=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,o]of r.entries())if(o){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this._updateInfoTooltip()}};ui.template=`
{{*operationTooltip}}
${ii.map(Un).join("")}
${ii.map(Ln).join("")}
`;var xe=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return M("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};xe.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});xe.template=`
{{text}}
`;var hi=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};hi.template=`
`;var di={transition:"transition",visible:"visible",hidden:"hidden"},pi=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=di.visible,this._hiddenStyle=di.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",cr(this,{[di.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(di.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};pi.template=" ";var mi=class extends _{constructor(){super();c(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${n}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${n}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),o=Math.ceil(r/2),n=Math.ceil(o/15)-2;if(this._stepsCount===n)return;let a=document.createDocumentFragment(),l=document.createElement("div"),u=document.createElement("div");l.className="minor-step",u.className="border-step",a.appendChild(u);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.CLOUD_IMG_EDIT);c(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new ct,e=this.$.cdnUrl;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),t.addEventListener("apply",r=>this.handleApply(r)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var Pn=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Sr=function(s,i="i"){let t=s.split("*").map(Pn);return new RegExp("^"+t.join(".+")+"$",i)};var Mn=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],o=Object.keys(r).reduce((n,a)=>{let l=r[a];return n+`${a}: ${l};`},"");return t+`${e}{${o}}`},"");function $r({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let o=`solid 1px ${r}`;return Mn({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":o},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":o},".list-table-body .list-items":{"border-bottom":o},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var $t={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in $t){let t=$t[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var kr=function(s,i,t){s in $t||($t[s]=[]),$t[s].push([i,t])},Ir=function(s,i){s in $t&&($t[s]=$t[s].filter(t=>t[0]!==i))};function Or(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var fi=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.EXTERNAL);c(this,"init$",{...this.init$,activityIcon:"",activityCaption:"",counter:0,onDone:()=>{this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}});c(this,"_iframe",null);c(this,"_inheritedUpdateCssData",this.updateCssData);c(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.$.counter=0,this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()})}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){console.log(t),this.$.counter=this.$.counter+1;let e=(()=>{if(t.alternatives){let n=U(this.cfg.externalSourcesPreferredTypes);for(let a of n){let l=Sr(a);for(let[u,h]of Object.entries(t.alternatives))if(l.test(u))return h}}return t.url})(),{filename:r}=t,{externalSourceType:o}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:o})}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:$r(t)})}remoteUrl(){var a,l;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,o={lang:((l=(a=this.getCssData("--l10n-locale-name"))==null?void 0:a.split("-"))==null?void 0:l[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},n=new URL(this.cfg.socialBaseUrl);return n.pathname=`/window3/${r}`,n.search=Or(o),n.toString()}mountIframe(){let t=se({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),kr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t}unmountIframe(){this._iframe&&Ir("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null}};fi.template=`
{{activityCaption}}
{{counter}}
`;var we=class extends _{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;U(i).forEach(e=>{let r=se({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};we.bindAttributes({"tab-list":null,default:null});we.template=`
`;var Qt=class extends v{constructor(){super(...arguments);c(this,"processInnerHtml",!0);c(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Qt.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let o=document.createElement("input");o.type="hidden",o.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,o.value=r,this._dynamicInputsContainer.appendChild(o)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(n=>n.uuid),r=await this.getUploadClientOptions(),o=await Rs(e,{...r});this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};Qt.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ns=class extends g{};var gi=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(o=>{e+=``}),this.$.selectHtml=e})}};gi.template=``;var q={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Rr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},st=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,src:"",ppIcon:q.PLAY,fsIcon:q.FS_ON,volIcon:q.VOL_ON,capIcon:q.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Rr.exitFullscreen():Rr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===q.CAP_OFF?(this.$.capIcon=q.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(st.is+":captions","1")):(this.$.capIcon=q.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(st.is+":captions"))}toggleSound(){this.$.volIcon===q.VOL_ON?(this.$.volIcon=q.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=q.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(st.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let o=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${o}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(st.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=q.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=q.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=q.FS_OFF:this.$.fsIcon=q.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let o="";r==null||r.sources.forEach(n=>{o+=``}),r.tracks&&(r.tracks.forEach(n=>{o+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=o,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(st.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};st.template=`
{{currentTime}} / {{totalTime}}
`;st.bindAttributes({video:"video",src:"src"});var Nn="css-src";function _i(s){return class extends s{constructor(){super(...arguments);c(this,"renderShadow",!0);c(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Nn);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Te=class extends _i(_){};var bi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};c(bi,"template",`Powered by Uploadcare`);var kt=class extends Te{constructor(){super(...arguments);c(this,"init$",Me(this));c(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var vi=class extends kt{};vi.template=``;var yi=class extends kt{constructor(){super(...arguments);c(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.sub(L("sourceList"),e=>{e!=="local"&&(this.$[L("sourceList")]="local")}),this.sub(L("confirmUpload"),e=>{e!==!1&&(this.$[L("confirmUpload")]=!1)})}};yi.template=``;var Ci=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};Ci.template=``;var as=class extends _i(ct){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function ls(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var cs="LR";async function Dn(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[cs]){t(window[cs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let o=window[cs];i&&ls(o),t(o)},document.head.appendChild(r)})}export{g as ActivityBlock,ns as ActivityHeader,zt as BaseComponent,_ as Block,Ye as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,ct as CloudImageEditorBlock,ze as Config,Je as ConfirmationDialog,bi as Copyright,oi as CropFrame,E as Data,Qt as DataOutput,pe as DropArea,Yt as EditorCropButtonControl,Bt as EditorFilterControl,li as EditorImageCropper,rs as EditorImageFader,Zt as EditorOperationControl,ci as EditorScroller,ni as EditorSlider,ui as EditorToolbar,fi as ExternalSource,bt as FileItem,ge as FilePreview,Ci as FileUploaderInline,yi as FileUploaderMinimal,vi as FileUploaderRegular,he as Icon,qi as Img,hi as LineLoaderUi,xe as LrBtnUi,qe as MessageBox,F as Modal,Ds as PACKAGE_NAME,Bs as PACKAGE_VERSION,pi as PresenceToggle,ti as ProgressBar,Qe as ProgressBarCommon,gi as Select,Te as ShadowWrapper,We as SimpleBtn,mi as SliderUi,me as SourceBtn,Zi as SourceList,Gi as StartFrom,we as Tabs,Qi as UploadCtxProvider,Ze as UploadDetails,Ge as UploadList,v as UploaderBlock,Ke as UrlSource,st as Video,Dn as connectBlocksFrom,ls as registerBlocks,_i as shadowed,_t as toKebabCase}; \ No newline at end of file +var Dr=Object.defineProperty;var Fr=(s,i,t)=>i in s?Dr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(Fr(s,typeof i!="symbol"?i+"":i,t),t),Ei=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var F=(s,i,t)=>(Ei(s,i,"read from private field"),t?t.call(s):i.get(s)),Ot=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},re=(s,i,t,e)=>(Ei(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var Se=(s,i,t)=>(Ei(s,i,"access private method"),t);var Vr=Object.defineProperty,Br=(s,i,t)=>i in s?Vr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,$i=(s,i,t)=>(Br(s,typeof i!="symbol"?i+"":i,t),t);function zr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=zr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var C=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),ps="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",jr=ps.length-1,oe=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Wr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function Xr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||us;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=us;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function qr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function Gr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Hr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):fs(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var ke="{{",ne="}}",Kr="skip-text";function Yr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(Kr))&&r.textContent.includes(ke)&&r.textContent.includes(ne)&&1}});for(;i=e.nextNode();)t.push(i);return t}var Zr=function(s,i){Yr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(ne);)e.textContent.startsWith(ke)?(n=e.textContent.indexOf(ne)+ne.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(ke),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(ke,"").replace(ne,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Jr=[Wr,Xr,qr,Gr,Zr],Ie="'",Bt='"',Qr=/\\([0-9a-fA-F]{1,6} ?)/g;function tn(s){return(s[0]===Bt||s[0]===Ie)&&(s[s.length-1]===Bt||s[s.length-1]===Ie)}function en(s){return(s[0]===Bt||s[0]===Ie)&&(s=s.slice(1)),(s[s.length-1]===Bt||s[s.length-1]===Ie)&&(s=s.slice(0,-1)),s}function sn(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ +`,"\\n"),i=sn(i),i=Bt+i+Bt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Vt=null,pt=null,vt=class extends HTMLElement{constructor(){super(),$i(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return vt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=oe.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=vt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=vt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=vt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=vt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=vt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=vt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])fs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Jr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);pt==null||pt.delete(this.updateCssData),pt!=null&&pt.size||(Vt==null||Vt.disconnect(),Vt=null,pt=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${C.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=rn(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){pt||(pt=new Set),pt.add(this.updateCssData),Vt||(Vt=new MutationObserver(s=>{s[0].type==="attributes"&&pt.forEach(i=>{i()})}),Vt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=vt;$i(zt,"template");var Ai=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Ai.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Ai.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Ai.appMap=Object.create(null);function nn(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function on(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function le(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&on(i,s.attributes),s.styles&&nn(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=le(t);i.appendChild(e)}),i}var ms="idb-store-ready",ln="symbiote-db",an="symbiote-idb-update_",cn=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return an+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=ln,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new cn(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};$i(gs,"_reg",Object.create(null));function S(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var hn="--uploadcare-blocks-window-height",Oe="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Si(){return typeof window[Oe]=="undefined"?!1:!!window[Oe]}function _s(){if(Si())return;let s=()=>{document.documentElement.style.setProperty(hn,`${window.innerHeight}px`),window[Oe]=!0},i=S(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[Oe]=!1,window.removeEventListener("resize",i)}}var un=s=>s,ki="{{",ys="}}",bs="plural:";function ae(s,i,t={}){var o;let{openToken:e=ki,closeToken:r=ys,transform:n=un}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(ki);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(ki,e)}return i}function Cs(s){return Object.prototype.toString.call(s)==="[object Object]"}var dn=/\W|_/g;function pn(s){return s.split(dn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ws(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>mt(t,{ignoreKeys:i})):s}function mt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ws(s,{ignoreKeys:i});if(!Cs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Cs(r)?r=mt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ws(r,{ignoreKeys:i})),t[pn(e)]=r}return t}var fn=s=>new Promise(i=>setTimeout(i,s));function Mi({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var mn={factor:2,time:100};function gn(s,i=mn){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>fn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var qt=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,qt.prototype),this.originalProgressEvent=t}},Re=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Ct=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,Ct.prototype)}},_n=500,Ts=({check:s,interval:i=_n,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Re(e,()=>{o&&clearTimeout(o),n(new Ct("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ct("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),T={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Pe="application/octet-stream",Es="original",xt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Re(r,()=>{u=!0,a.abort(),l(new Ct)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let A=$.split(": "),x=A.shift(),w=A.join(": ");x&&typeof x!="undefined"&&(m[x]=w)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new qt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function bn(s,...i){return s}var yn=({name:s})=>s?[s]:[],vn=bn,Cn=()=>new FormData,As=s=>!1,Me=s=>typeof Blob!="undefined"&&s instanceof Blob,Ne=s=>typeof File!="undefined"&&s instanceof File,De=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",ce=s=>Me(s)||Ne(s)||As()||De(s),wn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",xn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),Tn=s=>!!s&&typeof s=="object"&&"data"in s&&ce(s.data);function En(s,i,t){if(Tn(t)){let{name:e,contentType:r}=t,n=vn(t.data,e,r!=null?r:Pe),o=yn({name:e,contentType:r});s.push([i,n,...o])}else if(xn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else wn(t)&&t&&s.push([i,t.toString()])}function An(s){let i=[];for(let[t,e]of Object.entries(s))En(i,t,e);return i}function Ni(s){let i=Cn(),t=An(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var P=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}},$n=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=$n(t)),e.toString()},Sn="6.6.1",kn="UploadcareUploadClient",In=Sn;function Rt(s){return Mi({libraryName:kn,libraryVersion:In,...s})}var On="RequestThrottledError",xs=15e3,Ln=1e3;function Un(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return xs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:xs}function Tt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return gn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===On&&r{let i="";return(Me(s)||Ne(s)||De(s))&&(i=s.type),i||Pe},Ss=s=>{let i="";return Ne(s)&&s.name?i=s.name:Me(s)||As()?i="":De(s)&&s.name&&(i=s.name),i||Es};function Di(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Rn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=T.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:_}){return Tt(()=>xt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Ni({file:{data:s,name:t||Ss(s),contentType:e||$s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Di(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:$,headers:A,request:x})=>{let w=mt(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,x,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Li;(function(s){s.Token="token",s.FileInfo="file_info"})(Li||(Li={}));function Pn(s,{publicKey:i,baseURL:t=T.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:_}){return Tt(()=>xt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Di(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:$,headers:A,request:x})=>{let w=mt(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,x,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var q;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(q||(q={}));var Mn=s=>"status"in s&&s.status===q.Error;function Nn(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}={}){return Tt(()=>xt({method:"GET",headers:i?{"X-UC-User-Agent":Rt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=mt(JSON.parse(a));if("error"in d&&!Mn(d))throw new P(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Dn(s,{publicKey:i,baseURL:t=T.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:a,userAgent:c})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=mt(JSON.parse(p));if("error"in _)throw new P(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"GET",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Fn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=T.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:_}){return Tt(()=>xt({method:"POST",url:ft(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Ni({filename:e||Es,size:s,content_type:t||Pe,part_size:r,UPLOADCARE_STORE:Di(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:$,headers:A,request:x})=>{let w=mt(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,x,w,A);return w.parts=Object.keys(w.parts).map(W=>w.parts[W]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Vn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Pe}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Bn(s,{publicKey:i,baseURL:t=T.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},data:Ni({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Fi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return Ts({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}var wt=class{constructor(i,{baseCDN:t=T.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=ft(t,`${r}/`),l=n?ft(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},zn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:$})=>Rn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:A})=>Fi({file:A,publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new wt(A,{baseCDN:_})),jn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Hn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Re(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Wn=window.WebSocket,Ui=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Xn=(s,i)=>s==="success"?{status:q.Success,...i}:s==="progress"?{status:q.Progress,...i}:{status:q.Error,...i},Ri=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ui);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Wn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,Xn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Ii=null,Vi=s=>{if(!Ii){let i=typeof window=="undefined"?0:3e4;Ii=new Ri(s,i)}return Ii},qn=s=>{Vi(s).connect()};function Gn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return Ts({check:c=>Nn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case q.Error:return new P(u.error,u.errorCode);case q.Waiting:return!1;case q.Unknown:return new P(`Token "${s}" was not found.`);case q.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case q.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Kn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Vi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Re(t,()=>{a(),n(new Ct("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case q.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case q.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case q.Error:a(),n(new P(c.msg,c.error_code))}})}),Yn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:$=T.pusherKey,metadata:A})=>Promise.resolve(qn($)).then(()=>Pn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(x=>{let w=Vi($);return w==null||w.disconnect(),Promise.reject(x)}).then(x=>x.type===Li.FileInfo?x:Hn([({signal:w})=>Gn({token:x.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:w}),({signal:w})=>Kn({token:x.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(x=>{if(x instanceof P)throw x;return x}).then(x=>Fi({file:x.uuid,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(x=>new wt(x,{baseCDN:r})),Oi=new WeakMap,Zn=async s=>{if(Oi.has(s))return Oi.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Oi.set(s,i),i},Is=async s=>{if(Ne(s)||Me(s))return s.size;if(De(s))return(await Zn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Jn=(s,i=T.multipartMinFileSize)=>s>=i,Os=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!ce(s)&&t.test(s)},Ls=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!ce(s)&&t.test(s)},Qn=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},eo=async(s,i,t)=>e=>to(s,e,i,t),io=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Vn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),so=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:$=T.multipartChunkSize,maxConcurrentRequests:A=T.maxConcurrentRequests,baseCDN:x,metadata:w})=>{let W=e!=null?e:await Is(s),ht,It=(R,J)=>{if(!c)return;ht||(ht=Array(R).fill(0));let ut=X=>X.reduce((dt,Ti)=>dt+Ti,0);return X=>{X.isComputable&&(ht[J]=X.value,c({isComputable:!0,value:ut(ht)/R}))}};return _||(_=$s(s)),Fn(W,{publicKey:i,contentType:_,fileName:t||Ss(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:R,parts:J})=>{let ut=await eo(s,W,$);return Promise.all([R,Qn(A,J.map((X,dt)=>()=>io(ut(dt),X,{publicKey:i,contentType:_,onProgress:It(J.length,dt),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([R])=>Bn(R,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(R=>R.isReady?R:Fi({file:R.uuid,publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(R=>new wt(R,{baseCDN:x}))};async function Bi(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:$,maxConcurrentRequests:A,baseCDN:x=T.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:W,pusherKey:ht,metadata:It}){if(ce(s)){let R=await Is(s);return Jn(R,_)?so(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:R,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x,metadata:It}):zn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x,metadata:It})}if(Ls(s))return Yn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:x,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:W,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:ht,metadata:It});if(Os(s))return jn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x});throw new TypeError(`File uploading from "${s}" is not supported`)}var Pi=class{constructor(i,t){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},ro=s=>{for(let i of s)if(!ce(i))return!1;return!0},no=s=>{for(let i of s)if(!Os(i))return!1;return!0},oo=s=>{for(let i of s)if(!Ls(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=T.multipartChunkSize,baseCDN:$=T.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x,jsonpCallback:w}){if(!ro(s)&&!oo(s)&&!no(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let W,ht=!0,It=s.length,R=(J,ut)=>{if(!a)return;W||(W=Array(J).fill(0));let X=dt=>dt.reduce((Ti,Nr)=>Ti+Nr)/J;return dt=>{if(!dt.isComputable||!ht){ht=!1,a({isComputable:!1});return}W[ut]=dt.value,a({isComputable:!0,value:X(W)})}};return Promise.all(s.map((J,ut)=>Bi(J,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:R(It,ut),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:$,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x}))).then(J=>{let ut=J.map(X=>X.uuid);return Dn(ut,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(X=>new Pi(X,J)).then(X=>(a&&a({isComputable:!0,value:1}),X))})}var Lt,jt,Ut,Ht,Wt,Xt,Le,Ue=class{constructor(i){Ot(this,Xt);Ot(this,Lt,1);Ot(this,jt,[]);Ot(this,Ut,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);re(this,Lt,i)}add(i){return new Promise((t,e)=>{F(this,Ht).set(i,t),F(this,Wt).set(i,e),F(this,jt).push(i),Se(this,Xt,Le).call(this)})}get pending(){return F(this,jt).length}get running(){return F(this,Ut)}set concurrency(i){re(this,Lt,i),Se(this,Xt,Le).call(this)}get concurrency(){return F(this,Lt)}};Lt=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,Le=function(){let i=F(this,Lt)-F(this,Ut);for(let t=0;t{F(this,Ht).delete(e),F(this,Wt).delete(e),re(this,Ut,F(this,Ut)-1),Se(this,Xt,Le).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var zi=()=>({"*blocksRegistry":new Set}),ji=s=>({...zi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Fe=s=>({...ji(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Ue(1)});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var Q=s=>`*cfg/${s}`;var gt=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ps=new Set;function Ve(s){Ps.has(s)||(Ps.add(s),console.warn(s))}var Be=(s,i)=>new Intl.PluralRules(s).select(i);var Hi="lr-",b=class extends zt{constructor(){super();h(this,"allowCustomTemplate",!0);h(this,"init$",zi());h(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return ae(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Be(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setForCtxTarget(t,e,r){this.hasBlockInCtx(n=>n.constructor.StateConsumerScope===t)&&(this.$[e]=r)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Hi}${t}`,!0),Si()||(this._destroyInnerHeightTracker=_s()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?ae(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=Q(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Ve("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${gt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(Q(t));r.ctx.has(r.name)?this.sub(Q(t),e):(this.bindCssData(`--cfg-${gt(t)}`),this.sub(`--cfg-${gt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Hi)?t:Hi+t)}};h(b,"StateConsumerScope",null),h(b,"className","");var Wi=class extends b{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setForCtxTarget(Wi.StateConsumerScope,"*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}},B=Wi;h(B,"StateConsumerScope","modal");B.template=``;var Ms="active",he="___ACTIVITY_IS_ACTIVE___",st=class extends b{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",ji(this));h(this,"_debouncedHistoryFlush",S(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=st._activityRegistry[this.activityKey];this[he]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=st._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[he]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[he]?this._deactivate():this.activityType===t&&!this[he]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!st._activityRegistry[this.activityKey]}get isActivityActive(){return this[he]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;st._activityRegistry||(st._activityRegistry=Object.create(null)),st._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),st._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(st._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!1)}}},g=st;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ue=33.333333333333336,y=1,Xi=24,Ns=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function tt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Vs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Bs({rect:s,delta:[i,t],imageBox:e}){return Kt({...s,x:s.x+i,y:s.y+t},e)}function Kt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function lo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Yt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Zt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Et(s,i,t){return Math.min(Math.max(s,i),t)}var je=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var et=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs="blocks",qs="0.25.6";function Gs(s){return Mi({...s,libraryName:Xs,libraryVersion:qs})}var Ks=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},He=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ks(i)).join("/-/"),I=(...s)=>{let i=He(...s);return i?`-/${i}/`:""};function Ys(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Js(s){let i=Qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ks(n))}function Qs(s){let i=new URL(s),t=Ys(s),e=tr(t)?er(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function tr(s){return s.startsWith("http")}function er(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var k=(s,i,t)=>{let e=new URL(Qs(s));if(t=t||Ys(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),tr(t)){let r=er(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var M=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var de=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],qi=s=>s?s.filter(i=>typeof i=="string").map(i=>M(i)).flat():[],Gi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ir=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),pe=s=>{let i=s==null?void 0:s.type;return i?Gi(i,de):!1};var nt=1e3,Mt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),fe=s=>Math.ceil(s*100)/100,sr=(s,i=Mt.AUTO)=>{let t=i===Mt.AUTO;if(i===Mt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};h(O,"_timeoutStore",Object.create(null));var rr="[Typed State] Wrong property name: ",go="[Typed State] Wrong property type: ",We=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||oe.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(go+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Xe=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||oe.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new We(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var nr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var v=class extends g{constructor(){super(...arguments);h(this,"couldBeUploadCollectionOwner",!1);h(this,"isUploadCollectionOwner",!1);h(this,"init$",Fe(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",S(this._runValidators.bind(this),100));h(this,"_handleCollectionUpdate",t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,O.emit(new V({type:L.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&O.emit(new V({type:L.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{O.emit(new V({type:L.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{O.emit(new V({type:L.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{O.emit(new V({type:L.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){Ve("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Xe({typedSchema:nr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromObject(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:pe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:pe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=qi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?de:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=de.join(",")):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:et.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=M(this.cfg.sourceList)),t}initFlow(t=!1){var e,r;if((e=this.$["*uploadList"])!=null&&e.length&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let n=this.sourceList[0];n==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(n)?this.set$({"*currentActivityParams":{externalSourceType:n},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=n,this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0);O.emit(new V({type:L.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!1),O.emit(new V({type:L.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=qi([...e?de:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Gi(o,n),c=ir(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:sr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=je(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=I(`crop/${u.width}x${u.height}/${u.x},${u.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:k(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Gs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};e.push(a)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(L).forEach(s=>{let i=O.eName(s),t=S(e=>{if([L.UPLOAD_FINISH,L.REMOVE,L.CDN_MODIFICATION].includes(e.detail.type)){let n=E.getCtx(e.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let c=E.getCtx(a).store,u=c.fileInfo;if(u){let d={...u,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||u.cdnUrl};l.push(d)}}),O.emit(new V({type:L.DATA_OUTPUT,ctx:e.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var _o="https://ucarecdn.com",bo="https://upload.uploadcare.com",yo="https://social.uploadcare.com",me=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:_o,baseUrl:bo,socialBaseUrl:yo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var K=s=>String(s),ot=s=>Number(s),z=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,vo=s=>s==="auto"?s:z(s),Co={pubkey:K,multiple:z,multipleMin:ot,multipleMax:ot,confirmUpload:z,imgOnly:z,accept:K,externalSourcesPreferredTypes:K,store:vo,cameraMirror:z,sourceList:K,maxLocalFileSizeBytes:ot,thumbSize:ot,showEmptyList:z,useLocalImageEditor:z,useCloudImageEditor:z,removeCopyright:z,cropPreset:K,modalScrollLock:z,modalBackdropStrokes:z,sourceListWrap:z,remoteTabSessionKey:K,cdnCname:K,baseUrl:K,socialBaseUrl:K,secureSignature:K,secureExpire:K,secureDeliveryProxy:K,retryThrottledRequestMaxTimes:ot,multipartMinFileSize:ot,multipartChunkSize:ot,maxConcurrentRequests:ot,multipartMaxConcurrentRequests:ot,multipartMaxAttempts:ot,checkForUrlDuplicates:z,saveUrlForRecurrentUploads:z,groupOutput:z,userAgentIntegration:K},or=(s,i)=>{if(!(typeof i=="undefined"||i===null))return Co[s](i)};var qe=Object.keys(me),wo=["metadata"],xo=s=>wo.includes(s),Ki=qe.filter(s=>!xo(s)),To={...Object.fromEntries(Ki.map(s=>[gt(s),s])),...Object.fromEntries(Ki.map(s=>[s.toLowerCase(),s]))},Eo={...Object.fromEntries(qe.map(s=>[gt(s),Q(s)])),...Object.fromEntries(qe.map(s=>[s.toLowerCase(),Q(s)]))},Ge=class extends b{constructor(){super();h(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(me).map(([t,e])=>[Q(t),e]))}}initCallback(){super.initCallback();for(let t of qe){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,Ki.includes(t)){let o=[...new Set([gt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[Q(t)]!==n&&(typeof n=="undefined"||n===null?this.$[Q(t)]=me[t]:this.$[Q(t)]=n)},get:()=>this.$[Q(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=To[t],o=or(n,r),l=o!=null?o:me[n],a=this;a[n]=l}};Ge.bindAttributes(Eo);var ge=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ge.template=``;ge.bindAttributes({name:"name",size:"size"});var Ao="https://ucarecdn.com",Nt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Ao},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var lr=s=>[...new Set(s)];var _e="--lr-img-",ar="unresolved",Jt=2,Qt=3,cr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ur=Object.create(null),hr;for(let s in Nt)ur[_e+s]=((hr=Nt[s])==null?void 0:hr.default)||"";var Ke=class extends zt{constructor(){super(...arguments);h(this,"cssInit$",ur)}$$(t){return this.$[_e+t]}set$$(t){for(let e in t)this.$[_e+e]=t[e]}sub$$(t,e){this.sub(_e+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!cr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return I(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Nt.format.default}`,`quality/${this.$$("quality")||Nt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(cr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return k(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(k(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(k(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(k(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(k(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?ae(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(ar,""),this.img.onload=()=>{this.img.removeAttribute(ar)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Nt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?lr(M(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Jt+"x")}") ${n*Jt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Qt+"x")}") ${n*Qt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Jt))}") ${Jt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Qt))}") ${Qt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Jt+"x")+` ${e*Jt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Qt+"x")+` ${e*Qt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null)}static get observedAttributes(){return Object.keys(Nt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[_e+t]=r})}};var Yi=class extends Ke{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var Ye=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};Ye.template=``;var Zi=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function $o(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function So(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push(c),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function dr(s){let i=[],t=[];for(let e=0;e{i.push(...a)}));continue}let o=r.getAsFile();t.push($o(o).then(l=>{l||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}var j={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},pr=["focus"],ko=100,Ji=new Map;function Io(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Qi(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=j.INACTIVE,o=f=>{s.shouldIgnore()&&f!==j.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(j.INACTIVE)},c=()=>{i+=1,n===j.INACTIVE&&o(j.ACTIVE)},u=()=>{i-=1,l()||o(j.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(j.INACTIVE)},p=f=>{l()||(i+=1),f.preventDefault();let _=[f.x,f.y],$=s.element.getBoundingClientRect(),A=Math.floor(Io(_,$)),x=A{if(s.shouldIgnore())return;f.preventDefault();let _=await dr(f.dataTransfer);s.onItems(_),o(j.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),pr.forEach(f=>{window.addEventListener(f,a)}),()=>{Ji.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),pr.forEach(f=>{window.removeEventListener(f,a)})}}var be=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,state:j.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return e&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!e})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:typeof e=="string"})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:typeof e=="string"})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:typeof e=="string"})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Qi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:et.DROP_AREA});return}this.addFileFromObject(r,{source:et.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Qi({element:t,onChange:e=>{var n;let r=(n=Object.entries(j).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var n;let r=(n=Object.entries(j).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=M(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,n;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};be.template=`
{{text}}
`;be.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Oo="src-type-",ye=class extends v{constructor(){super(...arguments);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${Oo}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ye.template=`
`;ye.bindAttributes({type:null});var ts=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=M(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function fr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function mr(s="#fff",i="rgba(0, 0, 0, .1)"){return fr(``)}function ve(s="hsl(209, 21%, 65%)",i=32,t=32){return fr(``)}function gr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var H=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),_t=class extends v{constructor(){super();h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",S(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",S(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:H.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);O.emit(new V({type:L.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=H.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=H.FAILED:t.getValue("validationMultipleLimitMsg")?e=H.LIMIT_OVERFLOW:t.getValue("isUploading")?e=H.UPLOADING:t.getValue("fileInfo")&&(e=H.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(k(At(this.cfg.cdnCname,this._entry.getValue("uuid")),I(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await gr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ve(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ve(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{_t.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),_t.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===H.FAILED,isLimitOverflow:t===H.LIMIT_OVERFLOW,isUploading:t===H.UPLOADING,isFinished:t===H.FINISHED,progressVisible:t===H.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===H.FAILED||t===H.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===H.FINISHED&&(this.$.badgeIcon="badge-success"),t===H.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),_t.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));O.emit(new V({type:L.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=await this.getUploadClientOptions();return Bi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof P?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};_t.template=`
{{itemName}}{{errorText}}
`;_t.activeInstances=new Set;var Ze=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},Je=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Je.template=`
{{captionTxt}}
{{msgTxt}}
`;var Qe=class extends v{constructor(){super();h(this,"couldBeUploadCollectionOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",S(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));O.emit(new V({type:L.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new Ze,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};Qe.template=`{{headerText}}
`;var ti=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:et.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};ti.template=`
`;var es=()=>typeof navigator.permissions!="undefined";var ei=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:es(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{es()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",S(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:et.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ei.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var is=class extends v{};var ii=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ve(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=pe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=k(n,I("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ii.template=`
{{fileSize}}
{{errorTxt}}
`;var ss=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},si=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ss);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};si.template=`{{activityCaption}}
{{messageTxt}}
`;var ri=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};ri.template=``;var ni=class extends b{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ni.template='
';var Y="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var Ce=class extends b{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:Y})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${mr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Y}};Ce.template='';Ce.bindAttributes({checkerboard:"checkerboard"});var _r="--cfg-ctx-name",U=class extends b{get cfgCssCtxName(){return this.getCssData(_r,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(_r,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function br(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function N(...s){let i=br(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function yr(s,...i){let t=br(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var Z={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function Lo(s,i){if(typeof i=="number")return Z[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Z[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Z[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var Cr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return He(...Cr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return Lo(i,t)}).filter(i=>!!i))}var oi=He("format/auto","progressive/yes"),bt=([s])=>typeof s!="undefined"?Number(s):void 0,vr=()=>!0,Uo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Ro=([s,i])=>({dimensions:M(s,"x").map(Number),coords:M(i).map(Number)}),Po={enhance:bt,brightness:bt,exposure:bt,gamma:bt,contrast:bt,saturation:bt,vibrance:bt,warmth:bt,filter:Uo,mirror:vr,flip:vr,rotate:bt,crop:Ro};function wr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!Cr.includes(e))continue;let n=Po[e],o=n(r);i[e]=o}return i}function xr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Y,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"","presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Y,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=I($t(i)),r=k(t,I(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var Tr=`
Network error
{{fileType}}
{{msg}}
`;var D={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},li=[D.CROP,D.SLIDERS,D.FILTERS],Er=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],Ar=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],$r=["rotate","mirror","flip"],lt={brightness:{zero:Z.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Z.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Z.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Z.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Z.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Z.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Z.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Z.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Z.filter,range:[0,100],keypointsNumber:1}};var at=class extends U{constructor(){super();h(this,"_debouncedShowLoader",S(this._showLoader.bind(this),300));this.init$={...this.init$,...xr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===D.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Zs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Js(this.$.cdnUrl),r=wr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=k(this.$["*originalUrl"],I("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===D.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Y&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Y)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=je(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=N("image",{image_hidden_to_cropper:t===D.CROP,image_hidden_effects:t!==D.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=I($t(t)),n=k(e,I(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(at,"className","cloud-image-editor");at.template=Tr;at.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset"});var ai=class extends U{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=tt("mask",{id:"backdrop-mask"}),a=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=tt("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Pt(n,f)}else{let f=Et(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:$}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(Xi*Et(Math.min(d,p)/Xi/3,0,1),Ns);Pt(n,{x:$[0]-A,y:$[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",N("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=tt("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=tt("rect",{fill:"transparent"}),l=tt("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=tt("svg"),t=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=tt("line",{x1:`${ue*e}%`,y1:"0%",x2:`${ue*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=tt("line",{x1:"0%",y1:`${ue*e}%`,x2:"100%",y2:`${ue*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Bs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Kt(Zt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Vs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",N("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",N({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ai.template='';var yt=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=N({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function No(s){let i=s+90;return i=i>=360?0:i,i}function Do(s,i){return s==="rotate"?No(i):["mirror","flip"].includes(s)?!i:null}var te=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Do(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var we={FILTER:"filter",COLOR_OPERATION:"color_operation"},ct="original",ci=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?we.FILTER:we.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ct?void 0:this.$.value,filter:this._filter===ct?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=lt[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===we.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===we.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===we.FILTER?this._filter===ct?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ci.template=``;function xe(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=Y)}}}function Te(s){let i=[];for(let n of s){let o=xe(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Ft=class extends yt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ct?{name:this._filter,amount:o}:void 0,k(this._originalUrl,I(oi,$t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=xe(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ct,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Ft.template=`
`;var ee=class extends yt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=lt[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Sr=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function kr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function ie(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return k(s,I(oi,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Fo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var hi=class extends U{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=S(this._commit.bind(this),300),this._handleResizeThrottled=Sr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=kr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=Yt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Zt(l)}_alignCrop(){var c;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[u,d],coords:[p,m]}=n,{width:f}=Yt(this._imageSize,r),_=o/f;i=Kt(Zt({x:l+p*_,y:a+m*_,width:u*_,height:d*_}),this.$["*imageBox"])}if(!n||!Hs(i,t)){let u=(c=this.$["*cropPresetList"])==null?void 0:c[0],d=u?u.width/u.height:void 0,p=t.width/t.height,m=t.width,f=t.height;d&&(p>d?m=Math.min(t.height*d,t.width):f=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Kt(Zt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=Yt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=N({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=Yt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[Et(Math.round(c/d),1,l),Et(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=Yt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),$={dimensions:_,coords:[Et(Math.round((d-l)/m),0,c-_[0]),Et(Math.round((p-a)/f),0,u-_[1])]};if(!Fo($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(_[0]===c&&_[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=N({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(ie(i,e,t)),{promise:n,cancel:o,image:l}=xe(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};hi.template=``;function rs(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Vo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function zo(s,i){return s.map((t,e)=>tn-o)}var ns=class extends U{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=S(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(ie(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=lt[i],r=this._keypoints.map(l=>l.value),n=Bo(r,t,e),o=zo(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Te(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Ir(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=Te(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Ir(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=N({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var jo=1,ui=class extends U{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>jo?this.scrollLeft+=e:this.scrollLeft+=t})}};ui.template=" ";function Ho(s){return``}function Wo(s){return`
`}var di=class extends U{constructor(){super();h(this,"_updateInfoTooltip",S(()=>{var n,o;let t=this.$["*editorTransformations"],e="",r=!1;if(this.$["*tabId"]===D.FILTERS)if(r=!0,this.$["*currentFilter"]&&((n=t==null?void 0:t.filter)==null?void 0:n.name)===this.$["*currentFilter"]){let l=((o=t==null?void 0:t.filter)==null?void 0:o.amount)||100;e=this.l10n(this.$["*currentFilter"])+" "+l}else e=this.l10n(ct);else if(this.$["*tabId"]===D.SLIDERS&&this.$["*currentOperation"]){r=!0;let l=(t==null?void 0:t[this.$["*currentOperation"]])||lt[this.$["*currentOperation"]].zero;e=this.$["*currentOperation"]+" "+l}r&&(this.$["*operationTooltip"]=e),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",r)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ct,"*currentOperation":null,"*tabId":D.CROP,showLoader:!1,filters:Ar,colorOperations:Er,cropOperations:$r,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":t=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":t=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":t=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":t=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=S(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===D.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=ee.is&&new ee;return e.operation=t,e}_createFilterControl(t){let e=Ft.is&&new Ft;return e.filter=t,e}_createToggleControl(t){let e=te.is&&new te;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===D.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===D.FILTERS?[ct,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===D.SLIDERS&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),r.childNodes.forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===D.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of li){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ie(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Te([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",t=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this._updateInfoTooltip()}};di.template=`
{{*operationTooltip}}
${li.map(Wo).join("")}
${li.map(Ho).join("")}
`;var Ee=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return N("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Ee.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Ee.template=`
{{text}}
`;var pi=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};pi.template=`
`;var fi={transition:"transition",visible:"visible",hidden:"hidden"},mi=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=fi.visible,this._hiddenStyle=fi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",yr(this,{[fi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(fi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};mi.template=" ";var gi=class extends b{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);h(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new at,e=this.$.cdnUrl,r=this.cfg.cropPreset;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),t.addEventListener("apply",n=>this.handleApply(n)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var Xo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Or=function(s,i="i"){let t=s.split("*").map(Xo);return new RegExp("^"+t.join(".+")+"$",i)};var qo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Lr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return qo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var St={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in St){let t=St[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ur=function(s,i,t){s in St||(St[s]=[]),St[s].push([i,t])},Rr=function(s,i){s in St&&(St[s]=St[s].filter(t=>t[0]!==i))};function Pr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var _i=class extends v{constructor(){super();h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=M(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Or(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Lr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Pr(n),o.toString()}mountIframe(){let t=le({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ur("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Rr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};_i.template=`
{{activityCaption}}
{{counter}}
`;var Ae=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;M(i).forEach(e=>{let r=le({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};Ae.bindAttributes({"tab-list":null,default:null});Ae.template=`
`;var se=class extends v{constructor(){super(...arguments);h(this,"processInnerHtml",!0);h(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return se.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Us(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};se.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ls=class extends g{};var bi=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};bi.template=``;var G={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Mr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},it=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:G.PLAY,fsIcon:G.FS_ON,volIcon:G.VOL_ON,capIcon:G.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Mr.exitFullscreen():Mr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===G.CAP_OFF?(this.$.capIcon=G.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(it.is+":captions","1")):(this.$.capIcon=G.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(it.is+":captions"))}toggleSound(){this.$.volIcon===G.VOL_ON?(this.$.volIcon=G.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=G.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(it.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(it.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=G.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=G.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=G.FS_OFF:this.$.fsIcon=G.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(it.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};it.template=`
{{currentTime}} / {{totalTime}}
`;it.bindAttributes({video:"video",src:"src"});var Go="css-src";function yi(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Go);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var $e=class extends yi(b){};var vi=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(vi,"template",`Powered by Uploadcare`);var kt=class extends $e{constructor(){super(...arguments);h(this,"init$",Fe(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var Ci=class extends kt{};Ci.template=``;var wi=class extends kt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};wi.template=``;var xi=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};xi.template=``;var as=class extends yi(at){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Ko(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,zt as BaseComponent,b as Block,ei as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,at as CloudImageEditorBlock,Ge as Config,si as ConfirmationDialog,vi as Copyright,ai as CropFrame,E as Data,se as DataOutput,be as DropArea,te as EditorCropButtonControl,Ft as EditorFilterControl,hi as EditorImageCropper,ns as EditorImageFader,ee as EditorOperationControl,ui as EditorScroller,ci as EditorSlider,di as EditorToolbar,_i as ExternalSource,_t as FileItem,Ce as FilePreview,xi as FileUploaderInline,wi as FileUploaderMinimal,Ci as FileUploaderRegular,ge as Icon,Yi as Img,pi as LineLoaderUi,Ee as LrBtnUi,Je as MessageBox,B as Modal,Xs as PACKAGE_NAME,qs as PACKAGE_VERSION,mi as PresenceToggle,ni as ProgressBar,ri as ProgressBarCommon,bi as Select,$e as ShadowWrapper,Ye as SimpleBtn,gi as SliderUi,ye as SourceBtn,ts as SourceList,Zi as StartFrom,Ae as Tabs,is as UploadCtxProvider,ii as UploadDetails,Qe as UploadList,v as UploaderBlock,ti as UrlSource,it as Video,Ko as connectBlocksFrom,cs as registerBlocks,yi as shadowed,gt as toKebabCase}; \ No newline at end of file diff --git a/web/lr-file-uploader-minimal.min.js b/web/lr-file-uploader-minimal.min.js index bbb9907ca..6a15d8863 100644 --- a/web/lr-file-uploader-minimal.min.js +++ b/web/lr-file-uploader-minimal.min.js @@ -23,5 +23,5 @@ * SOFTWARE. * */ -var Si=Object.defineProperty;var Ri=(e,i,t)=>i in e?Si(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t;var c=(e,i,t)=>(Ri(e,typeof i!="symbol"?i+"":i,t),t),ne=(e,i,t)=>{if(!i.has(e))throw TypeError("Cannot "+t)};var L=(e,i,t)=>(ne(e,i,"read from private field"),t?t.call(e):i.get(e)),at=(e,i,t)=>{if(i.has(e))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(e):i.set(e,t)},vt=(e,i,t,s)=>(ne(e,i,"write to private field"),s?s.call(e,t):i.set(e,t),t);var Lt=(e,i,t)=>(ne(e,i,"access private method"),t);function Oi(e){for(let i in e){let t=[...i].reduce((s,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),s+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),e[i].reg&&e[i].reg(t)}}var Ii=Object.defineProperty,Ui=(e,i,t)=>i in e?Ii(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t,le=(e,i,t)=>(Ui(e,typeof i!="symbol"?i+"":i,t),t);function Li(e){let i=t=>{var s;for(let r in t)((s=t[r])==null?void 0:s.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(e)}var E=class{constructor(e){e.constructor===Object?this.store=Li(e):(this._storeIsProxy=!0,this.store=e),this.callbackMap=Object.create(null)}static warn(e,i){console.warn(`Symbiote Data: cannot ${e}. Prop name: `+i)}read(e){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(E.warn("read",e),null):this.store[e]}has(e){return this._storeIsProxy?this.store[e]!==void 0:this.store.hasOwnProperty(e)}add(e,i,t=!1){!t&&Object.keys(this.store).includes(e)||(this.store[e]=i,this.notify(e))}pub(e,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(e)){E.warn("publish",e);return}this.store[e]=i,this.notify(e)}multiPub(e){for(let i in e)this.pub(i,e[i])}notify(e){this.callbackMap[e]&&this.callbackMap[e].forEach(i=>{i(this.store[e])})}sub(e,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(E.warn("subscribe",e),null):(this.callbackMap[e]||(this.callbackMap[e]=new Set),this.callbackMap[e].add(i),t&&i(this.store[e]),{remove:()=>{this.callbackMap[e].delete(i),this.callbackMap[e].size||delete this.callbackMap[e]},callback:i})}static registerCtx(e,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(e),E.globalStore.set(i,t)),t}static deleteCtx(e){E.globalStore.delete(e)}static getCtx(e,i=!0){return E.globalStore.get(e)||(i&&console.warn('State: wrong context UID - "'+e+'"'),null)}};E.globalStore=new Map;var g=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),$e="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",ki=$e.length-1,At=class{static generate(e="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Pi(e,i){[...e.querySelectorAll(`[${g.REPEAT_ATTR}]`)].forEach(t=>{let s=t.getAttribute(g.REPEAT_ITEM_TAG_ATTR),r;if(s&&(r=window.customElements.get(s)),!r){r=class extends i.BaseComponent{constructor(){super(),s||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(s)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(g.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,u=d=>{d.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let h=l.slice(d.length,l.length);for(let p of h)p.remove()};if(o.constructor===Array)u(o);else if(o.constructor===Object){let d=[];for(let h in o){let p=o[h];Object.defineProperty(p,"_KEY_",{value:h,enumerable:!0}),d.push(p)}u(d)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(g.REPEAT_ATTR),t.removeAttribute(g.REPEAT_ITEM_TAG_ATTR)})}var Ne="__default__";function Mi(e,i){if(i.shadowRoot)return;let t=[...e.querySelectorAll("slot")];if(!t.length)return;let s={};t.forEach(r=>{let n=r.getAttribute("name")||Ne;s[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=Ne;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=s[o])==null||n.fr.appendChild(r)}),Object.values(s).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function Ni(e,i){[...e.querySelectorAll(`[${g.EL_REF_ATTR}]`)].forEach(t=>{let s=t.getAttribute(g.EL_REF_ATTR);i.ref[s]=t,t.removeAttribute(g.EL_REF_ATTR)})}function Fi(e,i){[...e.querySelectorAll(`[${g.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(g.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Di(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(d=>d.trim()),l=o[0],a;l.indexOf(g.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(g.ATTR_BIND_PRFX,""));let u=o[1].split(",").map(d=>d.trim());for(let d of u){let h;d.startsWith("!!")?(h="double",d=d.replace("!!","")):d.startsWith("!")&&(h="single",d=d.replace("!","")),i.sub(d,p=>{h==="double"?p=!!p:h==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):Ve(t,l,p)||(t[g.SET_LATER_KEY]||(t[g.SET_LATER_KEY]=Object.create(null)),t[g.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(g.BIND_ATTR)})}var kt="{{",Tt="}}",$i="skip-text";function Vi(e){let i,t=[],s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute($i))&&r.textContent.includes(kt)&&r.textContent.includes(Tt)&&1}});for(;i=s.nextNode();)t.push(i);return t}var Bi=function(e,i){Vi(e).forEach(s=>{let r=[],n;for(;s.textContent.includes(Tt);)s.textContent.startsWith(kt)?(n=s.textContent.indexOf(Tt)+Tt.length,s.splitText(n),r.push(s)):(n=s.textContent.indexOf(kt),s.splitText(n)),s=s.nextSibling;r.forEach(o=>{let l=o.textContent.replace(kt,"").replace(Tt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},ji=[Pi,Mi,Ni,Fi,Bi],Dt="'",ft='"',zi=/\\([0-9a-fA-F]{1,6} ?)/g;function Hi(e){return(e[0]===ft||e[0]===Dt)&&(e[e.length-1]===ft||e[e.length-1]===Dt)}function Wi(e){return(e[0]===ft||e[0]===Dt)&&(e=e.slice(1)),(e[e.length-1]===ft||e[e.length-1]===Dt)&&(e=e.slice(0,-1)),e}function Xi(e){let i="",t="";for(var s=0;sString.fromCodePoint(parseInt(s.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=Xi(i),i=ft+i+ft);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${e}`)}}var Fe=0,pt=null,Y=null,tt=class extends HTMLElement{constructor(){super(),le(this,"updateCssData",()=>{var e;this.dropCssDataCache(),(e=this.__boundCssProps)==null||e.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return tt}initCallback(){}__initCallback(){var e;this.__initialized||(this.__initialized=!0,(e=this.initCallback)==null||e.call(this))}render(e,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(g.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?e=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(e||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(e==null?void 0:e.constructor)===DocumentFragment)t=e;else if((e==null?void 0:e.constructor)===String){let r=document.createElement("template");r.innerHTML=e,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let s=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=s,this.shadowRoot.prepend(r)}else s()}addTemplateProcessor(e){this.tplProcessors.add(e)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=At.generate(),this.style.setProperty(g.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(g.CSS_CTX_PROP,!0)}get ctxName(){var e;let i=((e=this.getAttribute(g.CTX_NAME_ATTR))==null?void 0:e.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(e,i){let t,s;if(e.startsWith(g.EXT_DATA_CTX_PRFX))t=i.nodeCtx,s=e.replace(g.EXT_DATA_CTX_PRFX,"");else if(e.includes(g.NAMED_DATA_CTX_SPLTR)){let r=e.split(g.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),s=r[1]}else t=i.localCtx,s=e;return{ctx:t,name:s}}sub(e,i,t=!0){let s=n=>{this.isConnected&&i(n)},r=tt.__parseProp(e,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,s,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,s,t))})}notify(e){let i=tt.__parseProp(e,this);i.ctx.notify(i.name)}has(e){let i=tt.__parseProp(e,this);return i.ctx.has(i.name)}add(e,i,t=!1){let s=tt.__parseProp(e,this);s.ctx.add(s.name,i,t)}add$(e,i=!1){for(let t in e)this.add(t,e[t],i)}get $(){if(!this.__stateProxy){let e=Object.create(null);this.__stateProxy=new Proxy(e,{set:(i,t,s)=>{let r=tt.__parseProp(t,this);return r.ctx.pub(r.name,s),!0},get:(i,t)=>{let s=tt.__parseProp(t,this);return s.ctx.read(s.name)}})}return this.__stateProxy}set$(e,i=!1){for(let t in e){let s=e[t];i||![String,Number,Boolean].includes(s==null?void 0:s.constructor)?this.$[t]=s:this.$[t]!==s&&(this.$[t]=s)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(g.CTX_OWNER_ATTR)&&this.getAttribute(g.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let e=this.constructor.__attrDesc;if(e)for(let i of Object.values(e))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(g.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(g.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(g.NAMED_DATA_CTX_SPLTR)){let t=i.split(g.NAMED_DATA_CTX_SPLTR),s=t[0].trim(),r=t[1].trim();if(s&&r){let n=E.getCtx(s,!1);n||(n=E.registerCtx({},s)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var e;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(e=this.getAttribute(g.CTX_NAME_ATTR))==null?void 0:e.trim();if(i&&this.style.setProperty(g.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[g.SET_LATER_KEY]){for(let t in this[g.SET_LATER_KEY])Ve(this,t,this[g.SET_LATER_KEY][t]);delete this[g.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of ji)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${g.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(g.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let e of this.allSubs)e.remove(),this.allSubs.delete(e);for(let e of this.tplProcessors)this.tplProcessors.delete(e);Y==null||Y.delete(this.updateCssData),Y!=null&&Y.size||(pt==null||pt.disconnect(),pt=null,Y=null)},100)))}static reg(e,i=!1){e||(Fe++,e=`${g.AUTO_TAG_PRFX}-${Fe}`),this.__tag=e;let t=window.customElements.get(e);if(t){!i&&t!==this&&console.warn([`Element with tag name "${e}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(e,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(e){this.observedAttributes=Object.keys(e),this.__attrDesc=e}attributeChangedCallback(e,i,t){var s;if(i===t)return;let r=(s=this.constructor.__attrDesc)==null?void 0:s[e];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[e]=t}getCssData(e,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(e)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(e).trim();try{this.__cssDataCache[e]=Gi(t)}catch{!i&&console.warn(`CSS Data error: ${e}`),this.__cssDataCache[e]=null}}return this.__cssDataCache[e]}__extractCssName(e){return e.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){Y||(Y=new Set),Y.add(this.updateCssData),pt||(pt=new MutationObserver(e=>{e[0].type==="attributes"&&Y.forEach(i=>{i()})}),pt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(e,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(e);let t=this.getCssData(this.__extractCssName(e),!0);t===null&&(t=i),this.add(e,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(e,i,t){let s="__"+e;this[s]=this[e],Object.defineProperty(this,e,{set:r=>{this[s]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[s]}),this[e]=this[s]}static set shadowStyles(e){let i=new Blob([e],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(e){if(!this.__rootStylesLink){let i=new Blob([e],{type:"text/css"}),t=URL.createObjectURL(i),s=document.createElement("link");s.href=t,s.rel="stylesheet",this.__rootStylesLink=s}}},ae=tt;le(ae,"template");var oe=class{static _print(e){console.warn(e)}static setDefaultTitle(e){this.defaultTitle=e}static setRoutingMap(e){Object.assign(this.appMap,e);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(e){this.__routingEventName=e}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let e={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))e.route=t.replace("?","");else if(t.includes("=")){let s=t.split("=");e.options[s[0]]=decodeURI(s[1])}else e.options[t]=!0}),e}static notify(){let e=this.readAddressBar(),i=this.appMap[e.route];if(i&&i.title&&(document.title=i.title),e.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${e.route}" not found...`);return}let t=new CustomEvent(oe.routingEventName,{detail:{route:e.route,options:Object.assign(i||{},e.options)}});window.dispatchEvent(t)}static reflect(e,i={}){let t=this.appMap[e];if(!t){this._print("Wrong route: "+e);return}let s="?"+e;for(let n in i)i[n]===!0?s+=this.separator+n:s+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,s),document.title=r}static applyRoute(e,i={}){this.reflect(e,i),this.notify()}static setSeparator(e){this._separator=e}static get separator(){return this._separator||"&"}static createRouterData(e,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},e);return window.addEventListener(this.routingEventName,s=>{var r;t.multiPub({route:s.detail.route,options:s.detail.options,title:((r=s.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),oe.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};oe.appMap=Object.create(null);var Be="idb-store-ready",qi="symbiote-db",Ki="symbiote-idb-update_",Yi=class{_notifyWhenReady(e=null){window.dispatchEvent(new CustomEvent(Be,{detail:{dbName:this.name,storeName:this.storeName,event:e}}))}get _updEventName(){return Ki+this.name}_getUpdateEvent(e){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:e}})}_notifySubscribers(e){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,e),window.dispatchEvent(this._getUpdateEvent(e))}constructor(e,i){this.name=e,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=s=>{this._notifyWhenReady(s)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(e){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(e);return new Promise((s,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?s(n.target.result._value):(s(null),console.warn(`IDB: cannot read "${e}"`))},t.onerror=n=>{r(n)}})}write(e,i,t=!1){let s={_key:e,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(s);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(e),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(e,i=!1){let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);return new Promise((r,n)=>{s.onsuccess=o=>{i||this._notifySubscribers(e),r(o)},s.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,s)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{s(r)}})}subscribe(e,i){this._subscriptionsMap[e]||(this._subscriptionsMap[e]=new Set);let t=this._subscriptionsMap[e];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[e]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,je.clear(this.name)}},je=class{static get readyEventName(){return Be}static open(e=qi,i="store"){let t=e+"/"+i;return this._reg[t]||(this._reg[t]=new Yi(e,i)),this._reg[t]}static clear(e){window.indexedDB.deleteDatabase(e);for(let i in this._reg)i.split("/")[0]===e&&delete this._reg[i]}};le(je,"_reg",Object.create(null));function z(e,i){let t,s=(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),i)};return s.cancel=()=>{clearTimeout(t)},s}var Ji="--uploadcare-blocks-window-height",Pt="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function ce(){return typeof window[Pt]=="undefined"?!1:!!window[Pt]}function ze(){if(ce())return;let e=()=>{document.documentElement.style.setProperty(Ji,`${window.innerHeight}px`),window[Pt]=!0},i=z(e,100);return window.addEventListener("resize",i,{passive:!0}),e(),()=>{window[Pt]=!1,window.removeEventListener("resize",i)}}var Qi=e=>e,ue="{{",We="}}",He="plural:";function de(e,i,t={}){var o;let{openToken:s=ue,closeToken:r=We,transform:n=Qi}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();e=e.replaceAll(s+l+r,typeof a=="string"?n(a):a)}return e}function Xe(e){let i=[],t=e.indexOf(ue);for(;t!==-1;){let s=e.indexOf(We,t),r=e.substring(t+2,s);if(r.startsWith(He)){let n=e.substring(t+2,s).replace(He,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=e.indexOf(ue,s)}return i}function Ge(e){return Object.prototype.toString.call(e)==="[object Object]"}var Zi=/\W|_/g;function ts(e){return e.split(Zi).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function qe(e,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(e)?e.map(t=>Q(t,{ignoreKeys:i})):e}function Q(e,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(e))return qe(e,{ignoreKeys:i});if(!Ge(e))return e;let t={};for(let s of Object.keys(e)){let r=e[s];if(i.includes(s)){t[s]=r;continue}Ge(r)?r=Q(r,{ignoreKeys:i}):Array.isArray(r)&&(r=qe(r,{ignoreKeys:i})),t[ts(s)]=r}return t}var es=e=>new Promise(i=>setTimeout(i,e));function be({libraryName:e,libraryVersion:i,userAgent:t,publicKey:s="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:s,libraryName:e,libraryVersion:i,languageName:n,integration:r});let o=[e,i,s].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var is={factor:2,time:100};function ss(e,i=is){let t=0;function s(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>es(l!=null?l:n).then(()=>(t+=1,s(r)))})}return s(e)}var yt=class extends Error{constructor(t){super();c(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,yt.prototype),this.originalProgressEvent=t}},Ft=(e,i)=>{e&&(e.aborted?Promise.resolve().then(i):e.addEventListener("abort",()=>i(),{once:!0}))},et=class extends Error{constructor(t="Request canceled"){super(t);c(this,"isCancel",!0);Object.setPrototypeOf(this,et.prototype)}},rs=500,Ye=({check:e,interval:i=rs,timeout:t,signal:s})=>new Promise((r,n)=>{let o,l;Ft(s,()=>{o&&clearTimeout(o),n(new et("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new et("Timed out"))},t));let a=()=>{try{Promise.resolve(e(s)).then(u=>{u?(l&&clearTimeout(l),r(u)):o=setTimeout(a,i)}).catch(u=>{l&&clearTimeout(l),n(u)})}catch(u){l&&clearTimeout(l),n(u)}};o=setTimeout(a,0)}),C={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},$t="application/octet-stream",Je="original",st=({method:e,url:i,data:t,headers:s={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,u=(e==null?void 0:e.toUpperCase())||"GET",d=!1;a.open(u,i,!0),s&&Object.entries(s).forEach(h=>{let[p,m]=h;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Ft(r,()=>{d=!0,a.abort(),l(new et)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let h={method:u,url:i,data:t,headers:s||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function(A){let T=A.split(": "),b=T.shift(),_=T.join(": ");b&&typeof b!="undefined"&&(m[b]=_)});let f=a.response,y=a.status;o({request:h,data:f,headers:m,status:y})}},a.onerror=h=>{d||l(new yt(h))},n&&typeof n=="function"&&(a.upload.onprogress=h=>{h.lengthComputable?n({isComputable:!0,value:h.loaded/h.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function ns(e,...i){return e}var os=({name:e})=>e?[e]:[],ls=ns,as=()=>new FormData,Qe=e=>!1,Vt=e=>typeof Blob!="undefined"&&e instanceof Blob,Bt=e=>typeof File!="undefined"&&e instanceof File,jt=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&"uri"in e&&typeof e.uri=="string",wt=e=>Vt(e)||Bt(e)||Qe()||jt(e),cs=e=>typeof e=="string"||typeof e=="number"||typeof e=="undefined",us=e=>!!e&&typeof e=="object"&&!Array.isArray(e),ds=e=>!!e&&typeof e=="object"&&"data"in e&&wt(e.data);function hs(e,i,t){if(ds(t)){let{name:s,contentType:r}=t,n=ls(t.data,s,r!=null?r:$t),o=os({name:s,contentType:r});e.push([i,n,...o])}else if(us(t))for(let[s,r]of Object.entries(t))typeof r!="undefined"&&e.push([`${i}[${s}]`,String(r)]);else cs(t)&&t&&e.push([i,t.toString()])}function ps(e){let i=[];for(let[t,s]of Object.entries(e))hs(i,t,s);return i}function ye(e){let i=as(),t=ps(e);for(let s of t){let[r,n,...o]=s;i.append(r,n,...o)}return i}var I=class extends Error{constructor(t,s,r,n,o){super();c(this,"isCancel");c(this,"code");c(this,"request");c(this,"response");c(this,"headers");this.name="UploadClientError",this.message=t,this.code=s,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,I.prototype)}},fs=e=>{let i=new URLSearchParams;for(let[t,s]of Object.entries(e))s&&typeof s=="object"&&!Array.isArray(s)?Object.entries(s).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(s)?s.forEach(r=>{i.append(`${t}[]`,r)}):typeof s=="string"&&s?i.set(t,s):typeof s=="number"&&i.set(t,s.toString());return i.toString()},J=(e,i,t)=>{let s=new URL(e);return s.pathname=(s.pathname+i).replace("//","/"),t&&(s.search=fs(t)),s.toString()},ms="6.6.1",gs="UploadcareUploadClient",_s=ms;function dt(e){return be({libraryName:gs,libraryVersion:_s,...e})}var bs="RequestThrottledError",Ke=15e3,ys=1e3;function Cs(e){let{headers:i}=e||{};if(!i||typeof i["retry-after"]!="string")return Ke;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Ke}function rt(e,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:s}=i;return ss(({attempt:r,retry:n})=>e().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===bs&&r{let i="";return(Vt(e)||Bt(e)||jt(e))&&(i=e.type),i||$t},ti=e=>{let i="";return Bt(e)&&e.name?i=e.name:Vt(e)||Qe()?i="":jt(e)&&e.name&&(i=e.name),i||Je};function Ce(e){return typeof e=="undefined"||e==="auto"?"auto":e?"1":"0"}function Es(e,{publicKey:i,fileName:t,contentType:s,baseURL:r=C.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:u,source:d="local",integration:h,userAgent:p,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=C.retryNetworkErrorMaxTimes,metadata:y}){return rt(()=>st({method:"POST",url:J(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":dt({publicKey:i,integration:h,userAgent:p})},data:ye({file:{data:e,name:t||ti(e),contentType:s||Ze(e)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Ce(l),signature:n,expire:o,source:d,metadata:y}),signal:a,onProgress:u}).then(({data:A,headers:T,request:b})=>{let _=Q(JSON.parse(A));if("error"in _)throw new I(_.error.content,_.error.errorCode,b,_,T);return _}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var fe;(function(e){e.Token="token",e.FileInfo="file_info"})(fe||(fe={}));function vs(e,{publicKey:i,baseURL:t=C.baseURL,store:s,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:u="url",signal:d,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=C.retryNetworkErrorMaxTimes,metadata:y}){return rt(()=>st({method:"POST",headers:{"X-UC-User-Agent":dt({publicKey:i,integration:h,userAgent:p})},url:J(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:e,store:Ce(s),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:u,metadata:y}),signal:d}).then(({data:A,headers:T,request:b})=>{let _=Q(JSON.parse(A));if("error"in _)throw new I(_.error.content,_.error.errorCode,b,_,T);return _}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var $;(function(e){e.Unknown="unknown",e.Waiting="waiting",e.Progress="progress",e.Error="error",e.Success="success"})($||($={}));var Ts=e=>"status"in e&&e.status===$.Error;function As(e,{publicKey:i,baseURL:t=C.baseURL,signal:s,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=C.retryNetworkErrorMaxTimes}={}){return rt(()=>st({method:"GET",headers:i?{"X-UC-User-Agent":dt({publicKey:i,integration:r,userAgent:n})}:void 0,url:J(t,"/from_url/status/",{jsonerrors:1,token:e}),signal:s}).then(({data:a,headers:u,request:d})=>{let h=Q(JSON.parse(a));if("error"in h&&!Ts(h))throw new I(h.error.content,void 0,d,h,u);return h}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function ws(e,{publicKey:i,baseURL:t=C.baseURL,jsonpCallback:s,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:u,retryThrottledRequestMaxTimes:d=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:h=C.retryNetworkErrorMaxTimes}){return rt(()=>st({method:"POST",headers:{"X-UC-User-Agent":dt({publicKey:i,integration:a,userAgent:u})},url:J(t,"/group/",{jsonerrors:1,pub_key:i,files:e,callback:s,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let y=Q(JSON.parse(p));if("error"in y)throw new I(y.error.content,y.error.errorCode,f,y,m);return y}),{retryNetworkErrorMaxTimes:h,retryThrottledRequestMaxTimes:d})}function ei(e,{publicKey:i,baseURL:t=C.baseURL,signal:s,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=C.retryNetworkErrorMaxTimes}){return rt(()=>st({method:"GET",headers:{"X-UC-User-Agent":dt({publicKey:i,integration:n,userAgent:o})},url:J(t,"/info/",{jsonerrors:1,pub_key:i,file_id:e,source:r}),signal:s}).then(({data:u,headers:d,request:h})=>{let p=Q(JSON.parse(u));if("error"in p)throw new I(p.error.content,p.error.errorCode,h,p,d);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function xs(e,{publicKey:i,contentType:t,fileName:s,multipartChunkSize:r=C.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:u,source:d="local",integration:h,userAgent:p,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=C.retryNetworkErrorMaxTimes,metadata:y}){return rt(()=>st({method:"POST",url:J(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":dt({publicKey:i,integration:h,userAgent:p})},data:ye({filename:s||Je,size:e,content_type:t||$t,part_size:r,UPLOADCARE_STORE:Ce(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:d,metadata:y}),signal:u}).then(({data:A,headers:T,request:b})=>{let _=Q(JSON.parse(A));if("error"in _)throw new I(_.error.content,_.error.errorCode,b,_,T);return _.parts=Object.keys(_.parts).map(N=>_.parts[N]),_}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Ss(e,i,{contentType:t,signal:s,onProgress:r,retryThrottledRequestMaxTimes:n=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=C.retryNetworkErrorMaxTimes}){return rt(()=>st({method:"PUT",url:i,data:e,onProgress:r,signal:s,headers:{"Content-Type":t||$t}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Rs(e,{publicKey:i,baseURL:t=C.baseURL,source:s="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=C.retryNetworkErrorMaxTimes}){return rt(()=>st({method:"POST",url:J(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":dt({publicKey:i,integration:n,userAgent:o})},data:ye({uuid:e,UPLOADCARE_PUB_KEY:i,source:s}),signal:r}).then(({data:u,headers:d,request:h})=>{let p=Q(JSON.parse(u));if("error"in p)throw new I(p.error.content,p.error.errorCode,h,p,d);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Ee({file:e,publicKey:i,baseURL:t,source:s,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:u}){return Ye({check:d=>ei(e,{publicKey:i,baseURL:t,signal:d,source:s,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(h=>h.isReady?h:(u&&u({isComputable:!0,value:1}),!1)),signal:a})}var it=class{constructor(i,{baseCDN:t=C.baseCDN,fileName:s}={}){c(this,"uuid");c(this,"name",null);c(this,"size",null);c(this,"isStored",null);c(this,"isImage",null);c(this,"mimeType",null);c(this,"cdnUrl",null);c(this,"s3Url",null);c(this,"originalFilename",null);c(this,"imageInfo",null);c(this,"videoInfo",null);c(this,"contentInfo",null);c(this,"metadata",null);c(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=J(t,`${r}/`),l=n?J(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=s||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},Os=(e,{publicKey:i,fileName:t,baseURL:s,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:u,source:d,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:y,metadata:A})=>Es(e,{publicKey:i,fileName:t,contentType:l,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:u,source:d,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:A}).then(({file:T})=>Ee({file:T,publicKey:i,baseURL:s,source:d,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:u,signal:a})).then(T=>new it(T,{baseCDN:y})),Is=(e,{publicKey:i,fileName:t,baseURL:s,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:u,retryNetworkErrorMaxTimes:d,baseCDN:h})=>ei(e,{publicKey:i,baseURL:s,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:u,retryNetworkErrorMaxTimes:d}).then(p=>new it(p,{baseCDN:h,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Us=(e,{signal:i}={})=>{let t=null,s=null,r=e.map(()=>new AbortController),n=o=>()=>{s=o,r.forEach((l,a)=>a!==o&&l.abort())};return Ft(i,()=>{r.forEach(o=>o.abort())}),Promise.all(e.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(u=>(a(),u)).catch(u=>(t=u,null))})).then(o=>{if(s===null)throw t;return o[s]})},Ls=window.WebSocket,me=class{constructor(){c(this,"events",Object.create({}))}emit(i,t){var s;(s=this.events[i])==null||s.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(s=>s!==t):this.events[i]=[]}},ks=(e,i)=>e==="success"?{status:$.Success,...i}:e==="progress"?{status:$.Progress,...i}:{status:$.Error,...i},ge=class{constructor(i,t=3e4){c(this,"key");c(this,"disconnectTime");c(this,"ws");c(this,"queue",[]);c(this,"isConnected",!1);c(this,"subscribers",0);c(this,"emmitter",new me);c(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Ls(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let s=JSON.parse(t.data.toString());switch(s.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(s.channel,ks(s.event,JSON.parse(s.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let s=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(s)}subscribe(i,t){this.subscribers+=1,this.connect();let s=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:s}};this.emmitter.on(s,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,s={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(s.event,s.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},he=null,ve=e=>{if(!he){let i=typeof window=="undefined"?0:3e4;he=new ge(e,i)}return he},Ds=e=>{ve(e).connect()};function Ps({token:e,publicKey:i,baseURL:t,integration:s,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return Ye({check:u=>As(e,{publicKey:i,baseURL:t,integration:s,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:u}).then(d=>{switch(d.status){case $.Error:return new I(d.error,d.errorCode);case $.Waiting:return!1;case $.Unknown:return new I(`Token "${e}" was not found.`);case $.Progress:return l&&(d.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:d.done/d.total})),!1;case $.Success:return l&&l({isComputable:!0,value:d.done/d.total}),d;default:throw new Error("Unknown status")}}),signal:a})}var Ms=({token:e,pusherKey:i,signal:t,onProgress:s})=>new Promise((r,n)=>{let o=ve(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(e)};Ft(t,()=>{a(),n(new et("pusher cancelled"))}),o.subscribe(e,u=>{switch(u.status){case $.Progress:{s&&(u.total==="unknown"?s({isComputable:!1}):s({isComputable:!0,value:u.done/u.total}));break}case $.Success:{a(),s&&s({isComputable:!0,value:u.done/u.total}),r(u);break}case $.Error:a(),n(new I(u.msg,u.error_code))}})}),Ns=(e,{publicKey:i,fileName:t,baseURL:s,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:u,signal:d,onProgress:h,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:y,pusherKey:A=C.pusherKey,metadata:T})=>Promise.resolve(Ds(A)).then(()=>vs(e,{publicKey:i,fileName:t,baseURL:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:u,signal:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:y,metadata:T})).catch(b=>{let _=ve(A);return _==null||_.disconnect(),Promise.reject(b)}).then(b=>b.type===fe.FileInfo?b:Us([({signal:_})=>Ps({token:b.token,publicKey:i,baseURL:s,integration:m,userAgent:f,retryThrottledRequestMaxTimes:y,onProgress:h,signal:_}),({signal:_})=>Ms({token:b.token,pusherKey:A,signal:_,onProgress:h})],{signal:d})).then(b=>{if(b instanceof I)throw b;return b}).then(b=>Ee({file:b.uuid,publicKey:i,baseURL:s,integration:m,userAgent:f,retryThrottledRequestMaxTimes:y,onProgress:h,signal:d})).then(b=>new it(b,{baseCDN:r})),pe=new WeakMap,Fs=async e=>{if(pe.has(e))return pe.get(e);let i=await fetch(e.uri).then(t=>t.blob());return pe.set(e,i),i},ii=async e=>{if(Bt(e)||Vt(e))return e.size;if(jt(e))return(await Fs(e)).size;throw new Error("Unknown file type. Cannot determine file size.")},$s=(e,i=C.multipartMinFileSize)=>e>=i,si=e=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!wt(e)&&t.test(e)},ri=e=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!wt(e)&&t.test(e)},Vs=(e,i)=>new Promise((t,s)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let u=i.length-l.length,d=l.shift();d&&d().then(h=>{n||(r[u]=h,o-=1,o?a():t(r))}).catch(h=>{n=!0,s(h)})};for(let u=0;u{let r=s*i,n=Math.min(r+s,t);return e.slice(r,n)},js=async(e,i,t)=>s=>Bs(e,s,i,t),zs=(e,i,{publicKey:t,contentType:s,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Ss(e,i,{publicKey:t,contentType:s,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Hs=async(e,{publicKey:i,fileName:t,fileSize:s,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:u,source:d,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:y,multipartChunkSize:A=C.multipartChunkSize,maxConcurrentRequests:T=C.maxConcurrentRequests,baseCDN:b,metadata:_})=>{let N=s!=null?s:await ii(e),G,lt=(O,B)=>{if(!u)return;G||(G=Array(O).fill(0));let q=F=>F.reduce((K,re)=>K+re,0);return F=>{F.isComputable&&(G[B]=F.value,u({isComputable:!0,value:q(G)/O}))}};return y||(y=Ze(e)),xs(N,{publicKey:i,contentType:y,fileName:t||ti(e),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:d,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:_}).then(async({uuid:O,parts:B})=>{let q=await js(e,N,A);return Promise.all([O,Vs(T,B.map((F,K)=>()=>zs(q(K),F,{publicKey:i,contentType:y,onProgress:lt(B.length,K),signal:a,integration:h,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([O])=>Rs(O,{publicKey:i,baseURL:r,source:d,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(O=>O.isReady?O:Ee({file:O.uuid,publicKey:i,baseURL:r,source:d,integration:h,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:u,signal:a})).then(O=>new it(O,{baseCDN:b}))};async function Te(e,{publicKey:i,fileName:t,baseURL:s=C.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:u,integration:d,userAgent:h,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:y,multipartChunkSize:A,maxConcurrentRequests:T,baseCDN:b=C.baseCDN,checkForUrlDuplicates:_,saveUrlForRecurrentUploads:N,pusherKey:G,metadata:lt}){if(wt(e)){let O=await ii(e);return $s(O,y)?Hs(e,{publicKey:i,contentType:f,multipartChunkSize:A,fileSize:O,fileName:t,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:u,integration:d,userAgent:h,maxConcurrentRequests:T,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:lt}):Os(e,{publicKey:i,fileName:t,contentType:f,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:u,integration:d,userAgent:h,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:lt})}if(ri(e))return Ns(e,{publicKey:i,fileName:t,baseURL:s,baseCDN:b,checkForUrlDuplicates:_,saveUrlForRecurrentUploads:N,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:u,integration:d,userAgent:h,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:G,metadata:lt});if(si(e))return Is(e,{publicKey:i,fileName:t,baseURL:s,signal:l,onProgress:a,source:u,integration:d,userAgent:h,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:b});throw new TypeError(`File uploading from "${e}" is not supported`)}var _e=class{constructor(i,t){c(this,"uuid");c(this,"filesCount");c(this,"totalSize");c(this,"isStored");c(this,"isImage");c(this,"cdnUrl");c(this,"files");c(this,"createdAt");c(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((s,r)=>s+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(s=>s.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Ws=e=>{for(let i of e)if(!wt(i))return!1;return!0},Xs=e=>{for(let i of e)if(!si(i))return!1;return!0},Gs=e=>{for(let i of e)if(!ri(i))return!1;return!0};function ni(e,{publicKey:i,fileName:t,baseURL:s=C.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:u,integration:d,userAgent:h,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:y=C.multipartChunkSize,baseCDN:A=C.baseCDN,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:b,jsonpCallback:_}){if(!Ws(e)&&!Gs(e)&&!Xs(e))throw new TypeError(`Group uploading from "${e}" is not supported`);let N,G=!0,lt=e.length,O=(B,q)=>{if(!a)return;N||(N=Array(B).fill(0));let F=K=>K.reduce((re,xi)=>re+xi)/B;return K=>{if(!K.isComputable||!G){G=!1,a({isComputable:!1});return}N[q]=K.value,a({isComputable:!0,value:F(N)})}};return Promise.all(e.map((B,q)=>Te(B,{publicKey:i,fileName:t,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:O(lt,q),source:u,integration:d,userAgent:h,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:y,baseCDN:A,checkForUrlDuplicates:T,saveUrlForRecurrentUploads:b}))).then(B=>{let q=B.map(F=>F.uuid);return ws(q,{publicKey:i,baseURL:s,jsonpCallback:_,secureSignature:r,secureExpire:n,signal:l,source:u,integration:d,userAgent:h,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(F=>new _e(F,B)).then(F=>(a&&a({isComputable:!0,value:1}),F))})}var ct,mt,ut,gt,_t,bt,Mt,Nt=class{constructor(i){at(this,bt);at(this,ct,1);at(this,mt,[]);at(this,ut,0);at(this,gt,new WeakMap);at(this,_t,new WeakMap);vt(this,ct,i)}add(i){return new Promise((t,s)=>{L(this,gt).set(i,t),L(this,_t).set(i,s),L(this,mt).push(i),Lt(this,bt,Mt).call(this)})}get pending(){return L(this,mt).length}get running(){return L(this,ut)}set concurrency(i){vt(this,ct,i),Lt(this,bt,Mt).call(this)}get concurrency(){return L(this,ct)}};ct=new WeakMap,mt=new WeakMap,ut=new WeakMap,gt=new WeakMap,_t=new WeakMap,bt=new WeakSet,Mt=function(){let i=L(this,ct)-L(this,ut);for(let t=0;t{L(this,gt).delete(s),L(this,_t).delete(s),vt(this,ut,L(this,ut)-1),Lt(this,bt,Mt).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var Ae=()=>({"*blocksRegistry":new Set}),we=e=>({...Ae(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{e.set$({"*modalActive":!1,"*currentActivity":""})}}),zt=e=>({...we(e),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Nt(1)});function oi(e,i){[...e.querySelectorAll("[l10n]")].forEach(t=>{let s=t.getAttribute("l10n"),r="textContent";if(s.includes(":")){let o=s.split(":");r=o[0],s=o[1]}let n="l10n:"+s;i.__l10nKeys.push(n),i.add(n,s),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var U=e=>`*cfg/${e}`;var nt=e=>{var i;return(i=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var li=new Set;function Ht(e){li.has(e)||(li.add(e),console.warn(e))}var Wt=(e,i)=>new Intl.PluralRules(e).select(i);var xe="lr-",w=class extends ae{constructor(){super();c(this,"allowCustomTemplate",!0);c(this,"init$",Ae());c(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let s of t)s.isConnected&&s.updateCssData()});this.activityType=null,this.addTemplateProcessor(oi),this.__l10nKeys=[]}l10n(t,s={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=Xe(r);for(let l of n)s[l.variable]=this.pluralize(l.pluralKey,Number(s[l.countVariable]));return de(r,s)}pluralize(t,s){let r=this.l10n("locale-name")||"en-US",n=Wt(r,s);return this.l10n(`${t}__${n}`)}applyL10nKey(t,s){let r="l10n:"+t;this.$[r]=s,this.__l10nKeys.push(t)}hasBlockInCtx(t){let s=this.$["*blocksRegistry"];for(let r of s)if(t(r))return!0;return!1}setForCtxTarget(t,s,r){this.hasBlockInCtx(n=>n.constructor.StateConsumerScope===t)&&(this.$[s]=r)}setActivity(t){if(this.hasBlockInCtx(s=>s.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${xe}${t}`,!0),ce()||(this._destroyInnerHeightTracker=ze()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,s=2){let r=["B","KB","MB","GB","TB"],n=u=>this.getCssData("--l10n-unit-"+u.toLowerCase(),!0)||u;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=s<0?0:s,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let s=this.cfg.secureDeliveryProxy;return s?de(s,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(s,r)=>{let n=U(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Ht("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${nt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,s){let r=this.parseCfgProp(U(t));r.ctx.has(r.name)?this.sub(U(t),s):(this.bindCssData(`--cfg-${nt(t)}`),this.sub(`--cfg-${nt(t)}`,s))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(xe)?t:xe+t)}};c(w,"StateConsumerScope",null),c(w,"className","");var qs="css-src";function Ks(e){return class extends e{constructor(){super(...arguments);c(this,"renderShadow",!0);c(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(qs);if(t){this.attachShadow({mode:"open"});let s=document.createElement("link");s.rel="stylesheet",s.type="text/css",s.href=t,s.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(s)}else console.error("Attribute `css-src`is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Xt=class extends Ks(w){};var Gt=class extends Xt{constructor(){super(...arguments);c(this,"init$",zt(this));c(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var Se=class extends w{constructor(){super(...arguments);c(this,"_handleBackdropClick",()=>{this._closeDialog()});c(this,"_closeDialog",()=>{this.setForCtxTarget(Se.StateConsumerScope,"*modalActive",!1)});c(this,"_handleDialogClose",()=>{this._closeDialog()});c(this,"_handleDialogClick",t=>{t.target===this.ref.dialog&&this._closeDialog()});c(this,"init$",{...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose})}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("click",this._handleDialogClick);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogClick)}},V=Se;c(V,"StateConsumerScope","modal");V.template=``;var ai="active",xt="___ACTIVITY_IS_ACTIVE___",H=class extends w{constructor(){super(...arguments);c(this,"historyTracked",!1);c(this,"init$",we(this));c(this,"_debouncedHistoryFlush",z(this._historyFlush.bind(this),10))}_deactivate(){var s;let t=H._activityRegistry[this.activityKey];this[xt]=!1,this.removeAttribute(ai),(s=t==null?void 0:t.deactivateCallback)==null||s.call(t)}_activate(){var s;let t=H._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[xt]=!0,this.setAttribute(ai,""),(s=t==null?void 0:t.activateCallback)==null||s.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[xt]?this._deactivate():this.activityType===t&&!this[xt]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!H._activityRegistry[this.activityKey]}get isActivityActive(){return this[xt]}registerActivity(t,s={}){let{onActivate:r,onDeactivate:n}=s;H._activityRegistry||(H._activityRegistry=Object.create(null)),H._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),H._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(H._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let s=t.pop();for(;s===this.activityType;)s=t.pop();this.$["*currentActivity"]=s,this.$["*history"]=t,s||this.setForCtxTarget(V.StateConsumerScope,"*modalActive",!1)}}},v=H;c(v,"_activityRegistry",Object.create(null));v.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var qt=class extends Gt{constructor(){super(...arguments);c(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",s=>{s||(this.$["*currentActivity"]=t.initActivity||v.activities.START_FROM)}),this.sub("*uploadList",s=>{(s==null?void 0:s.length)>0?this.$["*currentActivity"]=v.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||v.activities.START_FROM}),this.sub(U("sourceList"),s=>{s!=="local"&&(this.$[U("sourceList")]="local")}),this.sub(U("confirmUpload"),s=>{s!==!1&&(this.$[U("confirmUpload")]=!1)})}};qt.template=``;var Re=class extends v{constructor(){super(...arguments);c(this,"historyTracked",!0);c(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};var Ct=(e,i=",")=>e.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var St=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Oe=e=>e?e.filter(i=>typeof i=="string").map(i=>Ct(i)).flat():[],Ie=(e,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),e.startsWith(t)):e===t),ci=(e,i)=>i.some(t=>t.startsWith(".")?e.toLowerCase().endsWith(t.toLowerCase()):!1),Ue=e=>{let i=e==null?void 0:e.type;return i?Ie(i,St):!1};var ui=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:it,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var di="blocks",hi="0.25.6";function pi(e){return be({...e,libraryName:di,libraryVersion:hi})}var fi="[Typed State] Wrong property name: ",Ys="[Typed State] Wrong property type: ",Kt=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||At.generate(),this.__schema=Object.keys(i).reduce((s,r)=>(s[r]=i[r].value,s),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(fi+i);return}let s=this.__typedSchema[i];if((t==null?void 0:t.constructor)===s.type||t instanceof s.type||s.nullable&&t===null){this.__data.pub(i,t);return}console.warn(Ys+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(fi+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Yt=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||At.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(s,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[s]||(t[s]=new Set),t[s].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var s;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(s=this.__handler)==null||s.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Kt(this.__typedSchema);for(let s in i)t.setValue(s,i[s]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(s=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(s,()=>{this.__notifyObservers(s,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,s){this.read(i).setValue(t,s)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(s=>{let r=this.read(s);i(r)&&t.push(s)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var R={UPLOAD_START:"UPLOAD_START",REMOVE:"REMOVE",UPLOAD_PROGRESS:"UPLOAD_PROGRESS",UPLOAD_FINISH:"UPLOAD_FINISH",UPLOAD_ERROR:"UPLOAD_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",CDN_MODIFICATION:"CLOUD_MODIFICATION",DATA_OUTPUT:"DATA_OUTPUT",DONE_FLOW:"DONE_FLOW",INIT_FLOW:"INIT_FLOW"},k=class{constructor(i){this.ctx=i.ctx,this.type=i.type,this.data=i.data}},S=class{static eName(i){return"LR_"+i}static emit(i,t=window,s=!0){let r=()=>{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!s){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};c(S,"_timeoutStore",Object.create(null));var ot=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var W=1e3,ht=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),Rt=e=>Math.ceil(e*100)/100,mi=(e,i=ht.AUTO)=>{let t=i===ht.AUTO;if(i===ht.BYTE||t&&e{let s=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>s.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=s.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=s.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,S.emit(new k({type:R.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){let n=s.findItems(l=>!!l.getValue("fileInfo")),o=s.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(s.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&S.emit(new k({type:R.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&s.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{S.emit(new k({type:R.UPLOAD_ERROR,ctx:this.ctxName,data:s.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&s.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{S.emit(new k({type:R.VALIDATION_ERROR,ctx:this.ctxName,data:s.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&s.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{S.emit(new k({type:R.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){Ht("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let s=new Yt({typedSchema:ui,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",s)}let t=()=>this.hasBlockInCtx(s=>s instanceof x?s.isUploadCollectionOwner&&s.isConnected&&s!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(s,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=s.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",s=>{this.$["*uploadQueue"].concurrency=Number(s)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:s,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:s!=null?s:!1,source:n!=null?n:ot.API})}addFileFromUuid(t,{silent:s,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:s!=null?s:!1,source:n!=null?n:ot.API})}addFileFromObject(t,{silent:s,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:Ue(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:s!=null?s:!1,source:n!=null?n:ot.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(s=>{this.uploadCollection.add({file:s,isImage:Ue(s),mimeType:s.type,fileName:s.name,fileSize:s.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let s=Oe([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?St:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=St.join(",")):this.fileInput.accept=s,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:ot.LOCAL})),this.$["*currentActivity"]=v.activities.UPLOAD_LIST,this.setForCtxTarget(V.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=Ct(this.cfg.sourceList)),t}initFlow(t=!1){var s,r;if((s=this.$["*uploadList"])!=null&&s.length&&!t)this.set$({"*currentActivity":v.activities.UPLOAD_LIST}),this.setForCtxTarget(V.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let n=this.sourceList[0];n==="local"?(this.$["*currentActivity"]=v.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(x.extSrcList).includes(n)?this.set$({"*currentActivityParams":{externalSourceType:n},"*currentActivity":v.activities.EXTERNAL}):this.$["*currentActivity"]=n,this.setForCtxTarget(V.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":v.activities.START_FROM}),this.setForCtxTarget(V.StateConsumerScope,"*modalActive",!0);S.emit(new k({type:R.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(V.StateConsumerScope,"*modalActive",!1),S.emit(new k({type:R.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let s=this.cfg.imgOnly,r=this.cfg.accept,n=Oe([...s?St:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Ie(o,n),u=ci(l,n);if(!a&&!u)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let s=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(s&&r&&r>s)return this.l10n("files-max-size-limit-error",{maxFileSize:mi(s)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let s=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!s||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let s of this._validators){let r=s(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let s=this.uploadCollection.read(t);s&&this._runValidatorsForEntry(s)})}async getMetadata(){var s;let t=(s=this.cfg.metadata)!=null?s:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:pi,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let s=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};s.push(a)}),s}};x.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});x.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...x.extSrcList});Object.values(R).forEach(e=>{let i=S.eName(e);window.addEventListener(i,t=>{if([R.UPLOAD_FINISH,R.REMOVE,R.CDN_MODIFICATION].includes(t.detail.type)){let r=E.getCtx(t.detail.ctx),n=r.read("uploadCollection"),o=[];n.items().forEach(l=>{let a=E.getCtx(l).store,u=a.fileInfo;if(u){let d={...u,cdnUrlModifiers:a.cdnUrlModifiers,cdnUrl:a.cdnUrl||u.cdnUrl};o.push(d)}}),S.emit(new k({type:R.DATA_OUTPUT,ctx:t.detail.ctx,data:o})),r.pub("outputData",o)}})});function Js(e){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let s=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=s,t.onprogress=s,t.readAsDataURL(e)}catch{i(!1)}})}function Qs(e,i){return new Promise(t=>{let s=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(s++,l.file(a=>{s--;let u=new File([a],a.name,{type:a.type||i});r.push(u),s===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{s++,l.readEntries(a=>{s--;for(let u of a)n(u);s===0&&t(r)})};n(e)})}function gi(e){let i=[],t=[];for(let s=0;s{i.push(...a)}));continue}let o=r.getAsFile();t.push(Js(o).then(l=>{l||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}var P={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},_i=["focus"],Zs=100,Le=new Map;function tr(e,i){let t=Math.max(Math.min(e[0],i.x+i.width),i.x),s=Math.max(Math.min(e[1],i.y+i.height),i.y);return Math.sqrt((e[0]-t)*(e[0]-t)+(e[1]-s)*(e[1]-s))}function ke(e){let i=0,t=document.body,s=new Set,r=f=>s.add(f),n=P.INACTIVE,o=f=>{e.shouldIgnore()&&f!==P.INACTIVE||(n!==f&&s.forEach(y=>y(f)),n=f)},l=()=>i>0;r(f=>e.onChange(f));let a=()=>{i=0,o(P.INACTIVE)},u=()=>{i+=1,n===P.INACTIVE&&o(P.ACTIVE)},d=()=>{i-=1,l()||o(P.INACTIVE)},h=f=>{f.preventDefault(),i=0,o(P.INACTIVE)},p=f=>{l()||(i+=1),f.preventDefault();let y=[f.x,f.y],A=e.element.getBoundingClientRect(),T=Math.floor(tr(y,A)),b=T{if(e.shouldIgnore())return;f.preventDefault();let y=await gi(f.dataTransfer);e.onItems(y),o(P.INACTIVE)};return t.addEventListener("drop",h),t.addEventListener("dragleave",d),t.addEventListener("dragenter",u),t.addEventListener("dragover",p),e.element.addEventListener("drop",m),_i.forEach(f=>{window.addEventListener(f,a)}),()=>{Le.delete(e.element),t.removeEventListener("drop",h),t.removeEventListener("dragleave",d),t.removeEventListener("dragenter",u),t.removeEventListener("dragover",p),e.element.removeEventListener("drop",m),_i.forEach(f=>{window.removeEventListener(f,a)})}}var Ot=class extends x{constructor(){super(...arguments);c(this,"init$",{...this.init$,state:P.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),s=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return s&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",s=>{this.set$({isEnabled:!s})}),this.defineAccessor("clickable",s=>{this.set$({isClickable:typeof s=="string"})}),this.defineAccessor("with-icon",s=>{this.set$({withIcon:typeof s=="string"})}),this.defineAccessor("fullscreen",s=>{this.set$({isFullscreen:typeof s=="string"})}),this.defineAccessor("text",s=>{s?this.set$({text:this.l10n(s)||s}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=ke({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:s=>{this.$.state=s},onItems:s=>{s.length&&(s.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:ot.DROP_AREA});return}this.addFileFromObject(r,{source:ot.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":v.activities.UPLOAD_LIST}),this.setForCtxTarget(V.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=ke({element:t,onChange:s=>{var n;let r=(n=Object.entries(P).find(([,o])=>o===s))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",s=>{var n;let r=(n=Object.entries(P).find(([,o])=>o===s))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",s=>{let r=Ct(s);this.$.isEnabled=r.includes(x.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",s=>{this.toggleAttribute("hidden",!s)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,s=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&s&&r>=s||!t&&r>0)}destroyCallback(){var t,s,r,n;super.destroyCallback(),(s=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||s.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};Ot.template=`
{{text}}
`;Ot.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Jt=class{constructor(){c(this,"caption","");c(this,"text","");c(this,"iconName","");c(this,"isError",!1)}},Qt=class extends w{constructor(){super(...arguments);c(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Qt.template=`
{{captionTxt}}
{{msgTxt}}
`;var Zt=class extends x{constructor(){super(...arguments);c(this,"couldBeUploadCollectionOwner",!0);c(this,"historyTracked",!0);c(this,"activityType",v.activities.UPLOAD_LIST);c(this,"init$",{...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(s=>!!s.getValue("fileInfo"));S.emit(new k({type:R.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}});c(this,"_debouncedHandleCollectionUpdate",z(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0))}_validateFilesCount(){var d,h;let t=!!this.cfg.multiple,s=t?(d=this.cfg.multipleMin)!=null?d:0:1,r=t?(h=this.cfg.multipleMax)!=null?h:0:1,n=this.uploadCollection.size,o=s?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:s,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,s=this._validateFilesCount();if(t&&!s.passed){let r=new Jt,n=s.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:s.min,max:s.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,u=!1,d=!1,h=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?u=!0:(d=!0,h=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:d,doneBtnEnabled:h,uploadBtnVisible:u,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let s=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?s("uploading"):t.failed>0?s("failed"):t.succeed>0?s("succeed"):s("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var s;((s=this.uploadCollection)==null?void 0:s.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};Zt.template=`{{headerText}}
`;var er=e=>{if(typeof e!="string"||!e)return"";let i=e.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},ir=(...e)=>e.filter(i=>typeof i=="string"&&i).map(i=>er(i)).join("/-/"),bi=(...e)=>{let i=ir(...e);return i?`-/${i}/`:""};function yi(e){let i=new URL(e),t=i.pathname+i.search+i.hash,s=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return s>=0?n=t.slice(s):r>=0&&(n=t.slice(r+1)),n}function sr(e){let i=new URL(e),t=yi(e),s=Ci(t)?Ei(t).pathname:t;return i.pathname=i.pathname.replace(s,""),i.search="",i.hash="",i.toString()}function Ci(e){return e.startsWith("http")}function Ei(e){let i=new URL(e);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var vi=(e,i,t)=>{let s=new URL(sr(e));if(t=t||yi(e),s.pathname.startsWith("//")&&(s.pathname=s.pathname.replace("//","/")),Ci(t)){let r=Ei(t);s.pathname=s.pathname+(i||"")+(r.pathname||""),s.search=r.search,s.hash=r.hash}else s.pathname=s.pathname+(i||"")+(t||"");return s.toString()},Ti=(e,i)=>{let t=new URL(e);return t.pathname=i+"/",t.toString()};function rr(e){let i=new Blob([e],{type:"image/svg+xml"});return URL.createObjectURL(i)}function De(e="hsl(209, 21%, 65%)",i=32,t=32){return rr(``)}function Ai(e,i=40){if(e.type==="image/svg+xml")return URL.createObjectURL(e);let t=document.createElement("canvas"),s=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),s.fillStyle="rgb(240, 240, 240)",s.fillRect(0,0,t.width,t.height),s.drawImage(r,0,0,t.width,t.height),t.toBlob(u=>{if(!u){l();return}let d=URL.createObjectURL(u);o(d)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(e),n}var D=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),Z=class extends x{constructor(){super(...arguments);c(this,"pauseRender",!0);c(this,"_entrySubs",new Set);c(this,"_entry",null);c(this,"_isIntersecting",!1);c(this,"_debouncedGenerateThumb",z(this._generateThumbnail.bind(this),100));c(this,"_debouncedCalculateState",z(this._calculateState.bind(this),100));c(this,"_renderedOnce",!1);c(this,"init$",{...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:D.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===v.activities.DETAILS)?this.$["*currentActivity"]=v.activities.DETAILS:this.$["*currentActivity"]=v.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let s=this.getOutputData(r=>r.getValue("uuid")===t);S.emit(new k({type:R.REMOVE,ctx:this.ctxName,data:s}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}})}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[s]=t;this._isIntersecting=s.isIntersecting,s.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),s.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,s=D.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?s=D.FAILED:t.getValue("validationMultipleLimitMsg")?s=D.LIMIT_OVERFLOW:t.getValue("isUploading")?s=D.UPLOADING:t.getValue("fileInfo")&&(s=D.FINISHED),this.$.state=s}async _generateThumbnail(){var s;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(vi(Ti(this.cfg.cdnCname,this._entry.getValue("uuid")),bi(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((s=t.getValue("file"))!=null&&s.type.includes("image"))try{let r=await Ai(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",De(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",De(r))}}_subEntry(t,s){let r=this._entry.subscribe(t,n=>{this.isConnected&&s(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let s=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=s,s&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||s.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=s.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{Z.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),Z.activeInstances.add(this)}_handleState(t){var s,r;this.set$({isFailed:t===D.FAILED,isLimitOverflow:t===D.LIMIT_OVERFLOW,isUploading:t===D.UPLOADING,isFinished:t===D.FINISHED,progressVisible:t===D.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&t===D.FINISHED&&((s=this._entry)==null?void 0:s.getValue("isImage")),errorText:((r=this._entry.getValue("uploadError"))==null?void 0:r.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===D.FAILED||t===D.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===D.FINISHED&&(this.$.badgeIcon="badge-success"),t===D.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),Z.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let s=this.cfg.multiple?this.cfg.multipleMax:1;if(s&&this.uploadCollection.size>s)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));S.emit(new k({type:R.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let u=async()=>{let h=await this.getUploadClientOptions();return Te(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...h,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},d=await this.$["*uploadQueue"].add(u);t.setMultipleValues({fileInfo:d,isUploading:!1,fileName:d.originalFilename,fileSize:d.size,isImage:d.isImage,mimeType:(l=(o=(n=d.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:d.mimeType,uuid:d.uuid,cdnUrl:d.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof I?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};Z.template=`
{{itemName}}{{errorText}}
`;Z.activeInstances=new Set;var It=class extends w{constructor(){super(...arguments);c(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let s=this.getCssData(`--icon-${t}`);s&&(this.$.path=s)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};It.template=``;It.bindAttributes({name:"name",size:"size"});var te=class extends w{constructor(){super(...arguments);c(this,"_value",0);c(this,"_unknownMode",!1);c(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};te.template='
';var ee=class extends w{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};c(ee,"template",`Powered by Uploadcare`);var Et=class extends x{constructor(){super(...arguments);c(this,"processInnerHtml",!0);c(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Et.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let s=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of s){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=s.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let s=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await ni(s,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};Et.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var nr="https://ucarecdn.com",or="https://upload.uploadcare.com",lr="https://social.uploadcare.com",Ut=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:nr,baseUrl:or,socialBaseUrl:lr,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var j=e=>String(e),X=e=>Number(e),M=e=>typeof e=="boolean"?e:e==="true"||e===""?!0:e==="false"?!1:!!e,ar=e=>e==="auto"?e:M(e),cr={pubkey:j,multiple:M,multipleMin:X,multipleMax:X,confirmUpload:M,imgOnly:M,accept:j,externalSourcesPreferredTypes:j,store:ar,cameraMirror:M,sourceList:j,maxLocalFileSizeBytes:X,thumbSize:X,showEmptyList:M,useLocalImageEditor:M,useCloudImageEditor:M,removeCopyright:M,modalScrollLock:M,modalBackdropStrokes:M,sourceListWrap:M,remoteTabSessionKey:j,cdnCname:j,baseUrl:j,socialBaseUrl:j,secureSignature:j,secureExpire:j,secureDeliveryProxy:j,retryThrottledRequestMaxTimes:X,multipartMinFileSize:X,multipartChunkSize:X,maxConcurrentRequests:X,multipartMaxConcurrentRequests:X,multipartMaxAttempts:X,checkForUrlDuplicates:M,saveUrlForRecurrentUploads:M,groupOutput:M,userAgentIntegration:j},wi=(e,i)=>{if(!(typeof i=="undefined"||i===null))return cr[e](i)};var ie=Object.keys(Ut),ur=["metadata"],dr=e=>ur.includes(e),Pe=ie.filter(e=>!dr(e)),hr={...Object.fromEntries(Pe.map(e=>[nt(e),e])),...Object.fromEntries(Pe.map(e=>[e.toLowerCase(),e]))},pr={...Object.fromEntries(ie.map(e=>[nt(e),U(e)])),...Object.fromEntries(ie.map(e=>[e.toLowerCase(),U(e)]))},se=class extends w{constructor(){super(...arguments);c(this,"ctxOwner",!0);c(this,"init$",{...this.init$,...Object.fromEntries(Object.entries(Ut).map(([t,s])=>[U(t),s]))})}initCallback(){super.initCallback();for(let t of ie){let s=this,r="__"+t;s[r]=s[t],Object.defineProperty(this,t,{set:n=>{if(s[r]=n,Pe.includes(t)){let o=[...new Set([nt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[U(t)]!==n&&(typeof n=="undefined"||n===null?this.$[U(t)]=Ut[t]:this.$[U(t)]=n)},get:()=>this.$[U(t)]}),typeof s[t]!="undefined"&&s[t]!==null&&(s[t]=s[r])}}attributeChangedCallback(t,s,r){if(s===r)return;let n=hr[t],o=wi(n,r),l=o!=null?o:Ut[n],a=this;a[n]=l}};se.bindAttributes(pr);var Me=class extends x{};export{se as Config,ee as Copyright,Et as DataOutput,Ot as DropArea,Z as FileItem,qt as FileUploaderMinimal,It as Icon,Qt as MessageBox,te as ProgressBar,Re as StartFrom,Me as UploadCtxProvider,Zt as UploadList,Oi as registerBlocks}; \ No newline at end of file +var Ii=Object.defineProperty;var Ui=(e,i,t)=>i in e?Ii(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t;var u=(e,i,t)=>(Ui(e,typeof i!="symbol"?i+"":i,t),t),le=(e,i,t)=>{if(!i.has(e))throw TypeError("Cannot "+t)};var L=(e,i,t)=>(le(e,i,"read from private field"),t?t.call(e):i.get(e)),at=(e,i,t)=>{if(i.has(e))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(e):i.set(e,t)},vt=(e,i,t,s)=>(le(e,i,"write to private field"),s?s.call(e,t):i.set(e,t),t);var Rt=(e,i,t)=>(le(e,i,"access private method"),t);function Li(e){for(let i in e){let t=[...i].reduce((s,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),s+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),e[i].reg&&e[i].reg(t)}}var Ri=Object.defineProperty,ki=(e,i,t)=>i in e?Ri(e,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[i]=t,ue=(e,i,t)=>(ki(e,typeof i!="symbol"?i+"":i,t),t);function Mi(e){let i=t=>{var s;for(let r in t)((s=t[r])==null?void 0:s.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(e)}var E=class{constructor(e){e.constructor===Object?this.store=Mi(e):(this._storeIsProxy=!0,this.store=e),this.callbackMap=Object.create(null)}static warn(e,i){console.warn(`Symbiote Data: cannot ${e}. Prop name: `+i)}read(e){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(E.warn("read",e),null):this.store[e]}has(e){return this._storeIsProxy?this.store[e]!==void 0:this.store.hasOwnProperty(e)}add(e,i,t=!1){!t&&Object.keys(this.store).includes(e)||(this.store[e]=i,this.notify(e))}pub(e,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(e)){E.warn("publish",e);return}this.store[e]=i,this.notify(e)}multiPub(e){for(let i in e)this.pub(i,e[i])}notify(e){this.callbackMap[e]&&this.callbackMap[e].forEach(i=>{i(this.store[e])})}sub(e,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(e)?(E.warn("subscribe",e),null):(this.callbackMap[e]||(this.callbackMap[e]=new Set),this.callbackMap[e].add(i),t&&i(this.store[e]),{remove:()=>{this.callbackMap[e].delete(i),this.callbackMap[e].size||delete this.callbackMap[e]},callback:i})}static registerCtx(e,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(e),E.globalStore.set(i,t)),t}static deleteCtx(e){E.globalStore.delete(e)}static getCtx(e,i=!0){return E.globalStore.get(e)||(i&&console.warn('State: wrong context UID - "'+e+'"'),null)}};E.globalStore=new Map;var _=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),je="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Pi=je.length-1,Tt=class{static generate(e="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Ni(e,i){[...e.querySelectorAll(`[${_.REPEAT_ATTR}]`)].forEach(t=>{let s=t.getAttribute(_.REPEAT_ITEM_TAG_ATTR),r;if(s&&(r=window.customElements.get(s)),!r){r=class extends i.BaseComponent{constructor(){super(),s||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(s)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(_.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,h=c=>{c.forEach((f,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(f)});else for(let p in f)l[m][p]=f[p];else{a||(a=new DocumentFragment);let p=new r;Object.assign(p.init$,f),a.appendChild(p)}}),a&&t.appendChild(a);let d=l.slice(c.length,l.length);for(let f of d)f.remove()};if(o.constructor===Array)h(o);else if(o.constructor===Object){let c=[];for(let d in o){let f=o[d];Object.defineProperty(f,"_KEY_",{value:d,enumerable:!0}),c.push(f)}h(c)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(_.REPEAT_ATTR),t.removeAttribute(_.REPEAT_ITEM_TAG_ATTR)})}var Fe="__default__";function $i(e,i){if(i.shadowRoot)return;let t=[...e.querySelectorAll("slot")];if(!t.length)return;let s={};t.forEach(r=>{let n=r.getAttribute("name")||Fe;s[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=Fe;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=s[o])==null||n.fr.appendChild(r)}),Object.values(s).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function Fi(e,i){[...e.querySelectorAll(`[${_.EL_REF_ATTR}]`)].forEach(t=>{let s=t.getAttribute(_.EL_REF_ATTR);i.ref[s]=t,t.removeAttribute(_.EL_REF_ATTR)})}function Vi(e,i){[...e.querySelectorAll(`[${_.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(_.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Di(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(c=>c.trim()),l=o[0],a;l.indexOf(_.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(_.ATTR_BIND_PRFX,""));let h=o[1].split(",").map(c=>c.trim());for(let c of h){let d;c.startsWith("!!")?(d="double",c=c.replace("!!","")):c.startsWith("!")&&(d="single",c=c.replace("!","")),i.sub(c,f=>{d==="double"?f=!!f:d==="single"&&(f=!f),a?(f==null?void 0:f.constructor)===Boolean?f?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,f):ze(t,l,f)||(t[_.SET_LATER_KEY]||(t[_.SET_LATER_KEY]=Object.create(null)),t[_.SET_LATER_KEY][l]=f)})}}),t.removeAttribute(_.BIND_ATTR)})}var kt="{{",wt="}}",ji="skip-text";function zi(e){let i,t=[],s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(ji))&&r.textContent.includes(kt)&&r.textContent.includes(wt)&&1}});for(;i=s.nextNode();)t.push(i);return t}var Hi=function(e,i){zi(e).forEach(s=>{let r=[],n;for(;s.textContent.includes(wt);)s.textContent.startsWith(kt)?(n=s.textContent.indexOf(wt)+wt.length,s.splitText(n),r.push(s)):(n=s.textContent.indexOf(kt),s.splitText(n)),s=s.nextSibling;r.forEach(o=>{let l=o.textContent.replace(kt,"").replace(wt,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Wi=[Ni,$i,Fi,Vi,Hi],Mt="'",pt='"',Xi=/\\([0-9a-fA-F]{1,6} ?)/g;function Bi(e){return(e[0]===pt||e[0]===Mt)&&(e[e.length-1]===pt||e[e.length-1]===Mt)}function Gi(e){return(e[0]===pt||e[0]===Mt)&&(e=e.slice(1)),(e[e.length-1]===pt||e[e.length-1]===Mt)&&(e=e.slice(0,-1)),e}function qi(e){let i="",t="";for(var s=0;sString.fromCodePoint(parseInt(s.trim(),16))),i=i.replaceAll(`\\ +`,"\\n"),i=qi(i),i=pt+i+pt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${e}`)}}var Ve=0,ft=null,Y=null,tt=class extends HTMLElement{constructor(){super(),ue(this,"updateCssData",()=>{var e;this.dropCssDataCache(),(e=this.__boundCssProps)==null||e.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return tt}initCallback(){}__initCallback(){var e;this.__initialized||(this.__initialized=!0,(e=this.initCallback)==null||e.call(this))}render(e,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(_.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?e=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(e||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(e==null?void 0:e.constructor)===DocumentFragment)t=e;else if((e==null?void 0:e.constructor)===String){let r=document.createElement("template");r.innerHTML=e,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let s=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=s,this.shadowRoot.prepend(r)}else s()}addTemplateProcessor(e){this.tplProcessors.add(e)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=Tt.generate(),this.style.setProperty(_.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(_.CSS_CTX_PROP,!0)}get ctxName(){var e;let i=((e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(e,i){let t,s;if(e.startsWith(_.EXT_DATA_CTX_PRFX))t=i.nodeCtx,s=e.replace(_.EXT_DATA_CTX_PRFX,"");else if(e.includes(_.NAMED_DATA_CTX_SPLTR)){let r=e.split(_.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),s=r[1]}else t=i.localCtx,s=e;return{ctx:t,name:s}}sub(e,i,t=!0){let s=n=>{this.isConnected&&i(n)},r=tt.__parseProp(e,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,s,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,s,t))})}notify(e){let i=tt.__parseProp(e,this);i.ctx.notify(i.name)}has(e){let i=tt.__parseProp(e,this);return i.ctx.has(i.name)}add(e,i,t=!1){let s=tt.__parseProp(e,this);s.ctx.add(s.name,i,t)}add$(e,i=!1){for(let t in e)this.add(t,e[t],i)}get $(){if(!this.__stateProxy){let e=Object.create(null);this.__stateProxy=new Proxy(e,{set:(i,t,s)=>{let r=tt.__parseProp(t,this);return r.ctx.pub(r.name,s),!0},get:(i,t)=>{let s=tt.__parseProp(t,this);return s.ctx.read(s.name)}})}return this.__stateProxy}set$(e,i=!1){for(let t in e){let s=e[t];i||![String,Number,Boolean].includes(s==null?void 0:s.constructor)?this.$[t]=s:this.$[t]!==s&&(this.$[t]=s)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(_.CTX_OWNER_ATTR)&&this.getAttribute(_.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let e=this.constructor.__attrDesc;if(e)for(let i of Object.values(e))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(_.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(_.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(_.NAMED_DATA_CTX_SPLTR)){let t=i.split(_.NAMED_DATA_CTX_SPLTR),s=t[0].trim(),r=t[1].trim();if(s&&r){let n=E.getCtx(s,!1);n||(n=E.registerCtx({},s)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var e;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(e=this.getAttribute(_.CTX_NAME_ATTR))==null?void 0:e.trim();if(i&&this.style.setProperty(_.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[_.SET_LATER_KEY]){for(let t in this[_.SET_LATER_KEY])ze(this,t,this[_.SET_LATER_KEY][t]);delete this[_.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Wi)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${_.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(_.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let e of this.allSubs)e.remove(),this.allSubs.delete(e);for(let e of this.tplProcessors)this.tplProcessors.delete(e);Y==null||Y.delete(this.updateCssData),Y!=null&&Y.size||(ft==null||ft.disconnect(),ft=null,Y=null)},100)))}static reg(e,i=!1){e||(Ve++,e=`${_.AUTO_TAG_PRFX}-${Ve}`),this.__tag=e;let t=window.customElements.get(e);if(t){!i&&t!==this&&console.warn([`Element with tag name "${e}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(e,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(e){this.observedAttributes=Object.keys(e),this.__attrDesc=e}attributeChangedCallback(e,i,t){var s;if(i===t)return;let r=(s=this.constructor.__attrDesc)==null?void 0:s[e];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[e]=t}getCssData(e,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(e)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(e).trim();try{this.__cssDataCache[e]=Ki(t)}catch{!i&&console.warn(`CSS Data error: ${e}`),this.__cssDataCache[e]=null}}return this.__cssDataCache[e]}__extractCssName(e){return e.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){Y||(Y=new Set),Y.add(this.updateCssData),ft||(ft=new MutationObserver(e=>{e[0].type==="attributes"&&Y.forEach(i=>{i()})}),ft.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(e,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(e);let t=this.getCssData(this.__extractCssName(e),!0);t===null&&(t=i),this.add(e,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(e,i,t){let s="__"+e;this[s]=this[e],Object.defineProperty(this,e,{set:r=>{this[s]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[s]}),this[e]=this[s]}static set shadowStyles(e){let i=new Blob([e],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(e){if(!this.__rootStylesLink){let i=new Blob([e],{type:"text/css"}),t=URL.createObjectURL(i),s=document.createElement("link");s.href=t,s.rel="stylesheet",this.__rootStylesLink=s}}},ce=tt;ue(ce,"template");var ae=class{static _print(e){console.warn(e)}static setDefaultTitle(e){this.defaultTitle=e}static setRoutingMap(e){Object.assign(this.appMap,e);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(e){this.__routingEventName=e}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let e={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))e.route=t.replace("?","");else if(t.includes("=")){let s=t.split("=");e.options[s[0]]=decodeURI(s[1])}else e.options[t]=!0}),e}static notify(){let e=this.readAddressBar(),i=this.appMap[e.route];if(i&&i.title&&(document.title=i.title),e.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${e.route}" not found...`);return}let t=new CustomEvent(ae.routingEventName,{detail:{route:e.route,options:Object.assign(i||{},e.options)}});window.dispatchEvent(t)}static reflect(e,i={}){let t=this.appMap[e];if(!t){this._print("Wrong route: "+e);return}let s="?"+e;for(let n in i)i[n]===!0?s+=this.separator+n:s+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,s),document.title=r}static applyRoute(e,i={}){this.reflect(e,i),this.notify()}static setSeparator(e){this._separator=e}static get separator(){return this._separator||"&"}static createRouterData(e,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},e);return window.addEventListener(this.routingEventName,s=>{var r;t.multiPub({route:s.detail.route,options:s.detail.options,title:((r=s.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),ae.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};ae.appMap=Object.create(null);var He="idb-store-ready",Yi="symbiote-db",Ji="symbiote-idb-update_",Qi=class{_notifyWhenReady(e=null){window.dispatchEvent(new CustomEvent(He,{detail:{dbName:this.name,storeName:this.storeName,event:e}}))}get _updEventName(){return Ji+this.name}_getUpdateEvent(e){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:e}})}_notifySubscribers(e){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,e),window.dispatchEvent(this._getUpdateEvent(e))}constructor(e,i){this.name=e,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=s=>{this._notifyWhenReady(s)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(e){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(e);return new Promise((s,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?s(n.target.result._value):(s(null),console.warn(`IDB: cannot read "${e}"`))},t.onerror=n=>{r(n)}})}write(e,i,t=!1){let s={_key:e,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(s);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(e),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(e,i=!1){let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(e);return new Promise((r,n)=>{s.onsuccess=o=>{i||this._notifySubscribers(e),r(o)},s.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,s)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{s(r)}})}subscribe(e,i){this._subscriptionsMap[e]||(this._subscriptionsMap[e]=new Set);let t=this._subscriptionsMap[e];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[e]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,We.clear(this.name)}},We=class{static get readyEventName(){return He}static open(e=Yi,i="store"){let t=e+"/"+i;return this._reg[t]||(this._reg[t]=new Qi(e,i)),this._reg[t]}static clear(e){window.indexedDB.deleteDatabase(e);for(let i in this._reg)i.split("/")[0]===e&&delete this._reg[i]}};ue(We,"_reg",Object.create(null));function z(e,i){let t,s=(...r)=>{clearTimeout(t),t=setTimeout(()=>e(...r),i)};return s.cancel=()=>{clearTimeout(t)},s}var Zi="--uploadcare-blocks-window-height",Pt="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function he(){return typeof window[Pt]=="undefined"?!1:!!window[Pt]}function Xe(){if(he())return;let e=()=>{document.documentElement.style.setProperty(Zi,`${window.innerHeight}px`),window[Pt]=!0},i=z(e,100);return window.addEventListener("resize",i,{passive:!0}),e(),()=>{window[Pt]=!1,window.removeEventListener("resize",i)}}var ts=e=>e,de="{{",Ge="}}",Be="plural:";function fe(e,i,t={}){var o;let{openToken:s=de,closeToken:r=Ge,transform:n=ts}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();e=e.replaceAll(s+l+r,typeof a=="string"?n(a):a)}return e}function qe(e){let i=[],t=e.indexOf(de);for(;t!==-1;){let s=e.indexOf(Ge,t),r=e.substring(t+2,s);if(r.startsWith(Be)){let n=e.substring(t+2,s).replace(Be,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=e.indexOf(de,s)}return i}function Ke(e){return Object.prototype.toString.call(e)==="[object Object]"}var es=/\W|_/g;function is(e){return e.split(es).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Ye(e,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(e)?e.map(t=>Q(t,{ignoreKeys:i})):e}function Q(e,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(e))return Ye(e,{ignoreKeys:i});if(!Ke(e))return e;let t={};for(let s of Object.keys(e)){let r=e[s];if(i.includes(s)){t[s]=r;continue}Ke(r)?r=Q(r,{ignoreKeys:i}):Array.isArray(r)&&(r=Ye(r,{ignoreKeys:i})),t[is(s)]=r}return t}var ss=e=>new Promise(i=>setTimeout(i,e));function Ce({libraryName:e,libraryVersion:i,userAgent:t,publicKey:s="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:s,libraryName:e,libraryVersion:i,languageName:n,integration:r});let o=[e,i,s].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var rs={factor:2,time:100};function ns(e,i=rs){let t=0;function s(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>ss(l!=null?l:n).then(()=>(t+=1,s(r)))})}return s(e)}var yt=class extends Error{constructor(t){super();u(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,yt.prototype),this.originalProgressEvent=t}},$t=(e,i)=>{e&&(e.aborted?Promise.resolve().then(i):e.addEventListener("abort",()=>i(),{once:!0}))},et=class extends Error{constructor(t="Request canceled"){super(t);u(this,"isCancel",!0);Object.setPrototypeOf(this,et.prototype)}},os=500,Qe=({check:e,interval:i=os,timeout:t,signal:s})=>new Promise((r,n)=>{let o,l;$t(s,()=>{o&&clearTimeout(o),n(new et("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new et("Timed out"))},t));let a=()=>{try{Promise.resolve(e(s)).then(h=>{h?(l&&clearTimeout(l),r(h)):o=setTimeout(a,i)}).catch(h=>{l&&clearTimeout(l),n(h)})}catch(h){l&&clearTimeout(l),n(h)}};o=setTimeout(a,0)}),C={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Ft="application/octet-stream",Ze="original",st=({method:e,url:i,data:t,headers:s={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,h=(e==null?void 0:e.toUpperCase())||"GET",c=!1;a.open(h,i,!0),s&&Object.entries(s).forEach(d=>{let[f,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(f,m)}),a.responseType="text",$t(r,()=>{c=!0,a.abort(),l(new et)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:h,url:i,data:t,headers:s||void 0,signal:r,onProgress:n},f=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};f.forEach(function(T){let w=T.split(": "),b=w.shift(),g=w.join(": ");b&&typeof b!="undefined"&&(m[b]=g)});let p=a.response,y=a.status;o({request:d,data:p,headers:m,status:y})}},a.onerror=d=>{c||l(new yt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function ls(e,...i){return e}var as=({name:e})=>e?[e]:[],us=ls,cs=()=>new FormData,ti=e=>!1,Vt=e=>typeof Blob!="undefined"&&e instanceof Blob,jt=e=>typeof File!="undefined"&&e instanceof File,zt=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&"uri"in e&&typeof e.uri=="string",At=e=>Vt(e)||jt(e)||ti()||zt(e),hs=e=>typeof e=="string"||typeof e=="number"||typeof e=="undefined",ds=e=>!!e&&typeof e=="object"&&!Array.isArray(e),fs=e=>!!e&&typeof e=="object"&&"data"in e&&At(e.data);function ps(e,i,t){if(fs(t)){let{name:s,contentType:r}=t,n=us(t.data,s,r!=null?r:Ft),o=as({name:s,contentType:r});e.push([i,n,...o])}else if(ds(t))for(let[s,r]of Object.entries(t))typeof r!="undefined"&&e.push([`${i}[${s}]`,String(r)]);else hs(t)&&t&&e.push([i,t.toString()])}function ms(e){let i=[];for(let[t,s]of Object.entries(e))ps(i,t,s);return i}function Ee(e){let i=cs(),t=ms(e);for(let s of t){let[r,n,...o]=s;i.append(r,n,...o)}return i}var U=class extends Error{constructor(t,s,r,n,o){super();u(this,"isCancel");u(this,"code");u(this,"request");u(this,"response");u(this,"headers");this.name="UploadClientError",this.message=t,this.code=s,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,U.prototype)}},_s=e=>{let i=new URLSearchParams;for(let[t,s]of Object.entries(e))s&&typeof s=="object"&&!Array.isArray(s)?Object.entries(s).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(s)?s.forEach(r=>{i.append(`${t}[]`,r)}):typeof s=="string"&&s?i.set(t,s):typeof s=="number"&&i.set(t,s.toString());return i.toString()},J=(e,i,t)=>{let s=new URL(e);return s.pathname=(s.pathname+i).replace("//","/"),t&&(s.search=_s(t)),s.toString()},gs="6.6.1",bs="UploadcareUploadClient",ys=gs;function ht(e){return Ce({libraryName:bs,libraryVersion:ys,...e})}var Cs="RequestThrottledError",Je=15e3,Es=1e3;function vs(e){let{headers:i}=e||{};if(!i||typeof i["retry-after"]!="string")return Je;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:Je}function rt(e,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:s}=i;return ns(({attempt:r,retry:n})=>e().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===Cs&&r{let i="";return(Vt(e)||jt(e)||zt(e))&&(i=e.type),i||Ft},ii=e=>{let i="";return jt(e)&&e.name?i=e.name:Vt(e)||ti()?i="":zt(e)&&e.name&&(i=e.name),i||Ze};function ve(e){return typeof e=="undefined"||e==="auto"?"auto":e?"1":"0"}function ws(e,{publicKey:i,fileName:t,contentType:s,baseURL:r=C.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:h,source:c="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=C.retryNetworkErrorMaxTimes,metadata:y}){return rt(()=>st({method:"POST",url:J(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":ht({publicKey:i,integration:d,userAgent:f})},data:Ee({file:{data:e,name:t||ii(e),contentType:s||ei(e)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:ve(l),signature:n,expire:o,source:c,metadata:y}),signal:a,onProgress:h}).then(({data:T,headers:w,request:b})=>{let g=Q(JSON.parse(T));if("error"in g)throw new U(g.error.content,g.error.errorCode,b,g,w);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var _e;(function(e){e.Token="token",e.FileInfo="file_info"})(_e||(_e={}));function Ts(e,{publicKey:i,baseURL:t=C.baseURL,store:s,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:h="url",signal:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=C.retryNetworkErrorMaxTimes,metadata:y}){return rt(()=>st({method:"POST",headers:{"X-UC-User-Agent":ht({publicKey:i,integration:d,userAgent:f})},url:J(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:e,store:ve(s),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:h,metadata:y}),signal:c}).then(({data:T,headers:w,request:b})=>{let g=Q(JSON.parse(T));if("error"in g)throw new U(g.error.content,g.error.errorCode,b,g,w);return g}),{retryNetworkErrorMaxTimes:p,retryThrottledRequestMaxTimes:m})}var $;(function(e){e.Unknown="unknown",e.Waiting="waiting",e.Progress="progress",e.Error="error",e.Success="success"})($||($={}));var As=e=>"status"in e&&e.status===$.Error;function xs(e,{publicKey:i,baseURL:t=C.baseURL,signal:s,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=C.retryNetworkErrorMaxTimes}={}){return rt(()=>st({method:"GET",headers:i?{"X-UC-User-Agent":ht({publicKey:i,integration:r,userAgent:n})}:void 0,url:J(t,"/from_url/status/",{jsonerrors:1,token:e}),signal:s}).then(({data:a,headers:h,request:c})=>{let d=Q(JSON.parse(a));if("error"in d&&!As(d))throw new U(d.error.content,void 0,c,d,h);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Ss(e,{publicKey:i,baseURL:t=C.baseURL,jsonpCallback:s,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:h,retryThrottledRequestMaxTimes:c=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=C.retryNetworkErrorMaxTimes}){return rt(()=>st({method:"POST",headers:{"X-UC-User-Agent":ht({publicKey:i,integration:a,userAgent:h})},url:J(t,"/group/",{jsonerrors:1,pub_key:i,files:e,callback:s,signature:r,expire:n,source:l}),signal:o}).then(({data:f,headers:m,request:p})=>{let y=Q(JSON.parse(f));if("error"in y)throw new U(y.error.content,y.error.errorCode,p,y,m);return y}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:c})}function si(e,{publicKey:i,baseURL:t=C.baseURL,signal:s,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=C.retryNetworkErrorMaxTimes}){return rt(()=>st({method:"GET",headers:{"X-UC-User-Agent":ht({publicKey:i,integration:n,userAgent:o})},url:J(t,"/info/",{jsonerrors:1,pub_key:i,file_id:e,source:r}),signal:s}).then(({data:h,headers:c,request:d})=>{let f=Q(JSON.parse(h));if("error"in f)throw new U(f.error.content,f.error.errorCode,d,f,c);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Os(e,{publicKey:i,contentType:t,fileName:s,multipartChunkSize:r=C.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:h,source:c="local",integration:d,userAgent:f,retryThrottledRequestMaxTimes:m=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:p=C.retryNetworkErrorMaxTimes,metadata:y}){return rt(()=>st({method:"POST",url:J(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":ht({publicKey:i,integration:d,userAgent:f})},data:Ee({filename:s||Ze,size:e,content_type:t||Ft,part_size:r,UPLOADCARE_STORE:ve(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:c,metadata:y}),signal:h}).then(({data:T,headers:w,request:b})=>{let g=Q(JSON.parse(T));if("error"in g)throw new U(g.error.content,g.error.errorCode,b,g,w);return g.parts=Object.keys(g.parts).map(D=>g.parts[D]),g}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})}function Is(e,i,{contentType:t,signal:s,onProgress:r,retryThrottledRequestMaxTimes:n=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=C.retryNetworkErrorMaxTimes}){return rt(()=>st({method:"PUT",url:i,data:e,onProgress:r,signal:s,headers:{"Content-Type":t||Ft}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Us(e,{publicKey:i,baseURL:t=C.baseURL,source:s="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=C.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=C.retryNetworkErrorMaxTimes}){return rt(()=>st({method:"POST",url:J(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":ht({publicKey:i,integration:n,userAgent:o})},data:Ee({uuid:e,UPLOADCARE_PUB_KEY:i,source:s}),signal:r}).then(({data:h,headers:c,request:d})=>{let f=Q(JSON.parse(h));if("error"in f)throw new U(f.error.content,f.error.errorCode,d,f,c);return f}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function we({file:e,publicKey:i,baseURL:t,source:s,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:h}){return Qe({check:c=>si(e,{publicKey:i,baseURL:t,signal:c,source:s,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(h&&h({isComputable:!0,value:1}),!1)),signal:a})}var it=class{constructor(i,{baseCDN:t=C.baseCDN,fileName:s}={}){u(this,"uuid");u(this,"name",null);u(this,"size",null);u(this,"isStored",null);u(this,"isImage",null);u(this,"mimeType",null);u(this,"cdnUrl",null);u(this,"s3Url",null);u(this,"originalFilename",null);u(this,"imageInfo",null);u(this,"videoInfo",null);u(this,"contentInfo",null);u(this,"metadata",null);u(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=J(t,`${r}/`),l=n?J(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=s||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},Ls=(e,{publicKey:i,fileName:t,baseURL:s,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:h,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,baseCDN:y,metadata:T})=>ws(e,{publicKey:i,fileName:t,contentType:l,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:h,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:T}).then(({file:w})=>we({file:w,publicKey:i,baseURL:s,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:h,signal:a})).then(w=>new it(w,{baseCDN:y})),Rs=(e,{publicKey:i,fileName:t,baseURL:s,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:c,baseCDN:d})=>si(e,{publicKey:i,baseURL:s,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:h,retryNetworkErrorMaxTimes:c}).then(f=>new it(f,{baseCDN:d,fileName:t})).then(f=>(n&&n({isComputable:!0,value:1}),f)),ks=(e,{signal:i}={})=>{let t=null,s=null,r=e.map(()=>new AbortController),n=o=>()=>{s=o,r.forEach((l,a)=>a!==o&&l.abort())};return $t(i,()=>{r.forEach(o=>o.abort())}),Promise.all(e.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(h=>(a(),h)).catch(h=>(t=h,null))})).then(o=>{if(s===null)throw t;return o[s]})},Ms=window.WebSocket,ge=class{constructor(){u(this,"events",Object.create({}))}emit(i,t){var s;(s=this.events[i])==null||s.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(s=>s!==t):this.events[i]=[]}},Ps=(e,i)=>e==="success"?{status:$.Success,...i}:e==="progress"?{status:$.Progress,...i}:{status:$.Error,...i},be=class{constructor(i,t=3e4){u(this,"key");u(this,"disconnectTime");u(this,"ws");u(this,"queue",[]);u(this,"isConnected",!1);u(this,"subscribers",0);u(this,"emmitter",new ge);u(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Ms(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let s=JSON.parse(t.data.toString());switch(s.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(s.channel,Ps(s.event,JSON.parse(s.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let s=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(s)}subscribe(i,t){this.subscribers+=1,this.connect();let s=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:s}};this.emmitter.on(s,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,s={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(s.event,s.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},pe=null,Te=e=>{if(!pe){let i=typeof window=="undefined"?0:3e4;pe=new be(e,i)}return pe},Ds=e=>{Te(e).connect()};function Ns({token:e,publicKey:i,baseURL:t,integration:s,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return Qe({check:h=>xs(e,{publicKey:i,baseURL:t,integration:s,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:h}).then(c=>{switch(c.status){case $.Error:return new U(c.error,c.errorCode);case $.Waiting:return!1;case $.Unknown:return new U(`Token "${e}" was not found.`);case $.Progress:return l&&(c.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:c.done/c.total})),!1;case $.Success:return l&&l({isComputable:!0,value:c.done/c.total}),c;default:throw new Error("Unknown status")}}),signal:a})}var $s=({token:e,pusherKey:i,signal:t,onProgress:s})=>new Promise((r,n)=>{let o=Te(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(e)};$t(t,()=>{a(),n(new et("pusher cancelled"))}),o.subscribe(e,h=>{switch(h.status){case $.Progress:{s&&(h.total==="unknown"?s({isComputable:!1}):s({isComputable:!0,value:h.done/h.total}));break}case $.Success:{a(),s&&s({isComputable:!0,value:h.done/h.total}),r(h);break}case $.Error:a(),n(new U(h.msg,h.error_code))}})}),Fs=(e,{publicKey:i,fileName:t,baseURL:s,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:h,signal:c,onProgress:d,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,pusherKey:T=C.pusherKey,metadata:w})=>Promise.resolve(Ds(T)).then(()=>Ts(e,{publicKey:i,fileName:t,baseURL:s,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:h,signal:c,source:f,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,metadata:w})).catch(b=>{let g=Te(T);return g==null||g.disconnect(),Promise.reject(b)}).then(b=>b.type===_e.FileInfo?b:ks([({signal:g})=>Ns({token:b.token,publicKey:i,baseURL:s,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,onProgress:d,signal:g}),({signal:g})=>$s({token:b.token,pusherKey:T,signal:g,onProgress:d})],{signal:c})).then(b=>{if(b instanceof U)throw b;return b}).then(b=>we({file:b.uuid,publicKey:i,baseURL:s,integration:m,userAgent:p,retryThrottledRequestMaxTimes:y,onProgress:d,signal:c})).then(b=>new it(b,{baseCDN:r})),me=new WeakMap,Vs=async e=>{if(me.has(e))return me.get(e);let i=await fetch(e.uri).then(t=>t.blob());return me.set(e,i),i},ri=async e=>{if(jt(e)||Vt(e))return e.size;if(zt(e))return(await Vs(e)).size;throw new Error("Unknown file type. Cannot determine file size.")},js=(e,i=C.multipartMinFileSize)=>e>=i,ni=e=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!At(e)&&t.test(e)},oi=e=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!At(e)&&t.test(e)},zs=(e,i)=>new Promise((t,s)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let h=i.length-l.length,c=l.shift();c&&c().then(d=>{n||(r[h]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,s(d)})};for(let h=0;h{let r=s*i,n=Math.min(r+s,t);return e.slice(r,n)},Ws=async(e,i,t)=>s=>Hs(e,s,i,t),Xs=(e,i,{publicKey:t,contentType:s,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Is(e,i,{publicKey:t,contentType:s,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),Bs=async(e,{publicKey:i,fileName:t,fileSize:s,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:h,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,contentType:y,multipartChunkSize:T=C.multipartChunkSize,maxConcurrentRequests:w=C.maxConcurrentRequests,baseCDN:b,metadata:g})=>{let D=s!=null?s:await ri(e),G,lt=(I,j)=>{if(!h)return;G||(G=Array(I).fill(0));let q=N=>N.reduce((K,oe)=>K+oe,0);return N=>{N.isComputable&&(G[j]=N.value,h({isComputable:!0,value:q(G)/I}))}};return y||(y=ei(e)),Os(D,{publicKey:i,contentType:y,fileName:t||ii(e),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,metadata:g}).then(async({uuid:I,parts:j})=>{let q=await Ws(e,D,T);return Promise.all([I,zs(w,j.map((N,K)=>()=>Xs(q(K),N,{publicKey:i,contentType:y,onProgress:lt(j.length,K),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})))])}).then(([I])=>Us(I,{publicKey:i,baseURL:r,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p})).then(I=>I.isReady?I:we({file:I.uuid,publicKey:i,baseURL:r,source:c,integration:d,userAgent:f,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:p,onProgress:h,signal:a})).then(I=>new it(I,{baseCDN:b}))};async function Ae(e,{publicKey:i,fileName:t,baseURL:s=C.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartMinFileSize:y,multipartChunkSize:T,maxConcurrentRequests:w,baseCDN:b=C.baseCDN,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:D,pusherKey:G,metadata:lt}){if(At(e)){let I=await ri(e);return js(I,y)?Bs(e,{publicKey:i,contentType:p,multipartChunkSize:T,fileSize:I,fileName:t,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,maxConcurrentRequests:w,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:lt}):Ls(e,{publicKey:i,fileName:t,contentType:p,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:lt})}if(oi(e))return Fs(e,{publicKey:i,fileName:t,baseURL:s,baseCDN:b,checkForUrlDuplicates:g,saveUrlForRecurrentUploads:D,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,pusherKey:G,metadata:lt});if(ni(e))return Rs(e,{publicKey:i,fileName:t,baseURL:s,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b});throw new TypeError(`File uploading from "${e}" is not supported`)}var ye=class{constructor(i,t){u(this,"uuid");u(this,"filesCount");u(this,"totalSize");u(this,"isStored");u(this,"isImage");u(this,"cdnUrl");u(this,"files");u(this,"createdAt");u(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((s,r)=>s+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(s=>s.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},Gs=e=>{for(let i of e)if(!At(i))return!1;return!0},qs=e=>{for(let i of e)if(!ni(i))return!1;return!0},Ks=e=>{for(let i of e)if(!oi(i))return!1;return!0};function li(e,{publicKey:i,fileName:t,baseURL:s=C.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:y=C.multipartChunkSize,baseCDN:T=C.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:b,jsonpCallback:g}){if(!Gs(e)&&!Ks(e)&&!qs(e))throw new TypeError(`Group uploading from "${e}" is not supported`);let D,G=!0,lt=e.length,I=(j,q)=>{if(!a)return;D||(D=Array(j).fill(0));let N=K=>K.reduce((oe,Oi)=>oe+Oi)/j;return K=>{if(!K.isComputable||!G){G=!1,a({isComputable:!1});return}D[q]=K.value,a({isComputable:!0,value:N(D)})}};return Promise.all(e.map((j,q)=>Ae(j,{publicKey:i,fileName:t,baseURL:s,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:I(lt,q),source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:p,multipartChunkSize:y,baseCDN:T,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:b}))).then(j=>{let q=j.map(N=>N.uuid);return Ss(q,{publicKey:i,baseURL:s,jsonpCallback:g,secureSignature:r,secureExpire:n,signal:l,source:h,integration:c,userAgent:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m}).then(N=>new ye(N,j)).then(N=>(a&&a({isComputable:!0,value:1}),N))})}var ut,mt,ct,_t,gt,bt,Dt,Nt=class{constructor(i){at(this,bt);at(this,ut,1);at(this,mt,[]);at(this,ct,0);at(this,_t,new WeakMap);at(this,gt,new WeakMap);vt(this,ut,i)}add(i){return new Promise((t,s)=>{L(this,_t).set(i,t),L(this,gt).set(i,s),L(this,mt).push(i),Rt(this,bt,Dt).call(this)})}get pending(){return L(this,mt).length}get running(){return L(this,ct)}set concurrency(i){vt(this,ut,i),Rt(this,bt,Dt).call(this)}get concurrency(){return L(this,ut)}};ut=new WeakMap,mt=new WeakMap,ct=new WeakMap,_t=new WeakMap,gt=new WeakMap,bt=new WeakSet,Dt=function(){let i=L(this,ut)-L(this,ct);for(let t=0;t{L(this,_t).delete(s),L(this,gt).delete(s),vt(this,ct,L(this,ct)-1),Rt(this,bt,Dt).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var xe=()=>({"*blocksRegistry":new Set}),Se=e=>({...xe(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{e.set$({"*modalActive":!1,"*currentActivity":""})}}),Ht=e=>({...Se(e),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Nt(1)});function ai(e,i){[...e.querySelectorAll("[l10n]")].forEach(t=>{let s=t.getAttribute("l10n"),r="textContent";if(s.includes(":")){let o=s.split(":");r=o[0],s=o[1]}let n="l10n:"+s;i.__l10nKeys.push(n),i.add(n,s),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var H=e=>`*cfg/${e}`;var nt=e=>{var i;return(i=e.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var ui=new Set;function Wt(e){ui.has(e)||(ui.add(e),console.warn(e))}var Xt=(e,i)=>new Intl.PluralRules(e).select(i);var Oe="lr-",A=class extends ce{constructor(){super();u(this,"allowCustomTemplate",!0);u(this,"init$",xe());u(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let s of t)s.isConnected&&s.updateCssData()});this.activityType=null,this.addTemplateProcessor(ai),this.__l10nKeys=[]}l10n(t,s={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=qe(r);for(let l of n)s[l.variable]=this.pluralize(l.pluralKey,Number(s[l.countVariable]));return fe(r,s)}pluralize(t,s){let r=this.l10n("locale-name")||"en-US",n=Xt(r,s);return this.l10n(`${t}__${n}`)}applyL10nKey(t,s){let r="l10n:"+t;this.$[r]=s,this.__l10nKeys.push(t)}hasBlockInCtx(t){let s=this.$["*blocksRegistry"];for(let r of s)if(t(r))return!0;return!1}setForCtxTarget(t,s,r){this.hasBlockInCtx(n=>n.constructor.StateConsumerScope===t)&&(this.$[s]=r)}setActivity(t){if(this.hasBlockInCtx(s=>s.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Oe}${t}`,!0),he()||(this._destroyInnerHeightTracker=Xe()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,s=2){let r=["B","KB","MB","GB","TB"],n=h=>this.getCssData("--l10n-unit-"+h.toLowerCase(),!0)||h;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=s<0?0:s,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let s=this.cfg.secureDeliveryProxy;return s?fe(s,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(s,r)=>{let n=H(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Wt("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${nt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,s){let r=this.parseCfgProp(H(t));r.ctx.has(r.name)?this.sub(H(t),s):(this.bindCssData(`--cfg-${nt(t)}`),this.sub(`--cfg-${nt(t)}`,s))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Oe)?t:Oe+t)}};u(A,"StateConsumerScope",null),u(A,"className","");var Ie=class extends A{constructor(){super();u(this,"_handleBackdropClick",()=>{this._closeDialog()});u(this,"_closeDialog",()=>{this.setForCtxTarget(Ie.StateConsumerScope,"*modalActive",!1)});u(this,"_handleDialogClose",()=>{this._closeDialog()});u(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}},F=Ie;u(F,"StateConsumerScope","modal");F.template=``;var ci="active",xt="___ACTIVITY_IS_ACTIVE___",W=class extends A{constructor(){super(...arguments);u(this,"historyTracked",!1);u(this,"init$",Se(this));u(this,"_debouncedHistoryFlush",z(this._historyFlush.bind(this),10))}_deactivate(){var s;let t=W._activityRegistry[this.activityKey];this[xt]=!1,this.removeAttribute(ci),(s=t==null?void 0:t.deactivateCallback)==null||s.call(t)}_activate(){var s;let t=W._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[xt]=!0,this.setAttribute(ci,""),(s=t==null?void 0:t.activateCallback)==null||s.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[xt]?this._deactivate():this.activityType===t&&!this[xt]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!W._activityRegistry[this.activityKey]}get isActivityActive(){return this[xt]}registerActivity(t,s={}){let{onActivate:r,onDeactivate:n}=s;W._activityRegistry||(W._activityRegistry=Object.create(null)),W._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),W._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(W._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let s=t.pop();for(;s===this.activityType;)s=t.pop();this.$["*currentActivity"]=s,this.$["*history"]=t,s||this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!1)}}},v=W;u(v,"_activityRegistry",Object.create(null));v.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var Ys="css-src";function Js(e){return class extends e{constructor(){super(...arguments);u(this,"renderShadow",!0);u(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Ys);if(t){this.attachShadow({mode:"open"});let s=document.createElement("link");s.rel="stylesheet",s.type="text/css",s.href=t,s.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(s)}else console.error("Attribute `css-src`is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Bt=class extends Js(A){};var Gt=class extends Bt{constructor(){super(...arguments);u(this,"init$",Ht(this));u(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var qt=class extends Gt{constructor(){super(...arguments);u(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",s=>{s||(this.$["*currentActivity"]=t.initActivity||v.activities.START_FROM)}),this.sub("*uploadList",s=>{(s==null?void 0:s.length)>0?this.$["*currentActivity"]=v.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||v.activities.START_FROM}),this.subConfigValue("sourceList",s=>{s!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",s=>{s!==!1&&(this.cfg.confirmUpload=!1)})}};qt.template=``;var Ue=class extends v{constructor(){super(...arguments);u(this,"historyTracked",!0);u(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function hi(e,i,t){let s=e/i,r,n;s>t?(r=Math.round(i*t),n=i):(r=e,n=Math.round(e/t));let o=Math.round((e-r)/2),l=Math.round((i-n)/2);return o+r>e&&(r=e-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}var di=e=>{if(!e)return[];let[i,t]=e.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${e}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var ot=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var fi="blocks",pi="0.25.6";function mi(e){return Ce({...e,libraryName:fi,libraryVersion:pi})}var Qs=e=>{if(typeof e!="string"||!e)return"";let i=e.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},Zs=(...e)=>e.filter(i=>typeof i=="string"&&i).map(i=>Qs(i)).join("/-/"),Kt=(...e)=>{let i=Zs(...e);return i?`-/${i}/`:""};function _i(e){let i=new URL(e),t=i.pathname+i.search+i.hash,s=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return s>=0?n=t.slice(s):r>=0&&(n=t.slice(r+1)),n}function tr(e){let i=new URL(e),t=_i(e),s=gi(t)?bi(t).pathname:t;return i.pathname=i.pathname.replace(s,""),i.search="",i.hash="",i.toString()}function gi(e){return e.startsWith("http")}function bi(e){let i=new URL(e);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var Yt=(e,i,t)=>{let s=new URL(tr(e));if(t=t||_i(e),s.pathname.startsWith("//")&&(s.pathname=s.pathname.replace("//","/")),gi(t)){let r=bi(t);s.pathname=s.pathname+(i||"")+(r.pathname||""),s.search=r.search,s.hash=r.hash}else s.pathname=s.pathname+(i||"")+(t||"");return s.toString()},yi=(e,i)=>{let t=new URL(e);return t.pathname=i+"/",t.toString()};var Ct=(e,i=",")=>e.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var St=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Le=e=>e?e.filter(i=>typeof i=="string").map(i=>Ct(i)).flat():[],Re=(e,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),e.startsWith(t)):e===t),Ci=(e,i)=>i.some(t=>t.startsWith(".")?e.toLowerCase().endsWith(t.toLowerCase()):!1),ke=e=>{let i=e==null?void 0:e.type;return i?Re(i,St):!1};var X=1e3,dt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),Ot=e=>Math.ceil(e*100)/100,Ei=(e,i=dt.AUTO)=>{let t=i===dt.AUTO;if(i===dt.BYTE||t&&e{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!s){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};u(S,"_timeoutStore",Object.create(null));var vi="[Typed State] Wrong property name: ",er="[Typed State] Wrong property type: ",Jt=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||Tt.generate(),this.__schema=Object.keys(i).reduce((s,r)=>(s[r]=i[r].value,s),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(vi+i);return}let s=this.__typedSchema[i];if((t==null?void 0:t.constructor)===s.type||t instanceof s.type||s.nullable&&t===null){this.__data.pub(i,t);return}console.warn(er+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(vi+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Qt=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||Tt.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(s,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[s]||(t[s]=new Set),t[s].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var s;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(s=this.__handler)==null||s.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Jt(this.__typedSchema);for(let s in i)t.setValue(s,i[s]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(s=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(s,()=>{this.__notifyObservers(s,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,s){this.read(i).setValue(t,s)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(s=>{let r=this.read(s);i(r)&&t.push(s)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var wi=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:it,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var x=class extends v{constructor(){super(...arguments);u(this,"couldBeUploadCollectionOwner",!1);u(this,"isUploadCollectionOwner",!1);u(this,"init$",Ht(this));u(this,"__initialUploadMetadata",null);u(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);u(this,"_debouncedRunValidators",z(this._runValidators.bind(this),100));u(this,"_handleCollectionUpdate",t=>{let s=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>s.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=s.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=s.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,S.emit(new R({type:O.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=s.findItems(l=>!!l.getValue("fileInfo")),o=s.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(s.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&S.emit(new R({type:O.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&s.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{S.emit(new R({type:O.UPLOAD_ERROR,ctx:this.ctxName,data:s.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&s.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{S.emit(new R({type:O.VALIDATION_ERROR,ctx:this.ctxName,data:s.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&s.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{S.emit(new R({type:O.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){Wt("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let s=new Qt({typedSchema:wi,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",s)}let t=()=>this.hasBlockInCtx(s=>s instanceof x?s.isUploadCollectionOwner&&s.isConnected&&s!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(s,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=s.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",s=>{this.$["*uploadQueue"].concurrency=Number(s)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:s,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:s!=null?s:!1,source:n!=null?n:ot.API})}addFileFromUuid(t,{silent:s,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:s!=null?s:!1,source:n!=null?n:ot.API})}addFileFromObject(t,{silent:s,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:ke(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:s!=null?s:!1,source:n!=null?n:ot.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(s=>{this.uploadCollection.add({file:s,isImage:ke(s),mimeType:s.type,fileName:s.name,fileSize:s.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let s=Le([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?St:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=St.join(",")):this.fileInput.accept=s,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:ot.LOCAL})),this.$["*currentActivity"]=v.activities.UPLOAD_LIST,this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=Ct(this.cfg.sourceList)),t}initFlow(t=!1){var s,r;if((s=this.$["*uploadList"])!=null&&s.length&&!t)this.set$({"*currentActivity":v.activities.UPLOAD_LIST}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let n=this.sourceList[0];n==="local"?(this.$["*currentActivity"]=v.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(x.extSrcList).includes(n)?this.set$({"*currentActivityParams":{externalSourceType:n},"*currentActivity":v.activities.EXTERNAL}):this.$["*currentActivity"]=n,this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":v.activities.START_FROM}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0);S.emit(new R({type:O.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!1),S.emit(new R({type:O.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let s=this.cfg.imgOnly,r=this.cfg.accept,n=Le([...s?St:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Re(o,n),h=Ci(l,n);if(!a&&!h)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let s=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(s&&r&&r>s)return this.l10n("files-max-size-limit-error",{maxFileSize:Ei(s)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let s=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!s||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let s of this._validators){let r=s(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let s=this.uploadCollection.read(t);s&&this._runValidatorsForEntry(s)})}setInitialCrop(){let t=di(this.cfg.cropPreset);if(t){let[s]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,h=s.width/s.height,c=hi(l,a,h),d=Kt(`crop/${c.width}x${c.height}/${c.x},${c.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:Yt(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(f=>f.activityType===v.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=v.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var s;let t=(s=this.cfg.metadata)!=null?s:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:mi,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let s=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};s.push(a)}),s}};x.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});x.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...x.extSrcList});Object.values(O).forEach(e=>{let i=S.eName(e),t=z(s=>{if([O.UPLOAD_FINISH,O.REMOVE,O.CDN_MODIFICATION].includes(s.detail.type)){let n=E.getCtx(s.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let h=E.getCtx(a).store,c=h.fileInfo;if(c){let d={...c,cdnUrlModifiers:h.cdnUrlModifiers,cdnUrl:h.cdnUrl||c.cdnUrl};l.push(d)}}),S.emit(new R({type:O.DATA_OUTPUT,ctx:s.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});function ir(e){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let s=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=s,t.onprogress=s,t.readAsDataURL(e)}catch{i(!1)}})}function sr(e,i){return new Promise(t=>{let s=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(s++,l.file(a=>{s--;let h=new File([a],a.name,{type:a.type||i});r.push(h),s===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{s++,l.readEntries(a=>{s--;for(let h of a)n(h);s===0&&t(r)})};n(e)})}function Ti(e){let i=[],t=[];for(let s=0;s{i.push(...a)}));continue}let o=r.getAsFile();t.push(ir(o).then(l=>{l||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}var k={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},Ai=["focus"],rr=100,Me=new Map;function nr(e,i){let t=Math.max(Math.min(e[0],i.x+i.width),i.x),s=Math.max(Math.min(e[1],i.y+i.height),i.y);return Math.sqrt((e[0]-t)*(e[0]-t)+(e[1]-s)*(e[1]-s))}function Pe(e){let i=0,t=document.body,s=new Set,r=p=>s.add(p),n=k.INACTIVE,o=p=>{e.shouldIgnore()&&p!==k.INACTIVE||(n!==p&&s.forEach(y=>y(p)),n=p)},l=()=>i>0;r(p=>e.onChange(p));let a=()=>{i=0,o(k.INACTIVE)},h=()=>{i+=1,n===k.INACTIVE&&o(k.ACTIVE)},c=()=>{i-=1,l()||o(k.INACTIVE)},d=p=>{p.preventDefault(),i=0,o(k.INACTIVE)},f=p=>{l()||(i+=1),p.preventDefault();let y=[p.x,p.y],T=e.element.getBoundingClientRect(),w=Math.floor(nr(y,T)),b=w{if(e.shouldIgnore())return;p.preventDefault();let y=await Ti(p.dataTransfer);e.onItems(y),o(k.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",c),t.addEventListener("dragenter",h),t.addEventListener("dragover",f),e.element.addEventListener("drop",m),Ai.forEach(p=>{window.addEventListener(p,a)}),()=>{Me.delete(e.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",c),t.removeEventListener("dragenter",h),t.removeEventListener("dragover",f),e.element.removeEventListener("drop",m),Ai.forEach(p=>{window.removeEventListener(p,a)})}}var It=class extends x{constructor(){super(...arguments);u(this,"init$",{...this.init$,state:k.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),s=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return s&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",s=>{this.set$({isEnabled:!s})}),this.defineAccessor("clickable",s=>{this.set$({isClickable:typeof s=="string"})}),this.defineAccessor("with-icon",s=>{this.set$({withIcon:typeof s=="string"})}),this.defineAccessor("fullscreen",s=>{this.set$({isFullscreen:typeof s=="string"})}),this.defineAccessor("text",s=>{s?this.set$({text:this.l10n(s)||s}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Pe({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:s=>{this.$.state=s},onItems:s=>{s.length&&(s.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:ot.DROP_AREA});return}this.addFileFromObject(r,{source:ot.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":v.activities.UPLOAD_LIST}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Pe({element:t,onChange:s=>{var n;let r=(n=Object.entries(k).find(([,o])=>o===s))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",s=>{var n;let r=(n=Object.entries(k).find(([,o])=>o===s))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",s=>{let r=Ct(s);this.$.isEnabled=r.includes(x.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",s=>{this.toggleAttribute("hidden",!s)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,s=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&s&&r>=s||!t&&r>0)}destroyCallback(){var t,s,r,n;super.destroyCallback(),(s=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||s.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};It.template=`
{{text}}
`;It.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Zt=class{constructor(){u(this,"caption","");u(this,"text","");u(this,"iconName","");u(this,"isError",!1)}},te=class extends A{constructor(){super(...arguments);u(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};te.template=`
{{captionTxt}}
{{msgTxt}}
`;var ee=class extends x{constructor(){super();u(this,"couldBeUploadCollectionOwner",!0);u(this,"historyTracked",!0);u(this,"activityType",v.activities.UPLOAD_LIST);u(this,"_debouncedHandleCollectionUpdate",z(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(s=>!!s.getValue("fileInfo"));S.emit(new R({type:O.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var c,d;let t=!!this.cfg.multiple,s=t?(c=this.cfg.multipleMin)!=null?c:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=s?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:s,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,s=this._validateFilesCount();if(t&&!s.passed){let r=new Zt,n=s.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:s.min,max:s.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let p=this.uploadCollection.read(m);p.getValue("fileInfo")&&!p.getValue("validationErrorMsg")&&(r.succeed+=1),p.getValue("isUploading")&&(r.uploading+=1),(p.getValue("validationErrorMsg")||p.getValue("uploadError"))&&(r.failed+=1),p.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,h=!1,c=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?h=!0:(c=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:c,doneBtnEnabled:d,uploadBtnVisible:h,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let s=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?s("uploading"):t.failed>0?s("failed"):t.succeed>0?s("succeed"):s("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var s;((s=this.uploadCollection)==null?void 0:s.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};ee.template=`{{headerText}}
`;function or(e){let i=new Blob([e],{type:"image/svg+xml"});return URL.createObjectURL(i)}function De(e="hsl(209, 21%, 65%)",i=32,t=32){return or(``)}function xi(e,i=40){if(e.type==="image/svg+xml")return URL.createObjectURL(e);let t=document.createElement("canvas"),s=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),s.fillStyle="rgb(240, 240, 240)",s.fillRect(0,0,t.width,t.height),s.drawImage(r,0,0,t.width,t.height),t.toBlob(h=>{if(!h){l();return}let c=URL.createObjectURL(h);o(c)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(e),n}var M=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),Z=class extends x{constructor(){super();u(this,"pauseRender",!0);u(this,"_entrySubs",new Set);u(this,"_entry",null);u(this,"_isIntersecting",!1);u(this,"_debouncedGenerateThumb",z(this._generateThumbnail.bind(this),100));u(this,"_debouncedCalculateState",z(this._calculateState.bind(this),100));u(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:M.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===v.activities.DETAILS)?this.$["*currentActivity"]=v.activities.DETAILS:this.$["*currentActivity"]=v.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let s=this.getOutputData(r=>r.getValue("uuid")===t);S.emit(new R({type:O.REMOVE,ctx:this.ctxName,data:s}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[s]=t;this._isIntersecting=s.isIntersecting,s.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),s.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,s=M.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?s=M.FAILED:t.getValue("validationMultipleLimitMsg")?s=M.LIMIT_OVERFLOW:t.getValue("isUploading")?s=M.UPLOADING:t.getValue("fileInfo")&&(s=M.FINISHED),this.$.state=s}async _generateThumbnail(){var s;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(Yt(yi(this.cfg.cdnCname,this._entry.getValue("uuid")),Kt(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((s=t.getValue("file"))!=null&&s.type.includes("image"))try{let r=await xi(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",De(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",De(r))}}_subEntry(t,s){let r=this._entry.subscribe(t,n=>{this.isConnected&&s(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let s=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=s,s&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||s.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=s.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{Z.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),Z.activeInstances.add(this)}_handleState(t){var s,r,n;this.set$({isFailed:t===M.FAILED,isLimitOverflow:t===M.LIMIT_OVERFLOW,isUploading:t===M.UPLOADING,isFinished:t===M.FINISHED,progressVisible:t===M.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((s=this._entry)==null?void 0:s.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===M.FAILED||t===M.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===M.FINISHED&&(this.$.badgeIcon="badge-success"),t===M.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),Z.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let s=this.cfg.multiple?this.cfg.multipleMax:1;if(s&&this.uploadCollection.size>s)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));S.emit(new R({type:O.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let h=async()=>{let d=await this.getUploadClientOptions();return Ae(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:f=>{if(f.isComputable){let m=f.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!f.isComputable},signal:a.signal})},c=await this.$["*uploadQueue"].add(h);t.setMultipleValues({fileInfo:c,isUploading:!1,fileName:c.originalFilename,fileSize:c.size,isImage:c.isImage,mimeType:(l=(o=(n=c.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:c.mimeType,uuid:c.uuid,cdnUrl:c.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof U?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};Z.template=`
{{itemName}}{{errorText}}
`;Z.activeInstances=new Set;var Ut=class extends A{constructor(){super(...arguments);u(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let s=this.getCssData(`--icon-${t}`);s&&(this.$.path=s)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};Ut.template=``;Ut.bindAttributes({name:"name",size:"size"});var ie=class extends A{constructor(){super(...arguments);u(this,"_value",0);u(this,"_unknownMode",!1);u(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ie.template='
';var se=class extends A{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};u(se,"template",`Powered by Uploadcare`);var Et=class extends x{constructor(){super(...arguments);u(this,"processInnerHtml",!0);u(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Et.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let s=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of s){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=s.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let s=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await li(s,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};Et.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var lr="https://ucarecdn.com",ar="https://upload.uploadcare.com",ur="https://social.uploadcare.com",Lt=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:lr,baseUrl:ar,socialBaseUrl:ur,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var V=e=>String(e),B=e=>Number(e),P=e=>typeof e=="boolean"?e:e==="true"||e===""?!0:e==="false"?!1:!!e,cr=e=>e==="auto"?e:P(e),hr={pubkey:V,multiple:P,multipleMin:B,multipleMax:B,confirmUpload:P,imgOnly:P,accept:V,externalSourcesPreferredTypes:V,store:cr,cameraMirror:P,sourceList:V,maxLocalFileSizeBytes:B,thumbSize:B,showEmptyList:P,useLocalImageEditor:P,useCloudImageEditor:P,removeCopyright:P,cropPreset:V,modalScrollLock:P,modalBackdropStrokes:P,sourceListWrap:P,remoteTabSessionKey:V,cdnCname:V,baseUrl:V,socialBaseUrl:V,secureSignature:V,secureExpire:V,secureDeliveryProxy:V,retryThrottledRequestMaxTimes:B,multipartMinFileSize:B,multipartChunkSize:B,maxConcurrentRequests:B,multipartMaxConcurrentRequests:B,multipartMaxAttempts:B,checkForUrlDuplicates:P,saveUrlForRecurrentUploads:P,groupOutput:P,userAgentIntegration:V},Si=(e,i)=>{if(!(typeof i=="undefined"||i===null))return hr[e](i)};var re=Object.keys(Lt),dr=["metadata"],fr=e=>dr.includes(e),Ne=re.filter(e=>!fr(e)),pr={...Object.fromEntries(Ne.map(e=>[nt(e),e])),...Object.fromEntries(Ne.map(e=>[e.toLowerCase(),e]))},mr={...Object.fromEntries(re.map(e=>[nt(e),H(e)])),...Object.fromEntries(re.map(e=>[e.toLowerCase(),H(e)]))},ne=class extends A{constructor(){super();u(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(Lt).map(([t,s])=>[H(t),s]))}}initCallback(){super.initCallback();for(let t of re){let s=this,r="__"+t;s[r]=s[t],Object.defineProperty(this,t,{set:n=>{if(s[r]=n,Ne.includes(t)){let o=[...new Set([nt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[H(t)]!==n&&(typeof n=="undefined"||n===null?this.$[H(t)]=Lt[t]:this.$[H(t)]=n)},get:()=>this.$[H(t)]}),typeof s[t]!="undefined"&&s[t]!==null&&(s[t]=s[r])}}attributeChangedCallback(t,s,r){if(s===r)return;let n=pr[t],o=Si(n,r),l=o!=null?o:Lt[n],a=this;a[n]=l}};ne.bindAttributes(mr);var $e=class extends x{};export{ne as Config,se as Copyright,Et as DataOutput,It as DropArea,Z as FileItem,qt as FileUploaderMinimal,Ut as Icon,te as MessageBox,ie as ProgressBar,Ue as StartFrom,$e as UploadCtxProvider,ee as UploadList,Li as registerBlocks}; \ No newline at end of file diff --git a/web/lr-file-uploader-regular.min.js b/web/lr-file-uploader-regular.min.js index e46c306df..077d09a06 100644 --- a/web/lr-file-uploader-regular.min.js +++ b/web/lr-file-uploader-regular.min.js @@ -23,5 +23,5 @@ * SOFTWARE. * */ -var Ur=Object.defineProperty;var Pr=(s,i,t)=>i in s?Ur(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var c=(s,i,t)=>(Pr(s,typeof i!="symbol"?i+"":i,t),t),wi=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var N=(s,i,t)=>(wi(s,i,"read from private field"),t?t.call(s):i.get(s)),Ot=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},te=(s,i,t,e)=>(wi(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var Ee=(s,i,t)=>(wi(s,i,"access private method"),t);var Mr=Object.defineProperty,Nr=(s,i,t)=>i in s?Mr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,Ei=(s,i,t)=>(Nr(s,typeof i!="symbol"?i+"":i,t),t);function Dr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=Dr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var y=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),ds="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",Br=ds.length-1,ie=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{ai&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Vr(s,i){[...s.querySelectorAll(`[${y.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(y.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let n=t.innerHTML;r.template=n,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let o=t.getAttribute(y.REPEAT_ATTR);i.sub(o,n=>{if(!n){for(;t.firstChild;)t.firstChild.remove();return}let a=[...t.children],l,u=h=>{h.forEach((p,f)=>{if(a[f])if(a[f].set$)setTimeout(()=>{a[f].set$(p)});else for(let m in p)a[f][m]=p[m];else{l||(l=new DocumentFragment);let m=new r;Object.assign(m.init$,p),l.appendChild(m)}}),l&&t.appendChild(l);let d=a.slice(h.length,a.length);for(let p of d)p.remove()};if(n.constructor===Array)u(n);else if(n.constructor===Object){let h=[];for(let d in n){let p=n[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),h.push(p)}u(h)}else console.warn("Symbiote repeat data type error:"),console.log(n)}),t.removeAttribute(y.REPEAT_ATTR),t.removeAttribute(y.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function zr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let o=r.getAttribute("name")||us;e[o]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var o;let n=us;r instanceof Element&&r.hasAttribute("slot")&&(n=r.getAttribute("slot"),r.removeAttribute("slot")),(o=e[n])==null||o.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let o=document.createDocumentFragment();o.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(o,r.slot)}else r.slot.remove()})}function jr(s,i){[...s.querySelectorAll(`[${y.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(y.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(y.EL_REF_ATTR)})}function Hr(s,i){[...s.querySelectorAll(`[${y.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(y.BIND_ATTR).split(";");[...t.attributes].forEach(o=>{if(o.name.startsWith("-")&&o.value){let n=Fr(o.name.replace("-",""));r.push(n+":"+o.value),t.removeAttribute(o.name)}}),r.forEach(o=>{if(!o)return;let n=o.split(":").map(h=>h.trim()),a=n[0],l;a.indexOf(y.ATTR_BIND_PRFX)===0&&(l=!0,a=a.replace(y.ATTR_BIND_PRFX,""));let u=n[1].split(",").map(h=>h.trim());for(let h of u){let d;h.startsWith("!!")?(d="double",h=h.replace("!!","")):h.startsWith("!")&&(d="single",h=h.replace("!","")),i.sub(h,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),l?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(a,""):t.removeAttribute(a):t.setAttribute(a,p):ps(t,a,p)||(t[y.SET_LATER_KEY]||(t[y.SET_LATER_KEY]=Object.create(null)),t[y.SET_LATER_KEY][a]=p)})}}),t.removeAttribute(y.BIND_ATTR)})}var Ae="{{",ee="}}",Wr="skip-text";function Xr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var o;return!((o=r.parentElement)!=null&&o.hasAttribute(Wr))&&r.textContent.includes(Ae)&&r.textContent.includes(ee)&&1}});for(;i=e.nextNode();)t.push(i);return t}var qr=function(s,i){Xr(s).forEach(e=>{let r=[],o;for(;e.textContent.includes(ee);)e.textContent.startsWith(Ae)?(o=e.textContent.indexOf(ee)+ee.length,e.splitText(o),r.push(e)):(o=e.textContent.indexOf(Ae),e.splitText(o)),e=e.nextSibling;r.forEach(n=>{let a=n.textContent.replace(Ae,"").replace(ee,"");n.textContent="",i.sub(a,l=>{n.textContent=l})})})},Gr=[Vr,zr,jr,Hr,qr],Se="'",Vt='"',Kr=/\\([0-9a-fA-F]{1,6} ?)/g;function Yr(s){return(s[0]===Vt||s[0]===Se)&&(s[s.length-1]===Vt||s[s.length-1]===Se)}function Zr(s){return(s[0]===Vt||s[0]===Se)&&(s=s.slice(1)),(s[s.length-1]===Vt||s[s.length-1]===Se)&&(s=s.slice(0,-1)),s}function Jr(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ -`,"\\n"),i=Jr(i),i=Vt+i+Vt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var hs=0,Ft=null,mt=null,Ct=class extends HTMLElement{constructor(){super(),Ei(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return Ct}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(y.USE_TPL);if(r){let o=this.getRootNode(),n=(o==null?void 0:o.querySelector(r))||document.querySelector(r);n?s=n.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=ie.generate(),this.style.setProperty(y.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(y.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(y.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(y.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(y.EXT_DATA_CTX_PRFX,"");else if(s.includes(y.NAMED_DATA_CTX_SPLTR)){let r=s.split(y.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=o=>{this.isConnected&&i(o)},r=Ct.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=Ct.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=Ct.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=Ct.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=Ct.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=Ct.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(y.CTX_OWNER_ATTR)&&this.getAttribute(y.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(y.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(y.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(y.NAMED_DATA_CTX_SPLTR)){let t=i.split(y.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let o=E.getCtx(e,!1);o||(o=E.registerCtx({},e)),o.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(y.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(y.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[y.SET_LATER_KEY]){for(let t in this[y.SET_LATER_KEY])ps(this,t,this[y.SET_LATER_KEY][t]);delete this[y.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Gr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${y.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(y.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);mt==null||mt.delete(this.updateCssData),mt!=null&&mt.size||(Ft==null||Ft.disconnect(),Ft=null,mt=null)},100)))}static reg(s,i=!1){s||(hs++,s=`${y.AUTO_TAG_PRFX}-${hs}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=Qr(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){mt||(mt=new Set),mt.add(this.updateCssData),Ft||(Ft=new MutationObserver(s=>{s[0].type==="attributes"&&mt.forEach(i=>{i()})}),Ft.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=Ct;Ei(zt,"template");var Ti=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Ti.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let o in i)i[o]===!0?e+=this.separator+o:e+=this.separator+o+`=${i[o]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Ti.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Ti.appMap=Object.create(null);function to(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function eo(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function se(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&eo(i,s.attributes),s.styles&&to(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=se(t);i.appendChild(e)}),i}var ms="idb-store-ready",io="symbiote-db",so="symbiote-idb-update_",ro=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return so+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=o=>{var n;(n=o.target.result)!=null&&n._value?e(o.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=o=>{r(o)}})}write(s,i,t=!1){let e={_key:s,_value:i},o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((n,a)=>{o.onsuccess=l=>{t||this._notifySubscribers(s),n(l.target.result)},o.onerror=l=>{a(l)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,o)=>{e.onsuccess=n=>{i||this._notifySubscribers(s),r(n)},e.onerror=n=>{o(n)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let o=r.target.result;t(o.map(n=>n._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,fs.clear(this.name)}},fs=class{static get readyEventName(){return ms}static open(s=io,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new ro(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};Ei(fs,"_reg",Object.create(null));function G(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var oo="--uploadcare-blocks-window-height",$e="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Ai(){return typeof window[$e]=="undefined"?!1:!!window[$e]}function gs(){if(Ai())return;let s=()=>{document.documentElement.style.setProperty(oo,`${window.innerHeight}px`),window[$e]=!0},i=G(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[$e]=!1,window.removeEventListener("resize",i)}}var no=s=>s,Si="{{",bs="}}",_s="plural:";function re(s,i,t={}){var n;let{openToken:e=Si,closeToken:r=bs,transform:o=no}=t;for(let a in i){let l=(n=i[a])==null?void 0:n.toString();s=s.replaceAll(e+a+r,typeof l=="string"?o(l):l)}return s}function vs(s){let i=[],t=s.indexOf(Si);for(;t!==-1;){let e=s.indexOf(bs,t),r=s.substring(t+2,e);if(r.startsWith(_s)){let o=s.substring(t+2,e).replace(_s,""),n=o.substring(0,o.indexOf("(")),a=o.substring(o.indexOf("(")+1,o.indexOf(")"));i.push({variable:r,pluralKey:n,countVariable:a})}t=s.indexOf(Si,e)}return i}function ys(s){return Object.prototype.toString.call(s)==="[object Object]"}var ao=/\W|_/g;function lo(s){return s.split(ao).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function Cs(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>gt(t,{ignoreKeys:i})):s}function gt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return Cs(s,{ignoreKeys:i});if(!ys(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}ys(r)?r=gt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=Cs(r,{ignoreKeys:i})),t[lo(e)]=r}return t}var co=s=>new Promise(i=>setTimeout(i,s));function Ui({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let o="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:o,integration:r});let n=[s,i,e].filter(Boolean).join("/"),a=[o,r].filter(Boolean).join("; ");return`${n} (${a})`}var uo={factor:2,time:100};function ho(s,i=uo){let t=0;function e(r){let o=Math.round(i.time*i.factor**t);return r({attempt:t,retry:a=>co(a!=null?a:o).then(()=>(t+=1,e(r)))})}return e(s)}var qt=class extends Error{constructor(t){super();c(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,qt.prototype),this.originalProgressEvent=t}},Oe=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},xt=class extends Error{constructor(t="Request canceled"){super(t);c(this,"isCancel",!0);Object.setPrototypeOf(this,xt.prototype)}},po=500,ws=({check:s,interval:i=po,timeout:t,signal:e})=>new Promise((r,o)=>{let n,a;Oe(e,()=>{n&&clearTimeout(n),o(new xt("Poll cancelled"))}),t&&(a=setTimeout(()=>{n&&clearTimeout(n),o(new xt("Timed out"))},t));let l=()=>{try{Promise.resolve(s(e)).then(u=>{u?(a&&clearTimeout(a),r(u)):n=setTimeout(l,i)}).catch(u=>{a&&clearTimeout(a),o(u)})}catch(u){a&&clearTimeout(a),o(u)}};n=setTimeout(l,0)}),T={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Re="application/octet-stream",Ts="original",Tt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:o})=>new Promise((n,a)=>{let l=new XMLHttpRequest,u=(s==null?void 0:s.toUpperCase())||"GET",h=!1;l.open(u,i,!0),e&&Object.entries(e).forEach(d=>{let[p,f]=d;typeof f!="undefined"&&!Array.isArray(f)&&l.setRequestHeader(p,f)}),l.responseType="text",Oe(r,()=>{h=!0,l.abort(),a(new xt)}),l.onload=()=>{if(l.status!=200)a(new Error(`Error ${l.status}: ${l.statusText}`));else{let d={method:u,url:i,data:t,headers:e||void 0,signal:r,onProgress:o},p=l.getAllResponseHeaders().trim().split(/[\r\n]+/),f={};p.forEach(function(x){let A=x.split(": "),w=A.shift(),C=A.join(": ");w&&typeof w!="undefined"&&(f[w]=C)});let m=l.response,b=l.status;n({request:d,data:m,headers:f,status:b})}},l.onerror=d=>{h||a(new qt(d))},o&&typeof o=="function"&&(l.upload.onprogress=d=>{d.lengthComputable?o({isComputable:!0,value:d.loaded/d.total}):o({isComputable:!1})}),t?l.send(t):l.send()});function mo(s,...i){return s}var fo=({name:s})=>s?[s]:[],go=mo,_o=()=>new FormData,Es=s=>!1,Le=s=>typeof Blob!="undefined"&&s instanceof Blob,Ue=s=>typeof File!="undefined"&&s instanceof File,Pe=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",oe=s=>Le(s)||Ue(s)||Es()||Pe(s),bo=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",vo=s=>!!s&&typeof s=="object"&&!Array.isArray(s),yo=s=>!!s&&typeof s=="object"&&"data"in s&&oe(s.data);function Co(s,i,t){if(yo(t)){let{name:e,contentType:r}=t,o=go(t.data,e,r!=null?r:Re),n=fo({name:e,contentType:r});s.push([i,o,...n])}else if(vo(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else bo(t)&&t&&s.push([i,t.toString()])}function xo(s){let i=[];for(let[t,e]of Object.entries(s))Co(i,t,e);return i}function Pi(s){let i=_o(),t=xo(s);for(let e of t){let[r,o,...n]=e;i.append(r,o,...n)}return i}var R=class extends Error{constructor(t,e,r,o,n){super();c(this,"isCancel");c(this,"code");c(this,"request");c(this,"response");c(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=o,this.headers=n,Object.setPrototypeOf(this,R.prototype)}},wo=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var o;return(o=r[1])!=null?o:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=wo(t)),e.toString()},To="6.6.1",Eo="UploadcareUploadClient",Ao=To;function Ut(s){return Ui({libraryName:Eo,libraryVersion:Ao,...s})}var So="RequestThrottledError",xs=15e3,$o=1e3;function ko(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return xs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:xs}function Et(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return ho(({attempt:r,retry:o})=>s().catch(n=>{if("response"in n&&(n==null?void 0:n.code)===So&&r{let i="";return(Le(s)||Ue(s)||Pe(s))&&(i=s.type),i||Re},Ss=s=>{let i="";return Ue(s)&&s.name?i=s.name:Le(s)||Es()?i="":Pe(s)&&s.name&&(i=s.name),i||Ts};function Mi(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Io(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=T.baseURL,secureSignature:o,secureExpire:n,store:a,signal:l,onProgress:u,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=T.retryNetworkErrorMaxTimes,metadata:b}){return Et(()=>Tt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:d,userAgent:p})},data:Pi({file:{data:s,name:t||Ss(s),contentType:e||As(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Mi(a),signature:o,expire:n,source:h,metadata:b}),signal:l,onProgress:u}).then(({data:x,headers:A,request:w})=>{let C=gt(JSON.parse(x));if("error"in C)throw new R(C.error.content,C.error.errorCode,w,C,A);return C}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var Ii;(function(s){s.Token="token",s.FileInfo="file_info"})(Ii||(Ii={}));function Oo(s,{publicKey:i,baseURL:t=T.baseURL,store:e,fileName:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,source:u="url",signal:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=T.retryNetworkErrorMaxTimes,metadata:b}){return Et(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Mi(e),filename:r,check_URL_duplicates:o?1:void 0,save_URL_duplicates:n?1:void 0,signature:a,expire:l,source:u,metadata:b}),signal:h}).then(({data:x,headers:A,request:w})=>{let C=gt(JSON.parse(x));if("error"in C)throw new R(C.error.content,C.error.errorCode,w,C,A);return C}),{retryNetworkErrorMaxTimes:m,retryThrottledRequestMaxTimes:f})}var X;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(X||(X={}));var Ro=s=>"status"in s&&s.status===X.Error;function Lo(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}={}){return Et(()=>Tt({method:"GET",headers:i?{"X-UC-User-Agent":Ut({publicKey:i,integration:r,userAgent:o})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:l,headers:u,request:h})=>{let d=gt(JSON.parse(l));if("error"in d&&!Ro(d))throw new R(d.error.content,void 0,h,d,u);return d}),{retryNetworkErrorMaxTimes:a,retryThrottledRequestMaxTimes:n})}function Uo(s,{publicKey:i,baseURL:t=T.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:o,signal:n,source:a,integration:l,userAgent:u,retryThrottledRequestMaxTimes:h=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"POST",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:l,userAgent:u})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:o,source:a}),signal:n}).then(({data:p,headers:f,request:m})=>{let b=gt(JSON.parse(p));if("error"in b)throw new R(b.error.content,b.error.errorCode,m,b,f);return b}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:h})}function $s(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,source:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"GET",headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:o,userAgent:n})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:u,headers:h,request:d})=>{let p=gt(JSON.parse(u));if("error"in p)throw new R(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function Po(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=T.multipartChunkSize,baseURL:o="",secureSignature:n,secureExpire:a,store:l,signal:u,source:h="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:f=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:m=T.retryNetworkErrorMaxTimes,metadata:b}){return Et(()=>Tt({method:"POST",url:ft(o,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:d,userAgent:p})},data:Pi({filename:e||Ts,size:s,content_type:t||Re,part_size:r,UPLOADCARE_STORE:Mi(l),UPLOADCARE_PUB_KEY:i,signature:n,expire:a,source:h,metadata:b}),signal:u}).then(({data:x,headers:A,request:w})=>{let C=gt(JSON.parse(x));if("error"in C)throw new R(C.error.content,C.error.errorCode,w,C,A);return C.parts=Object.keys(C.parts).map(H=>C.parts[H]),C}),{retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})}function Mo(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:o=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:n=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Re}}).then(a=>(r&&r({isComputable:!0,value:1}),a)).then(({status:a})=>({code:a})),{retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n})}function No(s,{publicKey:i,baseURL:t=T.baseURL,source:e="local",signal:r,integration:o,userAgent:n,retryThrottledRequestMaxTimes:a=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}){return Et(()=>Tt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Ut({publicKey:i,integration:o,userAgent:n})},data:Pi({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:u,headers:h,request:d})=>{let p=gt(JSON.parse(u));if("error"in p)throw new R(p.error.content,p.error.errorCode,d,p,h);return p}),{retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})}function Ni({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a,signal:l,onProgress:u}){return ws({check:h=>$s(s,{publicKey:i,baseURL:t,signal:h,source:e,integration:r,userAgent:o,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:a}).then(d=>d.isReady?d:(u&&u({isComputable:!0,value:1}),!1)),signal:l})}var wt=class{constructor(i,{baseCDN:t=T.baseCDN,fileName:e}={}){c(this,"uuid");c(this,"name",null);c(this,"size",null);c(this,"isStored",null);c(this,"isImage",null);c(this,"mimeType",null);c(this,"cdnUrl",null);c(this,"s3Url",null);c(this,"originalFilename",null);c(this,"imageInfo",null);c(this,"videoInfo",null);c(this,"contentInfo",null);c(this,"metadata",null);c(this,"s3Bucket",null);let{uuid:r,s3Bucket:o}=i,n=ft(t,`${r}/`),a=o?ft(`https://${o}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=n,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=o||null,this.s3Url=a}},Do=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:n,contentType:a,signal:l,onProgress:u,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,baseCDN:b,metadata:x})=>Io(s,{publicKey:i,fileName:t,contentType:a,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:l,onProgress:u,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,metadata:x}).then(({file:A})=>Ni({file:A,publicKey:i,baseURL:e,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,onProgress:u,signal:l})).then(A=>new wt(A,{baseCDN:b})),Bo=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:o,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:u,retryNetworkErrorMaxTimes:h,baseCDN:d})=>$s(s,{publicKey:i,baseURL:e,signal:r,source:n,integration:a,userAgent:l,retryThrottledRequestMaxTimes:u,retryNetworkErrorMaxTimes:h}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(o&&o({isComputable:!0,value:1}),p)),Fo=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),o=n=>()=>{e=n,r.forEach((a,l)=>l!==n&&a.abort())};return Oe(i,()=>{r.forEach(n=>n.abort())}),Promise.all(s.map((n,a)=>{let l=o(a);return Promise.resolve().then(()=>n({stopRace:l,signal:r[a].signal})).then(u=>(l(),u)).catch(u=>(t=u,null))})).then(n=>{if(e===null)throw t;return n[e]})},Vo=window.WebSocket,Oi=class{constructor(){c(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},zo=(s,i)=>s==="success"?{status:X.Success,...i}:s==="progress"?{status:X.Progress,...i}:{status:X.Error,...i},Ri=class{constructor(i,t=3e4){c(this,"key");c(this,"disconnectTime");c(this,"ws");c(this,"queue",[]);c(this,"isConnected",!1);c(this,"subscribers",0);c(this,"emmitter",new Oi);c(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Vo(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,zo(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},$i=null,Di=s=>{if(!$i){let i=typeof window=="undefined"?0:3e4;$i=new Ri(s,i)}return $i},jo=s=>{Di(s).connect()};function Ho({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,onProgress:a,signal:l}){return ws({check:u=>Lo(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:n,signal:u}).then(h=>{switch(h.status){case X.Error:return new R(h.error,h.errorCode);case X.Waiting:return!1;case X.Unknown:return new R(`Token "${s}" was not found.`);case X.Progress:return a&&(h.total==="unknown"?a({isComputable:!1}):a({isComputable:!0,value:h.done/h.total})),!1;case X.Success:return a&&a({isComputable:!0,value:h.done/h.total}),h;default:throw new Error("Unknown status")}}),signal:l})}var Wo=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,o)=>{let n=Di(i),a=n.onError(o),l=()=>{a(),n.unsubscribe(s)};Oe(t,()=>{l(),o(new xt("pusher cancelled"))}),n.subscribe(s,u=>{switch(u.status){case X.Progress:{e&&(u.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:u.done/u.total}));break}case X.Success:{l(),e&&e({isComputable:!0,value:u.done/u.total}),r(u);break}case X.Error:l(),o(new R(u.msg,u.error_code))}})}),Xo=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:u,signal:h,onProgress:d,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,pusherKey:x=T.pusherKey,metadata:A})=>Promise.resolve(jo(x)).then(()=>Oo(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:o,saveUrlForRecurrentUploads:n,secureSignature:a,secureExpire:l,store:u,signal:h,source:p,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,metadata:A})).catch(w=>{let C=Di(x);return C==null||C.disconnect(),Promise.reject(w)}).then(w=>w.type===Ii.FileInfo?w:Fo([({signal:C})=>Ho({token:w.token,publicKey:i,baseURL:e,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:C}),({signal:C})=>Wo({token:w.token,pusherKey:x,signal:C,onProgress:d})],{signal:h})).then(w=>{if(w instanceof R)throw w;return w}).then(w=>Ni({file:w.uuid,publicKey:i,baseURL:e,integration:f,userAgent:m,retryThrottledRequestMaxTimes:b,onProgress:d,signal:h})).then(w=>new wt(w,{baseCDN:r})),ki=new WeakMap,qo=async s=>{if(ki.has(s))return ki.get(s);let i=await fetch(s.uri).then(t=>t.blob());return ki.set(s,i),i},ks=async s=>{if(Ue(s)||Le(s))return s.size;if(Pe(s))return(await qo(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Go=(s,i=T.multipartMinFileSize)=>s>=i,Is=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!oe(s)&&t.test(s)},Os=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!oe(s)&&t.test(s)},Ko=(s,i)=>new Promise((t,e)=>{let r=[],o=!1,n=i.length,a=[...i],l=()=>{let u=i.length-a.length,h=a.shift();h&&h().then(d=>{o||(r[u]=d,n-=1,n?l():t(r))}).catch(d=>{o=!0,e(d)})};for(let u=0;u{let r=e*i,o=Math.min(r+e,t);return s.slice(r,o)},Zo=async(s,i,t)=>e=>Yo(s,e,i,t),Jo=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:o,integration:n,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l})=>Mo(s,i,{publicKey:t,contentType:e,onProgress:r,signal:o,integration:n,retryThrottledRequestMaxTimes:a,retryNetworkErrorMaxTimes:l}),Qo=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:o,secureExpire:n,store:a,signal:l,onProgress:u,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,contentType:b,multipartChunkSize:x=T.multipartChunkSize,maxConcurrentRequests:A=T.maxConcurrentRequests,baseCDN:w,metadata:C})=>{let H=e!=null?e:await ks(s),ht,It=(O,Z)=>{if(!u)return;ht||(ht=Array(O).fill(0));let dt=W=>W.reduce((pt,xi)=>pt+xi,0);return W=>{W.isComputable&&(ht[Z]=W.value,u({isComputable:!0,value:dt(ht)/O}))}};return b||(b=As(s)),Po(H,{publicKey:i,contentType:b,fileName:t||Ss(s),baseURL:r,secureSignature:o,secureExpire:n,store:a,signal:l,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,metadata:C}).then(async({uuid:O,parts:Z})=>{let dt=await Zo(s,H,x);return Promise.all([O,Ko(A,Z.map((W,pt)=>()=>Jo(dt(pt),W,{publicKey:i,contentType:b,onProgress:It(Z.length,pt),signal:l,integration:d,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})))])}).then(([O])=>No(O,{publicKey:i,baseURL:r,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m})).then(O=>O.isReady?O:Ni({file:O.uuid,publicKey:i,baseURL:r,source:h,integration:d,userAgent:p,retryThrottledRequestMaxTimes:f,retryNetworkErrorMaxTimes:m,onProgress:u,signal:l})).then(O=>new wt(O,{baseCDN:w}))};async function Bi(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,contentType:m,multipartMinFileSize:b,multipartChunkSize:x,maxConcurrentRequests:A,baseCDN:w=T.baseCDN,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:H,pusherKey:ht,metadata:It}){if(oe(s)){let O=await ks(s);return Go(O,b)?Qo(s,{publicKey:i,contentType:m,multipartChunkSize:x,fileSize:O,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,baseCDN:w,metadata:It}):Do(s,{publicKey:i,fileName:t,contentType:m,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,baseCDN:w,metadata:It})}if(Os(s))return Xo(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:w,checkForUrlDuplicates:C,saveUrlForRecurrentUploads:H,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,pusherKey:ht,metadata:It});if(Is(s))return Bo(s,{publicKey:i,fileName:t,baseURL:e,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,baseCDN:w});throw new TypeError(`File uploading from "${s}" is not supported`)}var Li=class{constructor(i,t){c(this,"uuid");c(this,"filesCount");c(this,"totalSize");c(this,"isStored");c(this,"isImage");c(this,"cdnUrl");c(this,"files");c(this,"createdAt");c(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},tn=s=>{for(let i of s)if(!oe(i))return!1;return!0},en=s=>{for(let i of s)if(!Is(i))return!1;return!0},sn=s=>{for(let i of s)if(!Os(i))return!1;return!0};function Rs(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:l,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,contentType:m,multipartChunkSize:b=T.multipartChunkSize,baseCDN:x=T.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:w,jsonpCallback:C}){if(!tn(s)&&!sn(s)&&!en(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let H,ht=!0,It=s.length,O=(Z,dt)=>{if(!l)return;H||(H=Array(Z).fill(0));let W=pt=>pt.reduce((xi,Lr)=>xi+Lr)/Z;return pt=>{if(!pt.isComputable||!ht){ht=!1,l({isComputable:!1});return}H[dt]=pt.value,l({isComputable:!0,value:W(H)})}};return Promise.all(s.map((Z,dt)=>Bi(Z,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:o,store:n,signal:a,onProgress:O(It,dt),source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f,contentType:m,multipartChunkSize:b,baseCDN:x,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:w}))).then(Z=>{let dt=Z.map(W=>W.uuid);return Uo(dt,{publicKey:i,baseURL:e,jsonpCallback:C,secureSignature:r,secureExpire:o,signal:a,source:u,integration:h,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:f}).then(W=>new Li(W,Z)).then(W=>(l&&l({isComputable:!0,value:1}),W))})}var Rt,jt,Lt,Ht,Wt,Xt,ke,Ie=class{constructor(i){Ot(this,Xt);Ot(this,Rt,1);Ot(this,jt,[]);Ot(this,Lt,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);te(this,Rt,i)}add(i){return new Promise((t,e)=>{N(this,Ht).set(i,t),N(this,Wt).set(i,e),N(this,jt).push(i),Ee(this,Xt,ke).call(this)})}get pending(){return N(this,jt).length}get running(){return N(this,Lt)}set concurrency(i){te(this,Rt,i),Ee(this,Xt,ke).call(this)}get concurrency(){return N(this,Rt)}};Rt=new WeakMap,jt=new WeakMap,Lt=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,ke=function(){let i=N(this,Rt)-N(this,Lt);for(let t=0;t{N(this,Ht).delete(e),N(this,Wt).delete(e),te(this,Lt,N(this,Lt)-1),Ee(this,Xt,ke).call(this)}).then(n=>r(n)).catch(n=>o(n))}};var Fi=()=>({"*blocksRegistry":new Set}),Vi=s=>({...Fi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Me=s=>({...Vi(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Ie(1)});function Ls(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let n=e.split(":");r=n[0],e=n[1]}let o="l10n:"+e;i.__l10nKeys.push(o),i.add(o,e),i.sub(o,n=>{t[r]=i.l10n(n)}),t.removeAttribute("l10n")})}var L=s=>`*cfg/${s}`;var _t=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Us=new Set;function Ne(s){Us.has(s)||(Us.add(s),console.warn(s))}var De=(s,i)=>new Intl.PluralRules(s).select(i);var zi="lr-",_=class extends zt{constructor(){super();c(this,"allowCustomTemplate",!0);c(this,"init$",Fi());c(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Ls),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,o=vs(r);for(let a of o)e[a.variable]=this.pluralize(a.pluralKey,Number(e[a.countVariable]));return re(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",o=De(r,e);return this.l10n(`${t}__${o}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setForCtxTarget(t,e,r){this.hasBlockInCtx(o=>o.constructor.StateConsumerScope===t)&&(this.$[e]=r)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${zi}${t}`,!0),Ai()||(this._destroyInnerHeightTracker=gs()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],o=u=>this.getCssData("--l10n-unit-"+u.toLowerCase(),!0)||u;if(t===0)return`0 ${o(r[0])}`;let n=1024,a=e<0?0:e,l=Math.floor(Math.log(t)/Math.log(n));return parseFloat((t/n**l).toFixed(a))+" "+o(r[l])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?re(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let o=L(r),n=this.parseCfgProp(o);return n.ctx.has(n.name)?n.ctx.read(n.name):(Ne("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${_t(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(L(t));r.ctx.has(r.name)?this.sub(L(t),e):(this.bindCssData(`--cfg-${_t(t)}`),this.sub(`--cfg-${_t(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(zi)?t:zi+t)}};c(_,"StateConsumerScope",null),c(_,"className","");var ji=class extends _{constructor(){super(...arguments);c(this,"_handleBackdropClick",()=>{this._closeDialog()});c(this,"_closeDialog",()=>{this.setForCtxTarget(ji.StateConsumerScope,"*modalActive",!1)});c(this,"_handleDialogClose",()=>{this._closeDialog()});c(this,"_handleDialogClick",t=>{t.target===this.ref.dialog&&this._closeDialog()});c(this,"init$",{...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose})}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("click",this._handleDialogClick);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogClick)}},F=ji;c(F,"StateConsumerScope","modal");F.template=``;var Ps="active",ne="___ACTIVITY_IS_ACTIVE___",rt=class extends _{constructor(){super(...arguments);c(this,"historyTracked",!1);c(this,"init$",Vi(this));c(this,"_debouncedHistoryFlush",G(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=rt._activityRegistry[this.activityKey];this[ne]=!1,this.removeAttribute(Ps),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=rt._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[ne]=!0,this.setAttribute(Ps,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[ne]?this._deactivate():this.activityType===t&&!this[ne]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!rt._activityRegistry[this.activityKey]}get isActivityActive(){return this[ne]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:o}=e;rt._activityRegistry||(rt._activityRegistry=Object.create(null)),rt._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:o}}unregisterActivity(){this.isActivityActive&&this._deactivate(),rt._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(rt._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!1)}}},g=rt;c(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var U=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var ae=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],Hi=s=>s?s.filter(i=>typeof i=="string").map(i=>U(i)).flat():[],Wi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),Ms=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),le=s=>{let i=s==null?void 0:s.type;return i?Wi(i,ae):!1};var Ns=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var Ds="blocks",Bs="0.25.6";function Fs(s){return Ui({...s,libraryName:Ds,libraryVersion:Bs})}var Vs="[Typed State] Wrong property name: ",rn="[Typed State] Wrong property type: ",Be=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||ie.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Vs+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(rn+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(Vs+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Fe=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||ie.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(o=>{o({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new Be(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var k={UPLOAD_START:"UPLOAD_START",REMOVE:"REMOVE",UPLOAD_PROGRESS:"UPLOAD_PROGRESS",UPLOAD_FINISH:"UPLOAD_FINISH",UPLOAD_ERROR:"UPLOAD_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",CDN_MODIFICATION:"CLOUD_MODIFICATION",DATA_OUTPUT:"DATA_OUTPUT",DONE_FLOW:"DONE_FLOW",INIT_FLOW:"INIT_FLOW"},D=class{constructor(i){this.ctx=i.ctx,this.type=i.type,this.data=i.data}},$=class{static eName(i){return"LR_"+i}static emit(i,t=window,e=!0){let r=()=>{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let o=i.type+i.ctx;this._timeoutStore[o]&&window.clearTimeout(this._timeoutStore[o]),this._timeoutStore[o]=window.setTimeout(()=>{r(),delete this._timeoutStore[o]},20)}};c($,"_timeoutStore",Object.create(null));var J=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var ot=1e3,Pt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),ce=s=>Math.ceil(s*100)/100,zs=(s,i=Pt.AUTO)=>{let t=i===Pt.AUTO;if(i===Pt.BYTE||t&&s{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(o=>[...o]).flat())].map(o=>e.read(o)).filter(Boolean);for(let o of r)this._runValidatorsForEntry(o);if(t.uploadProgress){let o=0,n=e.findItems(l=>!l.getValue("uploadError"));n.forEach(l=>{o+=e.readProp(l,"uploadProgress")});let a=Math.round(o/n.length);this.$["*commonProgress"]=a,$.emit(new D({type:k.UPLOAD_PROGRESS,ctx:this.ctxName,data:a}),void 0,a===100)}if(t.fileInfo){let o=e.findItems(a=>!!a.getValue("fileInfo")),n=e.findItems(a=>!!a.getValue("uploadError")||!!a.getValue("validationErrorMsg"));if(e.size-n.length===o.length){let a=this.getOutputData(l=>!!l.getValue("fileInfo")&&!l.getValue("silentUpload"));a.length>0&&$.emit(new D({type:k.UPLOAD_FINISH,ctx:this.ctxName,data:a}))}}t.uploadError&&e.findItems(n=>!!n.getValue("uploadError")).forEach(n=>{$.emit(new D({type:k.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(n,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(n=>!!n.getValue("validationErrorMsg")).forEach(n=>{$.emit(new D({type:k.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(n,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(n=>!!n.getValue("cdnUrlModifiers")).forEach(n=>{$.emit(new D({type:k.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(n).store}),void 0,!1)})})}setUploadMetadata(t){Ne("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Fe({typedSchema:Ns,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,o)=>{var n;this._runValidators();for(let a of o)(n=a==null?void 0:a.getValue("abortController"))==null||n.abort(),a==null||a.setValue("abortController",null),URL.revokeObjectURL(a==null?void 0:a.getValue("thumbUrl"));this.$["*uploadList"]=e.map(a=>({uid:a}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:o!=null?o:J.API})}addFileFromUuid(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:o!=null?o:J.API})}addFileFromObject(t,{silent:e,fileName:r,source:o}={}){this.uploadCollection.add({file:t,isImage:le(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:o!=null?o:J.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:le(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=Hi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?ae:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=ae.join(",")):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(o=>this.addFileFromObject(o,{source:J.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=U(this.cfg.sourceList)),t}initFlow(t=!1){var e,r;if((e=this.$["*uploadList"])!=null&&e.length&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let o=this.sourceList[0];o==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(o)?this.set$({"*currentActivityParams":{externalSourceType:o},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=o,this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0);$.emit(new D({type:k.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!1),$.emit(new D({type:k.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,o=Hi([...e?ae:[],r]);if(!o.length)return;let n=t.getValue("mimeType"),a=t.getValue("fileName");if(!n||!a)return;let l=Wi(n,o),u=Ms(a,o);if(!l&&!u)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:zs(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),o=this.cfg.multiple?this.cfg.multipleMax:1;if(o&&r>=o)return this.l10n("files-count-allowed",{count:o})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Fs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(o=>{let n=E.getCtx(o).store,a=n.fileInfo||{name:n.fileName,fileSize:n.fileSize,isImage:n.isImage,mimeType:n.mimeType},l={...a,cdnUrlModifiers:n.cdnUrlModifiers,cdnUrl:n.cdnUrl||a.cdnUrl};e.push(l)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(k).forEach(s=>{let i=$.eName(s);window.addEventListener(i,t=>{if([k.UPLOAD_FINISH,k.REMOVE,k.CDN_MODIFICATION].includes(t.detail.type)){let r=E.getCtx(t.detail.ctx),o=r.read("uploadCollection"),n=[];o.items().forEach(a=>{let l=E.getCtx(a).store,u=l.fileInfo;if(u){let h={...u,cdnUrlModifiers:l.cdnUrlModifiers,cdnUrl:l.cdnUrl||u.cdnUrl};n.push(h)}}),$.emit(new D({type:k.DATA_OUTPUT,ctx:t.detail.ctx,data:n})),r.pub("outputData",n)}})});var on="https://ucarecdn.com",nn="https://upload.uploadcare.com",an="https://social.uploadcare.com",ue=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:on,baseUrl:nn,socialBaseUrl:an,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var Q=s=>String(s),nt=s=>Number(s),V=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,ln=s=>s==="auto"?s:V(s),cn={pubkey:Q,multiple:V,multipleMin:nt,multipleMax:nt,confirmUpload:V,imgOnly:V,accept:Q,externalSourcesPreferredTypes:Q,store:ln,cameraMirror:V,sourceList:Q,maxLocalFileSizeBytes:nt,thumbSize:nt,showEmptyList:V,useLocalImageEditor:V,useCloudImageEditor:V,removeCopyright:V,modalScrollLock:V,modalBackdropStrokes:V,sourceListWrap:V,remoteTabSessionKey:Q,cdnCname:Q,baseUrl:Q,socialBaseUrl:Q,secureSignature:Q,secureExpire:Q,secureDeliveryProxy:Q,retryThrottledRequestMaxTimes:nt,multipartMinFileSize:nt,multipartChunkSize:nt,maxConcurrentRequests:nt,multipartMaxConcurrentRequests:nt,multipartMaxAttempts:nt,checkForUrlDuplicates:V,saveUrlForRecurrentUploads:V,groupOutput:V,userAgentIntegration:Q},js=(s,i)=>{if(!(typeof i=="undefined"||i===null))return cn[s](i)};var Ve=Object.keys(ue),un=["metadata"],hn=s=>un.includes(s),Xi=Ve.filter(s=>!hn(s)),dn={...Object.fromEntries(Xi.map(s=>[_t(s),s])),...Object.fromEntries(Xi.map(s=>[s.toLowerCase(),s]))},pn={...Object.fromEntries(Ve.map(s=>[_t(s),L(s)])),...Object.fromEntries(Ve.map(s=>[s.toLowerCase(),L(s)]))},ze=class extends _{constructor(){super(...arguments);c(this,"ctxOwner",!0);c(this,"init$",{...this.init$,...Object.fromEntries(Object.entries(ue).map(([t,e])=>[L(t),e]))})}initCallback(){super.initCallback();for(let t of Ve){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:o=>{if(e[r]=o,Xi.includes(t)){let n=[...new Set([_t(t),t.toLowerCase()])];for(let a of n)typeof o=="undefined"||o===null?this.removeAttribute(a):this.setAttribute(a,o.toString())}this.$[L(t)]!==o&&(typeof o=="undefined"||o===null?this.$[L(t)]=ue[t]:this.$[L(t)]=o)},get:()=>this.$[L(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let o=dn[t],n=js(o,r),a=n!=null?n:ue[o],l=this;l[o]=a}};ze.bindAttributes(pn);var he=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};he.template=``;he.bindAttributes({name:"name",size:"size"});var Hs=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},je=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Hs(i)).join("/-/"),P=(...s)=>{let i=je(...s);return i?`-/${i}/`:""};function Ws(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),o="";return e>=0?o=t.slice(e):r>=0&&(o=t.slice(r+1)),o}function Xs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function qs(s){let i=Gs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(o=>Hs(o))}function Gs(s){let i=new URL(s),t=Ws(s),e=Ks(t)?Ys(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function Ks(s){return s.startsWith("http")}function Ys(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var S=(s,i,t)=>{let e=new URL(Gs(s));if(t=t||Ws(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),Ks(t)){let r=Ys(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var mn="https://ucarecdn.com",Mt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:mn},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var Zs=s=>[...new Set(s)];var de="--lr-img-",Js="unresolved",Gt=2,Kt=3,Qs=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),er=Object.create(null),tr;for(let s in Mt)er[de+s]=((tr=Mt[s])==null?void 0:tr.default)||"";var He=class extends zt{constructor(){super(...arguments);c(this,"cssInit$",er)}$$(t){return this.$[de+t]}set$$(t){for(let e in t)this.$[de+e]=t[e]}sub$$(t,e){this.sub(de+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!Qs&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return P(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Mt.format.default}`,`quality/${this.$$("quality")||Mt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(Qs&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return S(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(S(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(S(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(S(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(S(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?re(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let o=t.getBoundingClientRect(),n=e*Math.round(o.width),a=r?"":e*Math.round(o.height);return n||a?`${n||""}x${a||""}`:null}_setupEventProxy(t){let e=o=>{o.stopPropagation();let n=new Event(o.type,o);this.dispatchEvent(n)},r=["load","error"];for(let o of r)t.addEventListener(o,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(Js,""),this.img.onload=()=>{this.img.removeAttribute(Js)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Mt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?Zs(U(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(o=>{e.add(`url("${this._getUrlBase(o+"x")}") ${o}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(o*Gt+"x")}") ${o*Gt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(o*Kt+"x")}") ${o*Kt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Gt))}") ${Gt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Kt))}") ${Kt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Gt+"x")+` ${e*Gt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Kt+"x")+` ${e*Kt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(o=>{o.forEach(n=>{n.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null)}static get observedAttributes(){return Object.keys(Mt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[de+t]=r})}};var qi=class extends He{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var We=class extends v{constructor(){super(...arguments);c(this,"init$",{...this.init$,"*simpleButtonText":"",onClick:()=>{this.initFlow()}})}initCallback(){super.initCallback(),this.subConfigValue("multiple",t=>{this.$["*simpleButtonText"]=t?this.l10n("upload-files"):this.l10n("upload-file")})}};We.template=``;var Gi=class extends g{constructor(){super(...arguments);c(this,"historyTracked",!0);c(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function fn(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function gn(s,i){return new Promise(t=>{let e=0,r=[],o=a=>{a||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),a.isFile?(e++,a.file(l=>{e--;let u=new File([l],l.name,{type:l.type||i});r.push(u),e===0&&t(r)})):a.isDirectory&&n(a.createReader())},n=a=>{e++,a.readEntries(l=>{e--;for(let u of l)o(u);e===0&&t(r)})};o(s)})}function ir(s){let i=[],t=[];for(let e=0;e{i.push(...l)}));continue}let n=r.getAsFile();t.push(fn(n).then(a=>{a||i.push(n)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(o=>{r.getAsString(n=>{i.push(n),o()})}))}return Promise.all(t).then(()=>i)}var z={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},sr=["focus"],_n=100,Ki=new Map;function bn(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Yi(s){let i=0,t=document.body,e=new Set,r=m=>e.add(m),o=z.INACTIVE,n=m=>{s.shouldIgnore()&&m!==z.INACTIVE||(o!==m&&e.forEach(b=>b(m)),o=m)},a=()=>i>0;r(m=>s.onChange(m));let l=()=>{i=0,n(z.INACTIVE)},u=()=>{i+=1,o===z.INACTIVE&&n(z.ACTIVE)},h=()=>{i-=1,a()||n(z.INACTIVE)},d=m=>{m.preventDefault(),i=0,n(z.INACTIVE)},p=m=>{a()||(i+=1),m.preventDefault();let b=[m.x,m.y],x=s.element.getBoundingClientRect(),A=Math.floor(bn(b,x)),w=A<_n,C=m.composedPath().includes(s.element);Ki.set(s.element,A);let H=Math.min(...Ki.values())===A;n(C&&H?z.OVER:w&&H?z.NEAR:z.ACTIVE)},f=async m=>{if(s.shouldIgnore())return;m.preventDefault();let b=await ir(m.dataTransfer);s.onItems(b),n(z.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",h),t.addEventListener("dragenter",u),t.addEventListener("dragover",p),s.element.addEventListener("drop",f),sr.forEach(m=>{window.addEventListener(m,l)}),()=>{Ki.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",h),t.removeEventListener("dragenter",u),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",f),sr.forEach(m=>{window.removeEventListener(m,l)})}}var pe=class extends v{constructor(){super(...arguments);c(this,"init$",{...this.init$,state:z.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),o=window.getComputedStyle(this),n=o.visibility!=="hidden"&&o.display!=="none";return e&&n&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!e})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:typeof e=="string"})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:typeof e=="string"})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:typeof e=="string"})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Yi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:J.DROP_AREA});return}this.addFileFromObject(r,{source:J.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(F.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Yi({element:t,onChange:e=>{var o;let r=(o=Object.entries(z).find(([,n])=>n===e))==null?void 0:o[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var o;let r=(o=Object.entries(z).find(([,n])=>n===e))==null?void 0:o[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=U(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,o;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(o=this._destroyContentWrapperDropzone)==null||o.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};pe.template=`
{{text}}
`;pe.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var vn="src-type-",me=class extends v{constructor(){super(...arguments);c(this,"_registeredTypes",{});c(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:o=t,activity:n,onClick:a,activityParams:l={}}=e;this.applyL10nKey("src-type",`${vn}${r}`),this.$.iconName=o,this.onclick=u=>{(a?a(u):!!n)&&this.set$({"*currentActivityParams":l,"*currentActivity":n})}}};me.template=`
`;me.bindAttributes({type:null});var Zi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=U(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function rr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function or(s="#fff",i="rgba(0, 0, 0, .1)"){return rr(``)}function fe(s="hsl(209, 21%, 65%)",i=32,t=32){return rr(``)}function nr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,o=new Promise((n,a)=>{r.onload=()=>{let l=r.height/r.width;l>1?(t.width=i,t.height=i*l):(t.height=i,t.width=i/l),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(u=>{if(!u){a();return}let h=URL.createObjectURL(u);n(h)})},r.onerror=l=>{a(l)}});return r.src=URL.createObjectURL(s),o}var B=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),bt=class extends v{constructor(){super(...arguments);c(this,"pauseRender",!0);c(this,"_entrySubs",new Set);c(this,"_entry",null);c(this,"_isIntersecting",!1);c(this,"_debouncedGenerateThumb",G(this._generateThumbnail.bind(this),100));c(this,"_debouncedCalculateState",G(this._calculateState.bind(this),100));c(this,"_renderedOnce",!1);c(this,"init$",{...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:B.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);$.emit(new D({type:k.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}})}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=B.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=B.FAILED:t.getValue("validationMultipleLimitMsg")?e=B.LIMIT_OVERFLOW:t.getValue("isUploading")?e=B.UPLOADING:t.getValue("fileInfo")&&(e=B.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,o=this.proxyUrl(S(At(this.cfg.cdnCname,this._entry.getValue("uuid")),P(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),n=t.getValue("thumbUrl");n!==o&&(t.setValue("thumbUrl",o),n!=null&&n.startsWith("blob:")&&URL.revokeObjectURL(n));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await nr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let o=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",fe(o))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",fe(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,o=>{this.isConnected&&e(o)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",o=>{this.$.progressValue=o}),this._subEntry("fileName",o=>{this.$.itemName=o||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",o=>{this.$.itemName=e.getValue("fileName")||o||this.l10n("file-no-name")}),this._subEntry("uuid",o=>{this._debouncedCalculateState(),o&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",o=>{this.$.thumbUrl=o?`url(${o})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{bt.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),bt.activeInstances.add(this)}_handleState(t){var e,r;this.set$({isFailed:t===B.FAILED,isLimitOverflow:t===B.LIMIT_OVERFLOW,isUploading:t===B.UPLOADING,isFinished:t===B.FINISHED,progressVisible:t===B.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&t===B.FINISHED&&((e=this._entry)==null?void 0:e.getValue("isImage")),errorText:((r=this._entry.getValue("uploadError"))==null?void 0:r.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===B.FAILED||t===B.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===B.FINISHED&&(this.$.badgeIcon="badge-success"),t===B.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),bt.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var o,n,a;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(l=>!l.getValue("fileInfo"));$.emit(new D({type:k.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let l=new AbortController;t.setValue("abortController",l);let u=async()=>{let d=await this.getUploadClientOptions();return Bi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let f=p.value*100;t.setValue("uploadProgress",f)}this.$.progressUnknown=!p.isComputable},signal:l.signal})},h=await this.$["*uploadQueue"].add(u);t.setMultipleValues({fileInfo:h,isUploading:!1,fileName:h.originalFilename,fileSize:h.size,isImage:h.isImage,mimeType:(a=(n=(o=h.contentInfo)==null?void 0:o.mime)==null?void 0:n.mime)!=null?a:h.mimeType,uuid:h.uuid,cdnUrl:h.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(l){console.warn("Upload error",l),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),l instanceof R?l.isCancel||t.setValue("uploadError",l):t.setValue("uploadError",new Error("Unexpected error"))}}};bt.template=`
{{itemName}}{{errorText}}
`;bt.activeInstances=new Set;var Xe=class{constructor(){c(this,"caption","");c(this,"text","");c(this,"iconName","");c(this,"isError",!1)}},qe=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};qe.template=`
{{captionTxt}}
{{msgTxt}}
`;var Ge=class extends v{constructor(){super(...arguments);c(this,"couldBeUploadCollectionOwner",!0);c(this,"historyTracked",!0);c(this,"activityType",g.activities.UPLOAD_LIST);c(this,"init$",{...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));$.emit(new D({type:k.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}});c(this,"_debouncedHandleCollectionUpdate",G(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0))}_validateFilesCount(){var h,d;let t=!!this.cfg.multiple,e=t?(h=this.cfg.multipleMin)!=null?h:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,o=this.uploadCollection.size,n=e?or:!1;return{passed:!n&&!a,tooFew:n,tooMany:a,min:e,max:r,exact:r===o}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new Xe,o=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(o,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let f of t){let m=this.uploadCollection.read(f);m.getValue("fileInfo")&&!m.getValue("validationErrorMsg")&&(r.succeed+=1),m.getValue("isUploading")&&(r.uploading+=1),(m.getValue("validationErrorMsg")||m.getValue("uploadError"))&&(r.failed+=1),m.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:o,tooMany:n,exact:a}=this._validateFilesCount(),l=r.failed===0&&r.limitOverflow===0,u=!1,h=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&o?u=!0:(h=!0,d=r.total===r.succeed&&o&&l),this.set$({doneBtnVisible:h,doneBtnEnabled:d,uploadBtnVisible:u,addMoreBtnEnabled:r.total===0||!n&&!a,addMoreBtnVisible:!a||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let o=t[r];return this.l10n(`header-${r}`,{count:o})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};Ge.template=`{{headerText}}
`;var Ke=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.URL);c(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:J.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};Ke.template=`
`;var Ji=()=>typeof navigator.permissions!="undefined";var Ye=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.CAMERA);c(this,"_unsubPermissions",null);c(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:Ji(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});c(this,"_onActivate",()=>{Ji()&&this._subscribePermissions(),this._capture()});c(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});c(this,"_handlePermissionsChange",()=>{this._capture()});c(this,"_setPermissionsState",G(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let o=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(o,{source:J.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,o)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${o+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};Ye.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var Qi=class extends v{};var Ze=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.DETAILS);c(this,"pauseRender",!0);c(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=fe(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(o=>{this._entrySubs.delete(o),o.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let o=le(this._file);o&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),o||this.showNonImageThumb()}let r=(o,n)=>{this._entrySubs.add(this.entry.subscribe(o,n))};r("fileName",o=>{this.$.fileName=o,this.$.onNameInput=()=>{let n=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:n}),this.entry.setValue("fileName",n)}}),r("fileSize",o=>{this.$.fileSize=Number.isFinite(o)?this.fileSizeFmt(o):this.l10n("file-size-unknown")}),r("uploadError",o=>{this.$.errorTxt=o==null?void 0:o.message}),r("externalUrl",o=>{o&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",o=>{let n=this.cfg.useCloudImageEditor&&o&&this.entry.getValue("isImage");if(o&&this.ref.filePreview.clear(),this.set$({cdnUrl:o,cloudEditBtnHidden:!n}),o&&this.entry.getValue("isImage")){let a=S(o,P("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(a))}})})}};Ze.template=`
{{fileSize}}
{{errorTxt}}
`;var ts=class{constructor(){c(this,"captionL10nStr","confirm-your-action");c(this,"messageL10Str","are-you-sure");c(this,"confirmL10nStr","yes");c(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},Je=class extends g{constructor(){super(...arguments);c(this,"activityType",g.activities.CONFIRMATION);c(this,"_defaults",new ts);c(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};Je.template=`{{activityCaption}}
{{messageTxt}}
`;var Qe=class extends v{constructor(){super(...arguments);c(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};Qe.template=``;var ti=class extends _{constructor(){super(...arguments);c(this,"_value",0);c(this,"_unknownMode",!1);c(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ti.template='
';var K="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var ge=class extends _{constructor(){super();c(this,"init$",{...this.init$,checkerboard:!1,src:K})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${or()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=K}};ge.template='';ge.bindAttributes({checkerboard:"checkerboard"});var ar="--cfg-ctx-name",I=class extends _{get cfgCssCtxName(){return this.getCssData(ar,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(ar,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function lr(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function M(...s){let i=lr(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function cr(s,...i){let t=lr(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}function at(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var Y={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function yn(s,i){if(typeof i=="number")return Y[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Y[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Y[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var hr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function St(s){return je(...hr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return yn(i,t)}).filter(i=>!!i))}var ei=je("format/auto","progressive/yes"),vt=([s])=>typeof s!="undefined"?Number(s):void 0,ur=()=>!0,Cn=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),xn=([s,i])=>({dimensions:U(s,"x").map(Number),coords:U(i).map(Number)}),wn={enhance:vt,brightness:vt,exposure:vt,gamma:vt,contrast:vt,saturation:vt,vibrance:vt,warmth:vt,filter:Cn,mirror:ur,flip:ur,rotate:vt,crop:xn};function dr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!hr.includes(e))continue;let o=wn[e],n=o(r);i[e]=n}return i}function pr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:K,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,"presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=K,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=P(St(i)),r=S(t,P(e,"preview")),o={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:o,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var mr=`
Network error
{{fileType}}
{{msg}}
`;var j={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},ii=[j.CROP,j.SLIDERS,j.FILTERS],fr=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],gr=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],_r=["rotate","mirror","flip"],lt={brightness:{zero:Y.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Y.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Y.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Y.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Y.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Y.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Y.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Y.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Y.filter,range:[0,100],keypointsNumber:1}};var ct=class extends I{constructor(){super(...arguments);c(this,"init$",{...this.init$,...pr(this)});c(this,"_debouncedShowLoader",at(this._showLoader.bind(this),300))}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let o=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),n=new ResizeObserver(([a])=>{a.contentRect.width>0&&a.contentRect.height>0&&(e(),clearTimeout(o),n.disconnect())});n.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}if(this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==K&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||K)}),this.sub("*tabId",t=>{this.ref["img-el"].className=M("image",{image_hidden_to_cropper:t===j.CROP,image_hidden_effects:t!==j.CROP})}),this.$.cdnUrl){let t=Xs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=qs(this.$.cdnUrl),r=dr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{let e=this.$["*originalUrl"],r=P(St(t)),o=S(e,P(r,"preview")),n={originalUrl:e,cdnUrlModifiers:r,cdnUrl:o,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:n,bubbles:!0,composed:!0}))},!1);try{fetch(S(this.$["*originalUrl"],P("json"))).then(t=>t.json()).then(t=>{let{width:e,height:r}=t;this.$["*imageSize"]={width:e,height:r}})}catch(t){t&&console.error("Failed to load image info",t)}}};c(ct,"className","cloud-image-editor");ct.template=mr;ct.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl"});var _e=33.333333333333336,tt=24*2+34;function Nt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function et(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Nt(t,i),t}function br(s,i){let{x:t,y:e,width:r,height:o}=s,n=i.includes("w")?0:1,a=i.includes("n")?0:1,l=[-1,1][n],u=[-1,1][a],h=[t+n*r+1.5*l,e+a*o+1.5*u-24*u],d=[t+n*r+1.5*l,e+a*o+1.5*u],p=[t+n*r-24*l+1.5*l,e+a*o+1.5*u];return{d:`M ${h[0]} ${h[1]} L ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,center:d}}function vr(s,i){let{x:t,y:e,width:r,height:o}=s,n=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],l=[-1,1][n],u=[-1,1][a],h,d;["n","s"].includes(i)?(h=[t+n*r-34/2,e+a*o+1.5*u],d=[t+n*r+34/2,e+a*o+1.5*u]):(h=[t+n*r+1.5*l,e+a*o-34/2],d=[t+n*r+1.5*l,e+a*o+34/2]);let p=`M ${h[0]} ${h[1]} L ${d[0]} ${d[1]}`,f=[d[0]-(d[0]-h[0])/2,d[1]-(d[1]-h[1])/2];return{d:p,center:f}}function yr(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Cr(s,[i,t]){return{...s,x:s.x+i,y:s.y+t}}function si(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function xr(s,[i,t],e){let{x:r,y:o,width:n,height:a}=s;return e.includes("n")&&(o+=t,a-=t),e.includes("s")&&(a+=t),e.includes("w")&&(r+=i,n-=i),e.includes("e")&&(n+=i),{x:r,y:o,width:n,height:a}}function wr(s,i){let t=Math.max(s.x,i.x),e=Math.min(s.x+s.width,i.x+i.width),r=Math.max(s.y,i.y),o=Math.min(s.y+s.height,i.y+i.height);return{x:t,y:r,width:e-t,height:o-r}}function ri(s,[i,t],e){let{x:r,y:o,width:n,height:a}=s;if(e.includes("n")){let l=a;a=Math.max(t,a),o=o+l-a}if(e.includes("s")&&(a=Math.max(t,a)),e.includes("w")){let l=n;n=Math.max(i,n),r=r+l-n}return e.includes("e")&&(n=Math.max(i,n)),{x:r,y:o,width:n,height:a}}function Tr(s,[i,t]){return s.x<=i&&i<=s.x+s.width&&s.y<=t&&t<=s.y+s.height}var oi=class extends I{constructor(){super();c(this,"init$",{...this.init$,dragging:!1});this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(t){let e=this.$["*imageBox"];if(!e)return;if(t===""&&e.height<=tt&&e.width<=tt)return!0;let r=e.height<=tt&&(t.includes("n")||t.includes("s")),o=e.width<=tt&&(t.includes("e")||t.includes("w"));return r||o}_createBackdrop(){let t=this.$["*cropBox"];if(!t)return;let{x:e,y:r,width:o,height:n}=t,a=this.ref["svg-el"],l=et("mask",{id:"backdrop-mask"}),u=et("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),h=et("rect",{x:e,y:r,width:o,height:n,fill:"black"});l.appendChild(u),l.appendChild(h);let d=et("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});a.appendChild(d),a.appendChild(l),this._backdropMask=l,this._backdropMaskInner=h}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask.style.display="block"}))}_updateBackdrop(){let t=this.$["*cropBox"];if(!t)return;let{x:e,y:r,width:o,height:n}=t;Nt(this._backdropMaskInner,{x:e,y:r,width:o,height:n})}_updateFrame(){let t=this.$["*cropBox"];if(!t)return;for(let r of Object.values(this._frameThumbs)){let{direction:o,pathNode:n,interactionNode:a,groupNode:l}=r,u=o==="",h=o.length===2;if(u){let{x:p,y:f,width:m,height:b}=t,x=[p+m/2,f+b/2];Nt(a,{r:Math.min(m,b)/3,cx:x[0],cy:x[1]})}else{let{d:p,center:f}=h?br(t,o):vr(t,o);Nt(a,{cx:f[0],cy:f[1]}),Nt(n,{d:p})}let d=this._shouldThumbBeDisabled(o);l.setAttribute("class",M("thumb",{"thumb--hidden":d,"thumb--visible":!d}))}let e=this._frameGuides;Nt(e,{x:t.x-1*.5,y:t.y-1*.5,width:t.width+1,height:t.height+1})}_createThumbs(){let t={};for(let e=0;e<3;e++)for(let r=0;r<3;r++){let o=`${["n","","s"][e]}${["w","","e"][r]}`,n=et("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let a=et("circle",{r:24+1.5,fill:"transparent"}),l=et("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(a),t[o]={direction:o,pathNode:l,interactionNode:a,groupNode:n},a.addEventListener("pointerdown",this._handlePointerDown.bind(this,o))}return t}_createGuides(){let t=et("svg"),e=et("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});t.appendChild(e);for(let r=1;r<=2;r++){let o=et("line",{x1:`${_e*r}%`,y1:"0%",x2:`${_e*r}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});t.appendChild(o)}for(let r=1;r<=2;r++){let o=et("line",{x1:"0%",y1:`${_e*r}%`,x2:"100%",y2:`${_e*r}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});t.appendChild(o)}return t.classList.add("guides","guides--semi-hidden"),t}_createFrame(){let t=this.ref["svg-el"],e=document.createDocumentFragment(),r=this._createGuides();e.appendChild(r);let o=this._createThumbs();for(let{groupNode:n}of Object.values(o))e.appendChild(n);t.appendChild(e),this._frameThumbs=o,this._frameGuides=r}_handlePointerDown(t,e){let r=this._frameThumbs[t];if(this._shouldThumbBeDisabled(t))return;let o=this.$["*cropBox"],{x:n,y:a}=this.ref["svg-el"].getBoundingClientRect(),l=e.x-n,u=e.y-a;this.$.dragging=!0,this._draggingThumb=r,this._dragStartPoint=[l,u],this._dragStartCrop={...o}}_handlePointerUp_(t){this._updateCursor(),this.$.dragging&&(t.stopPropagation(),t.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(t){if(!this.$.dragging)return;t.stopPropagation(),t.preventDefault();let e=this.ref["svg-el"],{x:r,y:o}=e.getBoundingClientRect(),n=t.x-r,a=t.y-o,l=n-this._dragStartPoint[0],u=a-this._dragStartPoint[1],{direction:h}=this._draggingThumb,d=this.$["*imageBox"],p=this._dragStartCrop;h===""?(p=Cr(p,[l,u]),p=si(p,d)):(p=xr(p,[l,u],h),p=wr(p,d));let f=[Math.min(d.width,tt),Math.min(d.height,tt)];if(p=ri(p,f,h),!Object.values(p).every(m=>Number.isFinite(m)&&m>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:p});return}this.$["*cropBox"]=p}_handleSvgPointerMove_(t){let e=Object.values(this._frameThumbs).find(r=>{if(this._shouldThumbBeDisabled(r.direction))return!1;let n=r.groupNode.getBoundingClientRect(),a={x:n.x,y:n.y,width:n.width,height:n.height};return Tr(a,[t.x,t.y])});this._hoverThumb=e,this._updateCursor()}_updateCursor(){let t=this._hoverThumb;this.ref["svg-el"].style.cursor=t?yr(t.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(t){Object.values(this._frameThumbs).map(({groupNode:e})=>e).forEach(e=>{e.setAttribute("class",M("thumb",{"thumb--hidden":!t,"thumb--visible":t}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",t=>{t&&(this._guidesHidden=t.height<=tt||t.width<=tt,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",t=>{this._frameGuides.setAttribute("class",M({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&t,"guides--semi-hidden":!this._guidesHidden&&!t}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};oi.template='';var yt=class extends I{constructor(){super(...arguments);c(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=M({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function En(s){let i=s+90;return i=i>=360?0:i,i}function An(s,i){return s==="rotate"?En(i):["mirror","flip"].includes(s)?!i:null}var Yt=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=An(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var be={FILTER:"filter",COLOR_OPERATION:"color_operation"},ut="original",ni=class extends I{constructor(){super(...arguments);c(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?be.FILTER:be.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ut?void 0:this.$.value,filter:this._filter===ut?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=lt[this._operation],[r,o]=t;this.$.min=r,this.$.max=o,this.$.zero=e;let n=this.$["*editorTransformations"][this._operation];if(this._controlType===be.FILTER){let a=o;if(n){let{name:l,amount:u}=n;a=l===this._filter?u:o}this.$.value=a,this.$.defaultValue=a}if(this._controlType===be.COLOR_OPERATION){let a=typeof n!="undefined"?n:e;this.$.value=a,this.$.defaultValue=a}}apply(){let t;this._controlType===be.FILTER?this._filter===ut?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ni.template=``;function ve(s){let i=new Image;return{promise:new Promise((r,o)=>{i.src=s,i.onload=r,i.onerror=o}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=K)}}}function ye(s){let i=[];for(let o of s){let n=ve(o);i.push(n)}let t=i.map(o=>o.image);return{promise:Promise.allSettled(i.map(o=>o.promise)),images:t,cancel:()=>{i.forEach(o=>{o.cancel()})}}}var Bt=class extends yt{constructor(){super(...arguments);c(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),o=e>=2?"lightest":"normal",n=100,a={...this.$["*editorTransformations"]};return a[this._operation]=this._filter!==ut?{name:this._filter,amount:n}:void 0,S(this._originalUrl,P(ei,St(a),`quality/${o}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let o=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"],{promise:a,cancel:l}=ve(o);this._cancelPreload=l,a.catch(u=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:u})}).finally(()=>{n.style.backgroundImage=`url(${o})`,n.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ut,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let o=this.ref["preview-el"];e?o.style.opacity="0":o.style.backgroundImage&&(o.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"];o.style.backgroundImage&&(o.style.backgroundImage="none",o.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Bt.template=`
`;var Zt=class extends yt{constructor(){super(...arguments);c(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=lt[this._operation],r=t[this._operation],o=typeof r!="undefined"?r!==e:!1;this.$.active=o})}};function Er(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function Jt(s,i,t){let r=window.devicePixelRatio,o=Math.min(Math.ceil(i*r),3e3),n=r>=2?"lightest":"normal";return S(s,P(ei,St(t),`quality/${n}`,`stretch/off/-/resize/${o}x`))}function ai(s,i,t){return Math.min(Math.max(s,i),t)}function Ce({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function $n(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var li=class extends I{constructor(){super();c(this,"init$",{...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}});this._commitDebounced=at(this._commit.bind(this),300),this._handleResizeDebounced=at(this._handleResize.bind(this),10)}_handleResize(){this.isConnected&&(this.deactivate(),this.activate(this._imageSize,{fromViewer:!1}))}_syncTransformations(){let t=this.$["*editorTransformations"],e=Er(t,Object.keys(this.$["*operations"])),r={...this.$["*operations"],...e};this.$["*operations"]=r}_initCanvas(){let t=this.ref["canvas-el"],e=t.getContext("2d"),r=this.offsetWidth,o=this.offsetHeight,n=window.devicePixelRatio;t.style.width=`${r}px`,t.style.height=`${o}px`,t.width=r*n,t.height=o*n,e.scale(n,n),this._canvas=t,this._ctx=e}_alignImage(){if(!this._isActive||!this.$.image)return;let t=this.$.image,e=this.$["*padding"],r=this.$["*operations"],{rotate:o}=r,n={width:this.offsetWidth,height:this.offsetHeight},a=Ce({width:t.naturalWidth,height:t.naturalHeight},o);if(a.width>n.width-e*2||a.height>n.height-e*2){let l=a.width/a.height,u=n.width/n.height;if(l>u){let h=n.width-e*2,d=h/l,p=0+e,f=e+(n.height-e*2)/2-d/2;this.$["*imageBox"]={x:p,y:f,width:h,height:d}}else{let h=n.height-e*2,d=h*l,p=e+(n.width-e*2)/2-d/2,f=0+e;this.$["*imageBox"]={x:p,y:f,width:d,height:h}}}else{let{width:l,height:u}=a,h=e+(n.width-e*2)/2-l/2,d=e+(n.height-e*2)/2-u/2;this.$["*imageBox"]={x:h,y:d,width:l,height:u}}}_alignCrop(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,n=this.$["*editorTransformations"].crop;if(n){let{dimensions:[l,u],coords:[h,d]}=n,{width:p,x:f,y:m}=this.$["*imageBox"],{width:b}=Ce(this._imageSize,o),x=p/b;t={x:f+h*x,y:m+d*x,width:l*x,height:u*x}}else t={x:e.x,y:e.y,width:e.width,height:e.height};let a=[Math.min(e.width,tt),Math.min(e.height,tt)];t=ri(t,a,"se"),t=si(t,e),this.$["*cropBox"]=t}_drawImage(){let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:o,flip:n,rotate:a}=r,l=this._ctx,u=Ce({width:e.width,height:e.height},a);l.save(),l.translate(e.x+e.width/2,e.y+e.height/2),l.rotate(a*Math.PI*-1/180),l.scale(o?-1:1,n?-1:1),l.drawImage(t,-u.width/2,-u.height/2,u.width,u.height),l.restore()}_draw(){if(!this._isActive||!this.$.image)return;let t=this._canvas;this._ctx.clearRect(0,0,t.width,t.height),this._drawImage()}_animateIn({fromViewer:t}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=M({active_from_viewer:t,active_from_editor:!t,inactive_to_editor:!1})}))}_calculateDimensions(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a}=e,{width:l,height:u}=Ce(this._imageSize,o),{width:h,height:d}=t,p=n/l,f=a/u;return[ai(Math.round(h/p),1,l),ai(Math.round(d/f),1,u)]}_calculateCrop(){let t=this.$["*cropBox"],e=this.$["*imageBox"],r=this.$["*operations"],{rotate:o}=r,{width:n,height:a,x:l,y:u}=e,{width:h,height:d}=Ce(this._imageSize,o),{x:p,y:f}=t,m=n/h,b=a/d,x=this._calculateDimensions(),A={dimensions:x,coords:[ai(Math.round((p-l)/m),0,h-x[0]),ai(Math.round((f-u)/b),0,d-x[1])]};if(!$n(A)){console.error("Cropper is trying to create invalid crop object",{payload:A});return}if(!(x[0]===h&&x[1]===d))return A}_commit(){if(!this.isConnected)return;let t=this.$["*operations"],{rotate:e,mirror:r,flip:o}=t,n=this._calculateCrop(),l={...this.$["*editorTransformations"],crop:n,rotate:e,mirror:r,flip:o};this.$["*editorTransformations"]=l}setValue(t,e){console.log(`Apply cropper operation [${t}=${e}]`),this.$["*operations"]={...this.$["*operations"],[t]:e},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(t){return this.$["*operations"][t]}async activate(t,{fromViewer:e}){if(!this._isActive){this._isActive=!0,this._imageSize=t,this.removeEventListener("transitionend",this._reset),this._initCanvas();try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw(),this._animateIn({fromViewer:e})}catch(r){console.error("Failed to activate cropper",{error:r})}}}deactivate(){this._isActive&&(this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=M({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}))}_transitionToCrop(){let t=this._calculateDimensions(),e=Math.min(this.offsetWidth,t[0])/this.$["*cropBox"].width,r=Math.min(this.offsetHeight,t[1])/this.$["*cropBox"].height,o=Math.min(e,r),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,a=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${o}) translate(${(this.offsetWidth/2-n)/o}px, ${(this.offsetHeight/2-a)/o}px)`,this.style.transformOrigin=`${n}px ${a}px`}_transitionToImage(){let t=this.$["*cropBox"].x+this.$["*cropBox"].width/2,e=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${t}px ${e}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(t,e){let r=this.offsetWidth;e={...e,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let o=this.proxyUrl(Jt(t,r,e)),{promise:n,cancel:a,image:l}=ve(o),u=this._handleImageLoading(o);return l.addEventListener("load",u,{once:!0}),l.addEventListener("error",u,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=a,n.then(()=>l).catch(h=>(console.error("Failed to load image",{error:h}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(t){let e="crop",r=this.$["*loadingOperations"];return r.get(e)||r.set(e,new Map),r.get(e).get(t)||(r.set(e,r.get(e).set(t,!0)),this.$["*loadingOperations"]=r),()=>{var o;(o=r==null?void 0:r.get(e))!=null&&o.has(t)&&(r.get(e).delete(t),this.$["*loadingOperations"]=r)}}initCallback(){super.initCallback(),this._observer=new ResizeObserver(([t])=>{t.contentRect.width>0&&t.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeDebounced()}),this._observer.observe(this),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",t=>{this.$.image&&this._commitDebounced()}),setTimeout(()=>{this.sub("*networkProblems",t=>{t||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect()}};li.template=``;function ss(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function kn(s){return s.reduce((i,t,e)=>er<=i&&i<=o);return s.map(r=>{let o=Math.abs(e[0]-e[1]),n=Math.abs(i-e[0])/o;return e[0]===r?i>t?1:1-n:e[1]===r?i>=t?n:1:0})}function On(s,i){return s.map((t,e)=>to-n)}var rs=class extends I{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=at(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let o={...this._transformations};e&&(o[e]=t?{name:t,amount:r}:r);let n=this.offsetWidth;return this.proxyUrl(Jt(i,n,o))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(l=>l.value===e);if(r())return;let o=this._constructKeypoint(i,e),n=new Image;n.src=o.src;let a=this._handleImageLoading(o.src);n.addEventListener("load",a,{once:!0}),n.addEventListener("error",a,{once:!0}),o.image=n,n.classList.add("fader-image"),n.addEventListener("load",()=>{if(r())return;let l=this._keypoints,u=l.findIndex(d=>d.value>e),h=u{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=lt[i],r=this._keypoints.map(a=>a.value),o=In(r,t,e),n=On(r,e);for(let[a,l]of Object.entries(this._keypoints))l.opacity=o[a],l.zIndex=n[a];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(u=>u.src),{images:r,promise:o,cancel:n}=ye(e);r.forEach(u=>{let h=this._handleImageLoading(u.src);u.addEventListener("load",h),u.addEventListener("error",h)}),this._cancelLastImages=()=>{n(),this._cancelLastImages=void 0};let a=this._operation,l=this._filter;await o,this._isActive&&this._isSame(a,l)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((u,h)=>{let d=r[h];d.classList.add("fader-image"),u.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let n=Ar(e,r).map(l=>this._imageSrc({url:i,filter:t,operation:e,value:l})),{cancel:a}=ye(n);this._cancelBatchPreload=a}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=M({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=M({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:o}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=o,typeof e!="number"&&!r){let a=this._imageSrc({operation:t,value:e});this._setOriginalSrc(a),this._container&&this._container.remove();return}this._keypoints=Ar(t,e).map(a=>this._constructKeypoint(t,a)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=M({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var Rn=1,ci=class extends I{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>Rn?this.scrollLeft+=e:this.scrollLeft+=t})}};ci.template=" ";function Ln(s){return``}function Un(s){return`
`}var ui=class extends I{constructor(){super();c(this,"_updateInfoTooltip",at(()=>{var o,n;let t=this.$["*editorTransformations"],e="",r=!1;if(this.$["*tabId"]===j.FILTERS)if(r=!0,this.$["*currentFilter"]&&((o=t==null?void 0:t.filter)==null?void 0:o.name)===this.$["*currentFilter"]){let a=((n=t==null?void 0:t.filter)==null?void 0:n.amount)||100;e=this.l10n(this.$["*currentFilter"])+" "+a}else e=this.l10n(ut);else if(this.$["*tabId"]===j.SLIDERS&&this.$["*currentOperation"]){r=!0;let a=(t==null?void 0:t[this.$["*currentOperation"]])||lt[this.$["*currentOperation"]].zero;e=this.$["*currentOperation"]+" "+a}r&&(this.$["*operationTooltip"]=e),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",r)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ut,"*currentOperation":null,"*tabId":j.CROP,showLoader:!1,filters:gr,colorOperations:fr,cropOperations:_r,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":t=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":t=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":t=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":t=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=at(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===j.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=Zt.is&&new Zt;return e.operation=t,e}_createFilterControl(t){let e=Bt.is&&new Bt;return e.filter=t,e}_createToggleControl(t){let e=Yt.is&&new Yt;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===j.CROP?this.$.cropOperations.forEach(o=>{let n=this._createToggleControl(o);r.appendChild(n)}):t===j.FILTERS?[ut,...this.$.filters].forEach(o=>{let n=this._createFilterControl(o);r.appendChild(n)}):t===j.SLIDERS&&this.$.colorOperations.forEach(o=>{let n=this._createOperationControl(o);r.appendChild(n)}),r.childNodes.forEach((o,n)=>{n===r.childNodes.length-1&&o.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===j.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of ii){let o=r===t,n=this.ref[`tab-toggle-${r}`];n.active=o,o?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=o}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(Jt(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=ye([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",t=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,o]of r.entries())if(o){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this._updateInfoTooltip()}};ui.template=`
{{*operationTooltip}}
${ii.map(Un).join("")}
${ii.map(Ln).join("")}
`;var xe=class extends _{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return M("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};xe.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});xe.template=`
{{text}}
`;var hi=class extends _{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};hi.template=`
`;var di={transition:"transition",visible:"visible",hidden:"hidden"},pi=class extends _{constructor(){super(),this._visible=!1,this._visibleStyle=di.visible,this._hiddenStyle=di.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",cr(this,{[di.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(di.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};pi.template=" ";var mi=class extends _{constructor(){super();c(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${n}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),n=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${n}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),o=Math.ceil(r/2),n=Math.ceil(o/15)-2;if(this._stepsCount===n)return;let a=document.createDocumentFragment(),l=document.createElement("div"),u=document.createElement("div");l.className="minor-step",u.className="border-step",a.appendChild(u);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.CLOUD_IMG_EDIT);c(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new ct,e=this.$.cdnUrl;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),t.addEventListener("apply",r=>this.handleApply(r)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var Pn=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Sr=function(s,i="i"){let t=s.split("*").map(Pn);return new RegExp("^"+t.join(".+")+"$",i)};var Mn=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],o=Object.keys(r).reduce((n,a)=>{let l=r[a];return n+`${a}: ${l};`},"");return t+`${e}{${o}}`},"");function $r({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let o=`solid 1px ${r}`;return Mn({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":o},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":o},".list-table-body .list-items":{"border-bottom":o},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var $t={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in $t){let t=$t[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var kr=function(s,i,t){s in $t||($t[s]=[]),$t[s].push([i,t])},Ir=function(s,i){s in $t&&($t[s]=$t[s].filter(t=>t[0]!==i))};function Or(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var fi=class extends v{constructor(){super(...arguments);c(this,"activityType",g.activities.EXTERNAL);c(this,"init$",{...this.init$,activityIcon:"",activityCaption:"",counter:0,onDone:()=>{this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}});c(this,"_iframe",null);c(this,"_inheritedUpdateCssData",this.updateCssData);c(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.$.counter=0,this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()})}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){console.log(t),this.$.counter=this.$.counter+1;let e=(()=>{if(t.alternatives){let n=U(this.cfg.externalSourcesPreferredTypes);for(let a of n){let l=Sr(a);for(let[u,h]of Object.entries(t.alternatives))if(l.test(u))return h}}return t.url})(),{filename:r}=t,{externalSourceType:o}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:o})}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:$r(t)})}remoteUrl(){var a,l;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,o={lang:((l=(a=this.getCssData("--l10n-locale-name"))==null?void 0:a.split("-"))==null?void 0:l[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},n=new URL(this.cfg.socialBaseUrl);return n.pathname=`/window3/${r}`,n.search=Or(o),n.toString()}mountIframe(){let t=se({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),kr("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t}unmountIframe(){this._iframe&&Ir("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null}};fi.template=`
{{activityCaption}}
{{counter}}
`;var we=class extends _{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;U(i).forEach(e=>{let r=se({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};we.bindAttributes({"tab-list":null,default:null});we.template=`
`;var Qt=class extends v{constructor(){super(...arguments);c(this,"processInnerHtml",!0);c(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return Qt.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let o=document.createElement("input");o.type="hidden",o.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,o.value=r,this._dynamicInputsContainer.appendChild(o)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(n=>n.uuid),r=await this.getUploadClientOptions(),o=await Rs(e,{...r});this.$.output={groupData:o,files:t}}else this.$.output=t},!1)}};Qt.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ns=class extends g{};var gi=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(o=>{e+=``}),this.$.selectHtml=e})}};gi.template=``;var q={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Rr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},st=class extends _{constructor(){super(...arguments);c(this,"init$",{...this.init$,src:"",ppIcon:q.PLAY,fsIcon:q.FS_ON,volIcon:q.VOL_ON,capIcon:q.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Rr.exitFullscreen():Rr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===q.CAP_OFF?(this.$.capIcon=q.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(st.is+":captions","1")):(this.$.capIcon=q.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(st.is+":captions"))}toggleSound(){this.$.volIcon===q.VOL_ON?(this.$.volIcon=q.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=q.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(st.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let o=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${o}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(st.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=q.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=q.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=q.FS_OFF:this.$.fsIcon=q.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let o="";r==null||r.sources.forEach(n=>{o+=``}),r.tracks&&(r.tracks.forEach(n=>{o+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=o,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(st.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};st.template=`
{{currentTime}} / {{totalTime}}
`;st.bindAttributes({video:"video",src:"src"});var Nn="css-src";function _i(s){return class extends s{constructor(){super(...arguments);c(this,"renderShadow",!0);c(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Nn);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var Te=class extends _i(_){};var bi=class extends _{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};c(bi,"template",`Powered by Uploadcare`);var kt=class extends Te{constructor(){super(...arguments);c(this,"init$",Me(this));c(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var vi=class extends kt{};vi.template=``;var yi=class extends kt{constructor(){super(...arguments);c(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.sub(L("sourceList"),e=>{e!=="local"&&(this.$[L("sourceList")]="local")}),this.sub(L("confirmUpload"),e=>{e!==!1&&(this.$[L("confirmUpload")]=!1)})}};yi.template=``;var Ci=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};Ci.template=``;var as=class extends _i(ct){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function ls(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var cs="LR";async function Dn(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[cs]){t(window[cs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let o=window[cs];i&&ls(o),t(o)},document.head.appendChild(r)})}export{g as ActivityBlock,ns as ActivityHeader,zt as BaseComponent,_ as Block,Ye as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,ct as CloudImageEditorBlock,ze as Config,Je as ConfirmationDialog,bi as Copyright,oi as CropFrame,E as Data,Qt as DataOutput,pe as DropArea,Yt as EditorCropButtonControl,Bt as EditorFilterControl,li as EditorImageCropper,rs as EditorImageFader,Zt as EditorOperationControl,ci as EditorScroller,ni as EditorSlider,ui as EditorToolbar,fi as ExternalSource,bt as FileItem,ge as FilePreview,Ci as FileUploaderInline,yi as FileUploaderMinimal,vi as FileUploaderRegular,he as Icon,qi as Img,hi as LineLoaderUi,xe as LrBtnUi,qe as MessageBox,F as Modal,Ds as PACKAGE_NAME,Bs as PACKAGE_VERSION,pi as PresenceToggle,ti as ProgressBar,Qe as ProgressBarCommon,gi as Select,Te as ShadowWrapper,We as SimpleBtn,mi as SliderUi,me as SourceBtn,Zi as SourceList,Gi as StartFrom,we as Tabs,Qi as UploadCtxProvider,Ze as UploadDetails,Ge as UploadList,v as UploaderBlock,Ke as UrlSource,st as Video,Dn as connectBlocksFrom,ls as registerBlocks,_i as shadowed,_t as toKebabCase}; \ No newline at end of file +var Dr=Object.defineProperty;var Fr=(s,i,t)=>i in s?Dr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t;var h=(s,i,t)=>(Fr(s,typeof i!="symbol"?i+"":i,t),t),Ei=(s,i,t)=>{if(!i.has(s))throw TypeError("Cannot "+t)};var F=(s,i,t)=>(Ei(s,i,"read from private field"),t?t.call(s):i.get(s)),Ot=(s,i,t)=>{if(i.has(s))throw TypeError("Cannot add the same private member more than once");i instanceof WeakSet?i.add(s):i.set(s,t)},re=(s,i,t,e)=>(Ei(s,i,"write to private field"),e?e.call(s,t):i.set(s,t),t);var Se=(s,i,t)=>(Ei(s,i,"access private method"),t);var Vr=Object.defineProperty,Br=(s,i,t)=>i in s?Vr(s,i,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[i]=t,$i=(s,i,t)=>(Br(s,typeof i!="symbol"?i+"":i,t),t);function zr(s){let i=t=>{var e;for(let r in t)((e=t[r])==null?void 0:e.constructor)===Object&&(t[r]=i(t[r]));return{...t}};return i(s)}var E=class{constructor(s){s.constructor===Object?this.store=zr(s):(this._storeIsProxy=!0,this.store=s),this.callbackMap=Object.create(null)}static warn(s,i){console.warn(`Symbiote Data: cannot ${s}. Prop name: `+i)}read(s){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("read",s),null):this.store[s]}has(s){return this._storeIsProxy?this.store[s]!==void 0:this.store.hasOwnProperty(s)}add(s,i,t=!1){!t&&Object.keys(this.store).includes(s)||(this.store[s]=i,this.notify(s))}pub(s,i){if(!this._storeIsProxy&&!this.store.hasOwnProperty(s)){E.warn("publish",s);return}this.store[s]=i,this.notify(s)}multiPub(s){for(let i in s)this.pub(i,s[i])}notify(s){this.callbackMap[s]&&this.callbackMap[s].forEach(i=>{i(this.store[s])})}sub(s,i,t=!0){return!this._storeIsProxy&&!this.store.hasOwnProperty(s)?(E.warn("subscribe",s),null):(this.callbackMap[s]||(this.callbackMap[s]=new Set),this.callbackMap[s].add(i),t&&i(this.store[s]),{remove:()=>{this.callbackMap[s].delete(i),this.callbackMap[s].size||delete this.callbackMap[s]},callback:i})}static registerCtx(s,i=Symbol()){let t=E.globalStore.get(i);return t?console.warn('State: context UID "'+i+'" already in use'):(t=new E(s),E.globalStore.set(i,t)),t}static deleteCtx(s){E.globalStore.delete(s)}static getCtx(s,i=!0){return E.globalStore.get(s)||(i&&console.warn('State: wrong context UID - "'+s+'"'),null)}};E.globalStore=new Map;var C=Object.freeze({BIND_ATTR:"set",ATTR_BIND_PRFX:"@",EXT_DATA_CTX_PRFX:"*",NAMED_DATA_CTX_SPLTR:"/",CTX_NAME_ATTR:"ctx-name",CTX_OWNER_ATTR:"ctx-owner",CSS_CTX_PROP:"--ctx-name",EL_REF_ATTR:"ref",AUTO_TAG_PRFX:"sym",REPEAT_ATTR:"repeat",REPEAT_ITEM_TAG_ATTR:"repeat-item-tag",SET_LATER_KEY:"__toSetLater__",USE_TPL:"use-template",ROOT_STYLE_ATTR_NAME:"sym-component"}),ps="1234567890QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm",jr=ps.length-1,oe=class{static generate(s="XXXXXXXXX-XXX"){let i="";for(let t=0;t{li&&t?i[0].toUpperCase()+i.slice(1):i).join("").split("_").map((i,t)=>i&&t?i.toUpperCase():i).join("")}function Wr(s,i){[...s.querySelectorAll(`[${C.REPEAT_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.REPEAT_ITEM_TAG_ATTR),r;if(e&&(r=window.customElements.get(e)),!r){r=class extends i.BaseComponent{constructor(){super(),e||(this.style.display="contents")}};let o=t.innerHTML;r.template=o,r.reg(e)}for(;t.firstChild;)t.firstChild.remove();let n=t.getAttribute(C.REPEAT_ATTR);i.sub(n,o=>{if(!o){for(;t.firstChild;)t.firstChild.remove();return}let l=[...t.children],a,c=u=>{u.forEach((p,m)=>{if(l[m])if(l[m].set$)setTimeout(()=>{l[m].set$(p)});else for(let f in p)l[m][f]=p[f];else{a||(a=new DocumentFragment);let f=new r;Object.assign(f.init$,p),a.appendChild(f)}}),a&&t.appendChild(a);let d=l.slice(u.length,l.length);for(let p of d)p.remove()};if(o.constructor===Array)c(o);else if(o.constructor===Object){let u=[];for(let d in o){let p=o[d];Object.defineProperty(p,"_KEY_",{value:d,enumerable:!0}),u.push(p)}c(u)}else console.warn("Symbiote repeat data type error:"),console.log(o)}),t.removeAttribute(C.REPEAT_ATTR),t.removeAttribute(C.REPEAT_ITEM_TAG_ATTR)})}var us="__default__";function Xr(s,i){if(i.shadowRoot)return;let t=[...s.querySelectorAll("slot")];if(!t.length)return;let e={};t.forEach(r=>{let n=r.getAttribute("name")||us;e[n]={slot:r,fr:document.createDocumentFragment()}}),i.initChildren.forEach(r=>{var n;let o=us;r instanceof Element&&r.hasAttribute("slot")&&(o=r.getAttribute("slot"),r.removeAttribute("slot")),(n=e[o])==null||n.fr.appendChild(r)}),Object.values(e).forEach(r=>{if(r.fr.childNodes.length)r.slot.parentNode.replaceChild(r.fr,r.slot);else if(r.slot.childNodes.length){let n=document.createDocumentFragment();n.append(...r.slot.childNodes),r.slot.parentNode.replaceChild(n,r.slot)}else r.slot.remove()})}function qr(s,i){[...s.querySelectorAll(`[${C.EL_REF_ATTR}]`)].forEach(t=>{let e=t.getAttribute(C.EL_REF_ATTR);i.ref[e]=t,t.removeAttribute(C.EL_REF_ATTR)})}function Gr(s,i){[...s.querySelectorAll(`[${C.BIND_ATTR}]`)].forEach(t=>{let r=t.getAttribute(C.BIND_ATTR).split(";");[...t.attributes].forEach(n=>{if(n.name.startsWith("-")&&n.value){let o=Hr(n.name.replace("-",""));r.push(o+":"+n.value),t.removeAttribute(n.name)}}),r.forEach(n=>{if(!n)return;let o=n.split(":").map(u=>u.trim()),l=o[0],a;l.indexOf(C.ATTR_BIND_PRFX)===0&&(a=!0,l=l.replace(C.ATTR_BIND_PRFX,""));let c=o[1].split(",").map(u=>u.trim());for(let u of c){let d;u.startsWith("!!")?(d="double",u=u.replace("!!","")):u.startsWith("!")&&(d="single",u=u.replace("!","")),i.sub(u,p=>{d==="double"?p=!!p:d==="single"&&(p=!p),a?(p==null?void 0:p.constructor)===Boolean?p?t.setAttribute(l,""):t.removeAttribute(l):t.setAttribute(l,p):fs(t,l,p)||(t[C.SET_LATER_KEY]||(t[C.SET_LATER_KEY]=Object.create(null)),t[C.SET_LATER_KEY][l]=p)})}}),t.removeAttribute(C.BIND_ATTR)})}var ke="{{",ne="}}",Kr="skip-text";function Yr(s){let i,t=[],e=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,{acceptNode:r=>{var n;return!((n=r.parentElement)!=null&&n.hasAttribute(Kr))&&r.textContent.includes(ke)&&r.textContent.includes(ne)&&1}});for(;i=e.nextNode();)t.push(i);return t}var Zr=function(s,i){Yr(s).forEach(e=>{let r=[],n;for(;e.textContent.includes(ne);)e.textContent.startsWith(ke)?(n=e.textContent.indexOf(ne)+ne.length,e.splitText(n),r.push(e)):(n=e.textContent.indexOf(ke),e.splitText(n)),e=e.nextSibling;r.forEach(o=>{let l=o.textContent.replace(ke,"").replace(ne,"");o.textContent="",i.sub(l,a=>{o.textContent=a})})})},Jr=[Wr,Xr,qr,Gr,Zr],Ie="'",Bt='"',Qr=/\\([0-9a-fA-F]{1,6} ?)/g;function tn(s){return(s[0]===Bt||s[0]===Ie)&&(s[s.length-1]===Bt||s[s.length-1]===Ie)}function en(s){return(s[0]===Bt||s[0]===Ie)&&(s=s.slice(1)),(s[s.length-1]===Bt||s[s.length-1]===Ie)&&(s=s.slice(0,-1)),s}function sn(s){let i="",t="";for(var e=0;eString.fromCodePoint(parseInt(e.trim(),16))),i=i.replaceAll(`\\ +`,"\\n"),i=sn(i),i=Bt+i+Bt);try{return JSON.parse(i)}catch{throw new Error(`Failed to parse CSS property value: ${i}. Original input: ${s}`)}}var ds=0,Vt=null,pt=null,vt=class extends HTMLElement{constructor(){super(),$i(this,"updateCssData",()=>{var s;this.dropCssDataCache(),(s=this.__boundCssProps)==null||s.forEach(i=>{let t=this.getCssData(this.__extractCssName(i),!0);t!==null&&this.$[i]!==t&&(this.$[i]=t)})}),this.init$=Object.create(null),this.cssInit$=Object.create(null),this.tplProcessors=new Set,this.ref=Object.create(null),this.allSubs=new Set,this.pauseRender=!1,this.renderShadow=!1,this.readyToDestroy=!0,this.processInnerHtml=!1,this.allowCustomTemplate=!1,this.ctxOwner=!1}get BaseComponent(){return vt}initCallback(){}__initCallback(){var s;this.__initialized||(this.__initialized=!0,(s=this.initCallback)==null||s.call(this))}render(s,i=this.renderShadow){let t;if((i||this.constructor.__shadowStylesUrl)&&!this.shadowRoot&&this.attachShadow({mode:"open"}),this.allowCustomTemplate){let r=this.getAttribute(C.USE_TPL);if(r){let n=this.getRootNode(),o=(n==null?void 0:n.querySelector(r))||document.querySelector(r);o?s=o.content.cloneNode(!0):console.warn(`Symbiote template "${r}" is not found...`)}}if(this.processInnerHtml)for(let r of this.tplProcessors)r(this,this);if(s||this.constructor.template){if(this.constructor.template&&!this.constructor.__tpl&&(this.constructor.__tpl=document.createElement("template"),this.constructor.__tpl.innerHTML=this.constructor.template),(s==null?void 0:s.constructor)===DocumentFragment)t=s;else if((s==null?void 0:s.constructor)===String){let r=document.createElement("template");r.innerHTML=s,t=r.content.cloneNode(!0)}else this.constructor.__tpl&&(t=this.constructor.__tpl.content.cloneNode(!0));for(let r of this.tplProcessors)r(t,this)}let e=()=>{t&&(i&&this.shadowRoot.appendChild(t)||this.appendChild(t)),this.__initCallback()};if(this.constructor.__shadowStylesUrl){i=!0;let r=document.createElement("link");r.rel="stylesheet",r.href=this.constructor.__shadowStylesUrl,r.onload=e,this.shadowRoot.prepend(r)}else e()}addTemplateProcessor(s){this.tplProcessors.add(s)}get autoCtxName(){return this.__autoCtxName||(this.__autoCtxName=oe.generate(),this.style.setProperty(C.CSS_CTX_PROP,`'${this.__autoCtxName}'`)),this.__autoCtxName}get cssCtxName(){return this.getCssData(C.CSS_CTX_PROP,!0)}get ctxName(){var s;let i=((s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim())||this.cssCtxName||this.__cachedCtxName||this.autoCtxName;return this.__cachedCtxName=i,i}get localCtx(){return this.__localCtx||(this.__localCtx=E.registerCtx({},this)),this.__localCtx}get nodeCtx(){return E.getCtx(this.ctxName,!1)||E.registerCtx({},this.ctxName)}static __parseProp(s,i){let t,e;if(s.startsWith(C.EXT_DATA_CTX_PRFX))t=i.nodeCtx,e=s.replace(C.EXT_DATA_CTX_PRFX,"");else if(s.includes(C.NAMED_DATA_CTX_SPLTR)){let r=s.split(C.NAMED_DATA_CTX_SPLTR);t=E.getCtx(r[0]),e=r[1]}else t=i.localCtx,e=s;return{ctx:t,name:e}}sub(s,i,t=!0){let e=n=>{this.isConnected&&i(n)},r=vt.__parseProp(s,this);r.ctx.has(r.name)?this.allSubs.add(r.ctx.sub(r.name,e,t)):window.setTimeout(()=>{this.allSubs.add(r.ctx.sub(r.name,e,t))})}notify(s){let i=vt.__parseProp(s,this);i.ctx.notify(i.name)}has(s){let i=vt.__parseProp(s,this);return i.ctx.has(i.name)}add(s,i,t=!1){let e=vt.__parseProp(s,this);e.ctx.add(e.name,i,t)}add$(s,i=!1){for(let t in s)this.add(t,s[t],i)}get $(){if(!this.__stateProxy){let s=Object.create(null);this.__stateProxy=new Proxy(s,{set:(i,t,e)=>{let r=vt.__parseProp(t,this);return r.ctx.pub(r.name,e),!0},get:(i,t)=>{let e=vt.__parseProp(t,this);return e.ctx.read(e.name)}})}return this.__stateProxy}set$(s,i=!1){for(let t in s){let e=s[t];i||![String,Number,Boolean].includes(e==null?void 0:e.constructor)?this.$[t]=e:this.$[t]!==e&&(this.$[t]=e)}}get __ctxOwner(){return this.ctxOwner||this.hasAttribute(C.CTX_OWNER_ATTR)&&this.getAttribute(C.CTX_OWNER_ATTR)!=="false"}__initDataCtx(){let s=this.constructor.__attrDesc;if(s)for(let i of Object.values(s))Object.keys(this.init$).includes(i)||(this.init$[i]="");for(let i in this.init$)if(i.startsWith(C.EXT_DATA_CTX_PRFX))this.nodeCtx.add(i.replace(C.EXT_DATA_CTX_PRFX,""),this.init$[i],this.__ctxOwner);else if(i.includes(C.NAMED_DATA_CTX_SPLTR)){let t=i.split(C.NAMED_DATA_CTX_SPLTR),e=t[0].trim(),r=t[1].trim();if(e&&r){let n=E.getCtx(e,!1);n||(n=E.registerCtx({},e)),n.add(r,this.init$[i])}}else this.localCtx.add(i,this.init$[i]);for(let i in this.cssInit$)this.bindCssData(i,this.cssInit$[i]);this.__dataCtxInitialized=!0}connectedCallback(){var s;if(this.isConnected){if(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),!this.connectedOnce){let i=(s=this.getAttribute(C.CTX_NAME_ATTR))==null?void 0:s.trim();if(i&&this.style.setProperty(C.CSS_CTX_PROP,`'${i}'`),this.__initDataCtx(),this[C.SET_LATER_KEY]){for(let t in this[C.SET_LATER_KEY])fs(this,t,this[C.SET_LATER_KEY][t]);delete this[C.SET_LATER_KEY]}this.initChildren=[...this.childNodes];for(let t of Jr)this.addTemplateProcessor(t);if(this.pauseRender)this.__initCallback();else if(this.constructor.__rootStylesLink){let t=this.getRootNode();if(!t)return;if(t==null?void 0:t.querySelector(`link[${C.ROOT_STYLE_ATTR_NAME}="${this.constructor.is}"]`)){this.render();return}let r=this.constructor.__rootStylesLink.cloneNode(!0);r.setAttribute(C.ROOT_STYLE_ATTR_NAME,this.constructor.is),r.onload=()=>{this.render()},t.nodeType===Node.DOCUMENT_NODE?t.head.appendChild(r):t.prepend(r)}else this.render()}this.connectedOnce=!0}}destroyCallback(){}disconnectedCallback(){this.connectedOnce&&(this.dropCssDataCache(),this.readyToDestroy&&(this.__disconnectTimeout&&window.clearTimeout(this.__disconnectTimeout),this.__disconnectTimeout=window.setTimeout(()=>{this.destroyCallback();for(let s of this.allSubs)s.remove(),this.allSubs.delete(s);for(let s of this.tplProcessors)this.tplProcessors.delete(s);pt==null||pt.delete(this.updateCssData),pt!=null&&pt.size||(Vt==null||Vt.disconnect(),Vt=null,pt=null)},100)))}static reg(s,i=!1){s||(ds++,s=`${C.AUTO_TAG_PRFX}-${ds}`),this.__tag=s;let t=window.customElements.get(s);if(t){!i&&t!==this&&console.warn([`Element with tag name "${s}" already registered.`,`You're trying to override it with another class "${this.name}".`,"This is most likely a mistake.","New element will not be registered."].join(` `));return}window.customElements.define(s,i?class extends this{}:this)}static get is(){return this.__tag||this.reg(),this.__tag}static bindAttributes(s){this.observedAttributes=Object.keys(s),this.__attrDesc=s}attributeChangedCallback(s,i,t){var e;if(i===t)return;let r=(e=this.constructor.__attrDesc)==null?void 0:e[s];r?this.__dataCtxInitialized?this.$[r]=t:this.init$[r]=t:this[s]=t}getCssData(s,i=!1){if(this.__cssDataCache||(this.__cssDataCache=Object.create(null)),!Object.keys(this.__cssDataCache).includes(s)){this.__computedStyle||(this.__computedStyle=window.getComputedStyle(this));let t=this.__computedStyle.getPropertyValue(s).trim();try{this.__cssDataCache[s]=rn(t)}catch{!i&&console.warn(`CSS Data error: ${s}`),this.__cssDataCache[s]=null}}return this.__cssDataCache[s]}__extractCssName(s){return s.split("--").map((i,t)=>t===0?"":i).join("--")}__initStyleAttrObserver(){pt||(pt=new Set),pt.add(this.updateCssData),Vt||(Vt=new MutationObserver(s=>{s[0].type==="attributes"&&pt.forEach(i=>{i()})}),Vt.observe(document,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style"]}))}bindCssData(s,i=""){this.__boundCssProps||(this.__boundCssProps=new Set),this.__boundCssProps.add(s);let t=this.getCssData(this.__extractCssName(s),!0);t===null&&(t=i),this.add(s,t),this.__initStyleAttrObserver()}dropCssDataCache(){this.__cssDataCache=null,this.__computedStyle=null}defineAccessor(s,i,t){let e="__"+s;this[e]=this[s],Object.defineProperty(this,s,{set:r=>{this[e]=r,t?window.setTimeout(()=>{i==null||i(r)}):i==null||i(r)},get:()=>this[e]}),this[s]=this[e]}static set shadowStyles(s){let i=new Blob([s],{type:"text/css"});this.__shadowStylesUrl=URL.createObjectURL(i)}static set rootStyles(s){if(!this.__rootStylesLink){let i=new Blob([s],{type:"text/css"}),t=URL.createObjectURL(i),e=document.createElement("link");e.href=t,e.rel="stylesheet",this.__rootStylesLink=e}}},zt=vt;$i(zt,"template");var Ai=class{static _print(s){console.warn(s)}static setDefaultTitle(s){this.defaultTitle=s}static setRoutingMap(s){Object.assign(this.appMap,s);for(let i in this.appMap)!this.defaultRoute&&this.appMap[i].default===!0?this.defaultRoute=i:!this.errorRoute&&this.appMap[i].error===!0&&(this.errorRoute=i)}static set routingEventName(s){this.__routingEventName=s}static get routingEventName(){return this.__routingEventName||"sym-on-route"}static readAddressBar(){let s={route:null,options:{}};return window.location.search.split(this.separator).forEach(t=>{if(t.includes("?"))s.route=t.replace("?","");else if(t.includes("=")){let e=t.split("=");s.options[e[0]]=decodeURI(e[1])}else s.options[t]=!0}),s}static notify(){let s=this.readAddressBar(),i=this.appMap[s.route];if(i&&i.title&&(document.title=i.title),s.route===null&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i&&this.errorRoute){this.applyRoute(this.errorRoute);return}else if(!i&&this.defaultRoute){this.applyRoute(this.defaultRoute);return}else if(!i){this._print(`Route "${s.route}" not found...`);return}let t=new CustomEvent(Ai.routingEventName,{detail:{route:s.route,options:Object.assign(i||{},s.options)}});window.dispatchEvent(t)}static reflect(s,i={}){let t=this.appMap[s];if(!t){this._print("Wrong route: "+s);return}let e="?"+s;for(let n in i)i[n]===!0?e+=this.separator+n:e+=this.separator+n+`=${i[n]}`;let r=t.title||this.defaultTitle||"";window.history.pushState(null,r,e),document.title=r}static applyRoute(s,i={}){this.reflect(s,i),this.notify()}static setSeparator(s){this._separator=s}static get separator(){return this._separator||"&"}static createRouterData(s,i){this.setRoutingMap(i);let t=E.registerCtx({route:null,options:null,title:null},s);return window.addEventListener(this.routingEventName,e=>{var r;t.multiPub({route:e.detail.route,options:e.detail.options,title:((r=e.detail.options)==null?void 0:r.title)||this.defaultTitle||""})}),Ai.notify(),this.initPopstateListener(),t}static initPopstateListener(){this.__onPopstate||(this.__onPopstate=()=>{this.notify()},window.addEventListener("popstate",this.__onPopstate))}static removePopstateListener(){window.removeEventListener("popstate",this.__onPopstate),this.__onPopstate=null}};Ai.appMap=Object.create(null);function nn(s,i){for(let t in i)t.includes("-")?s.style.setProperty(t,i[t]):s.style[t]=i[t]}function on(s,i){for(let t in i)i[t].constructor===Boolean?i[t]?s.setAttribute(t,""):s.removeAttribute(t):s.setAttribute(t,i[t])}function le(s={tag:"div"}){let i=document.createElement(s.tag);if(s.attributes&&on(i,s.attributes),s.styles&&nn(i,s.styles),s.properties)for(let t in s.properties)i[t]=s.properties[t];return s.processors&&s.processors.forEach(t=>{t(i)}),s.children&&s.children.forEach(t=>{let e=le(t);i.appendChild(e)}),i}var ms="idb-store-ready",ln="symbiote-db",an="symbiote-idb-update_",cn=class{_notifyWhenReady(s=null){window.dispatchEvent(new CustomEvent(ms,{detail:{dbName:this.name,storeName:this.storeName,event:s}}))}get _updEventName(){return an+this.name}_getUpdateEvent(s){return new CustomEvent(this._updEventName,{detail:{key:this.name,newValue:s}})}_notifySubscribers(s){window.localStorage.removeItem(this.name),window.localStorage.setItem(this.name,s),window.dispatchEvent(this._getUpdateEvent(s))}constructor(s,i){this.name=s,this.storeName=i,this.version=1,this.request=window.indexedDB.open(this.name,this.version),this.request.onupgradeneeded=t=>{this.db=t.target.result,this.objStore=this.db.createObjectStore(i,{keyPath:"_key"}),this.objStore.transaction.oncomplete=e=>{this._notifyWhenReady(e)}},this.request.onsuccess=t=>{this.db=t.target.result,this._notifyWhenReady(t)},this.request.onerror=t=>{console.error(t)},this._subscriptionsMap={},this._updateHandler=t=>{t.key===this.name&&this._subscriptionsMap[t.newValue]&&this._subscriptionsMap[t.newValue].forEach(async r=>{r(await this.read(t.newValue))})},this._localUpdateHandler=t=>{this._updateHandler(t.detail)},window.addEventListener("storage",this._updateHandler),window.addEventListener(this._updEventName,this._localUpdateHandler)}read(s){let t=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).get(s);return new Promise((e,r)=>{t.onsuccess=n=>{var o;(o=n.target.result)!=null&&o._value?e(n.target.result._value):(e(null),console.warn(`IDB: cannot read "${s}"`))},t.onerror=n=>{r(n)}})}write(s,i,t=!1){let e={_key:s,_value:i},n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).put(e);return new Promise((o,l)=>{n.onsuccess=a=>{t||this._notifySubscribers(s),o(a.target.result)},n.onerror=a=>{l(a)}})}delete(s,i=!1){let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).delete(s);return new Promise((r,n)=>{e.onsuccess=o=>{i||this._notifySubscribers(s),r(o)},e.onerror=o=>{n(o)}})}getAll(){let i=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).getAll();return new Promise((t,e)=>{i.onsuccess=r=>{let n=r.target.result;t(n.map(o=>o._value))},i.onerror=r=>{e(r)}})}subscribe(s,i){this._subscriptionsMap[s]||(this._subscriptionsMap[s]=new Set);let t=this._subscriptionsMap[s];return t.add(i),{remove:()=>{t.delete(i),t.size||delete this._subscriptionsMap[s]}}}stop(){window.removeEventListener("storage",this._updateHandler),this._subscriptionsMap=null,gs.clear(this.name)}},gs=class{static get readyEventName(){return ms}static open(s=ln,i="store"){let t=s+"/"+i;return this._reg[t]||(this._reg[t]=new cn(s,i)),this._reg[t]}static clear(s){window.indexedDB.deleteDatabase(s);for(let i in this._reg)i.split("/")[0]===s&&delete this._reg[i]}};$i(gs,"_reg",Object.create(null));function S(s,i){let t,e=(...r)=>{clearTimeout(t),t=setTimeout(()=>s(...r),i)};return e.cancel=()=>{clearTimeout(t)},e}var hn="--uploadcare-blocks-window-height",Oe="__UPLOADCARE_BLOCKS_WINDOW_HEIGHT_TRACKER_ENABLED__";function Si(){return typeof window[Oe]=="undefined"?!1:!!window[Oe]}function _s(){if(Si())return;let s=()=>{document.documentElement.style.setProperty(hn,`${window.innerHeight}px`),window[Oe]=!0},i=S(s,100);return window.addEventListener("resize",i,{passive:!0}),s(),()=>{window[Oe]=!1,window.removeEventListener("resize",i)}}var un=s=>s,ki="{{",ys="}}",bs="plural:";function ae(s,i,t={}){var o;let{openToken:e=ki,closeToken:r=ys,transform:n=un}=t;for(let l in i){let a=(o=i[l])==null?void 0:o.toString();s=s.replaceAll(e+l+r,typeof a=="string"?n(a):a)}return s}function vs(s){let i=[],t=s.indexOf(ki);for(;t!==-1;){let e=s.indexOf(ys,t),r=s.substring(t+2,e);if(r.startsWith(bs)){let n=s.substring(t+2,e).replace(bs,""),o=n.substring(0,n.indexOf("(")),l=n.substring(n.indexOf("(")+1,n.indexOf(")"));i.push({variable:r,pluralKey:o,countVariable:l})}t=s.indexOf(ki,e)}return i}function Cs(s){return Object.prototype.toString.call(s)==="[object Object]"}var dn=/\W|_/g;function pn(s){return s.split(dn).map((i,t)=>i.charAt(0)[t>0?"toUpperCase":"toLowerCase"]()+i.slice(1)).join("")}function ws(s,{ignoreKeys:i}={ignoreKeys:[]}){return Array.isArray(s)?s.map(t=>mt(t,{ignoreKeys:i})):s}function mt(s,{ignoreKeys:i}={ignoreKeys:[]}){if(Array.isArray(s))return ws(s,{ignoreKeys:i});if(!Cs(s))return s;let t={};for(let e of Object.keys(s)){let r=s[e];if(i.includes(e)){t[e]=r;continue}Cs(r)?r=mt(r,{ignoreKeys:i}):Array.isArray(r)&&(r=ws(r,{ignoreKeys:i})),t[pn(e)]=r}return t}var fn=s=>new Promise(i=>setTimeout(i,s));function Mi({libraryName:s,libraryVersion:i,userAgent:t,publicKey:e="",integration:r=""}){let n="JavaScript";if(typeof t=="string")return t;if(typeof t=="function")return t({publicKey:e,libraryName:s,libraryVersion:i,languageName:n,integration:r});let o=[s,i,e].filter(Boolean).join("/"),l=[n,r].filter(Boolean).join("; ");return`${o} (${l})`}var mn={factor:2,time:100};function gn(s,i=mn){let t=0;function e(r){let n=Math.round(i.time*i.factor**t);return r({attempt:t,retry:l=>fn(l!=null?l:n).then(()=>(t+=1,e(r)))})}return e(s)}var qt=class extends Error{constructor(t){super();h(this,"originalProgressEvent");this.name="UploadcareNetworkError",this.message="Network error",Object.setPrototypeOf(this,qt.prototype),this.originalProgressEvent=t}},Re=(s,i)=>{s&&(s.aborted?Promise.resolve().then(i):s.addEventListener("abort",()=>i(),{once:!0}))},Ct=class extends Error{constructor(t="Request canceled"){super(t);h(this,"isCancel",!0);Object.setPrototypeOf(this,Ct.prototype)}},_n=500,Ts=({check:s,interval:i=_n,timeout:t,signal:e})=>new Promise((r,n)=>{let o,l;Re(e,()=>{o&&clearTimeout(o),n(new Ct("Poll cancelled"))}),t&&(l=setTimeout(()=>{o&&clearTimeout(o),n(new Ct("Timed out"))},t));let a=()=>{try{Promise.resolve(s(e)).then(c=>{c?(l&&clearTimeout(l),r(c)):o=setTimeout(a,i)}).catch(c=>{l&&clearTimeout(l),n(c)})}catch(c){l&&clearTimeout(l),n(c)}};o=setTimeout(a,0)}),T={baseCDN:"https://ucarecdn.com",baseURL:"https://upload.uploadcare.com",maxContentLength:50*1024*1024,retryThrottledRequestMaxTimes:1,retryNetworkErrorMaxTimes:3,multipartMinFileSize:25*1024*1024,multipartChunkSize:5*1024*1024,multipartMinLastPartSize:1024*1024,maxConcurrentRequests:4,pollingTimeoutMilliseconds:1e4,pusherKey:"79ae88bd931ea68464d9"},Pe="application/octet-stream",Es="original",xt=({method:s,url:i,data:t,headers:e={},signal:r,onProgress:n})=>new Promise((o,l)=>{let a=new XMLHttpRequest,c=(s==null?void 0:s.toUpperCase())||"GET",u=!1;a.open(c,i,!0),e&&Object.entries(e).forEach(d=>{let[p,m]=d;typeof m!="undefined"&&!Array.isArray(m)&&a.setRequestHeader(p,m)}),a.responseType="text",Re(r,()=>{u=!0,a.abort(),l(new Ct)}),a.onload=()=>{if(a.status!=200)l(new Error(`Error ${a.status}: ${a.statusText}`));else{let d={method:c,url:i,data:t,headers:e||void 0,signal:r,onProgress:n},p=a.getAllResponseHeaders().trim().split(/[\r\n]+/),m={};p.forEach(function($){let A=$.split(": "),x=A.shift(),w=A.join(": ");x&&typeof x!="undefined"&&(m[x]=w)});let f=a.response,_=a.status;o({request:d,data:f,headers:m,status:_})}},a.onerror=d=>{u||l(new qt(d))},n&&typeof n=="function"&&(a.upload.onprogress=d=>{d.lengthComputable?n({isComputable:!0,value:d.loaded/d.total}):n({isComputable:!1})}),t?a.send(t):a.send()});function bn(s,...i){return s}var yn=({name:s})=>s?[s]:[],vn=bn,Cn=()=>new FormData,As=s=>!1,Me=s=>typeof Blob!="undefined"&&s instanceof Blob,Ne=s=>typeof File!="undefined"&&s instanceof File,De=s=>!!s&&typeof s=="object"&&!Array.isArray(s)&&"uri"in s&&typeof s.uri=="string",ce=s=>Me(s)||Ne(s)||As()||De(s),wn=s=>typeof s=="string"||typeof s=="number"||typeof s=="undefined",xn=s=>!!s&&typeof s=="object"&&!Array.isArray(s),Tn=s=>!!s&&typeof s=="object"&&"data"in s&&ce(s.data);function En(s,i,t){if(Tn(t)){let{name:e,contentType:r}=t,n=vn(t.data,e,r!=null?r:Pe),o=yn({name:e,contentType:r});s.push([i,n,...o])}else if(xn(t))for(let[e,r]of Object.entries(t))typeof r!="undefined"&&s.push([`${i}[${e}]`,String(r)]);else wn(t)&&t&&s.push([i,t.toString()])}function An(s){let i=[];for(let[t,e]of Object.entries(s))En(i,t,e);return i}function Ni(s){let i=Cn(),t=An(s);for(let e of t){let[r,n,...o]=e;i.append(r,n,...o)}return i}var P=class extends Error{constructor(t,e,r,n,o){super();h(this,"isCancel");h(this,"code");h(this,"request");h(this,"response");h(this,"headers");this.name="UploadClientError",this.message=t,this.code=e,this.request=r,this.response=n,this.headers=o,Object.setPrototypeOf(this,P.prototype)}},$n=s=>{let i=new URLSearchParams;for(let[t,e]of Object.entries(s))e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).filter(r=>{var n;return(n=r[1])!=null?n:!1}).forEach(r=>i.set(`${t}[${r[0]}]`,String(r[1]))):Array.isArray(e)?e.forEach(r=>{i.append(`${t}[]`,r)}):typeof e=="string"&&e?i.set(t,e):typeof e=="number"&&i.set(t,e.toString());return i.toString()},ft=(s,i,t)=>{let e=new URL(s);return e.pathname=(e.pathname+i).replace("//","/"),t&&(e.search=$n(t)),e.toString()},Sn="6.6.1",kn="UploadcareUploadClient",In=Sn;function Rt(s){return Mi({libraryName:kn,libraryVersion:In,...s})}var On="RequestThrottledError",xs=15e3,Ln=1e3;function Un(s){let{headers:i}=s||{};if(!i||typeof i["retry-after"]!="string")return xs;let t=parseInt(i["retry-after"],10);return Number.isFinite(t)?t*1e3:xs}function Tt(s,i){let{retryThrottledRequestMaxTimes:t,retryNetworkErrorMaxTimes:e}=i;return gn(({attempt:r,retry:n})=>s().catch(o=>{if("response"in o&&(o==null?void 0:o.code)===On&&r{let i="";return(Me(s)||Ne(s)||De(s))&&(i=s.type),i||Pe},Ss=s=>{let i="";return Ne(s)&&s.name?i=s.name:Me(s)||As()?i="":De(s)&&s.name&&(i=s.name),i||Es};function Di(s){return typeof s=="undefined"||s==="auto"?"auto":s?"1":"0"}function Rn(s,{publicKey:i,fileName:t,contentType:e,baseURL:r=T.baseURL,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:_}){return Tt(()=>xt({method:"POST",url:ft(r,"/base/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Ni({file:{data:s,name:t||Ss(s),contentType:e||$s(s)},UPLOADCARE_PUB_KEY:i,UPLOADCARE_STORE:Di(l),signature:n,expire:o,source:u,metadata:_}),signal:a,onProgress:c}).then(({data:$,headers:A,request:x})=>{let w=mt(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,x,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var Li;(function(s){s.Token="token",s.FileInfo="file_info"})(Li||(Li={}));function Pn(s,{publicKey:i,baseURL:t=T.baseURL,store:e,fileName:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,source:c="url",signal:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:_}){return Tt(()=>xt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},url:ft(t,"/from_url/",{jsonerrors:1,pub_key:i,source_url:s,store:Di(e),filename:r,check_URL_duplicates:n?1:void 0,save_URL_duplicates:o?1:void 0,signature:l,expire:a,source:c,metadata:_}),signal:u}).then(({data:$,headers:A,request:x})=>{let w=mt(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,x,w,A);return w}),{retryNetworkErrorMaxTimes:f,retryThrottledRequestMaxTimes:m})}var q;(function(s){s.Unknown="unknown",s.Waiting="waiting",s.Progress="progress",s.Error="error",s.Success="success"})(q||(q={}));var Mn=s=>"status"in s&&s.status===q.Error;function Nn(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:l=T.retryNetworkErrorMaxTimes}={}){return Tt(()=>xt({method:"GET",headers:i?{"X-UC-User-Agent":Rt({publicKey:i,integration:r,userAgent:n})}:void 0,url:ft(t,"/from_url/status/",{jsonerrors:1,token:s}),signal:e}).then(({data:a,headers:c,request:u})=>{let d=mt(JSON.parse(a));if("error"in d&&!Mn(d))throw new P(d.error.content,void 0,u,d,c);return d}),{retryNetworkErrorMaxTimes:l,retryThrottledRequestMaxTimes:o})}function Dn(s,{publicKey:i,baseURL:t=T.baseURL,jsonpCallback:e,secureSignature:r,secureExpire:n,signal:o,source:l,integration:a,userAgent:c,retryThrottledRequestMaxTimes:u=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:d=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"POST",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:a,userAgent:c})},url:ft(t,"/group/",{jsonerrors:1,pub_key:i,files:s,callback:e,signature:r,expire:n,source:l}),signal:o}).then(({data:p,headers:m,request:f})=>{let _=mt(JSON.parse(p));if("error"in _)throw new P(_.error.content,_.error.errorCode,f,_,m);return _}),{retryNetworkErrorMaxTimes:d,retryThrottledRequestMaxTimes:u})}function ks(s,{publicKey:i,baseURL:t=T.baseURL,signal:e,source:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"GET",headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},url:ft(t,"/info/",{jsonerrors:1,pub_key:i,file_id:s,source:r}),signal:e}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Fn(s,{publicKey:i,contentType:t,fileName:e,multipartChunkSize:r=T.multipartChunkSize,baseURL:n="",secureSignature:o,secureExpire:l,store:a,signal:c,source:u="local",integration:d,userAgent:p,retryThrottledRequestMaxTimes:m=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:f=T.retryNetworkErrorMaxTimes,metadata:_}){return Tt(()=>xt({method:"POST",url:ft(n,"/multipart/start/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:d,userAgent:p})},data:Ni({filename:e||Es,size:s,content_type:t||Pe,part_size:r,UPLOADCARE_STORE:Di(a),UPLOADCARE_PUB_KEY:i,signature:o,expire:l,source:u,metadata:_}),signal:c}).then(({data:$,headers:A,request:x})=>{let w=mt(JSON.parse($));if("error"in w)throw new P(w.error.content,w.error.errorCode,x,w,A);return w.parts=Object.keys(w.parts).map(W=>w.parts[W]),w}),{retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})}function Vn(s,i,{contentType:t,signal:e,onProgress:r,retryThrottledRequestMaxTimes:n=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:o=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"PUT",url:i,data:s,onProgress:r,signal:e,headers:{"Content-Type":t||Pe}}).then(l=>(r&&r({isComputable:!0,value:1}),l)).then(({status:l})=>({code:l})),{retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o})}function Bn(s,{publicKey:i,baseURL:t=T.baseURL,source:e="local",signal:r,integration:n,userAgent:o,retryThrottledRequestMaxTimes:l=T.retryThrottledRequestMaxTimes,retryNetworkErrorMaxTimes:a=T.retryNetworkErrorMaxTimes}){return Tt(()=>xt({method:"POST",url:ft(t,"/multipart/complete/",{jsonerrors:1}),headers:{"X-UC-User-Agent":Rt({publicKey:i,integration:n,userAgent:o})},data:Ni({uuid:s,UPLOADCARE_PUB_KEY:i,source:e}),signal:r}).then(({data:c,headers:u,request:d})=>{let p=mt(JSON.parse(c));if("error"in p)throw new P(p.error.content,p.error.errorCode,d,p,u);return p}),{retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})}function Fi({file:s,publicKey:i,baseURL:t,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l,signal:a,onProgress:c}){return Ts({check:u=>ks(s,{publicKey:i,baseURL:t,signal:u,source:e,integration:r,userAgent:n,retryThrottledRequestMaxTimes:o,retryNetworkErrorMaxTimes:l}).then(d=>d.isReady?d:(c&&c({isComputable:!0,value:1}),!1)),signal:a})}var wt=class{constructor(i,{baseCDN:t=T.baseCDN,fileName:e}={}){h(this,"uuid");h(this,"name",null);h(this,"size",null);h(this,"isStored",null);h(this,"isImage",null);h(this,"mimeType",null);h(this,"cdnUrl",null);h(this,"s3Url",null);h(this,"originalFilename",null);h(this,"imageInfo",null);h(this,"videoInfo",null);h(this,"contentInfo",null);h(this,"metadata",null);h(this,"s3Bucket",null);let{uuid:r,s3Bucket:n}=i,o=ft(t,`${r}/`),l=n?ft(`https://${n}.s3.amazonaws.com/`,`${r}/${i.filename}`):null;this.uuid=r,this.name=e||i.filename,this.size=i.size,this.isStored=i.isStored,this.isImage=i.isImage,this.mimeType=i.mimeType,this.cdnUrl=o,this.originalFilename=i.originalFilename,this.imageInfo=i.imageInfo,this.videoInfo=i.videoInfo,this.contentInfo=i.contentInfo,this.metadata=i.metadata||null,this.s3Bucket=n||null,this.s3Url=l}},zn=(s,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,contentType:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,baseCDN:_,metadata:$})=>Rn(s,{publicKey:i,fileName:t,contentType:l,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:$}).then(({file:A})=>Fi({file:A,publicKey:i,baseURL:e,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(A=>new wt(A,{baseCDN:_})),jn=(s,{publicKey:i,fileName:t,baseURL:e,signal:r,onProgress:n,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u,baseCDN:d})=>ks(s,{publicKey:i,baseURL:e,signal:r,source:o,integration:l,userAgent:a,retryThrottledRequestMaxTimes:c,retryNetworkErrorMaxTimes:u}).then(p=>new wt(p,{baseCDN:d,fileName:t})).then(p=>(n&&n({isComputable:!0,value:1}),p)),Hn=(s,{signal:i}={})=>{let t=null,e=null,r=s.map(()=>new AbortController),n=o=>()=>{e=o,r.forEach((l,a)=>a!==o&&l.abort())};return Re(i,()=>{r.forEach(o=>o.abort())}),Promise.all(s.map((o,l)=>{let a=n(l);return Promise.resolve().then(()=>o({stopRace:a,signal:r[l].signal})).then(c=>(a(),c)).catch(c=>(t=c,null))})).then(o=>{if(e===null)throw t;return o[e]})},Wn=window.WebSocket,Ui=class{constructor(){h(this,"events",Object.create({}))}emit(i,t){var e;(e=this.events[i])==null||e.forEach(r=>r(t))}on(i,t){this.events[i]=this.events[i]||[],this.events[i].push(t)}off(i,t){t?this.events[i]=this.events[i].filter(e=>e!==t):this.events[i]=[]}},Xn=(s,i)=>s==="success"?{status:q.Success,...i}:s==="progress"?{status:q.Progress,...i}:{status:q.Error,...i},Ri=class{constructor(i,t=3e4){h(this,"key");h(this,"disconnectTime");h(this,"ws");h(this,"queue",[]);h(this,"isConnected",!1);h(this,"subscribers",0);h(this,"emmitter",new Ui);h(this,"disconnectTimeoutId",null);this.key=i,this.disconnectTime=t}connect(){if(this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),!this.isConnected&&!this.ws){let i=`wss://ws.pusherapp.com/app/${this.key}?protocol=5&client=js&version=1.12.2`;this.ws=new Wn(i),this.ws.addEventListener("error",t=>{this.emmitter.emit("error",new Error(t.message))}),this.emmitter.on("connected",()=>{this.isConnected=!0,this.queue.forEach(t=>this.send(t.event,t.data)),this.queue=[]}),this.ws.addEventListener("message",t=>{let e=JSON.parse(t.data.toString());switch(e.event){case"pusher:connection_established":{this.emmitter.emit("connected",void 0);break}case"pusher:ping":{this.send("pusher:pong",{});break}case"progress":case"success":case"fail":this.emmitter.emit(e.channel,Xn(e.event,JSON.parse(e.data)))}})}}disconnect(){let i=()=>{var t;(t=this.ws)==null||t.close(),this.ws=void 0,this.isConnected=!1};this.disconnectTime?this.disconnectTimeoutId=setTimeout(()=>{i()},this.disconnectTime):i()}send(i,t){var r;let e=JSON.stringify({event:i,data:t});(r=this.ws)==null||r.send(e)}subscribe(i,t){this.subscribers+=1,this.connect();let e=`task-status-${i}`,r={event:"pusher:subscribe",data:{channel:e}};this.emmitter.on(e,t),this.isConnected?this.send(r.event,r.data):this.queue.push(r)}unsubscribe(i){this.subscribers-=1;let t=`task-status-${i}`,e={event:"pusher:unsubscribe",data:{channel:t}};this.emmitter.off(t),this.isConnected?this.send(e.event,e.data):this.queue=this.queue.filter(r=>r.data.channel!==t),this.subscribers===0&&this.disconnect()}onError(i){return this.emmitter.on("error",i),()=>this.emmitter.off("error",i)}},Ii=null,Vi=s=>{if(!Ii){let i=typeof window=="undefined"?0:3e4;Ii=new Ri(s,i)}return Ii},qn=s=>{Vi(s).connect()};function Gn({token:s,publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,onProgress:l,signal:a}){return Ts({check:c=>Nn(s,{publicKey:i,baseURL:t,integration:e,userAgent:r,retryThrottledRequestMaxTimes:n,retryNetworkErrorMaxTimes:o,signal:c}).then(u=>{switch(u.status){case q.Error:return new P(u.error,u.errorCode);case q.Waiting:return!1;case q.Unknown:return new P(`Token "${s}" was not found.`);case q.Progress:return l&&(u.total==="unknown"?l({isComputable:!1}):l({isComputable:!0,value:u.done/u.total})),!1;case q.Success:return l&&l({isComputable:!0,value:u.done/u.total}),u;default:throw new Error("Unknown status")}}),signal:a})}var Kn=({token:s,pusherKey:i,signal:t,onProgress:e})=>new Promise((r,n)=>{let o=Vi(i),l=o.onError(n),a=()=>{l(),o.unsubscribe(s)};Re(t,()=>{a(),n(new Ct("pusher cancelled"))}),o.subscribe(s,c=>{switch(c.status){case q.Progress:{e&&(c.total==="unknown"?e({isComputable:!1}):e({isComputable:!0,value:c.done/c.total}));break}case q.Success:{a(),e&&e({isComputable:!0,value:c.done/c.total}),r(c);break}case q.Error:a(),n(new P(c.msg,c.error_code))}})}),Yn=(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:r,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,onProgress:d,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,pusherKey:$=T.pusherKey,metadata:A})=>Promise.resolve(qn($)).then(()=>Pn(s,{publicKey:i,fileName:t,baseURL:e,checkForUrlDuplicates:n,saveUrlForRecurrentUploads:o,secureSignature:l,secureExpire:a,store:c,signal:u,source:p,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,metadata:A})).catch(x=>{let w=Vi($);return w==null||w.disconnect(),Promise.reject(x)}).then(x=>x.type===Li.FileInfo?x:Hn([({signal:w})=>Gn({token:x.token,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:w}),({signal:w})=>Kn({token:x.token,pusherKey:$,signal:w,onProgress:d})],{signal:u})).then(x=>{if(x instanceof P)throw x;return x}).then(x=>Fi({file:x.uuid,publicKey:i,baseURL:e,integration:m,userAgent:f,retryThrottledRequestMaxTimes:_,onProgress:d,signal:u})).then(x=>new wt(x,{baseCDN:r})),Oi=new WeakMap,Zn=async s=>{if(Oi.has(s))return Oi.get(s);let i=await fetch(s.uri).then(t=>t.blob());return Oi.set(s,i),i},Is=async s=>{if(Ne(s)||Me(s))return s.size;if(De(s))return(await Zn(s)).size;throw new Error("Unknown file type. Cannot determine file size.")},Jn=(s,i=T.multipartMinFileSize)=>s>=i,Os=s=>{let i="[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",t=new RegExp(i);return!ce(s)&&t.test(s)},Ls=s=>{let i="^(?:\\w+:)?\\/\\/([^\\s\\.]+\\.\\S{2}|localhost[\\:?\\d]*)\\S*$",t=new RegExp(i);return!ce(s)&&t.test(s)},Qn=(s,i)=>new Promise((t,e)=>{let r=[],n=!1,o=i.length,l=[...i],a=()=>{let c=i.length-l.length,u=l.shift();u&&u().then(d=>{n||(r[c]=d,o-=1,o?a():t(r))}).catch(d=>{n=!0,e(d)})};for(let c=0;c{let r=e*i,n=Math.min(r+e,t);return s.slice(r,n)},eo=async(s,i,t)=>e=>to(s,e,i,t),io=(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a})=>Vn(s,i,{publicKey:t,contentType:e,onProgress:r,signal:n,integration:o,retryThrottledRequestMaxTimes:l,retryNetworkErrorMaxTimes:a}),so=async(s,{publicKey:i,fileName:t,fileSize:e,baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,onProgress:c,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,contentType:_,multipartChunkSize:$=T.multipartChunkSize,maxConcurrentRequests:A=T.maxConcurrentRequests,baseCDN:x,metadata:w})=>{let W=e!=null?e:await Is(s),ht,It=(R,J)=>{if(!c)return;ht||(ht=Array(R).fill(0));let ut=X=>X.reduce((dt,Ti)=>dt+Ti,0);return X=>{X.isComputable&&(ht[J]=X.value,c({isComputable:!0,value:ut(ht)/R}))}};return _||(_=$s(s)),Fn(W,{publicKey:i,contentType:_,fileName:t||Ss(s),baseURL:r,secureSignature:n,secureExpire:o,store:l,signal:a,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,metadata:w}).then(async({uuid:R,parts:J})=>{let ut=await eo(s,W,$);return Promise.all([R,Qn(A,J.map((X,dt)=>()=>io(ut(dt),X,{publicKey:i,contentType:_,onProgress:It(J.length,dt),signal:a,integration:d,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})))])}).then(([R])=>Bn(R,{publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f})).then(R=>R.isReady?R:Fi({file:R.uuid,publicKey:i,baseURL:r,source:u,integration:d,userAgent:p,retryThrottledRequestMaxTimes:m,retryNetworkErrorMaxTimes:f,onProgress:c,signal:a})).then(R=>new wt(R,{baseCDN:x}))};async function Bi(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartMinFileSize:_,multipartChunkSize:$,maxConcurrentRequests:A,baseCDN:x=T.baseCDN,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:W,pusherKey:ht,metadata:It}){if(ce(s)){let R=await Is(s);return Jn(R,_)?so(s,{publicKey:i,contentType:f,multipartChunkSize:$,fileSize:R,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,maxConcurrentRequests:A,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x,metadata:It}):zn(s,{publicKey:i,fileName:t,contentType:f,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x,metadata:It})}if(Ls(s))return Yn(s,{publicKey:i,fileName:t,baseURL:e,baseCDN:x,checkForUrlDuplicates:w,saveUrlForRecurrentUploads:W,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,pusherKey:ht,metadata:It});if(Os(s))return jn(s,{publicKey:i,fileName:t,baseURL:e,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,baseCDN:x});throw new TypeError(`File uploading from "${s}" is not supported`)}var Pi=class{constructor(i,t){h(this,"uuid");h(this,"filesCount");h(this,"totalSize");h(this,"isStored");h(this,"isImage");h(this,"cdnUrl");h(this,"files");h(this,"createdAt");h(this,"storedAt",null);this.uuid=i.id,this.filesCount=i.filesCount,this.totalSize=Object.values(i.files).reduce((e,r)=>e+r.size,0),this.isStored=!!i.datetimeStored,this.isImage=!!Object.values(i.files).filter(e=>e.isImage).length,this.cdnUrl=i.cdnUrl,this.files=t,this.createdAt=i.datetimeCreated,this.storedAt=i.datetimeStored}},ro=s=>{for(let i of s)if(!ce(i))return!1;return!0},no=s=>{for(let i of s)if(!Os(i))return!1;return!0},oo=s=>{for(let i of s)if(!Ls(i))return!1;return!0};function Us(s,{publicKey:i,fileName:t,baseURL:e=T.baseURL,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:a,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_=T.multipartChunkSize,baseCDN:$=T.baseCDN,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x,jsonpCallback:w}){if(!ro(s)&&!oo(s)&&!no(s))throw new TypeError(`Group uploading from "${s}" is not supported`);let W,ht=!0,It=s.length,R=(J,ut)=>{if(!a)return;W||(W=Array(J).fill(0));let X=dt=>dt.reduce((Ti,Nr)=>Ti+Nr)/J;return dt=>{if(!dt.isComputable||!ht){ht=!1,a({isComputable:!1});return}W[ut]=dt.value,a({isComputable:!0,value:X(W)})}};return Promise.all(s.map((J,ut)=>Bi(J,{publicKey:i,fileName:t,baseURL:e,secureSignature:r,secureExpire:n,store:o,signal:l,onProgress:R(It,ut),source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m,contentType:f,multipartChunkSize:_,baseCDN:$,checkForUrlDuplicates:A,saveUrlForRecurrentUploads:x}))).then(J=>{let ut=J.map(X=>X.uuid);return Dn(ut,{publicKey:i,baseURL:e,jsonpCallback:w,secureSignature:r,secureExpire:n,signal:l,source:c,integration:u,userAgent:d,retryThrottledRequestMaxTimes:p,retryNetworkErrorMaxTimes:m}).then(X=>new Pi(X,J)).then(X=>(a&&a({isComputable:!0,value:1}),X))})}var Lt,jt,Ut,Ht,Wt,Xt,Le,Ue=class{constructor(i){Ot(this,Xt);Ot(this,Lt,1);Ot(this,jt,[]);Ot(this,Ut,0);Ot(this,Ht,new WeakMap);Ot(this,Wt,new WeakMap);re(this,Lt,i)}add(i){return new Promise((t,e)=>{F(this,Ht).set(i,t),F(this,Wt).set(i,e),F(this,jt).push(i),Se(this,Xt,Le).call(this)})}get pending(){return F(this,jt).length}get running(){return F(this,Ut)}set concurrency(i){re(this,Lt,i),Se(this,Xt,Le).call(this)}get concurrency(){return F(this,Lt)}};Lt=new WeakMap,jt=new WeakMap,Ut=new WeakMap,Ht=new WeakMap,Wt=new WeakMap,Xt=new WeakSet,Le=function(){let i=F(this,Lt)-F(this,Ut);for(let t=0;t{F(this,Ht).delete(e),F(this,Wt).delete(e),re(this,Ut,F(this,Ut)-1),Se(this,Xt,Le).call(this)}).then(o=>r(o)).catch(o=>n(o))}};var zi=()=>({"*blocksRegistry":new Set}),ji=s=>({...zi(),"*currentActivity":"","*currentActivityParams":{},"*history":[],"*historyBack":null,"*closeModal":()=>{s.set$({"*modalActive":!1,"*currentActivity":""})}}),Fe=s=>({...ji(s),"*commonProgress":0,"*uploadList":[],"*outputData":null,"*focusedEntry":null,"*uploadMetadata":null,"*uploadQueue":new Ue(1)});function Rs(s,i){[...s.querySelectorAll("[l10n]")].forEach(t=>{let e=t.getAttribute("l10n"),r="textContent";if(e.includes(":")){let o=e.split(":");r=o[0],e=o[1]}let n="l10n:"+e;i.__l10nKeys.push(n),i.add(n,e),i.sub(n,o=>{t[r]=i.l10n(o)}),t.removeAttribute("l10n")})}var Q=s=>`*cfg/${s}`;var gt=s=>{var i;return(i=s.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g))==null?void 0:i.map(t=>t.toLowerCase()).join("-")};var Ps=new Set;function Ve(s){Ps.has(s)||(Ps.add(s),console.warn(s))}var Be=(s,i)=>new Intl.PluralRules(s).select(i);var Hi="lr-",b=class extends zt{constructor(){super();h(this,"allowCustomTemplate",!0);h(this,"init$",zi());h(this,"updateCtxCssData",()=>{let t=this.$["*blocksRegistry"];for(let e of t)e.isConnected&&e.updateCssData()});this.activityType=null,this.addTemplateProcessor(Rs),this.__l10nKeys=[]}l10n(t,e={}){if(!t)return"";let r=this.getCssData("--l10n-"+t,!0)||t,n=vs(r);for(let l of n)e[l.variable]=this.pluralize(l.pluralKey,Number(e[l.countVariable]));return ae(r,e)}pluralize(t,e){let r=this.l10n("locale-name")||"en-US",n=Be(r,e);return this.l10n(`${t}__${n}`)}applyL10nKey(t,e){let r="l10n:"+t;this.$[r]=e,this.__l10nKeys.push(t)}hasBlockInCtx(t){let e=this.$["*blocksRegistry"];for(let r of e)if(t(r))return!0;return!1}setForCtxTarget(t,e,r){this.hasBlockInCtx(n=>n.constructor.StateConsumerScope===t)&&(this.$[e]=r)}setActivity(t){if(this.hasBlockInCtx(e=>e.activityType===t)){this.$["*currentActivity"]=t;return}console.warn(`Activity type "${t}" not found in the context`)}connectedCallback(){let t=this.constructor.className;t&&this.classList.toggle(`${Hi}${t}`,!0),Si()||(this._destroyInnerHeightTracker=_s()),this.hasAttribute("retpl")&&(this.constructor.template=null,this.processInnerHtml=!0),super.connectedCallback()}disconnectedCallback(){var t;super.disconnectedCallback(),(t=this._destroyInnerHeightTracker)==null||t.call(this)}initCallback(){this.$["*blocksRegistry"].add(this)}destroyCallback(){this.$["*blocksRegistry"].delete(this)}fileSizeFmt(t,e=2){let r=["B","KB","MB","GB","TB"],n=c=>this.getCssData("--l10n-unit-"+c.toLowerCase(),!0)||c;if(t===0)return`0 ${n(r[0])}`;let o=1024,l=e<0?0:e,a=Math.floor(Math.log(t)/Math.log(o));return parseFloat((t/o**a).toFixed(l))+" "+n(r[a])}proxyUrl(t){let e=this.cfg.secureDeliveryProxy;return e?ae(e,{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}parseCfgProp(t){return{ctx:this.nodeCtx,name:t.replace("*","")}}get cfg(){if(!this.__cfgProxy){let t=Object.create(null);this.__cfgProxy=new Proxy(t,{get:(e,r)=>{let n=Q(r),o=this.parseCfgProp(n);return o.ctx.has(o.name)?o.ctx.read(o.name):(Ve("Using CSS variables for configuration is deprecated. Please use `lr-config` instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.getCssData(`--cfg-${gt(r)}`))}})}return this.__cfgProxy}subConfigValue(t,e){let r=this.parseCfgProp(Q(t));r.ctx.has(r.name)?this.sub(Q(t),e):(this.bindCssData(`--cfg-${gt(t)}`),this.sub(`--cfg-${gt(t)}`,e))}static reg(t){if(!t){super.reg();return}super.reg(t.startsWith(Hi)?t:Hi+t)}};h(b,"StateConsumerScope",null),h(b,"className","");var Wi=class extends b{constructor(){super();h(this,"_handleBackdropClick",()=>{this._closeDialog()});h(this,"_closeDialog",()=>{this.setForCtxTarget(Wi.StateConsumerScope,"*modalActive",!1)});h(this,"_handleDialogClose",()=>{this._closeDialog()});h(this,"_handleDialogPointerUp",t=>{t.target===this.ref.dialog&&this._closeDialog()});this.init$={...this.init$,"*modalActive":!1,isOpen:!1,closeClicked:this._handleDialogClose}}show(){this.ref.dialog.showModal?this.ref.dialog.showModal():this.ref.dialog.setAttribute("open","")}hide(){this.ref.dialog.close?this.ref.dialog.close():this.ref.dialog.removeAttribute("open")}initCallback(){if(super.initCallback(),typeof HTMLDialogElement=="function")this.ref.dialog.addEventListener("close",this._handleDialogClose),this.ref.dialog.addEventListener("pointerup",this._handleDialogPointerUp);else{this.setAttribute("dialog-fallback","");let t=document.createElement("div");t.className="backdrop",this.appendChild(t),t.addEventListener("click",this._handleBackdropClick)}this.sub("*modalActive",t=>{this.$.isOpen!==t&&(this.$.isOpen=t),t&&this.cfg.modalScrollLock?document.body.style.overflow="hidden":document.body.style.overflow=""}),this.subConfigValue("modalBackdropStrokes",t=>{t?this.setAttribute("strokes",""):this.removeAttribute("strokes")}),this.sub("isOpen",t=>{t?this.show():this.hide()})}destroyCallback(){super.destroyCallback(),document.body.style.overflow="",this.ref.dialog.removeEventListener("close",this._handleDialogClose),this.ref.dialog.removeEventListener("click",this._handleDialogPointerUp)}},B=Wi;h(B,"StateConsumerScope","modal");B.template=``;var Ms="active",he="___ACTIVITY_IS_ACTIVE___",st=class extends b{constructor(){super(...arguments);h(this,"historyTracked",!1);h(this,"init$",ji(this));h(this,"_debouncedHistoryFlush",S(this._historyFlush.bind(this),10))}_deactivate(){var e;let t=st._activityRegistry[this.activityKey];this[he]=!1,this.removeAttribute(Ms),(e=t==null?void 0:t.deactivateCallback)==null||e.call(t)}_activate(){var e;let t=st._activityRegistry[this.activityKey];this.$["*historyBack"]=this.historyBack.bind(this),this[he]=!0,this.setAttribute(Ms,""),(e=t==null?void 0:t.activateCallback)==null||e.call(t),this._debouncedHistoryFlush()}initCallback(){super.initCallback(),this.hasAttribute("current-activity")&&this.sub("*currentActivity",t=>{this.setAttribute("current-activity",t)}),this.activityType&&(this.hasAttribute("activity")||this.setAttribute("activity",this.activityType),this.sub("*currentActivity",t=>{this.activityType!==t&&this[he]?this._deactivate():this.activityType===t&&!this[he]&&this._activate(),t||(this.$["*history"]=[])}))}_historyFlush(){let t=this.$["*history"];t&&(t.length>10&&(t=t.slice(t.length-11,t.length-1)),this.historyTracked&&t.push(this.activityType),this.$["*history"]=t)}_isActivityRegistered(){return this.activityType&&!!st._activityRegistry[this.activityKey]}get isActivityActive(){return this[he]}registerActivity(t,e={}){let{onActivate:r,onDeactivate:n}=e;st._activityRegistry||(st._activityRegistry=Object.create(null)),st._activityRegistry[this.activityKey]={activateCallback:r,deactivateCallback:n}}unregisterActivity(){this.isActivityActive&&this._deactivate(),st._activityRegistry[this.activityKey]=void 0}destroyCallback(){super.destroyCallback(),this._isActivityRegistered()&&this.unregisterActivity(),Object.keys(st._activityRegistry).length===0&&(this.$["*currentActivity"]=null)}get activityKey(){return this.ctxName+this.activityType}get activityParams(){return this.$["*currentActivityParams"]}get initActivity(){return this.getCssData("--cfg-init-activity")}get doneActivity(){return this.getCssData("--cfg-done-activity")}historyBack(){let t=this.$["*history"];if(t){let e=t.pop();for(;e===this.activityType;)e=t.pop();this.$["*currentActivity"]=e,this.$["*history"]=t,e||this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!1)}}},g=st;h(g,"_activityRegistry",Object.create(null));g.activities=Object.freeze({START_FROM:"start-from",CAMERA:"camera",DRAW:"draw",UPLOAD_LIST:"upload-list",URL:"url",CONFIRMATION:"confirmation",CLOUD_IMG_EDIT:"cloud-image-edit",EXTERNAL:"external",DETAILS:"details"});var ue=33.333333333333336,y=1,Xi=24,Ns=6;function Pt(s,i){for(let t in i)s.setAttributeNS(null,t,i[t].toString())}function tt(s,i={}){let t=document.createElementNS("http://www.w3.org/2000/svg",s);return Pt(t,i),t}function Ds(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=i.includes("w")?0:1,a=i.includes("n")?0:1,c=[-1,1][l],u=[-1,1][a],d=[e+l*n+1.5*c,r+a*o+1.5*u-24*t*u],p=[e+l*n+1.5*c,r+a*o+1.5*u],m=[e+l*n-24*t*c+1.5*c,r+a*o+1.5*u];return{d:`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]} L ${m[0]} ${m[1]}`,center:p}}function Fs(s,i,t){let{x:e,y:r,width:n,height:o}=s,l=["n","s"].includes(i)?.5:{w:0,e:1}[i],a=["w","e"].includes(i)?.5:{n:0,s:1}[i],c=[-1,1][l],u=[-1,1][a],d,p;["n","s"].includes(i)?(d=[e+l*n-34*t/2,r+a*o+1.5*u],p=[e+l*n+34*t/2,r+a*o+1.5*u]):(d=[e+l*n+1.5*c,r+a*o-34*t/2],p=[e+l*n+1.5*c,r+a*o+34*t/2]);let m=`M ${d[0]} ${d[1]} L ${p[0]} ${p[1]}`,f=[p[0]-(p[0]-d[0])/2,p[1]-(p[1]-d[1])/2];return{d:m,center:f}}function Vs(s){return s===""?"move":["e","w"].includes(s)?"ew-resize":["n","s"].includes(s)?"ns-resize":["nw","se"].includes(s)?"nwse-resize":"nesw-resize"}function Bs({rect:s,delta:[i,t],imageBox:e}){return Kt({...s,x:s.x+i,y:s.y+t},e)}function Kt(s,i){let{x:t}=s,{y:e}=s;return s.xi.x+i.width&&(t=i.x+i.width-s.width),s.yi.y+i.height&&(e=i.y+i.height-s.height),{...s,x:t,y:e}}function lo({rect:s,delta:i,aspectRatio:t,imageBox:e}){let[,r]=i,{y:n,width:o,height:l}=s;n+=r,l-=r,t&&(o=l*t);let a=s.x+s.width/2-o/2;return n<=e.y&&(n=e.y,l=s.y+s.height-n,t&&(o=l*t,a=s.x+s.width/2-o/2)),a<=e.x&&(a=e.x,n=s.y+s.height-l),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y+s.height-l),l=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x+s.width-o),l=e.y+e.height&&(l=e.y+e.height-n,t&&(o=l*t),a=s.x+s.width/2-o/2),a<=e.x&&(a=e.x,n=s.y),a+o>=e.x+e.width&&(a=Math.max(e.x,e.x+e.width-o),o=e.x+e.width-a,t&&(l=o/t),n=s.y),l=e.x+e.width&&(o=e.x+e.width-n,t&&(l=o/t),a=s.y+s.height/2-l/2),a<=e.y&&(a=e.y,n=s.x),a+l>=e.y+e.height&&(a=Math.max(e.y,e.y+e.height-l),l=e.y+e.height-a,t&&(o=l*t),n=s.x),lt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x+s.width-a,l=e.y)):t&&(r=c*t-a,a=a+r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y+s.height-c)),ce.x+e.width&&(r=e.x+e.width-o-a),l+nt?(n=a/t-c,c+=n,l-=n,l<=e.y&&(c=c-(e.y-l),a=c*t,o=s.x,l=e.y)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y+s.height-c)),ce.y+e.height&&(n=e.y+e.height-l-c),o+=r,a-=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x+s.width-a,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o-=r,o<=e.x&&(a=a-(e.x-o),c=a/t,o=e.x,l=s.y)),ce.x+e.width&&(r=e.x+e.width-o-a),l+c+n>e.y+e.height&&(n=e.y+e.height-l-c),a+=r,c+=n,t&&Math.abs(a/c)>t?(n=a/t-c,c+=n,l+c>=e.y+e.height&&(c=e.y+e.height-l,a=c*t,o=s.x,l=e.y+e.height-c)):t&&(r=c*t-a,a+=r,o+a>=e.x+e.width&&(a=e.x+e.width-o,c=a/t,o=e.x+e.width-a,l=s.y)),c=i.x&&s.y>=i.y&&s.x+s.width<=i.x+i.width&&s.y+s.height<=i.y+i.height}function Yt({width:s,height:i},t){let e=t/90%2!==0;return{width:e?i:s,height:e?s:i}}function Ws(s,i,t){let e=s/i,r,n;e>t?(r=Math.round(i*t),n=i):(r=s,n=Math.round(s/t));let o=Math.round((s-r)/2),l=Math.round((i-n)/2);return o+r>s&&(r=s-o),l+n>i&&(n=i-l),{x:o,y:l,width:r,height:n}}function Zt(s){return{x:Math.round(s.x),y:Math.round(s.y),width:Math.round(s.width),height:Math.round(s.height)}}function Et(s,i,t){return Math.min(Math.max(s,i),t)}var je=s=>{if(!s)return[];let[i,t]=s.split(":").map(Number);if(!Number.isFinite(i)||!Number.isFinite(t)){console.error(`Invalid crop preset: ${s}`);return}return[{type:"aspect-ratio",width:i,height:t}]};var et=Object.freeze({LOCAL:"local",DROP_AREA:"drop-area",URL_TAB:"url-tab",CAMERA:"camera",EXTERNAL:"external",API:"js-api"});var Xs="blocks",qs="0.25.6";function Gs(s){return Mi({...s,libraryName:Xs,libraryVersion:qs})}var Ks=s=>{if(typeof s!="string"||!s)return"";let i=s.trim();return i.startsWith("-/")?i=i.slice(2):i.startsWith("/")&&(i=i.slice(1)),i.endsWith("/")&&(i=i.slice(0,i.length-1)),i},He=(...s)=>s.filter(i=>typeof i=="string"&&i).map(i=>Ks(i)).join("/-/"),I=(...s)=>{let i=He(...s);return i?`-/${i}/`:""};function Ys(s){let i=new URL(s),t=i.pathname+i.search+i.hash,e=t.lastIndexOf("http"),r=t.lastIndexOf("/"),n="";return e>=0?n=t.slice(e):r>=0&&(n=t.slice(r+1)),n}function Zs(s){let i=new URL(s),{pathname:t}=i,e=t.indexOf("/"),r=t.indexOf("/",e+1);return t.substring(e+1,r)}function Js(s){let i=Qs(s),t=new URL(i),e=t.pathname.indexOf("/-/");return e===-1?[]:t.pathname.substring(e).split("/-/").filter(Boolean).map(n=>Ks(n))}function Qs(s){let i=new URL(s),t=Ys(s),e=tr(t)?er(t).pathname:t;return i.pathname=i.pathname.replace(e,""),i.search="",i.hash="",i.toString()}function tr(s){return s.startsWith("http")}function er(s){let i=new URL(s);return{pathname:i.origin+i.pathname||"",search:i.search||"",hash:i.hash||""}}var k=(s,i,t)=>{let e=new URL(Qs(s));if(t=t||Ys(s),e.pathname.startsWith("//")&&(e.pathname=e.pathname.replace("//","/")),tr(t)){let r=er(t);e.pathname=e.pathname+(i||"")+(r.pathname||""),e.search=r.search,e.hash=r.hash}else e.pathname=e.pathname+(i||"")+(t||"");return e.toString()},At=(s,i)=>{let t=new URL(s);return t.pathname=i+"/",t.toString()};var M=(s,i=",")=>s.trim().split(i).map(t=>t.trim()).filter(t=>t.length>0);var de=["image/*","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/avif","image/avif-sequence",".heif",".heifs",".heic",".heics",".avif",".avifs"],qi=s=>s?s.filter(i=>typeof i=="string").map(i=>M(i)).flat():[],Gi=(s,i)=>i.some(t=>t.endsWith("*")?(t=t.replace("*",""),s.startsWith(t)):s===t),ir=(s,i)=>i.some(t=>t.startsWith(".")?s.toLowerCase().endsWith(t.toLowerCase()):!1),pe=s=>{let i=s==null?void 0:s.type;return i?Gi(i,de):!1};var nt=1e3,Mt=Object.freeze({AUTO:"auto",BYTE:"byte",KB:"kb",MB:"mb",GB:"gb",TB:"tb",PB:"pb"}),fe=s=>Math.ceil(s*100)/100,sr=(s,i=Mt.AUTO)=>{let t=i===Mt.AUTO;if(i===Mt.BYTE||t&&s{t.dispatchEvent(new CustomEvent(this.eName(i.type),{detail:i}))};if(!e){r();return}let n=i.type+i.ctx;this._timeoutStore[n]&&window.clearTimeout(this._timeoutStore[n]),this._timeoutStore[n]=window.setTimeout(()=>{r(),delete this._timeoutStore[n]},20)}};h(O,"_timeoutStore",Object.create(null));var rr="[Typed State] Wrong property name: ",go="[Typed State] Wrong property type: ",We=class{constructor(i,t){this.__typedSchema=i,this.__ctxId=t||oe.generate(),this.__schema=Object.keys(i).reduce((e,r)=>(e[r]=i[r].value,e),{}),this.__data=E.registerCtx(this.__schema,this.__ctxId)}get uid(){return this.__ctxId}setValue(i,t){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}let e=this.__typedSchema[i];if((t==null?void 0:t.constructor)===e.type||t instanceof e.type||e.nullable&&t===null){this.__data.pub(i,t);return}console.warn(go+i)}setMultipleValues(i){for(let t in i)this.setValue(t,i[t])}getValue(i){if(!this.__typedSchema.hasOwnProperty(i)){console.warn(rr+i);return}return this.__data.read(i)}subscribe(i,t){return this.__data.sub(i,t)}remove(){E.deleteCtx(this.__ctxId)}};var Xe=class{constructor(i){this.__typedSchema=i.typedSchema,this.__ctxId=i.ctxName||oe.generate(),this.__data=E.registerCtx({},this.__ctxId),this.__watchList=i.watchList||[],this.__handler=i.handler||null,this.__subsMap=Object.create(null),this.__observers=new Set,this.__items=new Set,this.__removed=new Set,this.__added=new Set;let t=Object.create(null);this.__notifyObservers=(e,r)=>{this.__observeTimeout&&window.clearTimeout(this.__observeTimeout),t[e]||(t[e]=new Set),t[e].add(r),this.__observeTimeout=window.setTimeout(()=>{this.__observers.forEach(n=>{n({...t})}),t=Object.create(null)})}}notify(){this.__notifyTimeout&&window.clearTimeout(this.__notifyTimeout),this.__notifyTimeout=window.setTimeout(()=>{var e;let i=new Set(this.__added),t=new Set(this.__removed);this.__added.clear(),this.__removed.clear(),(e=this.__handler)==null||e.call(this,[...this.__items],i,t)})}setHandler(i){this.__handler=i,this.notify()}getHandler(){return this.__handler}removeHandler(){this.__handler=null}add(i){let t=new We(this.__typedSchema);for(let e in i)t.setValue(e,i[e]);return this.__data.add(t.uid,t),this.__added.add(t),this.__watchList.forEach(e=>{this.__subsMap[t.uid]||(this.__subsMap[t.uid]=[]),this.__subsMap[t.uid].push(t.subscribe(e,()=>{this.__notifyObservers(e,t.uid)}))}),this.__items.add(t.uid),this.notify(),t}read(i){return this.__data.read(i)}readProp(i,t){return this.read(i).getValue(t)}publishProp(i,t,e){this.read(i).setValue(t,e)}remove(i){this.__removed.add(this.__data.read(i)),this.__items.delete(i),this.notify(),this.__data.pub(i,null),delete this.__subsMap[i]}clearAll(){this.__items.forEach(i=>{this.remove(i)})}observe(i){this.__observers.add(i)}unobserve(i){this.__observers.delete(i)}findItems(i){let t=[];return this.__items.forEach(e=>{let r=this.read(e);i(r)&&t.push(e)}),t}items(){return[...this.__items]}get size(){return this.__items.size}destroy(){E.deleteCtx(this.__data),this.__observers=null,this.__handler=null;for(let i in this.__subsMap)this.__subsMap[i].forEach(t=>{t.remove()}),delete this.__subsMap[i]}};var nr=Object.freeze({file:{type:File,value:null},externalUrl:{type:String,value:null},fileName:{type:String,value:null,nullable:!0},fileSize:{type:Number,value:null,nullable:!0},lastModified:{type:Number,value:Date.now()},uploadProgress:{type:Number,value:0},uuid:{type:String,value:null},isImage:{type:Boolean,value:!1},mimeType:{type:String,value:null,nullable:!0},uploadError:{type:Error,value:null,nullable:!0},validationErrorMsg:{type:String,value:null,nullable:!0},validationMultipleLimitMsg:{type:String,value:null,nullable:!0},ctxName:{type:String,value:null},cdnUrl:{type:String,value:null},cdnUrlModifiers:{type:String,value:null},fileInfo:{type:wt,value:null},isUploading:{type:Boolean,value:!1},abortController:{type:AbortController,value:null,nullable:!0},thumbUrl:{type:String,value:null,nullable:!0},silentUpload:{type:Boolean,value:!1},source:{type:String,value:!1,nullable:!0}});var v=class extends g{constructor(){super(...arguments);h(this,"couldBeUploadCollectionOwner",!1);h(this,"isUploadCollectionOwner",!1);h(this,"init$",Fe(this));h(this,"__initialUploadMetadata",null);h(this,"_validators",[this._validateMultipleLimit.bind(this),this._validateIsImage.bind(this),this._validateFileType.bind(this),this._validateMaxSizeLimit.bind(this)]);h(this,"_debouncedRunValidators",S(this._runValidators.bind(this),100));h(this,"_handleCollectionUpdate",t=>{let e=this.uploadCollection,r=[...new Set(Object.values(t).map(n=>[...n]).flat())].map(n=>e.read(n)).filter(Boolean);for(let n of r)this._runValidatorsForEntry(n);if(t.uploadProgress){let n=0,o=e.findItems(a=>!a.getValue("uploadError"));o.forEach(a=>{n+=e.readProp(a,"uploadProgress")});let l=Math.round(n/o.length);this.$["*commonProgress"]=l,O.emit(new V({type:L.UPLOAD_PROGRESS,ctx:this.ctxName,data:l}),void 0,l===100)}if(t.fileInfo){this.cfg.cropPreset&&this.setInitialCrop();let n=e.findItems(l=>!!l.getValue("fileInfo")),o=e.findItems(l=>!!l.getValue("uploadError")||!!l.getValue("validationErrorMsg"));if(e.size-o.length===n.length){let l=this.getOutputData(a=>!!a.getValue("fileInfo")&&!a.getValue("silentUpload"));l.length>0&&O.emit(new V({type:L.UPLOAD_FINISH,ctx:this.ctxName,data:l}))}}t.uploadError&&e.findItems(o=>!!o.getValue("uploadError")).forEach(o=>{O.emit(new V({type:L.UPLOAD_ERROR,ctx:this.ctxName,data:e.readProp(o,"uploadError")}),void 0,!1)}),t.validationErrorMsg&&e.findItems(o=>!!o.getValue("validationErrorMsg")).forEach(o=>{O.emit(new V({type:L.VALIDATION_ERROR,ctx:this.ctxName,data:e.readProp(o,"validationErrorMsg")}),void 0,!1)}),t.cdnUrlModifiers&&e.findItems(o=>!!o.getValue("cdnUrlModifiers")).forEach(o=>{O.emit(new V({type:L.CDN_MODIFICATION,ctx:this.ctxName,data:E.getCtx(o).store}),void 0,!1)})})}setUploadMetadata(t){Ve("setUploadMetadata is deprecated. Use `metadata` instance property on `lr-config` block instead. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/"),this.connectedOnce?this.$["*uploadMetadata"]=t:this.__initialUploadMetadata=t}initCallback(){if(super.initCallback(),!this.has("*uploadCollection")){let e=new Xe({typedSchema:nr,watchList:["uploadProgress","fileInfo","uploadError","validationErrorMsg","validationMultipleLimitMsg","cdnUrlModifiers"]});this.add("*uploadCollection",e)}let t=()=>this.hasBlockInCtx(e=>e instanceof v?e.isUploadCollectionOwner&&e.isConnected&&e!==this:!1);this.couldBeUploadCollectionOwner&&!t()&&(this.isUploadCollectionOwner=!0,this.__uploadCollectionHandler=(e,r,n)=>{var o;this._runValidators();for(let l of n)(o=l==null?void 0:l.getValue("abortController"))==null||o.abort(),l==null||l.setValue("abortController",null),URL.revokeObjectURL(l==null?void 0:l.getValue("thumbUrl"));this.$["*uploadList"]=e.map(l=>({uid:l}))},this.uploadCollection.setHandler(this.__uploadCollectionHandler),this.uploadCollection.observe(this._handleCollectionUpdate),this.subConfigValue("maxLocalFileSizeBytes",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMin",()=>this._debouncedRunValidators()),this.subConfigValue("multipleMax",()=>this._debouncedRunValidators()),this.subConfigValue("multiple",()=>this._debouncedRunValidators()),this.subConfigValue("imgOnly",()=>this._debouncedRunValidators()),this.subConfigValue("accept",()=>this._debouncedRunValidators())),this.__initialUploadMetadata&&(this.$["*uploadMetadata"]=this.__initialUploadMetadata),this.subConfigValue("maxConcurrentRequests",e=>{this.$["*uploadQueue"].concurrency=Number(e)||1})}destroyCallback(){super.destroyCallback(),this.isUploadCollectionOwner&&(this.uploadCollection.unobserve(this._handleCollectionUpdate),this.uploadCollection.getHandler()===this.__uploadCollectionHandler&&this.uploadCollection.removeHandler())}addFileFromUrl(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({externalUrl:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromUuid(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({uuid:t,fileName:r!=null?r:null,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFileFromObject(t,{silent:e,fileName:r,source:n}={}){this.uploadCollection.add({file:t,isImage:pe(t),mimeType:t.type,fileName:r!=null?r:t.name,fileSize:t.size,silentUpload:e!=null?e:!1,source:n!=null?n:et.API})}addFiles(t){console.warn("`addFiles` method is deprecated. Please use `addFileFromObject`, `addFileFromUrl` or `addFileFromUuid` instead."),t.forEach(e=>{this.uploadCollection.add({file:e,isImage:pe(e),mimeType:e.type,fileName:e.name,fileSize:e.size})})}uploadAll(){this.$["*uploadTrigger"]={}}openSystemDialog(t={}){var r;let e=qi([(r=this.cfg.accept)!=null?r:"",...this.cfg.imgOnly?de:[]]).join(",");this.cfg.accept&&this.cfg.imgOnly&&console.warn("There could be a mistake.\nBoth `accept` and `imgOnly` parameters are set.\nThe value of `accept` will be concatenated with the internal image mime types list."),this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.multiple=this.cfg.multiple,t.captureCamera?(this.fileInput.capture="",this.fileInput.accept=de.join(",")):this.fileInput.accept=e,this.fileInput.dispatchEvent(new MouseEvent("click")),this.fileInput.onchange=()=>{[...this.fileInput.files].forEach(n=>this.addFileFromObject(n,{source:et.LOCAL})),this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0),this.fileInput.value="",this.fileInput=null}}get sourceList(){let t=[];return this.cfg.sourceList&&(t=M(this.cfg.sourceList)),t}initFlow(t=!1){var e,r;if((e=this.$["*uploadList"])!=null&&e.length&&!t)this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0);else if(((r=this.sourceList)==null?void 0:r.length)===1){let n=this.sourceList[0];n==="local"?(this.$["*currentActivity"]=g.activities.UPLOAD_LIST,this==null||this.openSystemDialog()):(Object.values(v.extSrcList).includes(n)?this.set$({"*currentActivityParams":{externalSourceType:n},"*currentActivity":g.activities.EXTERNAL}):this.$["*currentActivity"]=n,this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0))}else this.set$({"*currentActivity":g.activities.START_FROM}),this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0);O.emit(new V({type:L.INIT_FLOW,ctx:this.ctxName}),void 0,!1)}doneFlow(){this.set$({"*currentActivity":this.doneActivity,"*history":this.doneActivity?[this.doneActivity]:[]}),this.$["*currentActivity"]||this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!1),O.emit(new V({type:L.DONE_FLOW,ctx:this.ctxName}),void 0,!1)}get uploadCollection(){return this.$["*uploadCollection"]}_validateFileType(t){let e=this.cfg.imgOnly,r=this.cfg.accept,n=qi([...e?de:[],r]);if(!n.length)return;let o=t.getValue("mimeType"),l=t.getValue("fileName");if(!o||!l)return;let a=Gi(o,n),c=ir(l,n);if(!a&&!c)return this.l10n("file-type-not-allowed")}_validateMaxSizeLimit(t){let e=this.cfg.maxLocalFileSizeBytes,r=t.getValue("fileSize");if(e&&r&&r>e)return this.l10n("files-max-size-limit-error",{maxFileSize:sr(e)})}_validateMultipleLimit(t){let r=this.uploadCollection.items().indexOf(t.uid),n=this.cfg.multiple?this.cfg.multipleMax:1;if(n&&r>=n)return this.l10n("files-count-allowed",{count:n})}_validateIsImage(t){let e=this.cfg.imgOnly,r=t.getValue("isImage");if(!(!e||r)&&!(!t.getValue("fileInfo")&&t.getValue("externalUrl"))&&!(!t.getValue("fileInfo")&&!t.getValue("mimeType")))return this.l10n("images-only-accepted")}_runValidatorsForEntry(t){for(let e of this._validators){let r=e(t);if(r){t.setValue("validationErrorMsg",r);return}}t.setValue("validationErrorMsg",null)}_runValidators(){for(let t of this.uploadCollection.items())setTimeout(()=>{let e=this.uploadCollection.read(t);e&&this._runValidatorsForEntry(e)})}setInitialCrop(){let t=je(this.cfg.cropPreset);if(t){let[e]=t,r=this.uploadCollection.findItems(n=>{var o;return n.getValue("fileInfo")&&n.getValue("isImage")&&!((o=n.getValue("cdnUrlModifiers"))!=null&&o.includes("/crop/"))}).map(n=>this.uploadCollection.read(n));for(let n of r){let o=n.getValue("fileInfo"),{width:l,height:a}=o.imageInfo,c=e.width/e.height,u=Ws(l,a,c),d=I(`crop/${u.width}x${u.height}/${u.x},${u.y}`);n.setMultipleValues({cdnUrlModifiers:d,cdnUrl:k(n.getValue("cdnUrl"),d)}),this.uploadCollection.size===1&&this.cfg.useCloudImageEditor&&this.hasBlockInCtx(p=>p.activityType===g.activities.CLOUD_IMG_EDIT)&&(this.$["*focusedEntry"]=n,this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}}}async getMetadata(){var e;let t=(e=this.cfg.metadata)!=null?e:this.$["*uploadMetadata"];return typeof t=="function"?await t():t}async getUploadClientOptions(){let t={store:this.cfg.store,publicKey:this.cfg.pubkey,baseCDN:this.cfg.cdnCname,baseURL:this.cfg.baseUrl,userAgent:Gs,integration:this.cfg.userAgentIntegration,secureSignature:this.cfg.secureSignature,secureExpire:this.cfg.secureExpire,retryThrottledRequestMaxTimes:this.cfg.retryThrottledRequestMaxTimes,multipartMinFileSize:this.cfg.multipartMinFileSize,multipartChunkSize:this.cfg.multipartChunkSize,maxConcurrentRequests:this.cfg.multipartMaxConcurrentRequests,multipartMaxAttempts:this.cfg.multipartMaxAttempts,checkForUrlDuplicates:!!this.cfg.checkForUrlDuplicates,saveUrlForRecurrentUploads:!!this.cfg.saveUrlForRecurrentUploads,metadata:await this.getMetadata()};return console.log("Upload client options:",t),t}getOutputData(t){let e=[];return this.uploadCollection.findItems(t).forEach(n=>{let o=E.getCtx(n).store,l=o.fileInfo||{name:o.fileName,fileSize:o.fileSize,isImage:o.isImage,mimeType:o.mimeType},a={...l,cdnUrlModifiers:o.cdnUrlModifiers,cdnUrl:o.cdnUrl||l.cdnUrl};e.push(a)}),e}};v.extSrcList=Object.freeze({FACEBOOK:"facebook",DROPBOX:"dropbox",GDRIVE:"gdrive",GPHOTOS:"gphotos",INSTAGRAM:"instagram",FLICKR:"flickr",VK:"vk",EVERNOTE:"evernote",BOX:"box",ONEDRIVE:"onedrive",HUDDLE:"huddle"});v.sourceTypes=Object.freeze({LOCAL:"local",URL:"url",CAMERA:"camera",DRAW:"draw",...v.extSrcList});Object.values(L).forEach(s=>{let i=O.eName(s),t=S(e=>{if([L.UPLOAD_FINISH,L.REMOVE,L.CDN_MODIFICATION].includes(e.detail.type)){let n=E.getCtx(e.detail.ctx),o=n.read("uploadCollection"),l=[];o.items().forEach(a=>{let c=E.getCtx(a).store,u=c.fileInfo;if(u){let d={...u,cdnUrlModifiers:c.cdnUrlModifiers,cdnUrl:c.cdnUrl||u.cdnUrl};l.push(d)}}),O.emit(new V({type:L.DATA_OUTPUT,ctx:e.detail.ctx,data:l})),n.pub("outputData",l)}},0);window.addEventListener(i,t)});var _o="https://ucarecdn.com",bo="https://upload.uploadcare.com",yo="https://social.uploadcare.com",me=Object.freeze({pubkey:"",multiple:!0,multipleMin:0,multipleMax:0,confirmUpload:!1,imgOnly:!1,accept:"",externalSourcesPreferredTypes:"",store:"auto",cameraMirror:!1,sourceList:"local, url, camera, dropbox, gdrive",maxLocalFileSizeBytes:0,thumbSize:76,showEmptyList:!1,useLocalImageEditor:!1,useCloudImageEditor:!0,removeCopyright:!1,cropPreset:"",modalScrollLock:!0,modalBackdropStrokes:!1,sourceListWrap:!0,remoteTabSessionKey:"",cdnCname:_o,baseUrl:bo,socialBaseUrl:yo,secureSignature:"",secureExpire:"",secureDeliveryProxy:"",retryThrottledRequestMaxTimes:1,multipartMinFileSize:26214400,multipartChunkSize:5242880,maxConcurrentRequests:10,multipartMaxConcurrentRequests:4,multipartMaxAttempts:3,checkForUrlDuplicates:!1,saveUrlForRecurrentUploads:!1,groupOutput:!1,userAgentIntegration:"",metadata:null});var K=s=>String(s),ot=s=>Number(s),z=s=>typeof s=="boolean"?s:s==="true"||s===""?!0:s==="false"?!1:!!s,vo=s=>s==="auto"?s:z(s),Co={pubkey:K,multiple:z,multipleMin:ot,multipleMax:ot,confirmUpload:z,imgOnly:z,accept:K,externalSourcesPreferredTypes:K,store:vo,cameraMirror:z,sourceList:K,maxLocalFileSizeBytes:ot,thumbSize:ot,showEmptyList:z,useLocalImageEditor:z,useCloudImageEditor:z,removeCopyright:z,cropPreset:K,modalScrollLock:z,modalBackdropStrokes:z,sourceListWrap:z,remoteTabSessionKey:K,cdnCname:K,baseUrl:K,socialBaseUrl:K,secureSignature:K,secureExpire:K,secureDeliveryProxy:K,retryThrottledRequestMaxTimes:ot,multipartMinFileSize:ot,multipartChunkSize:ot,maxConcurrentRequests:ot,multipartMaxConcurrentRequests:ot,multipartMaxAttempts:ot,checkForUrlDuplicates:z,saveUrlForRecurrentUploads:z,groupOutput:z,userAgentIntegration:K},or=(s,i)=>{if(!(typeof i=="undefined"||i===null))return Co[s](i)};var qe=Object.keys(me),wo=["metadata"],xo=s=>wo.includes(s),Ki=qe.filter(s=>!xo(s)),To={...Object.fromEntries(Ki.map(s=>[gt(s),s])),...Object.fromEntries(Ki.map(s=>[s.toLowerCase(),s]))},Eo={...Object.fromEntries(qe.map(s=>[gt(s),Q(s)])),...Object.fromEntries(qe.map(s=>[s.toLowerCase(),Q(s)]))},Ge=class extends b{constructor(){super();h(this,"ctxOwner",!0);this.init$={...this.init$,...Object.fromEntries(Object.entries(me).map(([t,e])=>[Q(t),e]))}}initCallback(){super.initCallback();for(let t of qe){let e=this,r="__"+t;e[r]=e[t],Object.defineProperty(this,t,{set:n=>{if(e[r]=n,Ki.includes(t)){let o=[...new Set([gt(t),t.toLowerCase()])];for(let l of o)typeof n=="undefined"||n===null?this.removeAttribute(l):this.setAttribute(l,n.toString())}this.$[Q(t)]!==n&&(typeof n=="undefined"||n===null?this.$[Q(t)]=me[t]:this.$[Q(t)]=n)},get:()=>this.$[Q(t)]}),typeof e[t]!="undefined"&&e[t]!==null&&(e[t]=e[r])}}attributeChangedCallback(t,e,r){if(e===r)return;let n=To[t],o=or(n,r),l=o!=null?o:me[n],a=this;a[n]=l}};Ge.bindAttributes(Eo);var ge=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,name:"",path:"",size:"24",viewBox:""})}initCallback(){super.initCallback(),this.sub("name",t=>{if(!t)return;let e=this.getCssData(`--icon-${t}`);e&&(this.$.path=e)}),this.sub("path",t=>{if(!t)return;t.trimStart().startsWith("<")?(this.setAttribute("raw",""),this.ref.svg.innerHTML=t):(this.removeAttribute("raw"),this.ref.svg.innerHTML=``)}),this.sub("size",t=>{this.$.viewBox=`0 0 ${t} ${t}`})}};ge.template=``;ge.bindAttributes({name:"name",size:"size"});var Ao="https://ucarecdn.com",Nt=Object.freeze({"dev-mode":{},pubkey:{},uuid:{},src:{},lazy:{default:1},intersection:{},breakpoints:{},"cdn-cname":{default:Ao},"proxy-cname":{},"secure-delivery-proxy":{},"hi-res-support":{default:1},"ultra-res-support":{},format:{default:"auto"},"cdn-operations":{},progressive:{},quality:{default:"smart"},"is-background-for":{}});var lr=s=>[...new Set(s)];var _e="--lr-img-",ar="unresolved",Jt=2,Qt=3,cr=!window.location.host.trim()||window.location.host.includes(":")||window.location.hostname.includes("localhost"),ur=Object.create(null),hr;for(let s in Nt)ur[_e+s]=((hr=Nt[s])==null?void 0:hr.default)||"";var Ke=class extends zt{constructor(){super(...arguments);h(this,"cssInit$",ur)}$$(t){return this.$[_e+t]}set$$(t){for(let e in t)this.$[_e+e]=t[e]}sub$$(t,e){this.sub(_e+t,r=>{r===null||r===""||e(r)})}_fmtAbs(t){return!t.includes("//")&&!cr&&(t=new URL(t,document.baseURI).href),t}_getCdnModifiers(t=""){return I(t&&`resize/${t}`,this.$$("cdn-operations")||"",`format/${this.$$("format")||Nt.format.default}`,`quality/${this.$$("quality")||Nt.quality.default}`)}_getUrlBase(t=""){if(this.$$("src").startsWith("data:")||this.$$("src").startsWith("blob:"))return this.$$("src");if(cr&&this.$$("src")&&!this.$$("src").includes("//"))return this._proxyUrl(this.$$("src"));let e=this._getCdnModifiers(t);if(this.$$("src").startsWith(this.$$("cdn-cname")))return k(this.$$("src"),e);if(this.$$("cdn-cname")&&this.$$("uuid"))return this._proxyUrl(k(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("uuid"))return this._proxyUrl(k(At(this.$$("cdn-cname"),this.$$("uuid")),e));if(this.$$("proxy-cname"))return this._proxyUrl(k(this.$$("proxy-cname"),e,this._fmtAbs(this.$$("src"))));if(this.$$("pubkey"))return this._proxyUrl(k(`https://${this.$$("pubkey")}.ucr.io/`,e,this._fmtAbs(this.$$("src"))))}_proxyUrl(t){return this.$$("secure-delivery-proxy")?ae(this.$$("secure-delivery-proxy"),{previewUrl:t},{transform:r=>window.encodeURIComponent(r)}):t}_getElSize(t,e=1,r=!0){let n=t.getBoundingClientRect(),o=e*Math.round(n.width),l=r?"":e*Math.round(n.height);return o||l?`${o||""}x${l||""}`:null}_setupEventProxy(t){let e=n=>{n.stopPropagation();let o=new Event(n.type,n);this.dispatchEvent(o)},r=["load","error"];for(let n of r)t.addEventListener(n,e)}get img(){return this._img||(this._img=new Image,this._setupEventProxy(this.img),this._img.setAttribute(ar,""),this.img.onload=()=>{this.img.removeAttribute(ar)},this.initAttributes(),this.appendChild(this._img)),this._img}get bgSelector(){return this.$$("is-background-for")}initAttributes(){[...this.attributes].forEach(t=>{Nt[t.name]||this.img.setAttribute(t.name,t.value)})}get breakpoints(){return this.$$("breakpoints")?lr(M(this.$$("breakpoints")).map(t=>Number(t))):null}renderBg(t){let e=new Set;this.breakpoints?this.breakpoints.forEach(n=>{e.add(`url("${this._getUrlBase(n+"x")}") ${n}w`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(n*Jt+"x")}") ${n*Jt}w`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(n*Qt+"x")}") ${n*Qt}w`)}):(e.add(`url("${this._getUrlBase(this._getElSize(t))}") 1x`),this.$$("hi-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Jt))}") ${Jt}x`),this.$$("ultra-res-support")&&e.add(`url("${this._getUrlBase(this._getElSize(t,Qt))}") ${Qt}x`));let r=`image-set(${[...e].join(", ")})`;t.style.setProperty("background-image",r),t.style.setProperty("background-image","-webkit-"+r)}getSrcset(){let t=new Set;return this.breakpoints?this.breakpoints.forEach(e=>{t.add(this._getUrlBase(e+"x")+` ${e}w`),this.$$("hi-res-support")&&t.add(this._getUrlBase(e*Jt+"x")+` ${e*Jt}w`),this.$$("ultra-res-support")&&t.add(this._getUrlBase(e*Qt+"x")+` ${e*Qt}w`)}):(t.add(this._getUrlBase(this._getElSize(this.img))+" 1x"),this.$$("hi-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,2))+" 2x"),this.$$("ultra-res-support")&&t.add(this._getUrlBase(this._getElSize(this.img,3))+" 3x")),[...t].join()}getSrc(){return this._getUrlBase()}init(){this.bgSelector?[...document.querySelectorAll(this.bgSelector)].forEach(t=>{this.$$("intersection")?this.initIntersection(t,()=>{this.renderBg(t)}):this.renderBg(t)}):this.$$("intersection")?this.initIntersection(this.img,()=>{this.img.srcset=this.getSrcset(),this.img.src=this.getSrc()}):(this.img.srcset=this.getSrcset(),this.img.src=this.getSrc())}initIntersection(t,e){let r={root:null,rootMargin:"0px"};this._isnObserver=new IntersectionObserver(n=>{n.forEach(o=>{o.isIntersecting&&(e(),this._isnObserver.unobserve(t))})},r),this._isnObserver.observe(t),this._observed||(this._observed=new Set),this._observed.add(t)}destroyCallback(){super.destroyCallback(),this._isnObserver&&(this._observed.forEach(t=>{this._isnObserver.unobserve(t)}),this._isnObserver=null)}static get observedAttributes(){return Object.keys(Nt)}attributeChangedCallback(t,e,r){window.setTimeout(()=>{this.$[_e+t]=r})}};var Yi=class extends Ke{initCallback(){super.initCallback(),this.sub$$("src",()=>{this.init()}),this.sub$$("uuid",()=>{this.init()}),this.sub$$("lazy",i=>{this.$$("is-background-for")||(this.img.loading=i?"lazy":"eager")})}};var Ye=class extends v{constructor(){super(),this.init$={...this.init$,"*simpleButtonText":"",onClick:()=>{this.initFlow()}}}initCallback(){super.initCallback(),this.subConfigValue("multiple",i=>{this.$["*simpleButtonText"]=i?this.l10n("upload-files"):this.l10n("upload-file")})}};Ye.template=``;var Zi=class extends g{constructor(){super(...arguments);h(this,"historyTracked",!0);h(this,"activityType","start-from")}initCallback(){super.initCallback(),this.registerActivity(this.activityType)}};function $o(s){return new Promise(i=>{typeof window.FileReader!="function"&&i(!1);try{let t=new FileReader;t.onerror=()=>{i(!0)};let e=r=>{r.type!=="loadend"&&t.abort(),i(!1)};t.onloadend=e,t.onprogress=e,t.readAsDataURL(s)}catch{i(!1)}})}function So(s,i){return new Promise(t=>{let e=0,r=[],n=l=>{l||(console.warn("Unexpectedly received empty content entry",{scope:"drag-and-drop"}),t(null)),l.isFile?(e++,l.file(a=>{e--;let c=new File([a],a.name,{type:a.type||i});r.push(c),e===0&&t(r)})):l.isDirectory&&o(l.createReader())},o=l=>{e++,l.readEntries(a=>{e--;for(let c of a)n(c);e===0&&t(r)})};n(s)})}function dr(s){let i=[],t=[];for(let e=0;e{i.push(...a)}));continue}let o=r.getAsFile();t.push($o(o).then(l=>{l||i.push(o)}))}else r.kind==="string"&&r.type.match("^text/uri-list")&&t.push(new Promise(n=>{r.getAsString(o=>{i.push(o),n()})}))}return Promise.all(t).then(()=>i)}var j={ACTIVE:0,INACTIVE:1,NEAR:2,OVER:3},pr=["focus"],ko=100,Ji=new Map;function Io(s,i){let t=Math.max(Math.min(s[0],i.x+i.width),i.x),e=Math.max(Math.min(s[1],i.y+i.height),i.y);return Math.sqrt((s[0]-t)*(s[0]-t)+(s[1]-e)*(s[1]-e))}function Qi(s){let i=0,t=document.body,e=new Set,r=f=>e.add(f),n=j.INACTIVE,o=f=>{s.shouldIgnore()&&f!==j.INACTIVE||(n!==f&&e.forEach(_=>_(f)),n=f)},l=()=>i>0;r(f=>s.onChange(f));let a=()=>{i=0,o(j.INACTIVE)},c=()=>{i+=1,n===j.INACTIVE&&o(j.ACTIVE)},u=()=>{i-=1,l()||o(j.INACTIVE)},d=f=>{f.preventDefault(),i=0,o(j.INACTIVE)},p=f=>{l()||(i+=1),f.preventDefault();let _=[f.x,f.y],$=s.element.getBoundingClientRect(),A=Math.floor(Io(_,$)),x=A{if(s.shouldIgnore())return;f.preventDefault();let _=await dr(f.dataTransfer);s.onItems(_),o(j.INACTIVE)};return t.addEventListener("drop",d),t.addEventListener("dragleave",u),t.addEventListener("dragenter",c),t.addEventListener("dragover",p),s.element.addEventListener("drop",m),pr.forEach(f=>{window.addEventListener(f,a)}),()=>{Ji.delete(s.element),t.removeEventListener("drop",d),t.removeEventListener("dragleave",u),t.removeEventListener("dragenter",c),t.removeEventListener("dragover",p),s.element.removeEventListener("drop",m),pr.forEach(f=>{window.removeEventListener(f,a)})}}var be=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,state:j.INACTIVE,withIcon:!1,isClickable:!1,isFullscreen:!1,isEnabled:!0,isVisible:!0,text:this.l10n("drop-files-here"),"lr-drop-area/targets":null})}isActive(){if(!this.$.isEnabled)return!1;let t=this.getBoundingClientRect(),e=t.width>0&&t.height>0,r=t.top>=0&&t.left>=0&&t.bottom<=(window.innerHeight||document.documentElement.clientHeight)&&t.right<=(window.innerWidth||document.documentElement.clientWidth),n=window.getComputedStyle(this),o=n.visibility!=="hidden"&&n.display!=="none";return e&&o&&r}initCallback(){super.initCallback(),this.$["lr-drop-area/targets"]||(this.$["lr-drop-area/targets"]=new Set),this.$["lr-drop-area/targets"].add(this),this.defineAccessor("disabled",e=>{this.set$({isEnabled:!e})}),this.defineAccessor("clickable",e=>{this.set$({isClickable:typeof e=="string"})}),this.defineAccessor("with-icon",e=>{this.set$({withIcon:typeof e=="string"})}),this.defineAccessor("fullscreen",e=>{this.set$({isFullscreen:typeof e=="string"})}),this.defineAccessor("text",e=>{e?this.set$({text:this.l10n(e)||e}):this.set$({text:this.l10n("drop-files-here")})}),this._destroyDropzone=Qi({element:this,shouldIgnore:()=>this._shouldIgnore(),onChange:e=>{this.$.state=e},onItems:e=>{e.length&&(e.forEach(r=>{if(typeof r=="string"){this.addFileFromUrl(r,{source:et.DROP_AREA});return}this.addFileFromObject(r,{source:et.DROP_AREA})}),this.uploadCollection.size&&(this.set$({"*currentActivity":g.activities.UPLOAD_LIST}),this.setForCtxTarget(B.StateConsumerScope,"*modalActive",!0)))}});let t=this.ref["content-wrapper"];t&&(this._destroyContentWrapperDropzone=Qi({element:t,onChange:e=>{var n;let r=(n=Object.entries(j).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&t.setAttribute("drag-state",r)},onItems:()=>{},shouldIgnore:()=>this._shouldIgnore()})),this.sub("state",e=>{var n;let r=(n=Object.entries(j).find(([,o])=>o===e))==null?void 0:n[0].toLowerCase();r&&this.setAttribute("drag-state",r)}),this.subConfigValue("sourceList",e=>{let r=M(e);this.$.isEnabled=r.includes(v.sourceTypes.LOCAL),this.$.isVisible=this.$.isEnabled||!this.querySelector("[data-default-slot]")}),this.sub("isVisible",e=>{this.toggleAttribute("hidden",!e)}),this.$.isClickable&&(this._onAreaClicked=()=>{this.openSystemDialog()},this.addEventListener("click",this._onAreaClicked))}_shouldIgnore(){return!this.$.isEnabled||!this._couldHandleFiles()?!0:this.$.isFullscreen?[...this.$["lr-drop-area/targets"]].filter(r=>r!==this).filter(r=>r.isActive()).length>0:!1}_couldHandleFiles(){let t=this.cfg.multiple,e=this.cfg.multipleMax,r=this.uploadCollection.size;return!(t&&e&&r>=e||!t&&r>0)}destroyCallback(){var t,e,r,n;super.destroyCallback(),(e=(t=this.$["lr-drop-area/targets"])==null?void 0:t.remove)==null||e.call(t,this),(r=this._destroyDropzone)==null||r.call(this),(n=this._destroyContentWrapperDropzone)==null||n.call(this),this._onAreaClicked&&this.removeEventListener("click",this._onAreaClicked)}};be.template=`
{{text}}
`;be.bindAttributes({"with-icon":null,clickable:null,text:null,fullscreen:null,disabled:null});var Oo="src-type-",ye=class extends v{constructor(){super(...arguments);h(this,"_registeredTypes",{});h(this,"init$",{...this.init$,iconName:"default"})}initTypes(){this.registerType({type:v.sourceTypes.LOCAL,onClick:()=>{this.openSystemDialog()}}),this.registerType({type:v.sourceTypes.URL,activity:g.activities.URL,textKey:"from-url"}),this.registerType({type:v.sourceTypes.CAMERA,activity:g.activities.CAMERA,onClick:()=>{var e=document.createElement("input").capture!==void 0;return e&&this.openSystemDialog({captureCamera:!0}),!e}}),this.registerType({type:"draw",activity:g.activities.DRAW,icon:"edit-draw"});for(let t of Object.values(v.extSrcList))this.registerType({type:t,activity:g.activities.EXTERNAL,activityParams:{externalSourceType:t}})}initCallback(){super.initCallback(),this.initTypes(),this.setAttribute("role","button"),this.defineAccessor("type",t=>{t&&this.applyType(t)})}registerType(t){this._registeredTypes[t.type]=t}getType(t){return this._registeredTypes[t]}applyType(t){let e=this._registeredTypes[t];if(!e){console.warn("Unsupported source type: "+t);return}let{textKey:r=t,icon:n=t,activity:o,onClick:l,activityParams:a={}}=e;this.applyL10nKey("src-type",`${Oo}${r}`),this.$.iconName=n,this.onclick=c=>{(l?l(c):!!o)&&this.set$({"*currentActivityParams":a,"*currentActivity":o})}}};ye.template=`
`;ye.bindAttributes({type:null});var ts=class extends b{initCallback(){super.initCallback(),this.subConfigValue("sourceList",i=>{let t=M(i),e="";t.forEach(r=>{e+=``}),this.cfg.sourceListWrap?this.innerHTML=e:this.outerHTML=e})}};function fr(s){let i=new Blob([s],{type:"image/svg+xml"});return URL.createObjectURL(i)}function mr(s="#fff",i="rgba(0, 0, 0, .1)"){return fr(``)}function ve(s="hsl(209, 21%, 65%)",i=32,t=32){return fr(``)}function gr(s,i=40){if(s.type==="image/svg+xml")return URL.createObjectURL(s);let t=document.createElement("canvas"),e=t.getContext("2d"),r=new Image,n=new Promise((o,l)=>{r.onload=()=>{let a=r.height/r.width;a>1?(t.width=i,t.height=i*a):(t.height=i,t.width=i/a),e.fillStyle="rgb(240, 240, 240)",e.fillRect(0,0,t.width,t.height),e.drawImage(r,0,0,t.width,t.height),t.toBlob(c=>{if(!c){l();return}let u=URL.createObjectURL(c);o(u)})},r.onerror=a=>{l(a)}});return r.src=URL.createObjectURL(s),n}var H=Object.freeze({FINISHED:Symbol(0),FAILED:Symbol(1),UPLOADING:Symbol(2),IDLE:Symbol(3),LIMIT_OVERFLOW:Symbol(4)}),_t=class extends v{constructor(){super();h(this,"pauseRender",!0);h(this,"_entrySubs",new Set);h(this,"_entry",null);h(this,"_isIntersecting",!1);h(this,"_debouncedGenerateThumb",S(this._generateThumbnail.bind(this),100));h(this,"_debouncedCalculateState",S(this._calculateState.bind(this),100));h(this,"_renderedOnce",!1);this.init$={...this.init$,uid:"",itemName:"",errorText:"",thumbUrl:"",progressValue:0,progressVisible:!1,progressUnknown:!1,badgeIcon:"",isFinished:!1,isFailed:!1,isUploading:!1,isFocused:!1,isEditable:!1,isLimitOverflow:!1,state:H.IDLE,"*uploadTrigger":null,onEdit:()=>{this.set$({"*focusedEntry":this._entry}),this.hasBlockInCtx(t=>t.activityType===g.activities.DETAILS)?this.$["*currentActivity"]=g.activities.DETAILS:this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT},onRemove:()=>{let t=this._entry.getValue("uuid");if(t){let e=this.getOutputData(r=>r.getValue("uuid")===t);O.emit(new V({type:L.REMOVE,ctx:this.ctxName,data:e}))}this.uploadCollection.remove(this.$.uid)},onUpload:()=>{this.upload()}}}_reset(){for(let t of this._entrySubs)t.remove();this._debouncedGenerateThumb.cancel(),this._debouncedCalculateState.cancel(),this._entrySubs=new Set,this._entry=null}_observerCallback(t){let[e]=t;this._isIntersecting=e.isIntersecting,e.isIntersecting&&!this._renderedOnce&&(this.render(),this._renderedOnce=!0),e.intersectionRatio===0?this._debouncedGenerateThumb.cancel():this._debouncedGenerateThumb()}_calculateState(){if(!this._entry)return;let t=this._entry,e=H.IDLE;t.getValue("uploadError")||t.getValue("validationErrorMsg")?e=H.FAILED:t.getValue("validationMultipleLimitMsg")?e=H.LIMIT_OVERFLOW:t.getValue("isUploading")?e=H.UPLOADING:t.getValue("fileInfo")&&(e=H.FINISHED),this.$.state=e}async _generateThumbnail(){var e;if(!this._entry)return;let t=this._entry;if(t.getValue("fileInfo")&&t.getValue("isImage")){let r=this.cfg.thumbSize,n=this.proxyUrl(k(At(this.cfg.cdnCname,this._entry.getValue("uuid")),I(t.getValue("cdnUrlModifiers"),`scale_crop/${r}x${r}/center`))),o=t.getValue("thumbUrl");o!==n&&(t.setValue("thumbUrl",n),o!=null&&o.startsWith("blob:")&&URL.revokeObjectURL(o));return}if(!t.getValue("thumbUrl"))if((e=t.getValue("file"))!=null&&e.type.includes("image"))try{let r=await gr(t.getValue("file"),this.cfg.thumbSize);t.setValue("thumbUrl",r)}catch{let n=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ve(n))}else{let r=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon");t.setValue("thumbUrl",ve(r))}}_subEntry(t,e){let r=this._entry.subscribe(t,n=>{this.isConnected&&e(n)});this._entrySubs.add(r)}_handleEntryId(t){var r;this._reset();let e=(r=this.uploadCollection)==null?void 0:r.read(t);this._entry=e,e&&(this._subEntry("uploadProgress",n=>{this.$.progressValue=n}),this._subEntry("fileName",n=>{this.$.itemName=n||e.getValue("externalUrl")||this.l10n("file-no-name"),this._debouncedCalculateState()}),this._subEntry("externalUrl",n=>{this.$.itemName=e.getValue("fileName")||n||this.l10n("file-no-name")}),this._subEntry("uuid",n=>{this._debouncedCalculateState(),n&&this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("cdnUrlModifiers",()=>{this._isIntersecting&&this._debouncedGenerateThumb()}),this._subEntry("thumbUrl",n=>{this.$.thumbUrl=n?`url(${n})`:""}),this._subEntry("validationMultipleLimitMsg",()=>this._debouncedCalculateState()),this._subEntry("validationErrorMsg",()=>this._debouncedCalculateState()),this._subEntry("uploadError",()=>this._debouncedCalculateState()),this._subEntry("isUploading",()=>this._debouncedCalculateState()),this._subEntry("fileSize",()=>this._debouncedCalculateState()),this._subEntry("mimeType",()=>this._debouncedCalculateState()),this._subEntry("isImage",()=>this._debouncedCalculateState()),this._isIntersecting&&this._debouncedGenerateThumb())}initCallback(){super.initCallback(),this.sub("uid",t=>{this._handleEntryId(t)}),this.sub("state",t=>{this._handleState(t)}),this.subConfigValue("useCloudImageEditor",()=>this._debouncedCalculateState()),this.onclick=()=>{_t.activeInstances.forEach(t=>{t===this?t.setAttribute("focused",""):t.removeAttribute("focused")})},this.$["*uploadTrigger"]=null,this.sub("*uploadTrigger",t=>{t&&setTimeout(()=>this.isConnected&&this.upload())}),_t.activeInstances.add(this)}_handleState(t){var e,r,n;this.set$({isFailed:t===H.FAILED,isLimitOverflow:t===H.LIMIT_OVERFLOW,isUploading:t===H.UPLOADING,isFinished:t===H.FINISHED,progressVisible:t===H.UPLOADING,isEditable:this.cfg.useCloudImageEditor&&((e=this._entry)==null?void 0:e.getValue("isImage"))&&((r=this._entry)==null?void 0:r.getValue("cdnUrl")),errorText:((n=this._entry.getValue("uploadError"))==null?void 0:n.message)||this._entry.getValue("validationErrorMsg")||this._entry.getValue("validationMultipleLimitMsg")}),t===H.FAILED||t===H.LIMIT_OVERFLOW?this.$.badgeIcon="badge-error":t===H.FINISHED&&(this.$.badgeIcon="badge-success"),t===H.UPLOADING?this.$.isFocused=!1:this.$.progressValue=0}destroyCallback(){super.destroyCallback(),_t.activeInstances.delete(this),this._reset()}connectedCallback(){super.connectedCallback(),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{root:this.parentElement,rootMargin:"50% 0px 50% 0px",threshold:[0,1]}),this._observer.observe(this)}disconnectedCallback(){var t;super.disconnectedCallback(),this._debouncedGenerateThumb.cancel(),(t=this._observer)==null||t.disconnect()}async upload(){var n,o,l;let t=this._entry;if(!this.uploadCollection.read(t.uid)||t.getValue("fileInfo")||t.getValue("isUploading")||t.getValue("uploadError")||t.getValue("validationErrorMsg")||t.getValue("validationMultipleLimitMsg"))return;let e=this.cfg.multiple?this.cfg.multipleMax:1;if(e&&this.uploadCollection.size>e)return;let r=this.getOutputData(a=>!a.getValue("fileInfo"));O.emit(new V({type:L.UPLOAD_START,ctx:this.ctxName,data:r})),this._debouncedCalculateState(),t.setValue("isUploading",!0),t.setValue("uploadError",null),t.setValue("validationErrorMsg",null),t.setValue("validationMultipleLimitMsg",null),!t.getValue("file")&&t.getValue("externalUrl")&&(this.$.progressUnknown=!0);try{let a=new AbortController;t.setValue("abortController",a);let c=async()=>{let d=await this.getUploadClientOptions();return Bi(t.getValue("file")||t.getValue("externalUrl")||t.getValue("uuid"),{...d,fileName:t.getValue("fileName"),source:t.getValue("source"),onProgress:p=>{if(p.isComputable){let m=p.value*100;t.setValue("uploadProgress",m)}this.$.progressUnknown=!p.isComputable},signal:a.signal})},u=await this.$["*uploadQueue"].add(c);t.setMultipleValues({fileInfo:u,isUploading:!1,fileName:u.originalFilename,fileSize:u.size,isImage:u.isImage,mimeType:(l=(o=(n=u.contentInfo)==null?void 0:n.mime)==null?void 0:o.mime)!=null?l:u.mimeType,uuid:u.uuid,cdnUrl:u.cdnUrl}),t===this._entry&&this._debouncedCalculateState()}catch(a){console.warn("Upload error",a),t.setMultipleValues({abortController:null,isUploading:!1,uploadProgress:0}),t===this._entry&&this._debouncedCalculateState(),a instanceof P?a.isCancel||t.setValue("uploadError",a):t.setValue("uploadError",new Error("Unexpected error"))}}};_t.template=`
{{itemName}}{{errorText}}
`;_t.activeInstances=new Set;var Ze=class{constructor(){h(this,"caption","");h(this,"text","");h(this,"iconName","");h(this,"isError",!1)}},Je=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,iconName:"info",captionTxt:"Message caption",msgTxt:"Message...","*message":null,onClose:()=>{this.$["*message"]=null}})}initCallback(){super.initCallback(),this.sub("*message",t=>{t?(this.setAttribute("active",""),this.set$({captionTxt:t.caption||"",msgTxt:t.text||"",iconName:t.isError?"error":"info"}),t.isError?this.setAttribute("error",""):this.removeAttribute("error")):this.removeAttribute("active")})}};Je.template=`
{{captionTxt}}
{{msgTxt}}
`;var Qe=class extends v{constructor(){super();h(this,"couldBeUploadCollectionOwner",!0);h(this,"historyTracked",!0);h(this,"activityType",g.activities.UPLOAD_LIST);h(this,"_debouncedHandleCollectionUpdate",S(()=>{this.isConnected&&(this._updateUploadsState(),this._updateCountLimitMessage())},0));this.init$={...this.init$,doneBtnVisible:!1,doneBtnEnabled:!1,uploadBtnVisible:!1,addMoreBtnVisible:!1,addMoreBtnEnabled:!1,headerText:"",hasFiles:!1,onAdd:()=>{this.initFlow(!0)},onUpload:()=>{this.uploadAll(),this._updateUploadsState()},onDone:()=>{this.doneFlow()},onCancel:()=>{let t=this.getOutputData(e=>!!e.getValue("fileInfo"));O.emit(new V({type:L.REMOVE,ctx:this.ctxName,data:t})),this.uploadCollection.clearAll()}}}_validateFilesCount(){var u,d;let t=!!this.cfg.multiple,e=t?(u=this.cfg.multipleMin)!=null?u:0:1,r=t?(d=this.cfg.multipleMax)!=null?d:0:1,n=this.uploadCollection.size,o=e?nr:!1;return{passed:!o&&!l,tooFew:o,tooMany:l,min:e,max:r,exact:r===n}}_updateCountLimitMessage(){let t=this.uploadCollection.size,e=this._validateFilesCount();if(t&&!e.passed){let r=new Ze,n=e.tooFew?"files-count-limit-error-too-few":"files-count-limit-error-too-many";r.caption=this.l10n("files-count-limit-error-title"),r.text=this.l10n(n,{min:e.min,max:e.max,total:t}),r.isError=!0,this.set$({"*message":r})}else this.set$({"*message":null})}_updateUploadsState(){let t=this.uploadCollection.items(),r={total:t.length,succeed:0,uploading:0,failed:0,limitOverflow:0};for(let m of t){let f=this.uploadCollection.read(m);f.getValue("fileInfo")&&!f.getValue("validationErrorMsg")&&(r.succeed+=1),f.getValue("isUploading")&&(r.uploading+=1),(f.getValue("validationErrorMsg")||f.getValue("uploadError"))&&(r.failed+=1),f.getValue("validationMultipleLimitMsg")&&(r.limitOverflow+=1)}let{passed:n,tooMany:o,exact:l}=this._validateFilesCount(),a=r.failed===0&&r.limitOverflow===0,c=!1,u=!1,d=!1;r.total-r.succeed-r.uploading-r.failed>0&&n?c=!0:(u=!0,d=r.total===r.succeed&&n&&a),this.set$({doneBtnVisible:u,doneBtnEnabled:d,uploadBtnVisible:c,addMoreBtnEnabled:r.total===0||!o&&!l,addMoreBtnVisible:!l||this.cfg.multiple,headerText:this._getHeaderText(r)})}_getHeaderText(t){let e=r=>{let n=t[r];return this.l10n(`header-${r}`,{count:n})};return t.uploading>0?e("uploading"):t.failed>0?e("failed"):t.succeed>0?e("succeed"):e("total")}initCallback(){super.initCallback(),this.registerActivity(this.activityType),this.subConfigValue("multiple",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMin",this._debouncedHandleCollectionUpdate),this.subConfigValue("multipleMax",this._debouncedHandleCollectionUpdate),this.sub("*currentActivity",t=>{var e;((e=this.uploadCollection)==null?void 0:e.size)===0&&!this.cfg.showEmptyList&&t===this.activityType&&(this.$["*currentActivity"]=this.initActivity)}),this.uploadCollection.observe(this._debouncedHandleCollectionUpdate),this.sub("*uploadList",t=>{this._debouncedHandleCollectionUpdate(),this.set$({hasFiles:t.length>0}),(t==null?void 0:t.length)===0&&!this.cfg.showEmptyList&&this.historyBack(),this.cfg.confirmUpload||this.add$({"*uploadTrigger":{}},!0)})}destroyCallback(){super.destroyCallback(),this.uploadCollection.unobserve(this._debouncedHandleCollectionUpdate)}};Qe.template=`{{headerText}}
`;var ti=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.URL);h(this,"init$",{...this.init$,importDisabled:!0,onUpload:t=>{t.preventDefault();let e=this.ref.input.value;this.addFileFromUrl(e,{source:et.URL_TAB}),this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()},onInput:t=>{let e=t.target.value;this.set$({importDisabled:!e})}})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{this.ref.input.value="",this.ref.input.focus()}})}};ti.template=`
`;var es=()=>typeof navigator.permissions!="undefined";var ei=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CAMERA);h(this,"_unsubPermissions",null);h(this,"init$",{...this.init$,video:null,videoTransformCss:null,shotBtnDisabled:!0,videoHidden:!0,messageHidden:!0,requestBtnHidden:es(),l10nMessage:null,originalErrorMessage:null,cameraSelectOptions:null,cameraSelectHidden:!0,onCameraSelectChange:t=>{this._selectedCameraId=t.target.value,this._capture()},onCancel:()=>{this.historyBack()},onShot:()=>{this._shot()},onRequestPermissions:()=>{this._capture()}});h(this,"_onActivate",()=>{es()&&this._subscribePermissions(),this._capture()});h(this,"_onDeactivate",()=>{this._unsubPermissions&&this._unsubPermissions(),this._stopCapture()});h(this,"_handlePermissionsChange",()=>{this._capture()});h(this,"_setPermissionsState",S(t=>{this.$.originalErrorMessage=null,this.classList.toggle("initialized",t==="granted"),t==="granted"?this.set$({videoHidden:!1,shotBtnDisabled:!1,messageHidden:!0}):t==="prompt"?(this.$.l10nMessage=this.l10n("camera-permissions-prompt"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture()):(this.$.l10nMessage=this.l10n("camera-permissions-denied"),this.set$({videoHidden:!0,shotBtnDisabled:!0,messageHidden:!1}),this._stopCapture())},300))}async _subscribePermissions(){try{(await navigator.permissions.query({name:"camera"})).addEventListener("change",this._handlePermissionsChange)}catch(t){console.log("Failed to use permissions API. Fallback to manual request mode.",t),this._capture()}}async _capture(){let t={video:{width:{ideal:1920},height:{ideal:1080},frameRate:{ideal:30}},audio:!1};this._selectedCameraId&&(t.video.deviceId={exact:this._selectedCameraId}),this._canvas=document.createElement("canvas"),this._ctx=this._canvas.getContext("2d");try{this._setPermissionsState("prompt");let e=await navigator.mediaDevices.getUserMedia(t);e.addEventListener("inactive",()=>{this._setPermissionsState("denied")}),this.$.video=e,this._capturing=!0,this._setPermissionsState("granted")}catch(e){this._setPermissionsState("denied"),this.$.originalErrorMessage=e.message}}_stopCapture(){var t;this._capturing&&((t=this.$.video)==null||t.getTracks()[0].stop(),this.$.video=null,this._capturing=!1)}_shot(){this._canvas.height=this.ref.video.videoHeight,this._canvas.width=this.ref.video.videoWidth,this._ctx.drawImage(this.ref.video,0,0);let t=Date.now(),e=`camera-${t}.png`;this._canvas.toBlob(r=>{let n=new File([r],e,{lastModified:t,type:"image/png"});this.addFileFromObject(n,{source:et.CAMERA}),this.set$({"*currentActivity":g.activities.UPLOAD_LIST})})}async initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:this._onActivate,onDeactivate:this._onDeactivate}),this.subConfigValue("cameraMirror",t=>{this.$.videoTransformCss=t?"scaleX(-1)":null});try{let e=(await navigator.mediaDevices.enumerateDevices()).filter(r=>r.kind==="videoinput").map((r,n)=>({text:r.label.trim()||`${this.l10n("caption-camera")} ${n+1}`,value:r.deviceId}));e.length>1&&(this.$.cameraSelectOptions=e,this.$.cameraSelectHidden=!1)}catch{}}};ei.template=`
{{l10nMessage}}{{originalErrorMessage}}
`;var is=class extends v{};var ii=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.DETAILS);h(this,"pauseRender",!0);h(this,"init$",{...this.init$,checkerboard:!1,fileSize:null,fileName:"",cdnUrl:"",errorTxt:"",cloudEditBtnHidden:!0,onNameInput:null,onBack:()=>{this.historyBack()},onRemove:()=>{this.uploadCollection.remove(this.entry.uid),this.historyBack()},onCloudEdit:()=>{this.entry.getValue("uuid")&&(this.$["*currentActivity"]=g.activities.CLOUD_IMG_EDIT)}})}showNonImageThumb(){let t=window.getComputedStyle(this).getPropertyValue("--clr-generic-file-icon"),e=ve(t,108,108);this.ref.filePreview.setImageUrl(e),this.set$({checkerboard:!1})}initCallback(){super.initCallback(),this.render(),this.$.fileSize=this.l10n("file-size-unknown"),this.registerActivity(this.activityType,{onDeactivate:()=>{this.ref.filePreview.clear()}}),this.sub("*focusedEntry",t=>{if(!t)return;this._entrySubs?this._entrySubs.forEach(n=>{this._entrySubs.delete(n),n.remove()}):this._entrySubs=new Set,this.entry=t;let e=t.getValue("file");if(e){this._file=e;let n=pe(this._file);n&&!t.getValue("cdnUrl")&&(this.ref.filePreview.setImageFile(this._file),this.set$({checkerboard:!0})),n||this.showNonImageThumb()}let r=(n,o)=>{this._entrySubs.add(this.entry.subscribe(n,o))};r("fileName",n=>{this.$.fileName=n,this.$.onNameInput=()=>{let o=this.ref.file_name_input.value;Object.defineProperty(this._file,"name",{writable:!0,value:o}),this.entry.setValue("fileName",o)}}),r("fileSize",n=>{this.$.fileSize=Number.isFinite(n)?this.fileSizeFmt(n):this.l10n("file-size-unknown")}),r("uploadError",n=>{this.$.errorTxt=n==null?void 0:n.message}),r("externalUrl",n=>{n&&(this.entry.getValue("uuid")||this.showNonImageThumb())}),r("cdnUrl",n=>{let o=this.cfg.useCloudImageEditor&&n&&this.entry.getValue("isImage");if(n&&this.ref.filePreview.clear(),this.set$({cdnUrl:n,cloudEditBtnHidden:!o}),n&&this.entry.getValue("isImage")){let l=k(n,I("format/auto","preview"));this.ref.filePreview.setImageUrl(this.proxyUrl(l))}})})}};ii.template=`
{{fileSize}}
{{errorTxt}}
`;var ss=class{constructor(){h(this,"captionL10nStr","confirm-your-action");h(this,"messageL10Str","are-you-sure");h(this,"confirmL10nStr","yes");h(this,"denyL10nStr","no")}confirmAction(){console.log("Confirmed")}denyAction(){this.historyBack()}},si=class extends g{constructor(){super(...arguments);h(this,"activityType",g.activities.CONFIRMATION);h(this,"_defaults",new ss);h(this,"init$",{...this.init$,activityCaption:"",messageTxt:"",confirmBtnTxt:"",denyBtnTxt:"","*confirmation":null,onConfirm:this._defaults.confirmAction,onDeny:this._defaults.denyAction.bind(this)})}initCallback(){super.initCallback(),this.set$({messageTxt:this.l10n(this._defaults.messageL10Str),confirmBtnTxt:this.l10n(this._defaults.confirmL10nStr),denyBtnTxt:this.l10n(this._defaults.denyL10nStr)}),this.sub("*confirmation",t=>{t&&this.set$({"*currentActivity":g.activities.CONFIRMATION,activityCaption:this.l10n(t.captionL10nStr),messageTxt:this.l10n(t.messageL10Str),confirmBtnTxt:this.l10n(t.confirmL10nStr),denyBtnTxt:this.l10n(t.denyL10nStr),onDeny:()=>{t.denyAction()},onConfirm:()=>{t.confirmAction()}})})}};si.template=`{{activityCaption}}
{{messageTxt}}
`;var ri=class extends v{constructor(){super(...arguments);h(this,"init$",{...this.init$,visible:!1,unknown:!1,value:0,"*commonProgress":0})}initCallback(){super.initCallback(),this.uploadCollection.observe(()=>{let t=this.uploadCollection.items().some(e=>this.uploadCollection.read(e).getValue("isUploading"));this.$.visible=t}),this.sub("visible",t=>{t?this.setAttribute("active",""):this.removeAttribute("active")}),this.sub("*commonProgress",t=>{this.$.value=t})}};ri.template=``;var ni=class extends b{constructor(){super(...arguments);h(this,"_value",0);h(this,"_unknownMode",!1);h(this,"init$",{...this.init$,width:0,opacity:0})}initCallback(){super.initCallback(),this.defineAccessor("value",t=>{t!==void 0&&(this._value=t,this._unknownMode||this.style.setProperty("--l-width",this._value.toString()))}),this.defineAccessor("visible",t=>{this.ref.line.classList.toggle("progress--hidden",!t)}),this.defineAccessor("unknown",t=>{this._unknownMode=t,this.ref.line.classList.toggle("progress--unknown",t)})}};ni.template='
';var Y="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";var Ce=class extends b{constructor(){super();h(this,"init$",{...this.init$,checkerboard:!1,src:Y})}initCallback(){super.initCallback(),this.sub("checkerboard",()=>{this.style.backgroundImage=this.hasAttribute("checkerboard")?`url(${mr()})`:"unset"})}destroyCallback(){super.destroyCallback(),URL.revokeObjectURL(this._lastObjectUrl)}setImage(t){this.$.src=t.src}setImageFile(t){let e=URL.createObjectURL(t);this.$.src=e,this._lastObjectUrl=e}setImageUrl(t){this.$.src=t}clear(){URL.revokeObjectURL(this._lastObjectUrl),this.$.src=Y}};Ce.template='';Ce.bindAttributes({checkerboard:"checkerboard"});var _r="--cfg-ctx-name",U=class extends b{get cfgCssCtxName(){return this.getCssData(_r,!0)}get cfgCtxName(){var t;let i=((t=this.getAttribute("ctx-name"))==null?void 0:t.trim())||this.cfgCssCtxName||this.__cachedCfgCtxName;return this.__cachedCfgCtxName=i,i}connectedCallback(){var i;if(!this.connectedOnce){let t=(i=this.getAttribute("ctx-name"))==null?void 0:i.trim();t&&this.style.setProperty(_r,`'${t}'`)}super.connectedCallback()}parseCfgProp(i){return{...super.parseCfgProp(i),ctx:E.getCtx(this.cfgCtxName)}}};function br(...s){return s.reduce((i,t)=>{if(typeof t=="string")return i[t]=!0,i;for(let e of Object.keys(t))i[e]=t[e];return i},{})}function N(...s){let i=br(...s);return Object.keys(i).reduce((t,e)=>(i[e]&&t.push(e),t),[]).join(" ")}function yr(s,...i){let t=br(...i);for(let e of Object.keys(t))s.classList.toggle(e,t[e])}var Z={brightness:0,exposure:0,gamma:100,contrast:0,saturation:0,vibrance:0,warmth:0,enhance:0,filter:0,rotate:0};function Lo(s,i){if(typeof i=="number")return Z[s]!==i?`${s}/${i}`:"";if(typeof i=="boolean")return i&&Z[s]!==i?`${s}`:"";if(s==="filter"){if(!i||Z[s]===i.amount)return"";let{name:t,amount:e}=i;return`${s}/${t}/${e}`}if(s==="crop"){if(!i)return"";let{dimensions:t,coords:e}=i;return`${s}/${t.join("x")}/${e.join(",")}`}return""}var Cr=["enhance","brightness","exposure","gamma","contrast","saturation","vibrance","warmth","filter","mirror","flip","rotate","crop"];function $t(s){return He(...Cr.filter(i=>typeof s[i]!="undefined"&&s[i]!==null).map(i=>{let t=s[i];return Lo(i,t)}).filter(i=>!!i))}var oi=He("format/auto","progressive/yes"),bt=([s])=>typeof s!="undefined"?Number(s):void 0,vr=()=>!0,Uo=([s,i])=>({name:s,amount:typeof i!="undefined"?Number(i):100}),Ro=([s,i])=>({dimensions:M(s,"x").map(Number),coords:M(i).map(Number)}),Po={enhance:bt,brightness:bt,exposure:bt,gamma:bt,contrast:bt,saturation:bt,vibrance:bt,warmth:bt,filter:Uo,mirror:vr,flip:vr,rotate:bt,crop:Ro};function wr(s){let i={};for(let t of s){let[e,...r]=t.split("/");if(!Cr.includes(e))continue;let n=Po[e],o=n(r);i[e]=o}return i}function xr(s){return{"*originalUrl":null,"*faderEl":null,"*cropperEl":null,"*imgEl":null,"*imgContainerEl":null,"*networkProblems":!1,"*imageSize":null,"*editorTransformations":{},"*cropPresetList":[],entry:null,extension:null,editorMode:!1,modalCaption:"",isImage:!1,msg:"",src:Y,fileType:"",showLoader:!1,uuid:null,cdnUrl:null,cropPreset:"","presence.networkProblems":!1,"presence.modalCaption":!0,"presence.editorToolbar":!1,"presence.viewerToolbar":!0,"*on.retryNetwork":()=>{let i=s.querySelectorAll("img");for(let t of i){let e=t.src;t.src=Y,t.src=e}s.$["*networkProblems"]=!1},"*on.apply":i=>{if(!i)return;let t=s.$["*originalUrl"],e=I($t(i)),r=k(t,I(e,"preview")),n={originalUrl:t,cdnUrlModifiers:e,cdnUrl:r,transformations:i};s.dispatchEvent(new CustomEvent("apply",{detail:n,bubbles:!0,composed:!0})),s.remove()},"*on.cancel":()=>{s.remove(),s.dispatchEvent(new CustomEvent("cancel",{bubbles:!0,composed:!0}))}}}var Tr=`
Network error
{{fileType}}
{{msg}}
`;var D={CROP:"crop",SLIDERS:"sliders",FILTERS:"filters"},li=[D.CROP,D.SLIDERS,D.FILTERS],Er=["brightness","exposure","gamma","contrast","saturation","vibrance","warmth","enhance"],Ar=["adaris","briaril","calarel","carris","cynarel","cyren","elmet","elonni","enzana","erydark","fenralan","ferand","galen","gavin","gethriel","iorill","iothari","iselva","jadis","lavra","misiara","namala","nerion","nethari","pamaya","sarnar","sedis","sewen","sorahel","sorlen","tarian","thellassan","varriel","varven","vevera","virkas","yedis","yllara","zatvel","zevcen"],$r=["rotate","mirror","flip"],lt={brightness:{zero:Z.brightness,range:[-100,100],keypointsNumber:2},exposure:{zero:Z.exposure,range:[-500,500],keypointsNumber:2},gamma:{zero:Z.gamma,range:[0,1e3],keypointsNumber:2},contrast:{zero:Z.contrast,range:[-100,500],keypointsNumber:2},saturation:{zero:Z.saturation,range:[-100,500],keypointsNumber:1},vibrance:{zero:Z.vibrance,range:[-100,500],keypointsNumber:1},warmth:{zero:Z.warmth,range:[-100,100],keypointsNumber:1},enhance:{zero:Z.enhance,range:[0,100],keypointsNumber:1},filter:{zero:Z.filter,range:[0,100],keypointsNumber:1}};var at=class extends U{constructor(){super();h(this,"_debouncedShowLoader",S(this._showLoader.bind(this),300));this.init$={...this.init$,...xr(this)}}get ctxName(){return this.autoCtxName}_showLoader(t){this.$.showLoader=t}_waitForSize(){return new Promise((e,r)=>{let n=setTimeout(()=>{r(new Error("[cloud-image-editor] timeout waiting for non-zero container size"))},3e3),o=new ResizeObserver(([l])=>{l.contentRect.width>0&&l.contentRect.height>0&&(e(),clearTimeout(n),o.disconnect())});o.observe(this)})}initCallback(){super.initCallback(),this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async updateImage(){if(await this._waitForSize(),this.$["*tabId"]===D.CROP?this.$["*cropperEl"].deactivate({reset:!0}):this.$["*faderEl"].deactivate(),this.$["*editorTransformations"]={},this.$.cdnUrl){let t=Zs(this.$.cdnUrl);this.$["*originalUrl"]=At(this.$.cdnUrl,t);let e=Js(this.$.cdnUrl),r=wr(e);this.$["*editorTransformations"]=r}else if(this.$.uuid)this.$["*originalUrl"]=At(this.cfg.cdnCname,this.$.uuid);else throw new Error("No UUID nor CDN URL provided");try{let t=k(this.$["*originalUrl"],I("json")),e=await fetch(t).then(o=>o.json()),{width:r,height:n}=e;this.$["*imageSize"]={width:r,height:n},this.$["*tabId"]===D.CROP?this.$["*cropperEl"].activate(this.$["*imageSize"]):this.$["*faderEl"].activate({url:this.$["*originalUrl"]})}catch(t){t&&console.error("Failed to load image info",t)}}async initEditor(){try{await this._waitForSize()}catch(t){this.isConnected&&console.error(t.message);return}this.ref["img-el"].addEventListener("load",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$.src!==Y&&(this.$["*networkProblems"]=!1)}),this.ref["img-el"].addEventListener("error",()=>{this._imgLoading=!1,this._debouncedShowLoader(!1),this.$["*networkProblems"]=!0}),this.sub("src",t=>{let e=this.ref["img-el"];e.src!==t&&(this._imgLoading=!0,e.src=t||Y)}),this.sub("cropPreset",t=>{this.$["*cropPresetList"]=je(t)}),this.sub("*tabId",t=>{this.ref["img-el"].className=N("image",{image_hidden_to_cropper:t===D.CROP,image_hidden_effects:t!==D.CROP})}),this.classList.add("editor_ON"),this.sub("*networkProblems",t=>{this.$["presence.networkProblems"]=t,this.$["presence.modalCaption"]=!t}),this.sub("*editorTransformations",t=>{if(Object.keys(t).length===0)return;let e=this.$["*originalUrl"],r=I($t(t)),n=k(e,I(r,"preview")),o={originalUrl:e,cdnUrlModifiers:r,cdnUrl:n,transformations:t};this.dispatchEvent(new CustomEvent("change",{detail:o,bubbles:!0,composed:!0}))},!1),this.sub("uuid",t=>t&&this.updateImage()),this.sub("cdnUrl",t=>t&&this.updateImage())}};h(at,"className","cloud-image-editor");at.template=Tr;at.bindAttributes({uuid:"uuid","cdn-url":"cdnUrl","crop-preset":"cropPreset"});var ai=class extends U{constructor(){super(),this.init$={...this.init$,dragging:!1},this._handlePointerUp=this._handlePointerUp_.bind(this),this._handlePointerMove=this._handlePointerMove_.bind(this),this._handleSvgPointerMove=this._handleSvgPointerMove_.bind(this)}_shouldThumbBeDisabled(i){let t=this.$["*imageBox"];if(!t)return;if(i===""&&t.height<=y&&t.width<=y)return!0;let e=t.height<=y&&(i.includes("n")||i.includes("s")),r=t.width<=y&&(i.includes("e")||i.includes("w"));return e||r}_createBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i,o=this.ref["svg-el"],l=tt("mask",{id:"backdrop-mask"}),a=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"white"}),c=tt("rect",{x:t,y:e,width:r,height:n,fill:"black"});l.appendChild(a),l.appendChild(c);let u=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"var(--color-image-background)","fill-opacity":.85,mask:"url(#backdrop-mask)"});o.appendChild(u),o.appendChild(l),this._backdropMask=l,this._backdropMaskInner=c}_resizeBackdrop(){this._backdropMask&&(this._backdropMask.style.display="none",window.requestAnimationFrame(()=>{this._backdropMask&&(this._backdropMask.style.display="block")}))}_updateBackdrop(){let i=this.$["*cropBox"];if(!i)return;let{x:t,y:e,width:r,height:n}=i;this._backdropMaskInner&&Pt(this._backdropMaskInner,{x:t,y:e,width:r,height:n})}_updateFrame(){let i=this.$["*cropBox"];if(!(!i||!this._frameGuides||!this._frameThumbs)){for(let t of Object.values(this._frameThumbs)){let{direction:e,pathNode:r,interactionNode:n,groupNode:o}=t,l=e==="",a=e.length===2,{x:c,y:u,width:d,height:p}=i;if(l){let f={x:c+d/3,y:u+p/3,width:d/3,height:p/3};Pt(n,f)}else{let f=Et(Math.min(d,p)/(24*2+34)/2,0,1),{d:_,center:$}=a?Ds(i,e,f):Fs(i,e,f),A=Math.max(Xi*Et(Math.min(d,p)/Xi/3,0,1),Ns);Pt(n,{x:$[0]-A,y:$[1]-A,width:A*2,height:A*2}),Pt(r,{d:_})}let m=this._shouldThumbBeDisabled(e);o.setAttribute("class",N("thumb",{"thumb--hidden":m,"thumb--visible":!m}))}Pt(this._frameGuides,{x:i.x-1*.5,y:i.y-1*.5,width:i.width+1,height:i.height+1})}}_createThumbs(){let i={};for(let t=0;t<3;t++)for(let e=0;e<3;e++){let r=`${["n","","s"][t]}${["w","","e"][e]}`,n=tt("g");n.classList.add("thumb"),n.setAttribute("with-effects","");let o=tt("rect",{fill:"transparent"}),l=tt("path",{stroke:"currentColor",fill:"none","stroke-width":3});n.appendChild(l),n.appendChild(o),i[r]={direction:r,pathNode:l,interactionNode:o,groupNode:n},o.addEventListener("pointerdown",this._handlePointerDown.bind(this,r))}return i}_createGuides(){let i=tt("svg"),t=tt("rect",{x:0,y:0,width:"100%",height:"100%",fill:"none",stroke:"#000000","stroke-width":1,"stroke-opacity":.5});i.appendChild(t);for(let e=1;e<=2;e++){let r=tt("line",{x1:`${ue*e}%`,y1:"0%",x2:`${ue*e}%`,y2:"100%",stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}for(let e=1;e<=2;e++){let r=tt("line",{x1:"0%",y1:`${ue*e}%`,x2:"100%",y2:`${ue*e}%`,stroke:"#000000","stroke-width":1,"stroke-opacity":.3});i.appendChild(r)}return i.classList.add("guides","guides--semi-hidden"),i}_createFrame(){let i=this.ref["svg-el"],t=document.createDocumentFragment(),e=this._createGuides();t.appendChild(e);let r=this._createThumbs();for(let{groupNode:n}of Object.values(r))t.appendChild(n);i.appendChild(t),this._frameThumbs=r,this._frameGuides=e}_handlePointerDown(i,t){if(!this._frameThumbs)return;let e=this._frameThumbs[i];if(this._shouldThumbBeDisabled(i))return;let r=this.$["*cropBox"],{x:n,y:o}=this.ref["svg-el"].getBoundingClientRect(),l=t.x-n,a=t.y-o;this.$.dragging=!0,this._draggingThumb=e,this._dragStartPoint=[l,a],this._dragStartCrop={...r}}_handlePointerUp_(i){this._updateCursor(),this.$.dragging&&(i.stopPropagation(),i.preventDefault(),this.$.dragging=!1)}_handlePointerMove_(i){if(!this.$.dragging||!this._dragStartPoint||!this._draggingThumb)return;i.stopPropagation(),i.preventDefault();let t=this.ref["svg-el"],{x:e,y:r}=t.getBoundingClientRect(),n=i.x-e,o=i.y-r,l=n-this._dragStartPoint[0],a=o-this._dragStartPoint[1],{direction:c}=this._draggingThumb,u=this._calcCropBox(c,[l,a]);u&&(this.$["*cropBox"]=u)}_calcCropBox(i,t){var c,u;let[e,r]=t,n=this.$["*imageBox"],o=(c=this._dragStartCrop)!=null?c:this.$["*cropBox"],l=(u=this.$["*cropPresetList"])==null?void 0:u[0],a=l?l.width/l.height:void 0;if(i===""?o=Bs({rect:o,delta:[e,r],imageBox:n}):o=zs({rect:o,delta:[e,r],direction:i,aspectRatio:a,imageBox:n}),!Object.values(o).every(d=>Number.isFinite(d)&&d>=0)){console.error("CropFrame is trying to create invalid rectangle",{payload:o});return}return Kt(Zt(o),this.$["*imageBox"])}_handleSvgPointerMove_(i){if(!this._frameThumbs)return;let t=Object.values(this._frameThumbs).find(e=>{if(this._shouldThumbBeDisabled(e.direction))return!1;let n=e.interactionNode.getBoundingClientRect(),o={x:n.x,y:n.y,width:n.width,height:n.height};return js(o,[i.x,i.y])});this._hoverThumb=t,this._updateCursor()}_updateCursor(){let i=this._hoverThumb;this.ref["svg-el"].style.cursor=i?Vs(i.direction):"initial"}_render(){this._updateBackdrop(),this._updateFrame()}toggleThumbs(i){this._frameThumbs&&Object.values(this._frameThumbs).map(({groupNode:t})=>t).forEach(t=>{t.setAttribute("class",N("thumb",{"thumb--hidden":!i,"thumb--visible":i}))})}initCallback(){super.initCallback(),this._createBackdrop(),this._createFrame(),this.sub("*imageBox",()=>{this._resizeBackdrop(),window.requestAnimationFrame(()=>{this._render()})}),this.sub("*cropBox",i=>{i&&(this._guidesHidden=i.height<=y||i.width<=y,window.requestAnimationFrame(()=>{this._render()}))}),this.sub("dragging",i=>{this._frameGuides&&this._frameGuides.setAttribute("class",N({"guides--hidden":this._guidesHidden,"guides--visible":!this._guidesHidden&&i,"guides--semi-hidden":!this._guidesHidden&&!i}))}),this.ref["svg-el"].addEventListener("pointermove",this._handleSvgPointerMove,!0),document.addEventListener("pointermove",this._handlePointerMove,!0),document.addEventListener("pointerup",this._handlePointerUp,!0)}destroyCallback(){super.destroyCallback(),document.removeEventListener("pointermove",this._handlePointerMove),document.removeEventListener("pointerup",this._handlePointerUp)}};ai.template='';var yt=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"","on.click":null})}initCallback(){super.initCallback(),this._titleEl=this.ref["title-el"],this._iconEl=this.ref["icon-el"],this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.sub("title",t=>{this._titleEl&&(this._titleEl.style.display=t?"block":"none")}),this.sub("active",t=>{this.className=N({active:t,not_active:!t})}),this.sub("on.click",t=>{this.onclick=t})}};yt.template=`
{{title}}
`;function No(s){let i=s+90;return i=i>=360?0:i,i}function Do(s,i){return s==="rotate"?No(i):["mirror","flip"].includes(s)?!i:null}var te=class extends yt{initCallback(){super.initCallback(),this.defineAccessor("operation",i=>{i&&(this._operation=i,this.$.icon=i)}),this.$["on.click"]=i=>{let t=this.$["*cropperEl"].getValue(this._operation),e=Do(this._operation,t);this.$["*cropperEl"].setValue(this._operation,e)}}};var we={FILTER:"filter",COLOR_OPERATION:"color_operation"},ct="original",ci=class extends U{constructor(){super(...arguments);h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,value:0,defaultValue:0,zero:0,"on.input":t=>{this.$["*faderEl"].set(t),this.$.value=t}})}setOperation(t,e){this._controlType=t==="filter"?we.FILTER:we.COLOR_OPERATION,this._operation=t,this._iconName=t,this._title=t.toUpperCase(),this._filter=e,this._initializeValues(),this.$["*faderEl"].activate({url:this.$["*originalUrl"],operation:this._operation,value:this._filter===ct?void 0:this.$.value,filter:this._filter===ct?void 0:this._filter,fromViewer:!1})}_initializeValues(){let{range:t,zero:e}=lt[this._operation],[r,n]=t;this.$.min=r,this.$.max=n,this.$.zero=e;let o=this.$["*editorTransformations"][this._operation];if(this._controlType===we.FILTER){let l=n;if(o){let{name:a,amount:c}=o;l=a===this._filter?c:n}this.$.value=l,this.$.defaultValue=l}if(this._controlType===we.COLOR_OPERATION){let l=typeof o!="undefined"?o:e;this.$.value=l,this.$.defaultValue=l}}apply(){let t;this._controlType===we.FILTER?this._filter===ct?t=null:t={name:this._filter,amount:this.$.value}:t=this.$.value;let e={...this.$["*editorTransformations"],[this._operation]:t};this.$["*editorTransformations"]=e}cancel(){this.$["*faderEl"].deactivate({hide:!1})}initCallback(){super.initCallback(),this.sub("*originalUrl",t=>{this._originalUrl=t}),this.sub("value",t=>{let e=`${this._filter||this._operation} ${t}`;this.$["*operationTooltip"]=e})}};ci.template=``;function xe(s){let i=new Image;return{promise:new Promise((r,n)=>{i.src=s,i.onload=r,i.onerror=n}),image:i,cancel:()=>{i.naturalWidth===0&&(i.src=Y)}}}function Te(s){let i=[];for(let n of s){let o=xe(n);i.push(o)}let t=i.map(n=>n.image);return{promise:Promise.allSettled(i.map(n=>n.promise)),images:t,cancel:()=>{i.forEach(n=>{n.cancel()})}}}var Ft=class extends yt{constructor(){super(...arguments);h(this,"init$",{...this.init$,active:!1,title:"",icon:"",isOriginal:!1,iconSize:"20","on.click":null})}_previewSrc(){let t=parseInt(window.getComputedStyle(this).getPropertyValue("--l-base-min-width"),10),e=window.devicePixelRatio,r=Math.ceil(e*t),n=e>=2?"lightest":"normal",o=100,l={...this.$["*editorTransformations"]};return l[this._operation]=this._filter!==ct?{name:this._filter,amount:o}:void 0,k(this._originalUrl,I(oi,$t(l),`quality/${n}`,`scale_crop/${r}x${r}/center`))}_observerCallback(t,e){if(t[0].isIntersecting){let n=this.proxyUrl(this._previewSrc()),o=this.ref["preview-el"],{promise:l,cancel:a}=xe(n);this._cancelPreload=a,l.catch(c=>{this.$["*networkProblems"]=!0,console.error("Failed to load image",{error:c})}).finally(()=>{o.style.backgroundImage=`url(${n})`,o.setAttribute("loaded",""),e.unobserve(this)})}else this._cancelPreload&&this._cancelPreload()}initCallback(){super.initCallback(),this.$["on.click"]=e=>{this.$.active?this.$.isOriginal||(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*showSlider"]=!0):(this.$["*sliderEl"].setOperation(this._operation,this._filter),this.$["*sliderEl"].apply()),this.$["*currentFilter"]=this._filter},this.defineAccessor("filter",e=>{this._operation="filter",this._filter=e,this.$.isOriginal=e===ct,this.$.icon=this.$.isOriginal?"original":"slider"}),this._observer=new window.IntersectionObserver(this._observerCallback.bind(this),{threshold:[0,1]});let t=this.$["*originalUrl"];this._originalUrl=t,this.$.isOriginal?this.ref["icon-el"].classList.add("original-icon"):this._observer.observe(this),this.sub("*currentFilter",e=>{this.$.active=e&&e===this._filter}),this.sub("isOriginal",e=>{this.$.iconSize=e?40:20}),this.sub("active",e=>{if(this.$.isOriginal)return;let r=this.ref["icon-el"];r.style.opacity=e?"1":"0";let n=this.ref["preview-el"];e?n.style.opacity="0":n.style.backgroundImage&&(n.style.opacity="1")}),this.sub("*networkProblems",e=>{if(!e){let r=this.proxyUrl(this._previewSrc()),n=this.ref["preview-el"];n.style.backgroundImage&&(n.style.backgroundImage="none",n.style.backgroundImage=`url(${r})`)}})}destroyCallback(){var t;super.destroyCallback(),(t=this._observer)==null||t.disconnect(),this._cancelPreload&&this._cancelPreload()}};Ft.template=`
`;var ee=class extends yt{constructor(){super(...arguments);h(this,"_operation","")}initCallback(){super.initCallback(),this.$["on.click"]=t=>{this.$["*sliderEl"].setOperation(this._operation),this.$["*showSlider"]=!0,this.$["*currentOperation"]=this._operation},this.defineAccessor("operation",t=>{t&&(this._operation=t,this.$.icon=t,this.$.title=this.l10n(t))}),this.sub("*editorTransformations",t=>{if(!this._operation)return;let{zero:e}=lt[this._operation],r=t[this._operation],n=typeof r!="undefined"?r!==e:!1;this.$.active=n})}};var Sr=(s,i)=>{let t,e,r;return(...n)=>{t?(clearTimeout(e),e=setTimeout(()=>{Date.now()-r>=i&&(s(...n),r=Date.now())},Math.max(i-(Date.now()-r),0))):(s(...n),r=Date.now(),t=!0)}};function kr(s,i){let t={};for(let e of i){let r=s[e];(s.hasOwnProperty(e)||r!==void 0)&&(t[e]=r)}return t}function ie(s,i,t){let r=window.devicePixelRatio,n=Math.min(Math.ceil(i*r),3e3),o=r>=2?"lightest":"normal";return k(s,I(oi,$t(t),`quality/${o}`,`stretch/off/-/resize/${n}x`))}function Fo(s){return s?[({dimensions:t,coords:e})=>[...t,...e].every(r=>Number.isInteger(r)&&Number.isFinite(r)),({dimensions:t,coords:e})=>t.every(r=>r>0)&&e.every(r=>r>=0)].every(t=>t(s)):!0}var hi=class extends U{constructor(){super(),this.init$={...this.init$,image:null,"*padding":20,"*operations":{rotate:0,mirror:!1,flip:!1},"*imageBox":{x:0,y:0,width:0,height:0},"*cropBox":{x:0,y:0,width:0,height:0}},this._commitDebounced=S(this._commit.bind(this),300),this._handleResizeThrottled=Sr(this._handleResize.bind(this),100),this._imageSize={width:0,height:0}}_handleResize(){!this.isConnected||!this._isActive||(this._initCanvas(),this._syncTransformations(),this._alignImage(),this._alignCrop(),this._draw())}_syncTransformations(){let i=this.$["*editorTransformations"],t=kr(i,Object.keys(this.$["*operations"])),e={...this.$["*operations"],...t};this.$["*operations"]=e}_initCanvas(){let i=this.ref["canvas-el"],t=i.getContext("2d"),e=this.offsetWidth,r=this.offsetHeight,n=window.devicePixelRatio;i.style.width=`${e}px`,i.style.height=`${r}px`,i.width=e*n,i.height=r*n,t==null||t.scale(n,n),this._canvas=i,this._ctx=t}_alignImage(){if(!this._isActive||!this.$.image)return;let i=this.$.image,t=this.$["*padding"],e=this.$["*operations"],{rotate:r}=e,n={width:this.offsetWidth,height:this.offsetHeight},o=Yt({width:i.naturalWidth,height:i.naturalHeight},r),l;if(o.width>n.width-t*2||o.height>n.height-t*2){let a=o.width/o.height,c=n.width/n.height;if(a>c){let u=n.width-t*2,d=u/a,p=0+t,m=t+(n.height-t*2)/2-d/2;l={x:p,y:m,width:u,height:d}}else{let u=n.height-t*2,d=u*a,p=t+(n.width-t*2)/2-d/2,m=0+t;l={x:p,y:m,width:d,height:u}}}else{let{width:a,height:c}=o,u=t+(n.width-t*2)/2-a/2,d=t+(n.height-t*2)/2-c/2;l={x:u,y:d,width:a,height:c}}this.$["*imageBox"]=Zt(l)}_alignCrop(){var c;let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,n=this.$["*editorTransformations"].crop,{width:o,x:l,y:a}=this.$["*imageBox"];if(n){let{dimensions:[u,d],coords:[p,m]}=n,{width:f}=Yt(this._imageSize,r),_=o/f;i=Kt(Zt({x:l+p*_,y:a+m*_,width:u*_,height:d*_}),this.$["*imageBox"])}if(!n||!Hs(i,t)){let u=(c=this.$["*cropPresetList"])==null?void 0:c[0],d=u?u.width/u.height:void 0,p=t.width/t.height,m=t.width,f=t.height;d&&(p>d?m=Math.min(t.height*d,t.width):f=Math.min(t.width/d,t.height)),i={x:t.x+t.width/2-m/2,y:t.y+t.height/2-f/2,width:m,height:f}}this.$["*cropBox"]=Kt(Zt(i),this.$["*imageBox"])}_drawImage(){let i=this._ctx;if(!i)return;let t=this.$.image,e=this.$["*imageBox"],r=this.$["*operations"],{mirror:n,flip:o,rotate:l}=r,a=Yt({width:e.width,height:e.height},l);i.save(),i.translate(e.x+e.width/2,e.y+e.height/2),i.rotate(l*Math.PI*-1/180),i.scale(n?-1:1,o?-1:1),i.drawImage(t,-a.width/2,-a.height/2,a.width,a.height),i.restore()}_draw(){if(!this._isActive||!this.$.image||!this._canvas||!this._ctx)return;let i=this._canvas;this._ctx.clearRect(0,0,i.width,i.height),this._drawImage()}_animateIn({fromViewer:i}){this.$.image&&(this.ref["frame-el"].toggleThumbs(!0),this._transitionToImage(),setTimeout(()=>{this.className=N({active_from_viewer:i,active_from_editor:!i,inactive_to_editor:!1})}))}_getCropDimensions(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o}=t,{width:l,height:a}=Yt(this._imageSize,r),{width:c,height:u}=i,d=n/l,p=o/a;return[Et(Math.round(c/d),1,l),Et(Math.round(u/p),1,a)]}_getCropTransformation(){let i=this.$["*cropBox"],t=this.$["*imageBox"],e=this.$["*operations"],{rotate:r}=e,{width:n,height:o,x:l,y:a}=t,{width:c,height:u}=Yt(this._imageSize,r),{x:d,y:p}=i,m=n/c,f=o/u,_=this._getCropDimensions(),$={dimensions:_,coords:[Et(Math.round((d-l)/m),0,c-_[0]),Et(Math.round((p-a)/f),0,u-_[1])]};if(!Fo($)){console.error("Cropper is trying to create invalid crop object",{payload:$});return}if(!(_[0]===c&&_[1]===u))return $}_commit(){if(!this.isConnected)return;let i=this.$["*operations"],{rotate:t,mirror:e,flip:r}=i,n=this._getCropTransformation(),l={...this.$["*editorTransformations"],crop:n,rotate:t,mirror:e,flip:r};this.$["*editorTransformations"]=l}setValue(i,t){console.log(`Apply cropper operation [${i}=${t}]`),this.$["*operations"]={...this.$["*operations"],[i]:t},this._isActive&&(this._alignImage(),this._alignCrop(),this._draw())}getValue(i){return this.$["*operations"][i]}async activate(i,{fromViewer:t}={}){if(!this._isActive){this._isActive=!0,this._imageSize=i,this.removeEventListener("transitionend",this._reset);try{this.$.image=await this._waitForImage(this.$["*originalUrl"],this.$["*editorTransformations"]),this._syncTransformations(),this._animateIn({fromViewer:t})}catch(e){console.error("Failed to activate cropper",{error:e})}this._observer=new ResizeObserver(([e])=>{e.contentRect.width>0&&e.contentRect.height>0&&this._isActive&&this.$.image&&this._handleResizeThrottled()}),this._observer.observe(this)}}deactivate({reset:i=!1}={}){var t;this._isActive&&(!i&&this._commit(),this._isActive=!1,this._transitionToCrop(),this.className=N({active_from_viewer:!1,active_from_editor:!1,inactive_to_editor:!0}),this.ref["frame-el"].toggleThumbs(!1),this.addEventListener("transitionend",this._reset,{once:!0}),(t=this._observer)==null||t.disconnect())}_transitionToCrop(){let i=this._getCropDimensions(),t=Math.min(this.offsetWidth,i[0])/this.$["*cropBox"].width,e=Math.min(this.offsetHeight,i[1])/this.$["*cropBox"].height,r=Math.min(t,e),n=this.$["*cropBox"].x+this.$["*cropBox"].width/2,o=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform=`scale(${r}) translate(${(this.offsetWidth/2-n)/r}px, ${(this.offsetHeight/2-o)/r}px)`,this.style.transformOrigin=`${n}px ${o}px`}_transitionToImage(){let i=this.$["*cropBox"].x+this.$["*cropBox"].width/2,t=this.$["*cropBox"].y+this.$["*cropBox"].height/2;this.style.transform="scale(1)",this.style.transformOrigin=`${i}px ${t}px`}_reset(){this._isActive||(this.$.image=null)}_waitForImage(i,t){let e=this.offsetWidth;t={...t,crop:void 0,rotate:void 0,flip:void 0,mirror:void 0};let r=this.proxyUrl(ie(i,e,t)),{promise:n,cancel:o,image:l}=xe(r),a=this._handleImageLoading(r);return l.addEventListener("load",a,{once:!0}),l.addEventListener("error",a,{once:!0}),this._cancelPreload&&this._cancelPreload(),this._cancelPreload=o,n.then(()=>l).catch(c=>(console.error("Failed to load image",{error:c}),this.$["*networkProblems"]=!0,Promise.resolve(l)))}_handleImageLoading(i){let t="crop",e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}initCallback(){super.initCallback(),this.sub("*imageBox",()=>{this._draw()}),this.sub("*cropBox",()=>{this.$.image&&this._commitDebounced()}),this.sub("*cropPresetList",()=>{this._alignCrop()}),setTimeout(()=>{this.sub("*networkProblems",i=>{i||this._isActive&&this.activate(this._imageSize,{fromViewer:!1})})},0)}destroyCallback(){var i;super.destroyCallback(),(i=this._observer)==null||i.disconnect()}};hi.template=``;function rs(s,i,t){let e=Array(t);t--;for(let r=t;r>=0;r--)e[r]=Math.ceil((r*i+(t-r)*s)/t);return e}function Vo(s){return s.reduce((i,t,e)=>er<=i&&i<=n);return s.map(r=>{let n=Math.abs(e[0]-e[1]),o=Math.abs(i-e[0])/n;return e[0]===r?i>t?1:1-o:e[1]===r?i>=t?o:1:0})}function zo(s,i){return s.map((t,e)=>tn-o)}var ns=class extends U{constructor(){super(),this._isActive=!1,this._hidden=!0,this._addKeypointDebounced=S(this._addKeypoint.bind(this),600),this.classList.add("inactive_to_cropper")}_handleImageLoading(i){let t=this._operation,e=this.$["*loadingOperations"];return e.get(t)||e.set(t,new Map),e.get(t).get(i)||(e.set(t,e.get(t).set(i,!0)),this.$["*loadingOperations"]=e),()=>{var r;(r=e==null?void 0:e.get(t))!=null&&r.has(i)&&(e.get(t).delete(i),this.$["*loadingOperations"]=e)}}_flush(){window.cancelAnimationFrame(this._raf),this._raf=window.requestAnimationFrame(()=>{for(let i of this._keypoints){let{image:t}=i;t&&(t.style.opacity=i.opacity.toString(),t.style.zIndex=i.zIndex.toString())}})}_imageSrc({url:i=this._url,filter:t=this._filter,operation:e,value:r}={}){let n={...this._transformations};e&&(n[e]=t?{name:t,amount:r}:r);let o=this.offsetWidth;return this.proxyUrl(ie(i,o,n))}_constructKeypoint(i,t){return{src:this._imageSrc({operation:i,value:t}),image:null,opacity:0,zIndex:0,value:t}}_isSame(i,t){return this._operation===i&&this._filter===t}_addKeypoint(i,t,e){let r=()=>!this._isSame(i,t)||this._value!==e||!!this._keypoints.find(a=>a.value===e);if(r())return;let n=this._constructKeypoint(i,e),o=new Image;o.src=n.src;let l=this._handleImageLoading(n.src);o.addEventListener("load",l,{once:!0}),o.addEventListener("error",l,{once:!0}),n.image=o,o.classList.add("fader-image"),o.addEventListener("load",()=>{if(r())return;let a=this._keypoints,c=a.findIndex(d=>d.value>e),u=c{this.$["*networkProblems"]=!0},{once:!0})}set(i){i=typeof i=="string"?parseInt(i,10):i,this._update(this._operation,i),this._addKeypointDebounced(this._operation,this._filter,i)}_update(i,t){this._operation=i,this._value=t;let{zero:e}=lt[i],r=this._keypoints.map(l=>l.value),n=Bo(r,t,e),o=zo(r,e);for(let[l,a]of Object.entries(this._keypoints))a.opacity=n[l],a.zIndex=o[l];this._flush()}_createPreviewImage(){let i=new Image;return i.classList.add("fader-image","fader-image--preview"),i.style.opacity="0",i}async _initNodes(){let i=document.createDocumentFragment();this._previewImage=this._previewImage||this._createPreviewImage(),!this.contains(this._previewImage)&&i.appendChild(this._previewImage);let t=document.createElement("div");i.appendChild(t);let e=this._keypoints.map(c=>c.src),{images:r,promise:n,cancel:o}=Te(e);r.forEach(c=>{let u=this._handleImageLoading(c.src);c.addEventListener("load",u),c.addEventListener("error",u)}),this._cancelLastImages=()=>{o(),this._cancelLastImages=void 0};let l=this._operation,a=this._filter;await n,this._isActive&&this._isSame(l,a)&&(this._container&&this._container.remove(),this._container=t,this._keypoints.forEach((c,u)=>{let d=r[u];d.classList.add("fader-image"),c.image=d,this._container.appendChild(d)}),this.appendChild(i),this._flush())}setTransformations(i){if(this._transformations=i,this._previewImage){let t=this._imageSrc(),e=this._handleImageLoading(t);this._previewImage.src=t,this._previewImage.addEventListener("load",e,{once:!0}),this._previewImage.addEventListener("error",e,{once:!0}),this._previewImage.style.opacity="1",this._previewImage.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}}preload({url:i,filter:t,operation:e,value:r}){this._cancelBatchPreload&&this._cancelBatchPreload();let o=Ir(e,r).map(a=>this._imageSrc({url:i,filter:t,operation:e,value:a})),{cancel:l}=Te(o);this._cancelBatchPreload=l}_setOriginalSrc(i){let t=this._previewImage||this._createPreviewImage();if(!this.contains(t)&&this.appendChild(t),this._previewImage=t,t.src===i){t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1});return}t.style.opacity="0";let e=this._handleImageLoading(i);t.addEventListener("error",e,{once:!0}),t.src=i,t.addEventListener("load",()=>{e(),t&&(t.style.opacity="1",t.style.transform="scale(1)",this.className=N({active_from_viewer:this._fromViewer,active_from_cropper:!this._fromViewer,inactive_to_cropper:!1}))},{once:!0}),t.addEventListener("error",()=>{this.$["*networkProblems"]=!0},{once:!0})}activate({url:i,operation:t,value:e,filter:r,fromViewer:n}){if(this._isActive=!0,this._hidden=!1,this._url=i,this._operation=t||"initial",this._value=e,this._filter=r,this._fromViewer=n,typeof e!="number"&&!r){let l=this._imageSrc({operation:t,value:e});this._setOriginalSrc(l),this._container&&this._container.remove();return}this._keypoints=Ir(t,e).map(l=>this._constructKeypoint(t,l)),this._update(t,e),this._initNodes()}deactivate({hide:i=!0}={}){this._isActive=!1,this._cancelLastImages&&this._cancelLastImages(),this._cancelBatchPreload&&this._cancelBatchPreload(),i&&!this._hidden?(this._hidden=!0,this._previewImage&&(this._previewImage.style.transform="scale(1)"),this.className=N({active_from_viewer:!1,active_from_cropper:!1,inactive_to_cropper:!0}),this.addEventListener("transitionend",()=>{this._container&&this._container.remove()},{once:!0})):this._container&&this._container.remove()}};var jo=1,ui=class extends U{initCallback(){super.initCallback(),this.addEventListener("wheel",i=>{i.preventDefault();let{deltaY:t,deltaX:e}=i;Math.abs(e)>jo?this.scrollLeft+=e:this.scrollLeft+=t})}};ui.template=" ";function Ho(s){return``}function Wo(s){return`
`}var di=class extends U{constructor(){super();h(this,"_updateInfoTooltip",S(()=>{var n,o;let t=this.$["*editorTransformations"],e="",r=!1;if(this.$["*tabId"]===D.FILTERS)if(r=!0,this.$["*currentFilter"]&&((n=t==null?void 0:t.filter)==null?void 0:n.name)===this.$["*currentFilter"]){let l=((o=t==null?void 0:t.filter)==null?void 0:o.amount)||100;e=this.l10n(this.$["*currentFilter"])+" "+l}else e=this.l10n(ct);else if(this.$["*tabId"]===D.SLIDERS&&this.$["*currentOperation"]){r=!0;let l=(t==null?void 0:t[this.$["*currentOperation"]])||lt[this.$["*currentOperation"]].zero;e=this.$["*currentOperation"]+" "+l}r&&(this.$["*operationTooltip"]=e),this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",r)},0));this.init$={...this.init$,"*sliderEl":null,"*loadingOperations":new Map,"*showSlider":!1,"*currentFilter":ct,"*currentOperation":null,"*tabId":D.CROP,showLoader:!1,filters:Ar,colorOperations:Er,cropOperations:$r,"*operationTooltip":null,"l10n.cancel":this.l10n("cancel"),"l10n.apply":this.l10n("apply"),"presence.mainToolbar":!0,"presence.subToolbar":!1,"presence.tabContent.crop":!1,"presence.tabContent.sliders":!1,"presence.tabContent.filters":!1,"presence.subTopToolbarStyles":{hidden:"sub-toolbar--top-hidden",visible:"sub-toolbar--visible"},"presence.subBottomToolbarStyles":{hidden:"sub-toolbar--bottom-hidden",visible:"sub-toolbar--visible"},"presence.tabContentStyles":{hidden:"tab-content--hidden",visible:"tab-content--visible"},"on.cancel":t=>{this._cancelPreload&&this._cancelPreload(),this.$["*on.cancel"]()},"on.apply":t=>{this.$["*on.apply"](this.$["*editorTransformations"])},"on.applySlider":t=>{this.ref["slider-el"].apply(),this._onSliderClose()},"on.cancelSlider":t=>{this.ref["slider-el"].cancel(),this._onSliderClose()},"on.clickTab":t=>{let e=t.currentTarget.getAttribute("data-id");this._activateTab(e,{fromViewer:!1})}},this._debouncedShowLoader=S(this._showLoader.bind(this),500)}_onSliderClose(){this.$["*showSlider"]=!1,this.$["*tabId"]===D.SLIDERS&&this.ref["tooltip-el"].classList.toggle("info-tooltip_visible",!1)}_createOperationControl(t){let e=ee.is&&new ee;return e.operation=t,e}_createFilterControl(t){let e=Ft.is&&new Ft;return e.filter=t,e}_createToggleControl(t){let e=te.is&&new te;return e.operation=t,e}_renderControlsList(t){let e=this.ref[`controls-list-${t}`],r=document.createDocumentFragment();t===D.CROP?this.$.cropOperations.forEach(n=>{let o=this._createToggleControl(n);r.appendChild(o)}):t===D.FILTERS?[ct,...this.$.filters].forEach(n=>{let o=this._createFilterControl(n);r.appendChild(o)}):t===D.SLIDERS&&this.$.colorOperations.forEach(n=>{let o=this._createOperationControl(n);r.appendChild(o)}),r.childNodes.forEach((n,o)=>{o===r.childNodes.length-1&&n.classList.add("controls-list_last-item")}),e.innerHTML="",e.appendChild(r)}_activateTab(t,{fromViewer:e}){this.$["*tabId"]=t,t===D.CROP?(this.$["*faderEl"].deactivate(),this.$["*cropperEl"].activate(this.$["*imageSize"],{fromViewer:e})):(this.$["*faderEl"].activate({url:this.$["*originalUrl"],fromViewer:e}),this.$["*cropperEl"].deactivate());for(let r of li){let n=r===t,o=this.ref[`tab-toggle-${r}`];o.active=n,n?(this._renderControlsList(t),this._syncTabIndicator()):this._unmountTabControls(r),this.$[`presence.tabContent.${r}`]=n}}_unmountTabControls(t){let e=this.ref[`controls-list-${t}`];e&&(e.innerHTML="")}_syncTabIndicator(){let t=this.ref[`tab-toggle-${this.$["*tabId"]}`],e=this.ref["tabs-indicator"];e.style.transform=`translateX(${t.offsetLeft}px)`}_preloadEditedImage(){if(this.$["*imgContainerEl"]&&this.$["*originalUrl"]){let t=this.$["*imgContainerEl"].offsetWidth,e=this.proxyUrl(ie(this.$["*originalUrl"],t,this.$["*editorTransformations"]));this._cancelPreload&&this._cancelPreload();let{cancel:r}=Te([e]);this._cancelPreload=()=>{r(),this._cancelPreload=void 0}}}_showLoader(t){this.$.showLoader=t}initCallback(){super.initCallback(),this.$["*sliderEl"]=this.ref["slider-el"],this.sub("*imageSize",t=>{t&&setTimeout(()=>{this._activateTab(this.$["*tabId"],{fromViewer:!0})},0)}),this.sub("*editorTransformations",t=>{var r;let e=(r=t==null?void 0:t.filter)==null?void 0:r.name;this.$["*currentFilter"]!==e&&(this.$["*currentFilter"]=e)}),this.sub("*currentFilter",()=>{this._updateInfoTooltip()}),this.sub("*currentOperation",()=>{this._updateInfoTooltip()}),this.sub("*tabId",()=>{this._updateInfoTooltip()}),this.sub("*originalUrl",t=>{this.$["*faderEl"]&&this.$["*faderEl"].deactivate()}),this.sub("*editorTransformations",t=>{this._preloadEditedImage(),this.$["*faderEl"]&&this.$["*faderEl"].setTransformations(t)}),this.sub("*loadingOperations",t=>{let e=!1;for(let[,r]of t.entries()){if(e)break;for(let[,n]of r.entries())if(n){e=!0;break}}this._debouncedShowLoader(e)}),this.sub("*showSlider",t=>{this.$["presence.subToolbar"]=t,this.$["presence.mainToolbar"]=!t}),this._updateInfoTooltip()}};di.template=`
{{*operationTooltip}}
${li.map(Wo).join("")}
${li.map(Ho).join("")}
`;var Ee=class extends b{constructor(){super(),this._iconReversed=!1,this._iconSingle=!1,this._iconHidden=!1,this.init$={...this.init$,text:"",icon:"",iconCss:this._iconCss(),theme:null},this.defineAccessor("active",i=>{i?this.setAttribute("active",""):this.removeAttribute("active")})}_iconCss(){return N("icon",{icon_left:!this._iconReversed,icon_right:this._iconReversed,icon_hidden:this._iconHidden,icon_single:this._iconSingle})}initCallback(){super.initCallback(),this.sub("icon",i=>{this._iconSingle=!this.$.text,this._iconHidden=!i,this.$.iconCss=this._iconCss()}),this.sub("theme",i=>{i!=="custom"&&(this.className=i)}),this.sub("text",i=>{this._iconSingle=!1}),this.setAttribute("role","button"),this.tabIndex===-1&&(this.tabIndex=0),this.hasAttribute("theme")||this.setAttribute("theme","default")}set reverse(i){this.hasAttribute("reverse")?(this.style.flexDirection="row-reverse",this._iconReversed=!0):(this._iconReversed=!1,this.style.flexDirection=null)}};Ee.bindAttributes({text:"text",icon:"icon",reverse:"reverse",theme:"theme"});Ee.template=`
{{text}}
`;var pi=class extends b{constructor(){super(),this._active=!1,this._handleTransitionEndRight=()=>{let i=this.ref["line-el"];i.style.transition="initial",i.style.opacity="0",i.style.transform="translateX(-101%)",this._active&&this._start()}}initCallback(){super.initCallback(),this.defineAccessor("active",i=>{typeof i=="boolean"&&(i?this._start():this._stop())})}_start(){this._active=!0;let{width:i}=this.getBoundingClientRect(),t=this.ref["line-el"];t.style.transition="transform 1s",t.style.opacity="1",t.style.transform=`translateX(${i}px)`,t.addEventListener("transitionend",this._handleTransitionEndRight,{once:!0})}_stop(){this._active=!1}};pi.template=`
`;var fi={transition:"transition",visible:"visible",hidden:"hidden"},mi=class extends b{constructor(){super(),this._visible=!1,this._visibleStyle=fi.visible,this._hiddenStyle=fi.hidden,this._externalTransitions=!1,this.defineAccessor("styles",i=>{i&&(this._externalTransitions=!0,this._visibleStyle=i.visible,this._hiddenStyle=i.hidden)}),this.defineAccessor("visible",i=>{typeof i=="boolean"&&(this._visible=i,this._handleVisible())})}_handleVisible(){this.style.visibility=this._visible?"inherit":"hidden",yr(this,{[fi.transition]:!this._externalTransitions,[this._visibleStyle]:this._visible,[this._hiddenStyle]:!this._visible}),this.setAttribute("aria-hidden",this._visible?"false":"true")}initCallback(){super.initCallback(),this.setAttribute("hidden",""),this._externalTransitions||this.classList.add(fi.transition),this._handleVisible(),setTimeout(()=>this.removeAttribute("hidden"),0)}};mi.template=" ";var gi=class extends b{constructor(){super();h(this,"init$",{...this.init$,disabled:!1,min:0,max:100,onInput:null,onChange:null,defaultValue:null,"on.sliderInput":()=>{let t=parseInt(this.ref["input-el"].value,10);this._updateValue(t),this.$.onInput&&this.$.onInput(t)},"on.sliderChange":()=>{let t=parseInt(this.ref["input-el"].value,10);this.$.onChange&&this.$.onChange(t)}});this.setAttribute("with-effects","")}initCallback(){super.initCallback(),this.defineAccessor("disabled",e=>{this.$.disabled=e}),this.defineAccessor("min",e=>{this.$.min=e}),this.defineAccessor("max",e=>{this.$.max=e}),this.defineAccessor("defaultValue",e=>{this.$.defaultValue=e,this.ref["input-el"].value=e,this._updateValue(e)}),this.defineAccessor("zero",e=>{this._zero=e}),this.defineAccessor("onInput",e=>{e&&(this.$.onInput=e)}),this.defineAccessor("onChange",e=>{e&&(this.$.onChange=e)}),this._updateSteps(),this._observer=new ResizeObserver(()=>{this._updateSteps();let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)}),this._observer.observe(this),this._thumbSize=parseInt(window.getComputedStyle(this).getPropertyValue("--l-thumb-size"),10),setTimeout(()=>{let e=parseInt(this.ref["input-el"].value,10);this._updateValue(e)},0),this.sub("disabled",e=>{let r=this.ref["input-el"];e?r.setAttribute("disabled","disabled"):r.removeAttribute("disabled")});let t=this.ref["input-el"];t.addEventListener("focus",()=>{this.style.setProperty("--color-effect","var(--hover-color-rgb)")}),t.addEventListener("blur",()=>{this.style.setProperty("--color-effect","var(--idle-color-rgb)")})}_updateValue(t){this._updateZeroDot(t);let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(t-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this.ref["thumb-el"].style.transform=`translateX(${o}px)`})}_updateZeroDot(t){if(!this._zeroDotEl)return;t===this._zero?this._zeroDotEl.style.opacity="0":this._zeroDotEl.style.opacity="0.2";let{width:e}=this.getBoundingClientRect(),o=100/(this.$.max-this.$.min)*(this._zero-this.$.min)*(e-this._thumbSize)/100;window.requestAnimationFrame(()=>{this._zeroDotEl.style.transform=`translateX(${o}px)`})}_updateSteps(){let e=this.ref["steps-el"],{width:r}=e.getBoundingClientRect(),n=Math.ceil(r/2),o=Math.ceil(n/15)-2;if(this._stepsCount===o)return;let l=document.createDocumentFragment(),a=document.createElement("div"),c=document.createElement("div");a.className="minor-step",c.className="border-step",l.appendChild(c);for(let d=0;d
`;var os=class extends v{constructor(){super(...arguments);h(this,"activityType",g.activities.CLOUD_IMG_EDIT);h(this,"init$",{...this.init$,cdnUrl:null})}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>this.mountEditor(),onDeactivate:()=>this.unmountEditor()}),this.sub("*focusedEntry",t=>{t&&(this.entry=t,this.entry.subscribe("cdnUrl",e=>{e&&(this.$.cdnUrl=e)}))})}handleApply(t){let e=t.detail;this.entry.setMultipleValues({cdnUrl:e.cdnUrl,cdnUrlModifiers:e.cdnUrlModifiers}),this.historyBack()}handleCancel(){this.historyBack()}mountEditor(){let t=new at,e=this.$.cdnUrl,r=this.cfg.cropPreset;t.setAttribute("ctx-name",this.ctxName),t.setAttribute("cdn-url",e),r&&t.setAttribute("crop-preset",r),t.addEventListener("apply",n=>this.handleApply(n)),t.addEventListener("cancel",()=>this.handleCancel()),this.innerHTML="",this.appendChild(t)}unmountEditor(){this.innerHTML=""}};var Xo=function(s){return s.replace(/[\\-\\[]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},Or=function(s,i="i"){let t=s.split("*").map(Xo);return new RegExp("^"+t.join(".+")+"$",i)};var qo=s=>Object.keys(s).reduce((t,e)=>{let r=s[e],n=Object.keys(r).reduce((o,l)=>{let a=r[l];return o+`${l}: ${a};`},"");return t+`${e}{${n}}`},"");function Lr({textColor:s,backgroundColor:i,linkColor:t,linkColorHover:e,shadeColor:r}){let n=`solid 1px ${r}`;return qo({body:{color:s,"background-color":i},".side-bar":{background:"inherit","border-right":n},".main-content":{background:"inherit"},".main-content-header":{background:"inherit"},".main-content-footer":{background:"inherit"},".list-table-row":{color:"inherit"},".list-table-row:hover":{background:r},".list-table-row .list-table-cell-a, .list-table-row .list-table-cell-b":{"border-top":n},".list-table-body .list-items":{"border-bottom":n},".bread-crumbs a":{color:t},".bread-crumbs a:hover":{color:e},".main-content.loading":{background:`${i} url(/static/images/loading_spinner.gif) center no-repeat`,"background-size":"25px 25px"},".list-icons-item":{"background-color":r},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a":{color:t},".source-gdrive .side-bar-menu a, .source-gphotos .side-bar-menu a:hover":{color:e},".side-bar-menu a":{color:t},".side-bar-menu a:hover":{color:e},".source-gdrive .side-bar-menu .current, .source-gdrive .side-bar-menu a:hover, .source-gphotos .side-bar-menu .current, .source-gphotos .side-bar-menu a:hover":{color:e},".source-vk .side-bar-menu a":{color:t},".source-vk .side-bar-menu a:hover":{color:e,background:"none"}})}var St={};window.addEventListener("message",s=>{let i;try{i=JSON.parse(s.data)}catch{return}if((i==null?void 0:i.type)in St){let t=St[i.type];for(let[e,r]of t)s.source===e&&r(i)}});var Ur=function(s,i,t){s in St||(St[s]=[]),St[s].push([i,t])},Rr=function(s,i){s in St&&(St[s]=St[s].filter(t=>t[0]!==i))};function Pr(s){let i=[];for(let[t,e]of Object.entries(s))e==null||typeof e=="string"&&e.length===0||i.push(`${t}=${encodeURIComponent(e)}`);return i.join("&")}var _i=class extends v{constructor(){super();h(this,"activityType",g.activities.EXTERNAL);h(this,"_iframe",null);h(this,"updateCssData",()=>{this.isActivityActive&&(this._inheritedUpdateCssData(),this.applyStyles())});h(this,"_inheritedUpdateCssData",this.updateCssData);this.init$={...this.init$,activityIcon:"",activityCaption:"",selectedList:[],counter:0,onDone:()=>{for(let t of this.$.selectedList){let e=this.extractUrlFromMessage(t),{filename:r}=t,{externalSourceType:n}=this.activityParams;this.addFileFromUrl(e,{fileName:r,source:n})}this.$["*currentActivity"]=g.activities.UPLOAD_LIST},onCancel:()=>{this.historyBack()}}}initCallback(){super.initCallback(),this.registerActivity(this.activityType,{onActivate:()=>{let{externalSourceType:t}=this.activityParams;this.set$({activityCaption:`${t==null?void 0:t[0].toUpperCase()}${t==null?void 0:t.slice(1)}`,activityIcon:t}),this.mountIframe()}}),this.sub("*currentActivity",t=>{t!==this.activityType&&this.unmountIframe()}),this.sub("selectedList",t=>{this.$.counter=t.length})}extractUrlFromMessage(t){if(t.alternatives){let e=M(this.cfg.externalSourcesPreferredTypes);for(let r of e){let n=Or(r);for(let[o,l]of Object.entries(t.alternatives))if(n.test(o))return l}}return t.url}sendMessage(t){var e,r;(r=(e=this._iframe)==null?void 0:e.contentWindow)==null||r.postMessage(JSON.stringify(t),"*")}async handleFileSelected(t){this.$.selectedList=[...this.$.selectedList,t]}handleIframeLoad(){this.applyStyles()}getCssValue(t){return window.getComputedStyle(this).getPropertyValue(t).trim()}applyStyles(){let t={backgroundColor:this.getCssValue("--clr-background-light"),textColor:this.getCssValue("--clr-txt"),shadeColor:this.getCssValue("--clr-shade-lv1"),linkColor:"#157cfc",linkColorHover:"#3891ff"};this.sendMessage({type:"embed-css",style:Lr(t)})}remoteUrl(){var l,a;let t=this.cfg.pubkey,e=(!1).toString(),{externalSourceType:r}=this.activityParams,n={lang:((a=(l=this.getCssData("--l10n-locale-name"))==null?void 0:l.split("-"))==null?void 0:a[0])||"en",public_key:t,images_only:e,pass_window_open:!1,session_key:this.cfg.remoteTabSessionKey},o=new URL(this.cfg.socialBaseUrl);return o.pathname=`/window3/${r}`,o.search=Pr(n),o.toString()}mountIframe(){let t=le({tag:"iframe",attributes:{src:this.remoteUrl(),marginheight:0,marginwidth:0,frameborder:0,allowTransparency:!0}});t.addEventListener("load",this.handleIframeLoad.bind(this)),this.ref.iframeWrapper.innerHTML="",this.ref.iframeWrapper.appendChild(t),Ur("file-selected",t.contentWindow,this.handleFileSelected.bind(this)),this._iframe=t,this.$.selectedList=[]}unmountIframe(){this._iframe&&Rr("file-selected",this._iframe.contentWindow),this.ref.iframeWrapper.innerHTML="",this._iframe=null,this.$.selectedList=[],this.$.counter=0}};_i.template=`
{{activityCaption}}
{{counter}}
`;var Ae=class extends b{setCurrentTab(i){if(!i)return;[...this.ref.context.querySelectorAll("[tab-ctx]")].forEach(e=>{e.getAttribute("tab-ctx")===i?e.removeAttribute("hidden"):e.setAttribute("hidden","")});for(let e in this._tabMap)e===i?this._tabMap[e].setAttribute("current",""):this._tabMap[e].removeAttribute("current")}initCallback(){super.initCallback(),this._tabMap={},this.defineAccessor("tab-list",i=>{if(!i)return;M(i).forEach(e=>{let r=le({tag:"div",attributes:{class:"tab"},properties:{onclick:()=>{this.setCurrentTab(e)}}});r.textContent=this.l10n(e),this.ref.row.appendChild(r),this._tabMap[e]=r})}),this.defineAccessor("default",i=>{this.setCurrentTab(i)}),this.hasAttribute("default")||this.setCurrentTab(Object.keys(this._tabMap)[0])}};Ae.bindAttributes({"tab-list":null,default:null});Ae.template=`
`;var se=class extends v{constructor(){super(...arguments);h(this,"processInnerHtml",!0);h(this,"init$",{...this.init$,output:null,filesData:null})}get dict(){return se.dict}get validationInput(){return this._validationInputElement}initCallback(){if(super.initCallback(),this.hasAttribute(this.dict.FORM_INPUT_ATTR)&&(this._dynamicInputsContainer=document.createElement("div"),this.appendChild(this._dynamicInputsContainer),this.hasAttribute(this.dict.INPUT_REQUIRED))){let t=document.createElement("input");t.type="text",t.name="__UPLOADCARE_VALIDATION_INPUT__",t.required=!0,this.appendChild(t),this._validationInputElement=t}this.sub("output",t=>{if(t){if(this.hasAttribute(this.dict.FIRE_EVENT_ATTR)&&this.dispatchEvent(new CustomEvent(this.dict.EVENT_NAME,{bubbles:!0,composed:!0,detail:{timestamp:Date.now(),ctxName:this.ctxName,data:t}})),this.hasAttribute(this.dict.FORM_INPUT_ATTR)){this._dynamicInputsContainer.innerHTML="";let e=t.groupData?[t.groupData.cdnUrl]:t.map(r=>r.cdnUrl);for(let r of e){let n=document.createElement("input");n.type="hidden",n.name=this.getAttribute(this.dict.INPUT_NAME_ATTR)||this.ctxName,n.value=r,this._dynamicInputsContainer.appendChild(n)}this.hasAttribute(this.dict.INPUT_REQUIRED)&&(this._validationInputElement.value=e.length?"__VALUE__":"")}this.hasAttribute(this.dict.CONSOLE_ATTR)&&console.log(t)}},!1),this.sub(this.dict.SRC_CTX_KEY,async t=>{if(!t){this.$.output=null,this.$.filesData=null;return}if(this.$.filesData=t,this.cfg.groupOutput||this.hasAttribute(this.dict.GROUP_ATTR)){let e=t.map(o=>o.uuid),r=await this.getUploadClientOptions(),n=await Us(e,{...r});this.$.output={groupData:n,files:t}}else this.$.output=t},!1)}};se.dict=Object.freeze({SRC_CTX_KEY:"*outputData",EVENT_NAME:"lr-data-output",FIRE_EVENT_ATTR:"use-event",CONSOLE_ATTR:"use-console",GROUP_ATTR:"use-group",FORM_INPUT_ATTR:"use-input",INPUT_NAME_ATTR:"input-name",INPUT_REQUIRED:"input-required"});var ls=class extends g{};var bi=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,currentText:"",options:[],selectHtml:"",onSelect:t=>{var e;t.preventDefault(),t.stopPropagation(),this.value=this.ref.select.value,this.$.currentText=((e=this.$.options.find(r=>r.value==this.value))==null?void 0:e.text)||"",this.dispatchEvent(new Event("change"))}})}initCallback(){super.initCallback(),this.sub("options",t=>{var r;this.$.currentText=((r=t==null?void 0:t[0])==null?void 0:r.text)||"";let e="";t==null||t.forEach(n=>{e+=``}),this.$.selectHtml=e})}};bi.template=``;var G={PLAY:"play",PAUSE:"pause",FS_ON:"fullscreen-on",FS_OFF:"fullscreen-off",VOL_ON:"unmute",VOL_OFF:"mute",CAP_ON:"captions",CAP_OFF:"captions-off"},Mr={requestFullscreen:s=>{s.requestFullscreen?s.requestFullscreen():s.webkitRequestFullscreen&&s.webkitRequestFullscreen()},exitFullscreen:()=>{document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen&&document.webkitExitFullscreen()}},it=class extends b{constructor(){super(...arguments);h(this,"init$",{...this.init$,src:"",ppIcon:G.PLAY,fsIcon:G.FS_ON,volIcon:G.VOL_ON,capIcon:G.CAP_OFF,totalTime:"00:00",currentTime:"00:00",progressCssWidth:"0",hasSubtitles:!1,volumeDisabled:!1,volumeValue:0,onPP:()=>{this.togglePlay()},onFs:()=>{this.toggleFullscreen()},onCap:()=>{this.toggleCaptions()},onMute:()=>{this.toggleSound()},onVolChange:t=>{let e=parseFloat(t.currentTarget.$.value);this.setVolume(e)},progressClicked:t=>{let e=this.progress.getBoundingClientRect();this._video.currentTime=this._video.duration*(t.offsetX/e.width)}})}togglePlay(){this._video.paused||this._video.ended?this._video.play():this._video.pause()}toggleFullscreen(){(document.fullscreenElement||document.webkitFullscreenElement)===this?Mr.exitFullscreen():Mr.requestFullscreen(this)}toggleCaptions(){this.$.capIcon===G.CAP_OFF?(this.$.capIcon=G.CAP_ON,this._video.textTracks[0].mode="showing",window.localStorage.setItem(it.is+":captions","1")):(this.$.capIcon=G.CAP_OFF,this._video.textTracks[0].mode="hidden",window.localStorage.removeItem(it.is+":captions"))}toggleSound(){this.$.volIcon===G.VOL_ON?(this.$.volIcon=G.VOL_OFF,this.$.volumeDisabled=!0,this._video.muted=!0):(this.$.volIcon=G.VOL_ON,this.$.volumeDisabled=!1,this._video.muted=!1)}setVolume(t){window.localStorage.setItem(it.is+":volume",t);let e=t?t/100:0;this._video.volume=e}get progress(){return this.ref.progress}_getUrl(t){return t.includes("/")?t:`https://ucarecdn.com/${t}/`}_desc2attrs(t){let e=[];for(let r in t){let n=r==="src"?this._getUrl(t[r]):t[r];e.push(`${r}="${n}"`)}return e.join(" ")}_timeFmt(t){let e=new Date(Math.round(t)*1e3);return[e.getMinutes(),e.getSeconds()].map(r=>r<10?"0"+r:r).join(":")}_initTracks(){[...this._video.textTracks].forEach(t=>{t.mode="hidden"}),window.localStorage.getItem(it.is+":captions")&&this.toggleCaptions()}_castAttributes(){let t=["autoplay","loop","muted"];[...this.attributes].forEach(e=>{t.includes(e.name)&&this._video.setAttribute(e.name,e.value)})}initCallback(){super.initCallback(),this._video=this.ref.video,this._castAttributes(),this._video.addEventListener("play",()=>{this.$.ppIcon=G.PAUSE,this.setAttribute("playback","")}),this._video.addEventListener("pause",()=>{this.$.ppIcon=G.PLAY,this.removeAttribute("playback")}),this.addEventListener("fullscreenchange",e=>{console.log(e),document.fullscreenElement===this?this.$.fsIcon=G.FS_OFF:this.$.fsIcon=G.FS_ON}),this.sub("src",e=>{if(!e)return;let r=this._getUrl(e);this._video.src=r}),this.sub("video",async e=>{if(!e)return;let r=await(await window.fetch(this._getUrl(e))).json();r.poster&&(this._video.poster=this._getUrl(r.poster));let n="";r==null||r.sources.forEach(o=>{n+=``}),r.tracks&&(r.tracks.forEach(o=>{n+=``}),this.$.hasSubtitles=!0),this._video.innerHTML+=n,this._initTracks(),console.log(r)}),this._video.addEventListener("loadedmetadata",e=>{this.$.currentTime=this._timeFmt(this._video.currentTime),this.$.totalTime=this._timeFmt(this._video.duration)}),this._video.addEventListener("timeupdate",e=>{let r=Math.round(100*(this._video.currentTime/this._video.duration));this.$.progressCssWidth=r+"%",this.$.currentTime=this._timeFmt(this._video.currentTime)});let t=window.localStorage.getItem(it.is+":volume");if(t){let e=parseFloat(t);this.setVolume(e),this.$.volumeValue=e}}};it.template=`
{{currentTime}} / {{totalTime}}
`;it.bindAttributes({video:"video",src:"src"});var Go="css-src";function yi(s){return class extends s{constructor(){super(...arguments);h(this,"renderShadow",!0);h(this,"pauseRender",!0)}shadowReadyCallback(){}initCallback(){super.initCallback(),this.setAttribute("hidden",""),setTimeout(()=>{let t=this.getAttribute(Go);if(t){this.attachShadow({mode:"open"});let e=document.createElement("link");e.rel="stylesheet",e.type="text/css",e.href=t,e.onload=()=>{window.requestAnimationFrame(()=>{this.render(),window.setTimeout(()=>{this.removeAttribute("hidden"),this.shadowReadyCallback()})})},this.shadowRoot.prepend(e)}else console.error("Attribute `css-src` is required and it is not set. See migration guide: https://uploadcare.com/docs/file-uploader/migration-to-0.25.0/")})}}}var $e=class extends yi(b){};var vi=class extends b{initCallback(){super.initCallback(),this.subConfigValue("removeCopyright",i=>{this.toggleAttribute("hidden",!!i)})}};h(vi,"template",`Powered by Uploadcare`);var kt=class extends $e{constructor(){super(...arguments);h(this,"init$",Fe(this));h(this,"_template",null)}static set template(t){this._template=t+""}static get template(){return this._template}};var Ci=class extends kt{};Ci.template=``;var wi=class extends kt{constructor(){super(...arguments);h(this,"pauseRender",!0)}shadowReadyCallback(){let t=this.ref.uBlock;this.sub("*currentActivity",e=>{e||(this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",e=>{(e==null?void 0:e.length)>0?this.$["*currentActivity"]=g.activities.UPLOAD_LIST:this.$["*currentActivity"]=t.initActivity||g.activities.START_FROM}),this.subConfigValue("sourceList",e=>{e!=="local"&&(this.cfg.sourceList="local")}),this.subConfigValue("confirmUpload",e=>{e!==!1&&(this.cfg.confirmUpload=!1)})}};wi.template=``;var xi=class extends kt{shadowReadyCallback(){let i=this.ref.uBlock;this.sub("*currentActivity",t=>{t||(this.$["*currentActivity"]=i.initActivity||g.activities.START_FROM)}),this.sub("*uploadList",t=>{((t==null?void 0:t.length)>0&&this.$["*currentActivity"]===i.initActivity||g.activities.START_FROM)&&(this.$["*currentActivity"]=g.activities.UPLOAD_LIST)})}};xi.template=``;var as=class extends yi(at){shadowReadyCallback(){this.__shadowReady=!0,this.$["*faderEl"]=this.ref["fader-el"],this.$["*cropperEl"]=this.ref["cropper-el"],this.$["*imgContainerEl"]=this.ref["img-container-el"],this.initEditor()}async initEditor(){this.__shadowReady&&await super.initEditor()}};function cs(s){for(let i in s){let t=[...i].reduce((e,r)=>(r.toUpperCase()===r&&(r="-"+r.toLowerCase()),e+=r),"");t.startsWith("-")&&(t=t.replace("-","")),t.startsWith("lr-")||(t="lr-"+t),s[i].reg&&s[i].reg(t)}}var hs="LR";async function Ko(s,i=!1){return new Promise((t,e)=>{if(typeof document!="object"){t(null);return}if(typeof window=="object"&&window[hs]){t(window[hs]);return}let r=document.createElement("script");r.async=!0,r.src=s,r.onerror=()=>{e()},r.onload=()=>{let n=window[hs];i&&cs(n),t(n)},document.head.appendChild(r)})}export{g as ActivityBlock,ls as ActivityHeader,zt as BaseComponent,b as Block,ei as CameraSource,as as CloudImageEditor,os as CloudImageEditorActivity,at as CloudImageEditorBlock,Ge as Config,si as ConfirmationDialog,vi as Copyright,ai as CropFrame,E as Data,se as DataOutput,be as DropArea,te as EditorCropButtonControl,Ft as EditorFilterControl,hi as EditorImageCropper,ns as EditorImageFader,ee as EditorOperationControl,ui as EditorScroller,ci as EditorSlider,di as EditorToolbar,_i as ExternalSource,_t as FileItem,Ce as FilePreview,xi as FileUploaderInline,wi as FileUploaderMinimal,Ci as FileUploaderRegular,ge as Icon,Yi as Img,pi as LineLoaderUi,Ee as LrBtnUi,Je as MessageBox,B as Modal,Xs as PACKAGE_NAME,qs as PACKAGE_VERSION,mi as PresenceToggle,ni as ProgressBar,ri as ProgressBarCommon,bi as Select,$e as ShadowWrapper,Ye as SimpleBtn,gi as SliderUi,ye as SourceBtn,ts as SourceList,Zi as StartFrom,Ae as Tabs,is as UploadCtxProvider,ii as UploadDetails,Qe as UploadList,v as UploaderBlock,ti as UrlSource,it as Video,Ko as connectBlocksFrom,cs as registerBlocks,yi as shadowed,gt as toKebabCase}; \ No newline at end of file