@aceshooting/lyra-ui 32.1.0 → 33.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +224 -1583
- package/README.md +12 -1
- package/custom-elements.slim.json +1 -0
- package/dist/accent-roles.css +1 -0
- package/dist/cli/migrate-wa.mjs +50 -48
- package/dist/cli/migration-contract.json.gz +0 -0
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +1 -1
- package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +10 -0
- package/dist/components/conversation/code-block/code-block-base.class.d.ts +3 -1
- package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.d.ts +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
- package/dist/components/conversation/code-block/code-block.class.d.ts +3 -2
- package/dist/components/conversation/code-block/code-block.class.js +1 -1
- package/dist/components/conversation/code-block/code-grammar-registry.d.ts +35 -0
- package/dist/components/conversation/code-block/code-grammar-registry.js +1 -0
- package/dist/components/conversation/model-select/model-select.class.d.ts +8 -7
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +1 -1
- package/dist/components/conversation/usage-badge/usage-badge.class.d.ts +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +8 -7
- package/dist/components/data/table/table-support.d.ts +2 -3
- package/dist/components/data/table/table.class.d.ts +2 -1
- package/dist/components/data/timeline/timeline.class.d.ts +17 -6
- package/dist/components/data/timeline/timeline.class.js +2 -2
- package/dist/components/data/timeline/timeline.styles.js +1 -1
- package/dist/components/forms/catalog-picker-base.d.ts +14 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +4 -5
- package/dist/components/forms/checkbox-group/checkbox-group.styles.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.d.ts +14 -5
- package/dist/components/forms/code-editor/code-editor.styles.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.d.ts +18 -7
- package/dist/components/forms/color-picker/color-picker.styles.js +1 -1
- package/dist/components/forms/combobox/combobox-option-html.js +1 -0
- package/dist/components/forms/combobox/combobox.class.d.ts +30 -9
- package/dist/components/forms/combobox/combobox.class.js +110 -21
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/country-picker/country-picker.class.d.ts +4 -5
- package/dist/components/forms/currency-picker/currency-picker.class.d.ts +4 -5
- package/dist/components/forms/date-picker/date-input.class.d.ts +14 -5
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +10 -0
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +2 -1
- package/dist/components/forms/input/input-shared.d.ts +14 -5
- package/dist/components/forms/input/time-input.class.d.ts +15 -6
- package/dist/components/forms/input/time-input.styles.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +8 -7
- package/dist/components/forms/otp-input/otp-input.class.d.ts +4 -5
- package/dist/components/forms/otp-input/otp-input.styles.js +1 -1
- package/dist/components/forms/phone-input/phone-input.class.d.ts +14 -5
- package/dist/components/forms/phone-input/phone-input.styles.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +4 -5
- package/dist/components/forms/radio/radio-group.styles.js +1 -1
- package/dist/components/forms/radio/radio.class.js +2 -2
- package/dist/components/forms/select/select.class.d.ts +5 -6
- package/dist/components/forms/signature-pad/signature-pad.class.d.ts +4 -5
- package/dist/components/forms/signature-pad/signature-pad.styles.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +6 -5
- package/dist/components/forms/slider/slider.styles.js +1 -1
- package/dist/components/forms/textarea/textarea.class.d.ts +14 -5
- package/dist/components/forms/time-zone-picker/time-zone-picker.class.d.ts +4 -5
- package/dist/components/forms/token-input/token-input.class.d.ts +10 -10
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/forms/token-input/token-input.styles.js +1 -1
- package/dist/components/forms/unit-picker/unit-picker.class.d.ts +4 -5
- package/dist/components/layout/command-palette/command-palette.class.d.ts +1 -1
- package/dist/components/layout/menu/menu.class.d.ts +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +1 -1
- package/dist/components/layout/segmented/segmented.class.d.ts +2 -2
- package/dist/components/layout/stepper/step.class.d.ts +14 -1
- package/dist/components/layout/stepper/step.class.js +2 -2
- package/dist/components/media/file-input/file-input.class.d.ts +2 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/file-input/file-input.styles.js +1 -1
- package/dist/components/media/lightbox/lightbox-item.class.d.ts +10 -0
- package/dist/components/media/lightbox/lightbox-item.class.js +1 -1
- package/dist/components/media/lightbox/lightbox-source.js +1 -1
- package/dist/components/media/lightbox/lightbox-types.d.ts +4 -1
- package/dist/components/media/lightbox/lightbox.class.d.ts +42 -19
- package/dist/components/media/lightbox/lightbox.class.js +4 -3
- package/dist/components/media/lightbox/lightbox.styles.js +1 -1
- package/dist/components/overlays/context-menu/context-menu.class.d.ts +1 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +19 -3
- package/dist/components/overlays/dialog/dialog.class.js +1 -1
- package/dist/components/overlays/dialog/dialog.styles.js +1 -1
- package/dist/components/overlays/drawer/drawer.class.d.ts +8 -2
- package/dist/components/overlays/drawer/drawer.class.js +1 -1
- package/dist/components/overlays/overlay/dropdown.class.d.ts +1 -1
- package/dist/components/overlays/overlay/overlay.styles.js +1 -1
- package/dist/components/overlays/overlay/popover.class.d.ts +1 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -0
- package/dist/components/overlays/overlay/tooltip.class.js +2 -2
- package/dist/components/overlays/toast/toast-item.class.d.ts +2 -2
- package/dist/components/overlays/toast/toast-item.styles.js +1 -1
- package/dist/components/retrieval/citation-badge/citation-badge.class.d.ts +1 -1
- package/dist/components/retrieval/entity-chip/entity-chip.class.d.ts +1 -1
- package/dist/components/utility/copy-button/copy-button.class.d.ts +2 -1
- package/dist/components/utility/copy-button/copy-button.class.js +1 -1
- package/dist/components/utility/export-button/export-button.class.d.ts +1 -1
- package/dist/components/utility/icon/icon-library-bootstrap.d.ts +50 -0
- package/dist/components/utility/icon/icon-library-bootstrap.js +1 -0
- package/dist/components/utility/icon/icon-library-font-awesome.d.ts +68 -0
- package/dist/components/utility/icon/icon-library-font-awesome.js +1 -0
- package/dist/components/utility/known-date/known-date.class.d.ts +10 -0
- package/dist/components/utility/mention-popover/mention-popover.class.d.ts +1 -1
- package/dist/components/utility/number-ticker/number-ticker.class.d.ts +10 -2
- package/dist/components/utility/number-ticker/number-ticker.class.js +1 -1
- package/dist/components/utility/tour/tour.class.d.ts +1 -1
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/accessibility-visibility.js +1 -1
- package/dist/internal/autoloader-manifest.js +1 -1
- package/dist/internal/declarative-overlay-action.js +1 -0
- package/dist/internal/default-strings/forms.generated.js +1 -1
- package/dist/internal/document-token-css.generated.js +10 -0
- package/dist/internal/document-tokens.generated.js +2 -11
- package/dist/internal/document-tokens.js +2 -2
- package/dist/internal/dom-guards.js +1 -1
- package/dist/internal/external-label-association.js +1 -0
- package/dist/internal/focus-navigation.js +1 -1
- package/dist/internal/form-control/chrome.styles.js +1 -1
- package/dist/internal/form-control-labels.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.d.ts +11 -2
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/theme-observation.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/styles/tokens-root.css +1 -1
- package/dist/styles/utilities.css +1 -1
- package/dist/theme-core.css +1 -1
- package/dist/theme.css +1 -1
- package/llms/components/lr-checkbox-group.md +2 -2
- package/llms/components/lr-citation-badge.md +1 -1
- package/llms/components/lr-code-block-core.md +3 -1
- package/llms/components/lr-code-block.md +14 -0
- package/llms/components/lr-code-editor.md +2 -2
- package/llms/components/lr-color-picker.md +4 -4
- package/llms/components/lr-combobox.md +21 -5
- package/llms/components/lr-context-menu.md +1 -1
- package/llms/components/lr-copy-button.md +4 -3
- package/llms/components/lr-country-picker.md +2 -2
- package/llms/components/lr-currency-picker.md +2 -2
- package/llms/components/lr-date-input.md +1 -1
- package/llms/components/lr-date-picker.md +1 -1
- package/llms/components/lr-dialog.md +30 -2
- package/llms/components/lr-drawer.md +7 -1
- package/llms/components/lr-entity-chip.md +1 -1
- package/llms/components/lr-export-button.md +1 -1
- package/llms/components/lr-file-input.md +1 -1
- package/llms/components/lr-icon.md +96 -0
- package/llms/components/lr-input.md +2 -2
- package/llms/components/lr-lightbox.md +43 -17
- package/llms/components/lr-locale-picker.md +2 -2
- package/llms/components/lr-mention-popover.md +1 -1
- package/llms/components/lr-menu.md +1 -1
- package/llms/components/lr-model-select.md +4 -4
- package/llms/components/lr-native-time-input.md +2 -2
- package/llms/components/lr-number-input.md +2 -2
- package/llms/components/lr-number-ticker.md +7 -2
- package/llms/components/lr-otp-input.md +2 -2
- package/llms/components/lr-phone-input.md +2 -2
- package/llms/components/lr-popover.md +1 -1
- package/llms/components/lr-radio-group.md +2 -2
- package/llms/components/lr-segmented.md +1 -1
- package/llms/components/lr-select.md +3 -3
- package/llms/components/lr-selection-toolbar.md +1 -1
- package/llms/components/lr-signature-pad.md +2 -2
- package/llms/components/lr-slider.md +1 -1
- package/llms/components/lr-step.md +7 -1
- package/llms/components/lr-textarea.md +2 -2
- package/llms/components/lr-time-input.md +3 -3
- package/llms/components/lr-time-zone-picker.md +2 -2
- package/llms/components/lr-timeline.md +12 -5
- package/llms/components/lr-toast.md +1 -1
- package/llms/components/lr-token-input.md +10 -9
- package/llms/components/lr-tool-call-chip.md +1 -1
- package/llms/components/lr-tooltip.md +5 -0
- package/llms/components/lr-unit-picker.md +2 -2
- package/llms/components/lr-usage-badge.md +1 -1
- package/llms/components/lr-voice-picker.md +4 -3
- package/llms/index.md +115 -115
- package/llms/migration.md +87 -8
- package/llms/peers.md +2 -2
- package/llms/shared/forms-and-accessibility.md +4 -1
- package/llms/shared/frameworks-and-ssr.md +10 -1
- package/llms/shared/imports-and-registration.md +8 -1
- package/llms/shared/localization-and-rtl.md +5 -0
- package/llms/shared/native-styles-and-utilities.md +34 -5
- package/llms/shared/styles-and-tokens.md +58 -4
- package/llms/shared/testing-and-utilities.md +9 -0
- package/llms/shared.md +128 -12
- package/locales.json +1 -1
- package/package.json +14 -5
- package/registrations.json +1 -1
- package/skills/compose-lyra-interfaces/SKILL.md +1 -1
- package/skills/lyra-ui/SKILL.md +1 -1
- package/skills/lyra-ui/commands/migrate.md +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{shouldIgnoreActivationKey}from"../../../internal/list-navigation.js";import{emitValueEvents}from"../../../internal/value-events.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{normalizeLabel}from"../../../internal/accessible-name.js";import{formControlSupportingState}from"../../../internal/form-control-template.js";import{formatFileSize}from"../../../internal/bytes.js";import{FormControlController}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{srOnly}from"../../../internal/a11y.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{getFormOwner,isBarredFromValidation,isLiveDisabled,setFormOwner}from"../../../internal/form-associated.js";import{observeValidatorAttributes,runFormValidators}from"../../../internal/form-validator-runtime.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController,isFileValue,readFileList}from"../../../internal/drop-session-controller.js";import{falseDefaultBooleanConverter,blankNumberConverter}from"../../../internal/converters.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{classifyFiles,dragInstruction,EMPTY_MIME_TYPES,freezeDetail,handleDrop,mimeTypeFilter,rejectionMessages,selectionMessage,snapshotMimeTypes}from"../../../internal/file-intake.js";import{LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fileInputAccepted,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileInputRejectionsMore}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();import{DEFAULT_MAX_FILE_SIZE_BYTES,DEFAULT_MAX_FILES,DEFAULT_MAX_TOTAL_SIZE_BYTES}from"../../../internal/file-intake.js";const MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_THUMBNAIL_ROWS=50,MAX_RENDERED_FILE_ROWS=200,INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}class LyraFileInput extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAccepted:LYRA_DEFAULT_fileInputAccepted,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejected:LYRA_DEFAULT_fileInputRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileInputRejectionsMore:LYRA_DEFAULT_fileInputRejectionsMore,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-files","lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["value"]),"lr-change":Object.freeze(["value"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){if(next===this.inputs.allowed)return;this.inputs.allowed=next;const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){if(next===this.inputs.forbidden)return;this.inputs.forbidden=next;const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.accept="",this.capture="",this.inputs={},this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,this.directory=!1,this.withoutPaste=!1,this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.hostAccessibleLabel=null,this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.truncatedSelection=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.hasSyncedDescribedByElements=!1,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.intakeMessage=(key,values)=>this.localize(key,void 0,values),this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>handleDrop(this,this.dropSession,e,this.effectiveMultiple,(files,rejected)=>this.emitFiles(files,rejected)),this.onPaste=e=>{if(this.withoutPaste||isLiveDisabled(this))return;const files=readFileList(e.clipboardData?.files);files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!isLiveDisabled(this)&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(isLiveDisabled(this)){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{isLiveDisabled(this)||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{isLiveDisabled(this)||shouldIgnoreActivationKey(e)||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>isLiveDisabled(this),previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){if(next===this.inputs.files)return;this.inputs.files=next;const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=[...valid];const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?(this.files=this._files.slice(0,1),this.truncatedSelection=!0):this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}disconnectedCallback(){this.disconnectValidatorAttributeObserver(),this.dropSession.reset();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){if(super.updated(changed),this.truncatedSelection){this.truncatedSelection=!1;const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail=>this.emit("lr-input",detail)),emitValueEvents(this,"change",{value},detail=>this.emit("lr-change",detail))}changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),this.announcementsArmed&&changed.has("dragState")&&this.dragState!=="default"&&this.announcements.announcePolite(dragInstruction(this.dragState,this.intakeMessage)),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver(),this.disposeValidatorObserver=observeValidatorAttributes(this,this.validators,()=>{this.updateValidity(),this.validityRevision++})}disconnectValidatorAttributeObserver(){this.disposeValidatorObserver?.(),this.disposeValidatorObserver=void 0}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&!this.hasEffectiveValue&&(flags.valueMissing=!0,message=()=>this.localize("fieldRequired"));const configured=runFormValidators(this.validators,this.files,this,()=>this.localize("valueInvalid"));configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.dropSession.reset(),this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(this.dropSession.reset(),isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate())}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function",previewFiles=new Set(this._files.slice(0,MAX_THUMBNAIL_ROWS));let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!previewFiles.has(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of previewFiles){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}classify(fileList,isPreview=!1){const multiple=this.effectiveMultiple;return classifyFiles(this,fileList,multiple,this.nonRetaining||!multiple?[]:this._files,isPreview,mimeTypeFilter(this.allowedMimeTypes,this.forbiddenMimeTypes))}emitFiles(fileList,additionalRejected=[]){const detail=freezeDetail(this.classify(fileList),additionalRejected),{files,rejected}=detail;if(this.rejectedFiles=rejected,this.resultStatus=selectionMessage(detail,this.effectiveLocale,this.intakeMessage,this.acceptedMessage,this.rejectedMessage),this.resultStatus&&this.announcements.announcePolite(this.resultStatus),rejected.length>0&&this.announcements.announceAssertive(rejectionMessages(rejected,this.effectiveLocale,this.intakeMessage).join(" ")),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length){this.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files);const value=Object.freeze(this.nonRetaining?[...files]:[...this._files]);emitValueEvents(this,"input",{value},detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",{value},detail2=>this.emit("lr-change",detail2))}this.emit("lr-files",detail)}openPicker(){isLiveDisabled(this)||this.inputEl?.click()}focus(options){this.deferFocusUntilRendered(options)||isLiveDisabled(this)||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}statusText(){return this.dragState==="default"?this.resultStatus:dragInstruction(this.dragState,this.intakeMessage)}get dropzoneInstruction(){return this.localize("fileInputDefaultLabel")}removeFile(index,file){if(isLiveDisabled(this)||index<0||this._files[index]!==file)return;this.touched=!0;const hadFocus=shadowFocusTarget(this)?.matches('[part~="remove-button"]');this.files=this._files.filter((_,candidate)=>candidate!==index);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail=>this.emit("lr-input",detail)),emitValueEvents(this,"change",{value},detail=>this.emit("lr-change",detail)),hadFocus&&this.updateComplete.then(()=>{const buttons=this.renderRoot.querySelectorAll('[part~="remove-button"]');(buttons[Math.min(index,buttons.length-1)]??this.baseEl)?.focus()})}fileSize(file){return formatFileSize(file.size,this.effectiveLocale)}renderFile(file,index){const thumbnail=index<MAX_THUMBNAIL_ROWS?this.thumbnailUrls.get(file)?.url:void 0;return html`<div part="file">
|
|
1
|
+
import{__decorate}from"tslib";import{shouldIgnoreActivationKey}from"../../../internal/list-navigation.js";import{emitValueEvents}from"../../../internal/value-events.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{normalizeLabel}from"../../../internal/accessible-name.js";import{formControlSupportingState}from"../../../internal/form-control-template.js";import{formatFileSize}from"../../../internal/bytes.js";import{FormControlController}from"../../../internal/form-control-controller.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{srOnly}from"../../../internal/a11y.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{getFormOwner,isBarredFromValidation,isLiveDisabled,setFormOwner}from"../../../internal/form-associated.js";import{observeValidatorAttributes,runFormValidators}from"../../../internal/form-validator-runtime.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController,isFileValue,readFileList}from"../../../internal/drop-session-controller.js";import{falseDefaultBooleanConverter,blankNumberConverter}from"../../../internal/converters.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{classifyFiles,dragInstruction,EMPTY_MIME_TYPES,freezeDetail,handleDrop,mimeTypeFilter,rejectionMessages,selectionMessage,snapshotMimeTypes}from"../../../internal/file-intake.js";import{LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fileInputAccepted,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileInputRejectionsMore}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();import{DEFAULT_MAX_FILE_SIZE_BYTES,DEFAULT_MAX_FILES,DEFAULT_MAX_TOTAL_SIZE_BYTES}from"../../../internal/file-intake.js";const MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_THUMBNAIL_ROWS=50,MAX_RENDERED_FILE_ROWS=200,INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}class LyraFileInput extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAccepted:LYRA_DEFAULT_fileInputAccepted,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejected:LYRA_DEFAULT_fileInputRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileInputRejectionsMore:LYRA_DEFAULT_fileInputRejectionsMore,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-files","lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["value"]),"lr-change":Object.freeze(["value"])})}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){if(next===this.inputs.allowed)return;this.inputs.allowed=next;const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){if(next===this.inputs.forbidden)return;this.inputs.forbidden=next;const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.accept="",this.capture="",this.inputs={},this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,this.directory=!1,this.withoutPaste=!1,this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.hostAccessibleLabel=null,this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.truncatedSelection=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.hasSyncedDescribedByElements=!1,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.intakeMessage=(key,values)=>this.localize(key,void 0,values),this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>handleDrop(this,this.dropSession,e,this.effectiveMultiple,(files,rejected)=>this.emitFiles(files,rejected)),this.onPaste=e=>{if(this.withoutPaste||isLiveDisabled(this))return;const files=readFileList(e.clipboardData?.files);files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!isLiveDisabled(this)&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(isLiveDisabled(this)){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{isLiveDisabled(this)||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{isLiveDisabled(this)||shouldIgnoreActivationKey(e)||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>isLiveDisabled(this),previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){if(next===this.inputs.files)return;this.inputs.files=next;const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=[...valid];const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?(this.files=this._files.slice(0,1),this.truncatedSelection=!0):this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}disconnectedCallback(){this.disconnectValidatorAttributeObserver(),this.dropSession.reset();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){if(super.updated(changed),this.truncatedSelection){this.truncatedSelection=!1;const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail=>this.emit("lr-input",detail)),emitValueEvents(this,"change",{value},detail=>this.emit("lr-change",detail))}changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),this.announcementsArmed&&changed.has("dragState")&&this.dragState!=="default"&&this.announcements.announcePolite(dragInstruction(this.dragState,this.intakeMessage)),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver(),this.disposeValidatorObserver=observeValidatorAttributes(this,this.validators,()=>{this.updateValidity(),this.validityRevision++})}disconnectValidatorAttributeObserver(){this.disposeValidatorObserver?.(),this.disposeValidatorObserver=void 0}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&!this.hasEffectiveValue&&(flags.valueMissing=!0,message=()=>this.localize("fieldRequired"));const configured=runFormValidators(this.validators,this.files,this,()=>this.localize("valueInvalid"));configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.dropSession.reset(),this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(this.dropSession.reset(),isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate())}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function",previewFiles=new Set(this._files.slice(0,MAX_THUMBNAIL_ROWS));let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!previewFiles.has(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of previewFiles){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}classify(fileList,isPreview=!1){const multiple=this.effectiveMultiple;return classifyFiles(this,fileList,multiple,this.nonRetaining||!multiple?[]:this._files,isPreview,mimeTypeFilter(this.allowedMimeTypes,this.forbiddenMimeTypes))}emitFiles(fileList,additionalRejected=[]){const detail=freezeDetail(this.classify(fileList),additionalRejected),{files,rejected}=detail;if(this.rejectedFiles=rejected,this.resultStatus=selectionMessage(detail,this.effectiveLocale,this.intakeMessage,this.acceptedMessage,this.rejectedMessage),this.resultStatus&&this.announcements.announcePolite(this.resultStatus),rejected.length>0&&this.announcements.announceAssertive(rejectionMessages(rejected,this.effectiveLocale,this.intakeMessage).join(" ")),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length){this.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files);const value=Object.freeze(this.nonRetaining?[...files]:[...this._files]);emitValueEvents(this,"input",{value},detail2=>this.emit("lr-input",detail2)),emitValueEvents(this,"change",{value},detail2=>this.emit("lr-change",detail2))}this.emit("lr-files",detail)}openPicker(){isLiveDisabled(this)||this.inputEl?.click()}focus(options){this.deferFocusUntilRendered(options)||isLiveDisabled(this)||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}statusText(){return this.dragState==="default"?this.resultStatus:dragInstruction(this.dragState,this.intakeMessage)}get dropzoneInstruction(){return this.localize("fileInputDefaultLabel")}removeFile(index,file){if(isLiveDisabled(this)||index<0||this._files[index]!==file)return;this.touched=!0;const hadFocus=shadowFocusTarget(this)?.matches('[part~="remove-button"]');this.files=this._files.filter((_,candidate)=>candidate!==index);const value=Object.freeze([...this._files]);emitValueEvents(this,"input",{value},detail=>this.emit("lr-input",detail)),emitValueEvents(this,"change",{value},detail=>this.emit("lr-change",detail)),hadFocus&&this.updateComplete.then(()=>{const buttons=this.renderRoot.querySelectorAll('[part~="remove-button"]');(buttons[Math.min(index,buttons.length-1)]??this.baseEl)?.focus()})}fileSize(file){return formatFileSize(file.size,this.effectiveLocale)}renderFile(file,index){const thumbnail=index<MAX_THUMBNAIL_ROWS?this.thumbnailUrls.get(file)?.url:void 0;return html`<div part="file">
|
|
2
2
|
<span part="file-thumbnail" aria-hidden="true">
|
|
3
3
|
${thumbnail?html`<img part="file-image" src=${thumbnail} alt="" loading="lazy" decoding="async" />`:html`<span part="file-icon">${fileIcon()}</span>`}
|
|
4
4
|
</span>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{activeFill,disabledControl,focusRingShorthand,iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{dropzoneSizeLadder,dropzoneVerdictForcedColors}from"../../../internal/dropzone.styles.js";import{formControlLabelTypography,formControlFocusHalo,formControlRequiredMarker,formControlSupportingColor}from"../../../internal/form-control.styles.js";const styles=css` ${dropzoneSizeLadder} :host{display:flex;flex-direction:column;min-inline-size:0;max-inline-size:100%;--_lr-file-input-font-size:var(--lr-form-control-font-size);--_lr-file-input-detail-font-size:var(--lr-font-size-sm);--_lr-form-control-focus-shadow:var(--lr-form-control-focus-shadow, none)}:host([size="2xs"]),:host([size=xs]){--_lr-file-input-detail-font-size:var(--lr-font-size-2xs)}:host([size=s]),:host([size=small]){--_lr-file-input-detail-font-size:var(--lr-font-size-xs)}:host([size=l]),:host([size=large]){--_lr-file-input-detail-font-size:var(--lr-font-size-md-sm)}:host([size=xl]){--_lr-file-input-detail-font-size:var(--lr-font-size-m)}[part=form-control]{display:flex;flex-direction:column;flex:1;min-inline-size:0;max-inline-size:100%}[part~=form-control-label]{${formControlLabelTypography({size:css`var(--lr-file-input-font-size, var(--_lr-file-input-font-size))`})} display:block;min-inline-size:0;margin-block-end:var(--lr-form-control-label-
|
|
1
|
+
import{activeFill,disabledControl,focusRingShorthand,iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{dropzoneSizeLadder,dropzoneVerdictForcedColors}from"../../../internal/dropzone.styles.js";import{formControlLabelTypography,formControlFocusHalo,formControlRequiredMarker,formControlSupportingColor}from"../../../internal/form-control.styles.js";const styles=css` ${dropzoneSizeLadder} :host{display:flex;flex-direction:column;min-inline-size:0;max-inline-size:100%;--_lr-file-input-font-size:var(--lr-form-control-font-size);--_lr-file-input-detail-font-size:var(--lr-font-size-sm);--_lr-form-control-focus-shadow:var(--lr-form-control-focus-shadow, none)}:host([size="2xs"]),:host([size=xs]){--_lr-file-input-detail-font-size:var(--lr-font-size-2xs)}:host([size=s]),:host([size=small]){--_lr-file-input-detail-font-size:var(--lr-font-size-xs)}:host([size=l]),:host([size=large]){--_lr-file-input-detail-font-size:var(--lr-font-size-md-sm)}:host([size=xl]){--_lr-file-input-detail-font-size:var(--lr-font-size-m)}[part=form-control]{display:flex;flex-direction:column;flex:1;min-inline-size:0;max-inline-size:100%}[part~=form-control-label]{${formControlLabelTypography({size:css`var(--lr-file-input-font-size, var(--_lr-file-input-font-size))`})} display:block;min-inline-size:0;margin-block-end:var(--lr-form-control-label-gap,var(--lr-space-xs));overflow-wrap:anywhere}[part~=form-control-label][hidden],[part=hint][hidden],[part=error][hidden]{display:none}${formControlRequiredMarker} .dropzone{position:relative;display:grid;flex:1;min-inline-size:0}[part~=file-input]{grid-area:1 / 1;inline-size:100%;${iconHitTarget} box-sizing:border-box;font:inherit;cursor:pointer;appearance:none;padding:var(--lr-file-input-dropzone-padding,var(--_lr-dropzone-padding));border:var(--lr-border-width-medium) dashed var(--lr-file-input-dropzone-border-color,var(--lr-color-border));border-radius:var(--lr-file-input-radius,var(--lr-radius));background:var(--lr-file-input-dropzone-fill,var(--lr-color-surface));color:var(--lr-color-text-quiet);font-size:var(--lr-file-input-dropzone-font-size,var(--_lr-dropzone-font-size));transition:border-color var(--lr-transition-fast),background-color var(--lr-transition-fast)}.dropzone-content{grid-area:1 / 1;z-index:var(--lr-layer-content);min-inline-size:0;max-inline-size:100%;box-sizing:border-box;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--lr-file-input-gap,var(--lr-space-xs));padding:var(--lr-file-input-dropzone-padding,var(--_lr-dropzone-padding));color:var(--lr-color-text-quiet);text-align:center;font-size:var(--lr-file-input-dropzone-font-size,var(--_lr-dropzone-font-size));overflow-wrap:anywhere;pointer-events:none}[part=dropzone-icon]{display:inline-flex;align-items:center;justify-content:center;font-size:var(--lr-file-input-dropzone-icon-size,var(--_lr-dropzone-icon-size))}[part=dropzone-text]{min-inline-size:0;max-inline-size:100%;overflow-wrap:anywhere}::slotted(*){max-inline-size:100%;min-inline-size:0;pointer-events:auto}:host(:is([size=s],[size=small])) [part~=file-input],:host(:is([size=s],[size=small])) .dropzone-content{padding:var(--lr-file-input-compact-padding,var(--lr-file-input-dropzone-padding,var(--_lr-dropzone-padding)));font-size:var(--lr-file-input-compact-font-size,var(--lr-file-input-dropzone-font-size,var(--_lr-dropzone-font-size)))}:host(:is([size=s],[size=small])) .dropzone-content{gap:var(--lr-file-input-compact-gap,var(--lr-file-input-gap,var(--lr-space-xs)))}[part~=file-input][data-drag-state=accept]{border-color:var(--lr-file-input-accept-border-color,var(--lr-color-success));background:var(--lr-file-input-accept-bg,color-mix(in srgb,var(--lr-color-success) 8%,transparent))}[part~=file-input][data-drag-state=reject]{border-color:var(--lr-file-input-reject-border-color,var(--lr-color-danger));background:var(--lr-file-input-reject-bg,color-mix(in srgb,var(--lr-color-danger) 8%,transparent))}${dropzoneVerdictForcedColors('[part~="file-input"]')} :host(:not(:disabled)) [part~=file-input]:hover,:host(:not(:disabled)) .dropzone:hover [part~=file-input]{border-color:var(--lr-file-input-dropzone-hover-border-color,var(--lr-color-brand))}:host(:not(:disabled)) [part~=file-input]:active,:host(:not(:disabled)) .dropzone:active [part~=file-input]{border-color:var(--lr-file-input-dropzone-active-border-color,var(--lr-file-input-dropzone-hover-border-color,var(--lr-color-brand)));background:var(--lr-file-input-dropzone-active-bg,${activeFill("var(--lr-file-input-dropzone-fill, var(--lr-color-surface))")})}[part~=file-input]:focus-visible{${focusRingShorthand}}[part~=file-input]:focus{${formControlFocusHalo}}:host(:disabled) [part~=file-input]{${disabledControl}}[part=rejection]{min-inline-size:0;max-inline-size:100%;margin-block:var(--lr-space-2xs) 0;color:var(--lr-color-danger);font-size:var(--lr-file-input-detail-font-size,var(--_lr-file-input-detail-font-size));text-align:start;overflow-wrap:anywhere}[part=rejection] ul{margin:0;padding-inline-start:var(--lr-space-m)}[part=file-list]{display:grid;gap:var(--lr-space-xs);margin-block-start:var(--lr-space-xs)}[part=file-more]{color:var(--lr-color-text-quiet);font-size:var(--_lr-file-input-detail-font-size)}[part=file]{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:var(--lr-space-s);min-inline-size:0;padding:var(--lr-space-xs) var(--lr-space-s);border:var(--lr-border-width-thin) solid var(--lr-file-input-file-border-color,var(--lr-color-border-subtle));border-radius:var(--lr-file-input-file-radius,var(--lr-radius));background:var(--lr-file-input-file-bg,var(--lr-color-surface-raised))}[part=file-thumbnail]{display:inline-flex;align-items:center;justify-content:center;inline-size:var(--lr-file-input-thumbnail-size,var(--lr-icon-button-size));block-size:var(--lr-file-input-thumbnail-size,var(--lr-icon-button-size));overflow:hidden;border-radius:var(--lr-file-input-thumbnail-radius,var(--lr-radius-xs));color:var(--lr-color-text-quiet)}[part=file-image]{inline-size:100%;block-size:100%;object-fit:cover}[part=file-icon]{display:inline-flex;font-size:var(--lr-font-size-xl)}[part=file-details]{display:flex;flex-direction:column;min-inline-size:0}[part=file-name]{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--lr-color-text);font-size:var(--lr-file-input-font-size,var(--_lr-file-input-font-size))}[part=file-size]{color:var(--lr-color-text-quiet);font-size:var(--lr-file-input-detail-font-size,var(--_lr-file-input-detail-font-size))}[part~=remove-button]{display:inline-flex;align-items:center;justify-content:center;${iconHitTarget} padding:0;border:none;border-radius:var(--lr-radius);background:transparent;color:var(--lr-color-text-quiet);font:inherit;cursor:pointer;transition:background-color var(--lr-transition-fast),color var(--lr-transition-fast)}[part~=remove-button]:hover:where(:not(:disabled)){background:var(--lr-file-input-remove-hover-bg,var(--lr-color-brand-quiet));color:var(--lr-color-text)}[part~=remove-button]:active:where(:not(:disabled)){background:var(--lr-file-input-remove-active-bg,${activeFill("var(--lr-file-input-remove-hover-bg, var(--lr-color-brand-quiet))")})}[part~=remove-button]:focus-visible{${focusRingShorthand}}[part~=remove-button]:disabled{${disabledControl}}${formControlSupportingColor} [part=hint]{min-inline-size:0;margin-block-start:var(--lr-space-xs);font-size:var(--lr-file-input-detail-font-size,var(--_lr-file-input-detail-font-size));overflow-wrap:anywhere}[part=error]{min-inline-size:0;margin-block-start:var(--lr-space-xs);font-size:var(--lr-file-input-detail-font-size,var(--_lr-file-input-detail-font-size));overflow-wrap:anywhere}`;export{styles};
|
|
@@ -17,8 +17,18 @@ export type LyraLightboxItemType='image'|'video';
|
|
|
17
17
|
* largest. `width` and `height` reserve the item's own space (and the viewer's placeholder) before
|
|
18
18
|
* the media loads, so a gallery does not shift as it fills in.
|
|
19
19
|
*
|
|
20
|
+
* **Custom content.** For anything other than an image or a native video (an embed, a player, a
|
|
21
|
+
* comparison, another component), put it in a `<template>` that is a direct child of the item.
|
|
22
|
+
* The lightbox copies the template's content into the slide only while that slide is shown, so
|
|
23
|
+
* nothing in it loads or runs before then, and removes the copy when the slide changes or the
|
|
24
|
+
* viewer closes. The copy is light DOM, so page styles apply. `src` is optional for such an item
|
|
25
|
+
* (it still becomes the no-JavaScript link when set), `width` and `height` give the slide its
|
|
26
|
+
* proportions, and custom content cannot be zoomed. The slotted `<img>` or `thumbnail` remains
|
|
27
|
+
* the item's page thumbnail and its thumbnail in the strip.
|
|
28
|
+
*
|
|
20
29
|
* @customElement lr-lightbox-item
|
|
21
30
|
* @slot - The item's thumbnail, usually an `<img>`. Clicking it opens the lightbox at this item.
|
|
31
|
+
* A direct `<template>` child is not shown here; it holds the item's custom slide content.
|
|
22
32
|
* Leave it empty (with no `thumbnail`) for an item that only appears inside the lightbox.
|
|
23
33
|
* @slot caption - Optional caption text shown with the item in the lightbox. Not displayed on the
|
|
24
34
|
* page; the lightbox reads its text content.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{ifDefined}from"lit/directives/if-defined.js";import{LyraElement}from"../../../internal/lyra-element.js";import{playIcon}from"../../../internal/icons.js";import{tag}from"../../../internal/prefix.js";import{safeLinkHref,safeMediaSrc}from"../../../internal/safe-url.js";import{literalSetConverter}from"../../../internal/converters.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{setCustomState}from"../../../internal/custom-states.js";import{styles}from"./lightbox-item.styles.js";import{chooseSrcsetCandidate}from"../../../internal/srcset.js";const ITEM_TYPES=["image","video"];function dimension(value){const parsed=typeof value=="number"?value:typeof value=="string"&&value.trim()?Number(value):NaN;return Number.isFinite(parsed)&&parsed>0?Math.round(parsed):void 0}class LyraLightboxItem extends LyraElement{constructor(){super(...arguments),this.itemInternals=attachInternalsSafely(this),this.type="image",this.src="",this.srcset="",this.sizes="",this.alt="",this.caption="",this.thumbnail="",this.onSlotChange=()=>{const hasContent=(this.renderRoot.querySelector("slot:not([name])")?.assignedNodes({flatten:!0})??[]).some(node=>node.nodeType===Node.ELEMENT_NODE
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{ifDefined}from"lit/directives/if-defined.js";import{LyraElement}from"../../../internal/lyra-element.js";import{playIcon}from"../../../internal/icons.js";import{tag}from"../../../internal/prefix.js";import{safeLinkHref,safeMediaSrc}from"../../../internal/safe-url.js";import{literalSetConverter}from"../../../internal/converters.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{setCustomState}from"../../../internal/custom-states.js";import{styles}from"./lightbox-item.styles.js";import{chooseSrcsetCandidate}from"../../../internal/srcset.js";const ITEM_TYPES=["image","video"];function dimension(value){const parsed=typeof value=="number"?value:typeof value=="string"&&value.trim()?Number(value):NaN;return Number.isFinite(parsed)&&parsed>0?Math.round(parsed):void 0}class LyraLightboxItem extends LyraElement{constructor(){super(...arguments),this.itemInternals=attachInternalsSafely(this),this.type="image",this.src="",this.srcset="",this.sizes="",this.alt="",this.caption="",this.thumbnail="",this.onSlotChange=()=>{const hasContent=(this.renderRoot.querySelector("slot:not([name])")?.assignedNodes({flatten:!0})??[]).some(node=>node.nodeType===Node.ELEMENT_NODE?node.localName!=="template":!!node.textContent?.trim());this.toggleAttribute("data-empty",!hasContent&&!this.thumbnail),setCustomState(this.itemInternals,"empty",!hasContent&&!this.thumbnail),this.notifyLightbox()},this.onKeyDown=event=>{!safeLinkHref(this.src)&&(event.key==="Enter"||event.key===" ")&&(event.preventDefault(),this.triggerEl?.click())}}static{this.styles=[LyraElement.styles,styles]}get thumbnailElement(){return this.querySelector(":scope > img, :scope img")}get slideTemplate(){return this.querySelector(":scope > template")}get thumbnailSrc(){const image=this.thumbnailElement;return safeMediaSrc(image?.currentSrc||image?.getAttribute("src")||this.thumbnail)??""}get resolvedAlt(){return this.alt||this.thumbnailElement?.alt||""}get captionText(){return this.caption?this.caption:Array.from(this.children).find(child=>child.getAttribute("slot")==="caption")?.textContent?.trim()??""}get mediaSrc(){const chosen=this.src||chooseSrcsetCandidate(this.srcset,this.sizes,this.ownerDocument.defaultView);return safeMediaSrc(chosen)??""}setViewerState(name,present){setCustomState(this.itemInternals,name,present)}focus(options){this.deferFocusUntilRendered(options)||this.triggerEl?.focus(options)}updated(changed){super.updated(changed),this.notifyLightbox()}connectedCallback(){super.connectedCallback(),this.notifyLightbox()}disconnectedCallback(){super.disconnectedCallback(),this.notifyLightbox()}notifyLightbox(){this.closest(tag("lightbox"))?.itemChanged?.()}render(){const href=safeLinkHref(this.src)??void 0,name=this.thumbnailElement?.alt===""&&!this.textContent?.trim()&&this.alt?this.alt:void 0,width=dimension(this.width),height=dimension(this.height),thumbnail=safeMediaSrc(this.thumbnail);return html`
|
|
2
2
|
<a part="trigger" href=${ifDefined(href)} role=${ifDefined(href?void 0:"button")} tabindex=${ifDefined(href?void 0:"0")} aria-haspopup="dialog" aria-label=${ifDefined(name)} @keydown=${this.onKeyDown} >
|
|
3
3
|
<slot @slotchange=${this.onSlotChange}>${thumbnail?html`<img part="thumbnail-image" src=${thumbnail} alt=${this.resolvedAlt} width=${ifDefined(width)} height=${ifDefined(height)} loading="lazy" />`:nothing}</slot>
|
|
4
4
|
<slot name="caption"></slot>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SourceRequestController,sourceCount,sourceRevision}from"../../../internal/source-request-controller.js";import{SourceWindowController}from"../../../internal/source-window-controller.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{requireOwnDataValue}from"../../../internal/data-descriptors.js";const MAX_FIELD_UNITS=65536;function field(value,key){if(value===null||typeof value!="object")throw new TypeError("Invalid image record");return requireOwnDataValue(value,key,"Invalid image field")}function text(value,optional=!1){if(!(optional&&value===void 0)){if(typeof value!="string"||value.length>MAX_FIELD_UNITS)throw new TypeError("Invalid image text");return value}}function normalize(value){const key=text(field(value,"key"));if(!key.length)throw new TypeError("Invalid image key");const order=sourceCount(field(value,"order")),image=field(value,"value"),src=text(field(image,"src")),alt=text(field(image,"alt"),!0),caption=text(field(image,"caption"),!0);return Object.freeze({key,order,value:Object.freeze({src,...alt===void 0?{}:{alt},...caption===void 0?{}:{caption}})})}class LightboxSourceController{constructor(host,repaint){this.host=host,this.repaint=repaint,this.locale="",this.dirty=!0,this.transaction=0,this.requestedIndex=-1,this.count=0,this.state="empty",this.requests=new SourceRequestController(host,{channels:["image"],onReset:()=>this.clearImage()}),this.window=new SourceWindowController(host,{pageSize:1,maxRows:3,maxPages:3,maxConcurrent:1,keyOf:record=>record.key,normalize,onChange:repaint}),host.addController(this)}clearImage(){this.requestedIndex=-1,this.pendingImage&&(this.pendingImage.onload=null,this.pendingImage.onerror=null,this.pendingImage.removeAttribute("src"),this.pendingImage=void 0),this.image=void 0,this.state=this.count?"loading":"empty"}refresh(){this.dirty=!0,this.transaction++,this.requests.refresh(),this.window.bind(void 0),this.repaint()}update(input,locale){if(!this.dirty&&input===this.input&&locale===this.locale)return!0;const transaction=++this.transaction;if(this.input=input,this.locale=locale,this.dirty=!1,this.requests.refresh(),transaction!==this.transaction||(this.window.bind(void 0),transaction!==this.transaction))return!1;try{if(input!==void 0){if(input===null||typeof input!="object")throw new TypeError("Invalid image source");const revision=sourceRevision(input.revision);if(transaction!==this.transaction)return!1;const view=input.images;if(transaction!==this.transaction)return!1;const count=sourceCount(view.count);if(transaction!==this.transaction||(this.requests.setSource(input,revision),transaction!==this.transaction)||(this.window.bind({owner:input,revision,epoch:this.requests.epoch,locale,view}),transaction!==this.transaction))return!1;this.count=count}else{if(this.requests.setSource(void 0,void 0),transaction!==this.transaction)return!1;this.count=0}this.state=this.count?"loading":"empty"}catch{if(transaction!==this.transaction||(this.requests.setSource(void 0,void 0),transaction!==this.transaction)||(this.window.bind(void 0),transaction!==this.transaction))return!1;this.count=0,this.state=input===void 0?"empty":"error"}return!0}select(index){if(this.dirty||!this.count||index===this.requestedIndex||!this.host.isConnected)return;this.requests.invalidate("image"),this.clearImage(),this.requestedIndex=index,this.state="loading";const lease=this.requests.begin("image",this.locale);lease&&(this.window.requestRange(index,index+1),this.window.ensure(index).then(ready=>{if(!lease.isCurrent())return;const slot=ready?this.window.source.itemAt(index):void 0;if(slot?.state!=="ready"){this.state="error",this.repaint();return}const value=slot.value.value,src=safeMediaSrc(value.src);if(!src){this.state="error",this.repaint();return}const image=this.host.ownerDocument.createElement("img");this.pendingImage=image;const settle=loaded=>{!lease.isCurrent()||this.pendingImage!==image||(image.onload=null,image.onerror=null,this.pendingImage=void 0,this.image=loaded?Object.freeze({...value,src}):void 0,this.state=loaded?"ready":"error",this.repaint())};image.onload=()=>settle(!0),image.onerror=()=>settle(!1),image.src=src}))}retry(index){if(this.count===0){this.refresh();return}this.requestedIndex=-1,this.select(index),this.repaint()}adopted(){this.requests.adopted(),this.window.adopted(),this.refresh()}hostConnected(){this.dirty=!0,this.repaint()}hostDisconnected(){this.dirty=!0,this.clearImage()}}export{LightboxSourceController};
|
|
1
|
+
import{SourceRequestController,sourceCount,sourceRevision}from"../../../internal/source-request-controller.js";import{SourceWindowController}from"../../../internal/source-window-controller.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{requireOwnDataValue}from"../../../internal/data-descriptors.js";const MAX_FIELD_UNITS=65536;function field(value,key){if(value===null||typeof value!="object")throw new TypeError("Invalid image record");return requireOwnDataValue(value,key,"Invalid image field")}function text(value,optional=!1){if(!(optional&&value===void 0)){if(typeof value!="string"||value.length>MAX_FIELD_UNITS)throw new TypeError("Invalid image text");return value}}function normalize(value){const key=text(field(value,"key"));if(!key.length)throw new TypeError("Invalid image key");const order=sourceCount(field(value,"order")),image=field(value,"value"),src=text(field(image,"src")),alt=text(field(image,"alt"),!0),caption=text(field(image,"caption"),!0),thumbnail=text(field(image,"thumbnail"),!0);return Object.freeze({key,order,value:Object.freeze({src,...alt===void 0?{}:{alt},...caption===void 0?{}:{caption},...thumbnail===void 0?{}:{thumbnail}})})}const SOURCE_THUMBNAIL_WINDOW=15;class LightboxSourceController{constructor(host,repaint){this.host=host,this.repaint=repaint,this.stripBound=!1,this.locale="",this.dirty=!0,this.transaction=0,this.requestedIndex=-1,this.count=0,this.state="empty",this.requests=new SourceRequestController(host,{channels:["image"],onReset:()=>this.clearImage()}),this.window=new SourceWindowController(host,{pageSize:1,maxRows:3,maxPages:3,maxConcurrent:1,keyOf:record=>record.key,normalize,onChange:repaint}),this.strip=new SourceWindowController(host,{pageSize:5,maxRows:25,maxPages:5,maxConcurrent:1,keyOf:record=>record.key,normalize,onChange:repaint}),host.addController(this)}clearImage(){this.requestedIndex=-1,this.pendingImage&&(this.pendingImage.onload=null,this.pendingImage.onerror=null,this.pendingImage.removeAttribute("src"),this.pendingImage=void 0),this.image=void 0,this.state=this.count?"loading":"empty"}refresh(){this.dirty=!0,this.transaction++,this.requests.refresh(),this.window.bind(void 0),this.unbindStrip(),this.repaint()}unbindStrip(){this.stripBound&&(this.stripBound=!1,this.strip.bind(void 0))}requestThumbnails(start,end){if(!(this.dirty||!this.count||!this.input)){if(!this.stripBound){try{this.strip.bind({owner:this.input,revision:sourceRevision(this.input.revision),epoch:this.requests.epoch,locale:this.locale,view:this.input.images})}catch{return}this.stripBound=!0}this.strip.requestRange(start,Math.max(start,end))}}thumbnailAt(index){if(!this.stripBound)return;const slot=this.strip.source.itemAt(index);return slot.state==="ready"?slot.value.value:void 0}update(input,locale){if(!this.dirty&&input===this.input&&locale===this.locale)return!0;const transaction=++this.transaction;if(this.input=input,this.locale=locale,this.dirty=!1,this.unbindStrip(),this.requests.refresh(),transaction!==this.transaction||(this.window.bind(void 0),transaction!==this.transaction))return!1;try{if(input!==void 0){if(input===null||typeof input!="object")throw new TypeError("Invalid image source");const revision=sourceRevision(input.revision);if(transaction!==this.transaction)return!1;const view=input.images;if(transaction!==this.transaction)return!1;const count=sourceCount(view.count);if(transaction!==this.transaction||(this.requests.setSource(input,revision),transaction!==this.transaction)||(this.window.bind({owner:input,revision,epoch:this.requests.epoch,locale,view}),transaction!==this.transaction))return!1;this.count=count}else{if(this.requests.setSource(void 0,void 0),transaction!==this.transaction)return!1;this.count=0}this.state=this.count?"loading":"empty"}catch{if(transaction!==this.transaction||(this.requests.setSource(void 0,void 0),transaction!==this.transaction)||(this.window.bind(void 0),transaction!==this.transaction))return!1;this.count=0,this.state=input===void 0?"empty":"error"}return!0}select(index){if(this.dirty||!this.count||index===this.requestedIndex||!this.host.isConnected)return;this.requests.invalidate("image"),this.clearImage(),this.requestedIndex=index,this.state="loading";const lease=this.requests.begin("image",this.locale);lease&&(this.window.requestRange(index,index+1),this.window.ensure(index).then(ready=>{if(!lease.isCurrent())return;const slot=ready?this.window.source.itemAt(index):void 0;if(slot?.state!=="ready"){this.state="error",this.repaint();return}const value=slot.value.value,src=safeMediaSrc(value.src);if(!src){this.state="error",this.repaint();return}const image=this.host.ownerDocument.createElement("img");this.pendingImage=image;const settle=loaded=>{!lease.isCurrent()||this.pendingImage!==image||(image.onload=null,image.onerror=null,this.pendingImage=void 0,this.image=loaded?Object.freeze({...value,src}):void 0,this.state=loaded?"ready":"error",this.repaint())};image.onload=()=>settle(!0),image.onerror=()=>settle(!1),image.src=src}))}retry(index){if(this.count===0){this.refresh();return}this.requestedIndex=-1,this.select(index),this.repaint()}adopted(){this.requests.adopted(),this.window.adopted(),this.refresh()}hostConnected(){this.dirty=!0,this.repaint()}hostDisconnected(){this.dirty=!0,this.clearImage()}}export{LightboxSourceController,SOURCE_THUMBNAIL_WINDOW};
|
|
@@ -10,6 +10,9 @@ readonly src:string;
|
|
|
10
10
|
* real alt text for meaningful images. */
|
|
11
11
|
readonly alt?:string;
|
|
12
12
|
/** Optional visible caption for this image, rendered in `part="caption"` below the stage.*/
|
|
13
|
-
readonly caption?:string;
|
|
13
|
+
readonly caption?:string;
|
|
14
|
+
/** Optional small image for the `with-thumbnails` strip; the strip falls back to `src`.
|
|
15
|
+
* Validated with `safeMediaSrc()` before use. */
|
|
16
|
+
readonly thumbnail?:string;}
|
|
14
17
|
/** Host-owned access to the complete ordered image collection.*/
|
|
15
18
|
export interface LyraLightboxSource{readonly revision:LyraSourceRevision;readonly images:LyraIndexedView<LyraSourceRecord<LyraLightboxImage>>;}
|
|
@@ -50,10 +50,13 @@ export interface LyraLightboxItemChangeDetail{index:number;previousIndex:number;
|
|
|
50
50
|
* who had Tabbed into the frame's viewport mid-navigation.
|
|
51
51
|
*
|
|
52
52
|
* Lifecycle: `show()` emits cancelable `lr-show` before committing `open=true`, followed by
|
|
53
|
-
* `lr-after-show`
|
|
54
|
-
* `open=false`
|
|
55
|
-
* `lr-close` with `{ reason }` after the state commits, and
|
|
56
|
-
* `lr-after-hide`
|
|
53
|
+
* `lr-after-show` once the open panel has rendered and its enter animation has finished.
|
|
54
|
+
* `hide()`/`close()` and post-render writes to `open=false` emit cancelable `lr-hide` and
|
|
55
|
+
* `lr-close-request`, followed by `lr-close` with `{ reason }` after the state commits, and
|
|
56
|
+
* `lr-after-hide` once the exit animation has finished. Under `prefers-reduced-motion` or a zero
|
|
57
|
+
* `--show-duration`/`--hide-duration` the animations finish at once, so both events follow the
|
|
58
|
+
* render directly. A transition interrupted by the opposite one emits no after-event of its own.
|
|
59
|
+
* The returned promises resolve with the after-events. A veto leaves the property and reflected
|
|
57
60
|
* attribute synchronized. Initial `open` markup is state rather than a transition and emits no
|
|
58
61
|
* lifecycle events. Removing an open instance emits non-cancelable `lr-hide`, `lr-close` with
|
|
59
62
|
* reason `unmount`, and `lr-after-hide`; removal cannot be vetoed.
|
|
@@ -63,16 +66,27 @@ export interface LyraLightboxItemChangeDetail{index:number;previousIndex:number;
|
|
|
63
66
|
* page. Items with `type="video"` play in a native `<video>` that pauses when the slide changes
|
|
64
67
|
* or the viewer closes. `with-thumbnails` adds a thumbnail strip, `without-navigation` hides the
|
|
65
68
|
* previous/next buttons (swipe and arrow keys still work), and `without-zoom` removes zooming.
|
|
66
|
-
*
|
|
69
|
+
* An item whose direct child is a `<template>` shows a copy of that template's content as its
|
|
70
|
+
* slide (see `<lr-lightbox-item>`); the copy is made while the slide is shown and placed in a
|
|
71
|
+
* `<div slot="slide-content">` the lightbox appends to itself, so page styles reach it.
|
|
72
|
+
* Content that handles its own dragging should call `preventDefault()` on `pointerdown` so a swipe
|
|
73
|
+
* does not start there.
|
|
74
|
+
*
|
|
75
|
+
* **Swiping.** In every mode, a touch or pen drag that is clearly horizontal moves the slide with
|
|
76
|
+
* the pointer. Releasing it at least 50px from where it started, toward an existing item, moves to
|
|
77
|
+
* that item and the incoming slide continues from the release point; a shorter drag, a mostly
|
|
78
|
+
* vertical one, a drag past the first or last item without `loop` (which follows the pointer with
|
|
79
|
+
* resistance), and a `pointercancel` settle the slide back into place. Directions reverse under
|
|
80
|
+
* RTL. Under `prefers-reduced-motion` the slide does not follow the pointer and the release
|
|
81
|
+
* navigates or stays without motion. A mouse never swipes, nor does a drag that starts on a
|
|
82
|
+
* control, a link, a video or a form field, or while the image is zoomed in. The open/close and
|
|
67
83
|
* slide motion use the `--show-duration`/`--hide-duration`/`--slide-gap` properties and stop under
|
|
68
84
|
* `prefers-reduced-motion`.
|
|
69
85
|
*
|
|
70
86
|
* **Scope (deliberate, not oversights):** no dot-style indicators (a textual counter scales
|
|
71
87
|
* better to photo-set sizes); no click-on-image-to-navigate (the image is already meaningfully
|
|
72
88
|
* interactive -- it focuses the zoomable frame's viewport and drives its native scroll-to-pan);
|
|
73
|
-
* no inertial
|
|
74
|
-
* items show images through the embedded pan-zoom frame, so custom `<template>` slide content is
|
|
75
|
-
* not supported.
|
|
89
|
+
* no inertial fling (only the release distance decides).
|
|
76
90
|
*
|
|
77
91
|
* When opened outside an existing native modal dialog, the modal surface uses an internal
|
|
78
92
|
* native dialog so pointer, keyboard, and focus interaction remain available without moving
|
|
@@ -95,16 +109,21 @@ export interface LyraLightboxItemChangeDetail{index:number;previousIndex:number;
|
|
|
95
109
|
* Calling `preventDefault()` keeps the lightbox open.
|
|
96
110
|
* @event lr-close - Non-cancelable accepted dismissal with `{ reason }` detail, including unmount.
|
|
97
111
|
* @event lr-show - Cancelable request fired by `show()` before `open` changes.
|
|
98
|
-
* @event lr-after-show - Fired after a successful `show()` has rendered the open panel
|
|
99
|
-
*
|
|
112
|
+
* @event lr-after-show - Fired after a successful `show()` has rendered the open panel and its
|
|
113
|
+
* enter animation has finished (immediately under reduced motion or a zero duration).
|
|
114
|
+
* @event lr-after-hide - Fired after a successful `hide()`/`close()` has rendered closed and its
|
|
115
|
+
* exit animation has finished (immediately under reduced motion or a zero duration).
|
|
100
116
|
* @event lr-index-change - Fired for `next()`/`previous()`/`goTo()` navigation, including the
|
|
101
|
-
* built-in button and keyboard paths, and when a shrinking `images` moves the
|
|
102
|
-
* fired when a consumer sets `index` directly
|
|
117
|
+
* built-in button, swipe, thumbnail and keyboard paths, and when a shrinking `images` moves the
|
|
118
|
+
* shown image. Not fired when a consumer sets `index` directly (as `<lr-carousel>` does not fire
|
|
119
|
+
* `lr-slide-change` for a direct `currentSlide` write); call `goTo()` to change the item and be
|
|
120
|
+
* notified. Source mode uses the complete logical count
|
|
103
121
|
* and emits the requested index before asynchronous image resolution. `detail: { index }` is always the rendered
|
|
104
122
|
* integer index.
|
|
105
123
|
* @event lr-item-change - Fired alongside `lr-index-change` for the same navigations, with
|
|
106
124
|
* `detail: { index, previousIndex, item, previousItem }` (items are `null` in data mode). Like
|
|
107
|
-
* `lr-index-change` it reports navigation, so writing `index` directly does not fire it
|
|
125
|
+
* `lr-index-change` it reports navigation, so writing `index` directly does not fire it, whether
|
|
126
|
+
* the lightbox is open or closed; `goTo()`, `next()` and `previous()` do.
|
|
108
127
|
* @event lr-zoom-change - Not emitted by `LyraLightbox` itself -- see the interface doc above.
|
|
109
128
|
* `detail: { zoom }`.
|
|
110
129
|
* @csspart surface - The viewer's viewport layer. Only positioned and shown while open (slotted mode).
|
|
@@ -187,7 +206,8 @@ export declare class LyraLightbox extends LyraElement<LyraLightboxEventMap>{prot
|
|
|
187
206
|
get open():boolean;set open(next:boolean);protected static readonly identityCollectionObjectProperties:readonly string[];private _imageSource?;private navigationIntent;private pendingIndexChange?;private sourceBindingCurrent;private sourceState;private readonly sourceController;
|
|
188
207
|
/** Optional host-owned full image collection. Takes precedence over images; undefined restores
|
|
189
208
|
* legacy input. Reassign, including the same source, or call requestUpdate() after mutation.
|
|
190
|
-
* Only the current image loads; at most three descriptors are retained
|
|
209
|
+
* Only the current image loads; at most three descriptors are retained (with `with-thumbnails`,
|
|
210
|
+
* a separate strip window also reads the descriptors of the 15 positions around the current one). Each key/src/alt/caption
|
|
191
211
|
* is limited to 65,536 UTF-16 units. Invalid defined sources fail closed with a retry action.
|
|
192
212
|
* index remains the requested logical index while its image loads. */
|
|
193
213
|
get imageSource():LyraLightboxSource|undefined;set imageSource(value:LyraLightboxSource|undefined);requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;private imageCount;private _images;private _imagesSource?;private _fit;
|
|
@@ -210,8 +230,10 @@ lightDismiss:boolean;
|
|
|
210
230
|
* announcement remains active so navigation is still conveyed when visual chrome is hidden.
|
|
211
231
|
* Not reflected, matching the published contract. */
|
|
212
232
|
withoutCounter:boolean;
|
|
213
|
-
/** Shows a strip of thumbnails for jumping between items
|
|
214
|
-
*
|
|
233
|
+
/** Shows a strip of thumbnails for jumping between items. Each uses the item's `thumbnail`
|
|
234
|
+
* (slotted items and `images`/`imageSource` records), else the full image. With `imageSource`
|
|
235
|
+
* the strip covers the 15 positions around the current one and reads only their descriptors;
|
|
236
|
+
* a position whose descriptor is still loading shows its number. */
|
|
215
237
|
withThumbnails:boolean;
|
|
216
238
|
/** Hides the previous/next buttons. Swiping and the arrow keys still navigate.*/
|
|
217
239
|
withoutNavigation:boolean;
|
|
@@ -241,7 +263,7 @@ get currentItem():LyraLightboxItem|undefined;private get itemMode();private get
|
|
|
241
263
|
/** Zooms the current image in by one step. A no-op for video, or with `without-zoom`.*/
|
|
242
264
|
zoomIn():void;
|
|
243
265
|
/** Zooms the current image out by one step. A no-op for video, or with `without-zoom`.*/
|
|
244
|
-
zoomOut():void;private canZoom;private toggleZoom;private onZoomChange;private pauseVideos;private onSwipeStart;private onSwipeEnd;private onSwipeCancel;private liveText;private frameEl?;private readonly lightboxInternals;private overlay?;private readonly nativeModal;private readonly modalSurface;private readonly announcements;private sourceErrorAnnounced;private sourceHasRendered;private lastSourceImage?;private announcementBaseline?;private connectionGeneration;private transitionGeneration;private readonly openRequest;private readonly captionId;private currentIndex;private syncImages;private changeTo;
|
|
266
|
+
zoomOut():void;private canZoom;private toggleZoom;private onZoomChange;private pauseVideos;private onSwipeStart;private onSwipeMove;private onSwipeEnd;private onSwipeCancel;private releaseDrag;private swipeIsForward;private hasNeighbor;private slideElement;private swipeRelease;private liveText;private frameEl?;private readonly lightboxInternals;private overlay?;private readonly nativeModal;private readonly modalSurface;private readonly announcements;private sourceErrorAnnounced;private sourceHasRendered;private lastSourceImage?;private announcementBaseline?;private connectionGeneration;private transitionGeneration;private readonly openRequest;private readonly captionId;private currentIndex;private syncImages;private changeTo;
|
|
245
267
|
/** Advances to the next image, respecting `loop`.*/
|
|
246
268
|
next():void;
|
|
247
269
|
/** Moves to the previous image, respecting `loop`.*/
|
|
@@ -250,7 +272,8 @@ previous():void;
|
|
|
250
272
|
* clamping or loop wrapping, so `lr-index-change.detail.index` is always the rendered
|
|
251
273
|
* integer index. Non-finite values are no-ops. */
|
|
252
274
|
goTo(index:number):void;
|
|
253
|
-
/** Request opening, then resolve once the open panel is rendered
|
|
275
|
+
/** Request opening, then resolve once the open panel is rendered and its enter animation has
|
|
276
|
+
* finished (immediately under reduced motion or a zero duration). */
|
|
254
277
|
show():Promise<void>;
|
|
255
278
|
/** Close with the standard API reason.*/
|
|
256
279
|
hide():Promise<void>;
|
|
@@ -260,4 +283,4 @@ hide():Promise<void>;
|
|
|
260
283
|
* `'backdrop'`/`'close-button'`; a consumer's own close affordance (e.g. an `actions`-slotted
|
|
261
284
|
* button) should call this directly with its own reason string.
|
|
262
285
|
*/
|
|
263
|
-
close(reason?:LyraLightboxCloseReason):Promise<void>;private closeFrom;private cancelTransitionAnimations;private settleAnimations;private surfaceSpec;private startSurfaceAnimations;private playExit;private animateSlide;private markMorphing;private applyOpenState;private syncOpenAttribute;private updateLiveRegion;private captureAnnouncementBaseline;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;private activateOverlay;private deactivateOverlay;private onBackdropClick;private onCloseButtonClick;private onPanelKeyDown;constructor();private renderThumbnails;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-lightbox':LyraLightbox;}}
|
|
286
|
+
close(reason?:LyraLightboxCloseReason):Promise<void>;private closeFrom;private cancelTransitionAnimations;private settleAnimations;private surfaceSpec;private startSurfaceAnimations;private playExit;private animateSlide;private customSlide?;private syncCustomSlide;private removeCustomSlide;private markMorphing;private applyOpenState;private syncOpenAttribute;private updateLiveRegion;private captureAnnouncementBaseline;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;private activateOverlay;private deactivateOverlay;private onBackdropClick;private onCloseButtonClick;private onPanelKeyDown;constructor();private thumbnailRange;private renderThumbnails;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-lightbox':LyraLightbox;}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{tag}from"../../../internal/prefix.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{ModalOpenRequest}from"../../../internal/modal-open-request.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{keyed}from"lit/directives/keyed.js";import{ifDefined}from"lit/directives/if-defined.js";import{live}from"lit/directives/live.js";import{property,query,state}from"lit/decorators.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isAccessibilityVisible,nextId,srOnly}from"../../../internal/a11y.js";import{closeIcon,chevronIcon,minusIcon,playIcon,plusIcon}from"../../../internal/icons.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{shouldIgnoreNavigationKey}from"../../../internal/list-navigation.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./lightbox.styles.js";import{LightboxSourceController}from"./lightbox-source.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{isElement}from"../../../internal/rendered-tree-traversal.js";import{repairControlFocusOnUpdate}from"../../../internal/control-focus-repair.js";import{trackScrollRegions}from"../../../internal/scroll-region.js";import{blankNumberConverter}from"../../../internal/converters.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{setCustomState}from"../../../internal/custom-states.js";import{LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_lightboxImagePosition,LYRA_DEFAULT_lightboxLabel}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_close,LYRA_DEFAULT_loading,LYRA_DEFAULT_next,LYRA_DEFAULT_previous,LYRA_DEFAULT_retry,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";const MAX_LIGHTBOX_IMAGES=1e4,EMPTY_LIGHTBOX_IMAGES=/* @__PURE__ */(()=>Object.freeze([]))();function snapshotLightboxImages(value){try{if(!Array.isArray(value))return EMPTY_LIGHTBOX_IMAGES;const count=Math.min(value.length,MAX_LIGHTBOX_IMAGES),images=[];for(let index=0;index<count;index++)try{const candidate=value[index];if(typeof candidate!="object"||candidate===null)continue;const src=candidate.src;if(typeof src!="string")continue;const alt=candidate.alt,caption=candidate.caption;images.push(Object.freeze({src,...typeof alt=="string"?{alt}:{},...typeof caption=="string"?{caption}:{}}))}catch{}return images.length?Object.freeze(images):EMPTY_LIGHTBOX_IMAGES}catch{return EMPTY_LIGHTBOX_IMAGES}}function setItemViewerState(item,name,present){item.setViewerState?.(name,present)}const SWIPE_DISTANCE=50,SWIPE_SLOP=10,MAX_THUMBNAILS=200,SHOW_DURATION_PROPERTY="--show-duration",HIDE_DURATION_PROPERTY="--hide-duration";function queueDocumentMicrotask(ownerDocument,callback){const ownerWindow=ownerDocument.defaultView;if(ownerWindow){ownerWindow.queueMicrotask(callback);return}Promise.resolve().then(callback)}class LyraLightbox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,lightboxImagePosition:LYRA_DEFAULT_lightboxImagePosition,lightboxLabel:LYRA_DEFAULT_lightboxLabel,loading:LYRA_DEFAULT_loading,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,retry:LYRA_DEFAULT_retry,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-item-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-item-change":Object.freeze(["item","previousItem"])})}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,srOnly,styles]}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted(),this.hostDescription.adopted(),this.sourceController.adopted()}get open(){return this._open}set open(next){const normalized=!!next;if(!this.openRequest.coalesce(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}static{this.identityCollectionObjectProperties=Object.freeze(["imageSource"])}get imageSource(){return this._imageSource}set imageSource(value){const previous=this._imageSource;this.navigationIntent++,this.sourceBindingCurrent=!1,this._imageSource=value,this.sourceController?.refresh(),this.frameEl&&(this.frameEl.src=""),this.requestUpdate("imageSource",previous)}requestUpdate(...args){args[0]===void 0&&this._imageSource!==void 0&&(this.navigationIntent++,this.sourceBindingCurrent=!1,this.sourceController?.refresh(),this.frameEl&&(this.frameEl.src="")),super.requestUpdate(...args)}imageCount(){return this.imageSource===void 0?this.activeImages.length:this.sourceController.count}get images(){return this._images}set images(value){if(value===this._imagesSource||value===this._images)return;this._imagesSource=value;const old=this._images;this._images=snapshotLightboxImages(value),this.requestUpdate("images",old)}get index(){return this._index}set index(value){this.navigationIntent++;const previous=this._index;this._index=value,value!==previous&&this.imageSource!==void 0&&(this.sourceController?.select(this.currentIndex()),this.frameEl&&(this.frameEl.src="")),this.requestUpdate("index",previous)}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value,"actual"),this.requestUpdate("fit",old)}get items(){return this.collectItems()}get currentItem(){return this.itemMode?this.itemRecords[this.currentIndex()]?.element:void 0}get itemMode(){return this.imageSource===void 0&&this._images.length===0&&this.itemRecords.length>0}get activeImages(){return this.itemMode?this.itemImages:this._images}collectItems(){const own=tag("lightbox");return Array.from(this.querySelectorAll(tag("lightbox-item"))).filter(element=>element.closest(own)===this)}itemChanged(){this.syncItems()}syncItems(){const records=[],images=[];for(const element of this.collectItems()){const raw=element,src=raw.mediaSrc??safeMediaSrc(element.getAttribute("src"))??"";if(!src)continue;const type=(raw.type??element.getAttribute("type"))==="video"?"video":"image",alt=raw.resolvedAlt??element.getAttribute("alt")??"",caption=raw.captionText??element.getAttribute("caption")??"",width=Number(raw.width??element.getAttribute("width")),height=Number(raw.height??element.getAttribute("height"));records.push({element,type,thumbnail:raw.thumbnailSrc??safeMediaSrc(element.getAttribute("thumbnail"))??"",...Number.isFinite(width)&&width>0?{width}:{},...Number.isFinite(height)&&height>0?{height}:{}}),images.push(Object.freeze({src,alt,...caption?{caption}:{}}))}const signature=records.map((record,i)=>`${i}\0${images[i].src}\0${images[i].alt}\0${images[i].caption??""}\0${record.type}\0${record.thumbnail}\0${record.width??""}x${record.height??""}`).join(""),sameElements=records.length===this.itemRecords.length&&records.every((record,i)=>record.element===this.itemRecords[i].element);signature===this.lastItemSignature&&sameElements||(this.lastItemSignature=signature,this.itemRecords=Object.freeze(records),this.itemImages=images.length?Object.freeze(images):EMPTY_LIGHTBOX_IMAGES,this.itemsVersion++)}zoomIn(){this.canZoom()&&this.frameEl?.zoomIn()}zoomOut(){this.canZoom()&&this.frameEl?.zoomOut()}canZoom(){return!this.withoutZoom&&this.itemRecords[this.currentIndex()]?.type!=="video"}pauseVideos(){if(this.hasUpdated)for(const video of this.renderRoot.querySelectorAll("video"))video.pause()}currentIndex(){const count=this.imageCount();return count===0?0:finiteCount(this.index,0,count-1)}syncImages(){const current=this.currentIndex();this.index!==current&&(this.index=current)}changeTo(index){const count=this.imageCount();if(count===0||!Number.isFinite(index))return;const requested=finiteInteger(index,0),next=this.loop?(requested%count+count)%count:Math.min(count-1,Math.max(0,requested));next!==this.currentIndex()&&(this.pendingIndexChange=this.navigationIntent+1,this.index=next)}next(){this.changeTo(this.currentIndex()+1)}previous(){this.changeTo(this.currentIndex()-1)}goTo(index){this.changeTo(index)}async show(){if(this.openRequest.coalesce(!0)||this._open)return;this.openRequest.begin(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequest.superseded(!0);if(this.openRequest.finish(),prevented||superseded){this.syncOpenAttribute();return}this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.applyOpenState(!0);const generation=++this.transitionGeneration;await this.updateComplete,generation===this.transitionGeneration&&this._open&&this.emit("lr-after-show",null)}hide(){return this.close("api")}async close(reason="api"){return this.closeFrom(reason,this)}async closeFrom(reason,source){if(this.openRequest.coalesce(!1)||!this._open)return;if(this.openRequest.begin(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequest.superseded(!1)){this.openRequest.finish(),this.syncOpenAttribute();return}if(this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented||this.openRequest.superseded(!1)){this.openRequest.finish(),this.syncOpenAttribute();return}this.openRequest.finish(),this.cancelTransitionAnimations(),this.isConnected&&this.setAttribute("data-closing",""),this.pauseVideos(),this.applyOpenState(!1);const generation=++this.transitionGeneration;if(this.emit("lr-close",{reason}),await this.updateComplete,generation!==this.transitionGeneration||this._open){this._open&&this.removeAttribute("data-closing");return}const exit=this.playExit();this.emit("lr-after-hide",null),exit.then(()=>{generation===this.transitionGeneration&&!this._open&&this.removeAttribute("data-closing")})}cancelTransitionAnimations(){for(const animation of this.transitionAnimations)animation.cancel();this.transitionAnimations=[]}async settleAnimations(){const running=this.transitionAnimations;await Promise.all(running.map(animation=>animation.finished.catch(()=>{}))),this.transitionAnimations===running&&(this.transitionAnimations=[])}surfaceSpec(showing,panel){const offset="translateY(calc(-1 * var(--lr-size-0-5rem)))";return{keyframes:panel?showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}]:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:[showing?SHOW_DURATION_PROPERTY:HIDE_DURATION_PROPERTY,"--lr-lightbox-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}}startSurfaceAnimations(showing){const panel=this.renderRoot.querySelector('[part~="panel"]'),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),direction=this.effectiveDirection;return[panel&&animateRegistered(this,panel,showing?"lightbox.show":"lightbox.hide",direction,this.surfaceSpec(showing,!0)),backdrop&&animateRegistered(this,backdrop,showing?"lightbox.overlay.show":"lightbox.overlay.hide",direction,this.surfaceSpec(showing,!1))].filter(animation=>animation!=null)}async playExit(){!this.isConnected||this.nativeModal.requested||(this.cancelTransitionAnimations(),this.transitionAnimations=this.startSurfaceAnimations(!1),this.markMorphing(this.renderedRecord?.element??this.currentItem,this.transitionAnimations),await this.settleAnimations())}animateSlide(forward){const slide=this.renderRoot.querySelector('[part="slide"]');if(!slide)return;const gap="var(--slide-gap, var(--lr-lightbox-slide-gap, var(--lr-space-l)))",from=sign2=>`translateX(calc(${sign2} * (100% + ${gap})))`,spec=sign2=>({keyframes:[{opacity:0,transform:from(sign2)},{opacity:1,transform:"translateX(0)"}],rtlKeyframes:[{opacity:0,transform:from(-sign2)},{opacity:1,transform:"translateX(0)"}],durationProperties:["--lr-lightbox-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}),sign=forward?1:-1,animation=animateRegistered(this,slide,forward?"lightbox.slide.next":"lightbox.slide.previous",this.effectiveDirection,spec(sign));animation&&animation.finished.catch(()=>{})}markMorphing(item,animations){const generation=++this.morphGeneration;this.morphingItem&&setItemViewerState(this.morphingItem,"morphing",!1),this.morphingItem=void 0,!(!item||animations.length===0)&&(this.morphingItem=item,setItemViewerState(item,"morphing",!0),Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))).then(()=>{generation===this.morphGeneration&&(setItemViewerState(item,"morphing",!1),this.morphingItem=void 0)}))}applyOpenState(next){const old=this._open;this._open=next,this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}updateLiveRegion(){const count=this.imageCount(),formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveText=count===0?"":this.localize("lightboxImagePosition",void 0,{index:formatter.format(this.currentIndex()+1),total:formatter.format(count)})}captureAnnouncementBaseline(){this.announcementBaseline={index:this.currentIndex(),images:this.activeImages,source:this.imageSource}}willUpdate(changed){if(super.willUpdate(changed),this.sourceBindingCurrent=this.sourceController.update(this.imageSource,this.effectiveLocale),this.toggleAttribute("data-items",this.itemMode),(changed.has("index")||changed.has("open"))&&this.pauseVideos(),(changed.has("index")||changed.has("imageSource")||changed.has("itemsVersion"))&&this.zoomLevel!==1&&(this.zoomLevel=1),this.sourceBindingCurrent&&(changed.has("itemsVersion")||changed.has("images")||changed.has("index")||changed.has("imageSource")||changed.has("sourceState"))){const index=changed.has("index")?void 0:this.index,intent=this.navigationIntent+1;this.syncImages(),index!==void 0&&this.index!==index&&this.navigationIntent===intent&&this.sourceBindingCurrent&&(this.pendingIndexChange=intent)}if(this.sourceBindingCurrent&&this.imageSource!==void 0&&this.sourceController.select(this.currentIndex()),this.sourceBindingCurrent||queueDocumentMicrotask(this.ownerDocument,()=>{this.isConnected&&this.sourceState++}),this.sourceBindingCurrent&&(changed.has("index")||changed.has("itemsVersion")||changed.has("images")||changed.has("imageSource")||changed.has("sourceState")||changed.has("strings")||changed.has("locale"))&&this.updateLiveRegion(),changed.has("open"))if(this.open)this.modalSurface.open(()=>this.activateOverlay());else{const hadOverlay=this.overlay!==void 0;this.modalSurface.close(hadOverlay,()=>this.deactivateOverlay(),()=>!this.open)}}updated(changed){super.updated(changed),!(this.announcementBaseline?.index===this.currentIndex()&&this.announcementBaseline.images===this.activeImages&&this.announcementBaseline.source===this.imageSource)&&this.sourceBindingCurrent&&this.open&&this.liveText!==""&&isAccessibilityVisible(this)&&(changed.has("index")||changed.has("itemsVersion")||changed.has("images")||changed.has("imageSource"))&&this.announcements.announcePolite(this.liveText);const sourceError=this.sourceBindingCurrent&&this.imageSource!==void 0&&this.sourceController.state==="error";sourceError||(this.sourceErrorAnnounced=!1),sourceError&&!this.sourceErrorAnnounced&&this.sourceHasRendered&&this.open&&isAccessibilityVisible(this)&&(this.sourceErrorAnnounced=!0,this.announcements.announcePolite(this.localize("imageViewerFailedToLoad"))),this.sourceHasRendered=!0,this.isConnected&&this.sourceBindingCurrent&&this.captureAnnouncementBaseline(),changed.has("open")&&this.open&&(this.modalSurface.show(),this.overlay?.focusInitial());let currentSourceChanged=!1;if(changed.has("images")){const previousImages=changed.get("images"),previousIndex=changed.has("index")?changed.get("index")??0:this.index;currentSourceChanged=previousImages?.[previousImages.length>0?finiteCount(previousIndex,0,previousImages.length-1):0]?.src!==this.images[this.currentIndex()]?.src}const sourceImage=this.imageSource===void 0?void 0:this.sourceController.image;currentSourceChanged||=changed.has("imageSource")||sourceImage!==void 0&&sourceImage!==this.lastSourceImage,this.lastSourceImage=sourceImage;const shownSrc=this.imageSource===void 0?this.activeImages[this.currentIndex()]?.src??"":"";this.itemMode&&changed.has("itemsVersion")&&shownSrc!==this.lastShownSrc&&(currentSourceChanged=!0),this.lastShownSrc=shownSrc,this.open&&(changed.has("index")||currentSourceChanged)&&this.frameEl?.resetView();const current=this.currentIndex(),record=this.itemMode?this.itemRecords[current]:void 0;this.open&&this.firstUpdateDone&&changed.has("index")&&this.renderedIndex!==current&&this.animateSlide(this.effectiveDirection==="rtl"?current<this.renderedIndex:current>this.renderedIndex),changed.has("open")&&this.open&&this.firstUpdateDone&&(this.cancelTransitionAnimations(),this.transitionAnimations=this.startSurfaceAnimations(!0),this.markMorphing(record?.element,this.transitionAnimations));for(const item of this.itemRecords){const active=this.open&&item===record;item.element.toggleAttribute("data-active",active),setItemViewerState(item.element,"active",active)}setCustomState(this.lightboxInternals,"open",this.open),setCustomState(this.lightboxInternals,"zoomed",this.zoomLevel>1);const intent=this.pendingIndexChange;this.pendingIndexChange=void 0,intent===this.navigationIntent&&(this.emit("lr-index-change",{index:this.index}),this.emit("lr-item-change",{index:this.index,previousIndex:this.renderedIndex,item:record?.element??null,previousItem:this.renderedRecord?.element??null})),this.renderedIndex=current,this.renderedRecord=record,this.firstUpdateDone=!0}connectedCallback(){super.connectedCallback();const generation=++this.connectionGeneration,connectionDocument=this.ownerDocument;this.addEventListener("click",this.onHostClick),this.syncItems(),typeof MutationObserver=="function"&&(this.itemObserver?.disconnect(),this.itemObserver=new MutationObserver(()=>this.syncItems()),this.itemObserver.observe(this,{childList:!0,subtree:!0})),this.captureAnnouncementBaseline(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),queueDocumentMicrotask(connectionDocument,()=>{this.connectionGeneration===generation&&this.ownerDocument===connectionDocument&&this.isConnected&&this.open&&(this.modalSurface.show(),this.overlay?.focusInitial())}))}disconnectedCallback(){const generation=++this.connectionGeneration,connectionDocument=this.ownerDocument;this.announcementBaseline=void 0,this.sourceErrorAnnounced=!1,this.sourceHasRendered=!1,this.lastSourceImage=void 0,this.removeEventListener("click",this.onHostClick),this.itemObserver?.disconnect(),this.itemObserver=void 0,this.swipe=void 0,this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),super.disconnectedCallback(),this.modalSurface.disconnect(),this.overlay?.suspend(),this.open&&queueDocumentMicrotask(connectionDocument,()=>{this.connectionGeneration===generation&&this.ownerDocument===connectionDocument&&!this.isConnected&&this.open&&(this.transitionGeneration++,this.emit("lr-hide",{source:this}),this.applyOpenState(!1),this.emit("lr-close",{reason:"unmount"}),this.emit("lr-after-hide",null))})}activateOverlay(){this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part~="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.closeFrom("escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part="backdrop"]')??this;this.closeFrom("backdrop",backdrop)},preferredInitialFocus:()=>this.shadowRoot?.querySelector('[part="close-button"]')??null,lockScroll:!0,suspendWhenUnrendered:!0}))}deactivateOverlay(){this.overlay?.deactivate(),this.overlay=void 0}constructor(){super(),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector(this.nativeModal.requested?"dialog[data-native-modal-carrier]":'[part~="panel"][role="dialog"]')),this._open=!1,this.navigationIntent=0,this.sourceBindingCurrent=!0,this.sourceState=0,this.sourceController=new LightboxSourceController(this,()=>{this.sourceState++}),this._images=EMPTY_LIGHTBOX_IMAGES,this._fit="actual",this._index=0,this.loop=!1,this.lightDismiss=!1,this.withoutCounter=!1,this.withThumbnails=!1,this.withoutNavigation=!1,this.withoutZoom=!1,this.label="",this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this.accessibleLabel=null,this.slotPresence=new SlotPresenceController(this),this.itemsVersion=0,this.zoomLevel=1,this.itemRecords=[],this.itemImages=EMPTY_LIGHTBOX_IMAGES,this.renderedIndex=0,this.lastShownSrc="",this.firstUpdateDone=!1,this.transitionAnimations=[],this.morphGeneration=0,this.lastItemSignature="",this.onHostClick=event=>{if(event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey||!this.itemMode)return;const itemTag=tag("lightbox-item"),item=event.composedPath().find(node=>isElement(node)&&node.localName===itemTag);if(!item||item.closest(tag("lightbox"))!==this)return;const position=this.itemRecords.findIndex(record=>record.element===item);position<0||(event.preventDefault(),this.index=position,this.show())},this.toggleZoom=()=>{this.zoomLevel>1?this.frameEl?.resetZoom():this.zoomIn()},this.onZoomChange=event=>{const zoom=event.detail?.zoom;typeof zoom=="number"&&Number.isFinite(zoom)&&(this.zoomLevel=zoom)},this.onSwipeStart=event=>{event.pointerType==="mouse"||!event.isPrimary||this.imageCount()<2||this.zoomLevel>1||event.composedPath().some(node=>isElement(node)&&node.matches("video, button, a[href]"))||(this.swipe={id:event.pointerId,x:event.clientX,y:event.clientY})},this.onSwipeEnd=event=>{const swipe=this.swipe;if(!swipe||swipe.id!==event.pointerId)return;this.swipe=void 0;const dx=event.clientX-swipe.x,dy=event.clientY-swipe.y;if(Math.abs(dx)<SWIPE_DISTANCE||Math.abs(dx)<Math.abs(dy)*1.2||Math.abs(dx)<SWIPE_SLOP)return;(this.effectiveDirection==="rtl"?dx>0:dx<0)?this.next():this.previous()},this.onSwipeCancel=event=>{this.swipe?.id===event.pointerId&&(this.swipe=void 0)},this.liveText="",this.lightboxInternals=attachInternalsSafely(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.closeFrom("escape",this.renderRoot.querySelector('[part~="panel"]')??this)},onUnexpectedClose:()=>{this.hide().then(()=>{this.open&&this.modalSurface.show()})}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal),this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.sourceErrorAnnounced=!1,this.sourceHasRendered=!1,this.connectionGeneration=0,this.transitionGeneration=0,this.openRequest=new ModalOpenRequest,this.captionId=nextId("lightbox-caption"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part="close-button"]')??this;this.closeFrom("close-button",button)},this.onPanelKeyDown=event=>{if(event.defaultPrevented||shouldIgnoreNavigationKey(event)||event.shiftKey)return;for(const target of event.composedPath()){if(target===this)break;if(isElement(target)&&target.getRootNode()!==this.shadowRoot&&target.matches('a[href], button, [role="button"], [role="link"]'))return}if(event.composedPath().some(node=>isElement(node)&&node.localName==="video")||keyEventOwnedByInnerControl(event,{container:this,ownerTag:tag("pan-zoom")}))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey?(event.preventDefault(),this.previous()):event.key==="Home"?(event.preventDefault(),this.goTo(0)):event.key==="End"&&(event.preventDefault(),this.goTo(this.imageCount()-1))},repairControlFocusOnUpdate(this,()=>[this.renderRoot.querySelector('[part="close-button"]'),this.renderRoot.querySelector('[part~="frame"]')]),trackScrollRegions(this,()=>{const el=this.renderRoot.querySelector('[part="caption"]');return[el&&{el,role:!1}]})}renderThumbnails(count,current){if(!this.withThumbnails||count<2||this.imageSource!==void 0)return nothing;const half=Math.floor(MAX_THUMBNAILS/2),start=Math.max(0,Math.min(current-half,count-MAX_THUMBNAILS)),end=Math.min(count,start+MAX_THUMBNAILS),formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),thumbs=[];for(let i=start;i<end;i++){const image=this.activeImages[i];if(!image)continue;const record=this.itemMode?this.itemRecords[i]:void 0,source=safeMediaSrc(record?.thumbnail||(record?.type==="video"?"":image.src)),active=i===current,position=this.localize("lightboxImagePosition",void 0,{index:formatter.format(i+1),total:formatter.format(count)});thumbs.push(html`<button type="button" part=${active?"thumbnail thumbnail-active":"thumbnail"} aria-label=${image.alt||position} aria-current=${active?"true":"false"} @click=${()=>this.goTo(i)} >${source?html`<img src=${source} alt="" loading="lazy" decoding="async" />`:playIcon()}</button>`)}return html`<div part="thumbnails">${thumbs}</div>`}render(){const count=this.imageCount(),current=this.currentIndex(),image=this.imageSource===void 0?count>0?this.activeImages[current]:void 0:this.sourceController.image,record=this.itemMode?this.itemRecords[current]:void 0,isVideo=record?.type==="video",mediaSrc=isVideo?safeMediaSrc(image?.src)??"":"",sourceState=this.imageSource===void 0?void 0:this.sourceController.state,label=this.accessibleLabel?.trim()?this.accessibleLabel:(this.label??"").trim()?this.label:this.localize("lightboxLabel"),hasCaption=!!image?.caption,formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),positionText=count>0?this.localize("lightboxImagePosition",void 0,{index:formatter.format(current+1),total:formatter.format(count)}):"",zoomed=this.zoomLevel>1,showZoom=this.itemMode&&!this.withoutZoom&&!isVideo&&count>0;return html`<slot></slot><div part="surface">${this.nativeModal.render(html`
|
|
1
|
+
import{__decorate}from"tslib";import{tag}from"../../../internal/prefix.js";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{ModalOpenRequest}from"../../../internal/modal-open-request.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{keyed}from"lit/directives/keyed.js";import{ifDefined}from"lit/directives/if-defined.js";import{live}from"lit/directives/live.js";import{property,query,state}from"lit/decorators.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isAccessibilityVisible,nextId,srOnly}from"../../../internal/a11y.js";import{closeIcon,chevronIcon,minusIcon,playIcon,plusIcon}from"../../../internal/icons.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{shouldIgnoreNavigationKey}from"../../../internal/list-navigation.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./lightbox.styles.js";import{LightboxSourceController,SOURCE_THUMBNAIL_WINDOW}from"./lightbox-source.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{isElement}from"../../../internal/rendered-tree-traversal.js";import{repairControlFocusOnUpdate}from"../../../internal/control-focus-repair.js";import{trackScrollRegions}from"../../../internal/scroll-region.js";import{blankNumberConverter}from"../../../internal/converters.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{setCustomState}from"../../../internal/custom-states.js";import{LYRA_DEFAULT_imageViewerFailedToLoad,LYRA_DEFAULT_lightboxImagePosition,LYRA_DEFAULT_lightboxLabel}from"../../../internal/default-strings/media.generated.js";import{LYRA_DEFAULT_close,LYRA_DEFAULT_loading,LYRA_DEFAULT_next,LYRA_DEFAULT_previous,LYRA_DEFAULT_retry,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";const MAX_LIGHTBOX_IMAGES=1e4,EMPTY_LIGHTBOX_IMAGES=/* @__PURE__ */(()=>Object.freeze([]))();function snapshotLightboxImages(value){try{if(!Array.isArray(value))return EMPTY_LIGHTBOX_IMAGES;const count=Math.min(value.length,MAX_LIGHTBOX_IMAGES),images=[];for(let index=0;index<count;index++)try{const candidate=value[index];if(typeof candidate!="object"||candidate===null)continue;const src=candidate.src;if(typeof src!="string")continue;const alt=candidate.alt,caption=candidate.caption,thumbnail=candidate.thumbnail;images.push(Object.freeze({src,...typeof alt=="string"?{alt}:{},...typeof caption=="string"?{caption}:{},...typeof thumbnail=="string"?{thumbnail}:{}}))}catch{}return images.length?Object.freeze(images):EMPTY_LIGHTBOX_IMAGES}catch{return EMPTY_LIGHTBOX_IMAGES}}function setItemViewerState(item,name,present){item.setViewerState?.(name,present)}const SWIPE_DISTANCE=50,SWIPE_SLOP=10,SWIPE_EDGE_RESISTANCE=.3,CUSTOM_SLIDE_SLOT="slide-content",CUSTOM_SLIDE_ATTRIBUTE="data-lightbox-slide",SWIPE_EXEMPT='video, button, a[href], input, select, textarea, [contenteditable]:not([contenteditable="false"])',MAX_THUMBNAILS=200,SHOW_DURATION_PROPERTY="--show-duration",HIDE_DURATION_PROPERTY="--hide-duration";function queueDocumentMicrotask(ownerDocument,callback){const ownerWindow=ownerDocument.defaultView;if(ownerWindow){ownerWindow.queueMicrotask(callback);return}Promise.resolve().then(callback)}class LyraLightbox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,imageViewerFailedToLoad:LYRA_DEFAULT_imageViewerFailedToLoad,lightboxImagePosition:LYRA_DEFAULT_lightboxImagePosition,lightboxLabel:LYRA_DEFAULT_lightboxLabel,loading:LYRA_DEFAULT_loading,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,retry:LYRA_DEFAULT_retry,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-item-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-item-change":Object.freeze(["item","previousItem"])})}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,srOnly,styles]}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted(),this.hostDescription.adopted(),this.sourceController.adopted()}get open(){return this._open}set open(next){const normalized=!!next;if(!this.openRequest.coalesce(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}static{this.identityCollectionObjectProperties=Object.freeze(["imageSource"])}get imageSource(){return this._imageSource}set imageSource(value){const previous=this._imageSource;this.navigationIntent++,this.sourceBindingCurrent=!1,this._imageSource=value,this.sourceController?.refresh(),this.frameEl&&(this.frameEl.src=""),this.requestUpdate("imageSource",previous)}requestUpdate(...args){args[0]===void 0&&this._imageSource!==void 0&&(this.navigationIntent++,this.sourceBindingCurrent=!1,this.sourceController?.refresh(),this.frameEl&&(this.frameEl.src="")),super.requestUpdate(...args)}imageCount(){return this.imageSource===void 0?this.activeImages.length:this.sourceController.count}get images(){return this._images}set images(value){if(value===this._imagesSource||value===this._images)return;this._imagesSource=value;const old=this._images;this._images=snapshotLightboxImages(value),this.requestUpdate("images",old)}get index(){return this._index}set index(value){this.navigationIntent++;const previous=this._index;this._index=value,value!==previous&&this.imageSource!==void 0&&(this.sourceController?.select(this.currentIndex()),this.frameEl&&(this.frameEl.src="")),this.requestUpdate("index",previous)}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value,"actual"),this.requestUpdate("fit",old)}get items(){return this.collectItems()}get currentItem(){return this.itemMode?this.itemRecords[this.currentIndex()]?.element:void 0}get itemMode(){return this.imageSource===void 0&&this._images.length===0&&this.itemRecords.length>0}get activeImages(){return this.itemMode?this.itemImages:this._images}collectItems(){const own=tag("lightbox");return Array.from(this.querySelectorAll(tag("lightbox-item"))).filter(element=>element.closest(own)===this&&!element.closest(`[${CUSTOM_SLIDE_ATTRIBUTE}]`))}itemChanged(){this.syncItems()}syncItems(){const records=[],images=[];for(const element of this.collectItems()){const raw=element,src=raw.mediaSrc??safeMediaSrc(element.getAttribute("src"))??"",template=raw.slideTemplate??element.querySelector(":scope > template")??void 0;if(!src&&!template)continue;const type=template?"custom":(raw.type??element.getAttribute("type"))==="video"?"video":"image",alt=raw.resolvedAlt??element.getAttribute("alt")??"",caption=raw.captionText??element.getAttribute("caption")??"",width=Number(raw.width??element.getAttribute("width")),height=Number(raw.height??element.getAttribute("height"));records.push({element,type,...template?{template}:{},thumbnail:raw.thumbnailSrc??safeMediaSrc(element.getAttribute("thumbnail"))??"",...Number.isFinite(width)&&width>0?{width}:{},...Number.isFinite(height)&&height>0?{height}:{}}),images.push(Object.freeze({src,alt,...caption?{caption}:{}}))}const signature=records.map((record,i)=>`${i}\0${images[i].src}\0${images[i].alt}\0${images[i].caption??""}\0${record.type}\0${record.thumbnail}\0${record.width??""}x${record.height??""}`).join(""),sameElements=records.length===this.itemRecords.length&&records.every((record,i)=>record.element===this.itemRecords[i].element&&record.template===this.itemRecords[i].template);signature===this.lastItemSignature&&sameElements||(this.lastItemSignature=signature,this.itemRecords=Object.freeze(records),this.itemImages=images.length?Object.freeze(images):EMPTY_LIGHTBOX_IMAGES,this.itemsVersion++)}zoomIn(){this.canZoom()&&this.frameEl?.zoomIn()}zoomOut(){this.canZoom()&&this.frameEl?.zoomOut()}canZoom(){const type=this.itemMode?this.itemRecords[this.currentIndex()]?.type:void 0;return!this.withoutZoom&&type!=="video"&&type!=="custom"}pauseVideos(){if(this.hasUpdated)for(const video of this.renderRoot.querySelectorAll("video"))video.pause()}releaseDrag(settle){const swipe=this.swipe;this.swipe=void 0;const slide=this.slideElement();if(!slide||!slide.hasAttribute("data-dragging"))return;const from=slide.style.transform;if(slide.style.removeProperty("transform"),slide.removeAttribute("data-dragging"),!settle||!swipe?.dragging||!from)return;const animation=animateRegistered(this,slide,"lightbox.slide.return",this.effectiveDirection,{keyframes:[{transform:from},{transform:"translateX(0)"}],durationProperties:["--lr-lightbox-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]});animation&&animation.finished.catch(()=>{})}swipeIsForward(dx){return this.effectiveDirection==="rtl"?dx>0:dx<0}hasNeighbor(forward){const count=this.imageCount();if(count<2)return!1;if(this.loop)return!0;const current=this.currentIndex();return forward?current<count-1:current>0}slideElement(){return this.hasUpdated?this.renderRoot.querySelector('[part="slide"]'):null}currentIndex(){const count=this.imageCount();return count===0?0:finiteCount(this.index,0,count-1)}syncImages(){const current=this.currentIndex();this.index!==current&&(this.index=current)}changeTo(index){const count=this.imageCount();if(count===0||!Number.isFinite(index))return;const requested=finiteInteger(index,0),next=this.loop?(requested%count+count)%count:Math.min(count-1,Math.max(0,requested));next!==this.currentIndex()&&(this.pendingIndexChange=this.navigationIntent+1,this.index=next)}next(){this.changeTo(this.currentIndex()+1)}previous(){this.changeTo(this.currentIndex()-1)}goTo(index){this.changeTo(index)}async show(){if(this.openRequest.coalesce(!0)||this._open)return;this.openRequest.begin(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequest.superseded(!0);if(this.openRequest.finish(),prevented||superseded){this.syncOpenAttribute();return}this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),this.applyOpenState(!0);const generation=++this.transitionGeneration;await this.updateComplete,!(generation!==this.transitionGeneration||!this._open)&&(await this.settleAnimations(),generation===this.transitionGeneration&&this._open&&this.emit("lr-after-show",null))}hide(){return this.close("api")}async close(reason="api"){return this.closeFrom(reason,this)}async closeFrom(reason,source){if(this.openRequest.coalesce(!1)||!this._open)return;if(this.openRequest.begin(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequest.superseded(!1)){this.openRequest.finish(),this.syncOpenAttribute();return}if(this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented||this.openRequest.superseded(!1)){this.openRequest.finish(),this.syncOpenAttribute();return}this.openRequest.finish(),this.cancelTransitionAnimations(),this.isConnected&&this.setAttribute("data-closing",""),this.pauseVideos(),this.applyOpenState(!1);const generation=++this.transitionGeneration;if(this.emit("lr-close",{reason}),await this.updateComplete,generation!==this.transitionGeneration||this._open){this._open&&this.removeAttribute("data-closing");return}await this.playExit(),!(generation!==this.transitionGeneration||this._open)&&(this.removeAttribute("data-closing"),this.syncCustomSlide(),this.emit("lr-after-hide",null))}cancelTransitionAnimations(){for(const animation of this.transitionAnimations)animation.cancel();this.transitionAnimations=[]}async settleAnimations(){const running=this.transitionAnimations;await Promise.all(running.map(animation=>animation.finished.catch(()=>{}))),this.transitionAnimations===running&&(this.transitionAnimations=[])}surfaceSpec(showing,panel){const offset="translateY(calc(-1 * var(--lr-size-0-5rem)))";return{keyframes:panel?showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}]:showing?[{opacity:0},{opacity:1}]:[{opacity:1},{opacity:0}],durationProperties:[showing?SHOW_DURATION_PROPERTY:HIDE_DURATION_PROPERTY,"--lr-lightbox-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}}startSurfaceAnimations(showing){const panel=this.renderRoot.querySelector('[part~="panel"]'),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),direction=this.effectiveDirection;return[panel&&animateRegistered(this,panel,showing?"lightbox.show":"lightbox.hide",direction,this.surfaceSpec(showing,!0)),backdrop&&animateRegistered(this,backdrop,showing?"lightbox.overlay.show":"lightbox.overlay.hide",direction,this.surfaceSpec(showing,!1))].filter(animation=>animation!=null)}async playExit(){!this.isConnected||this.nativeModal.requested||(this.cancelTransitionAnimations(),this.transitionAnimations=this.startSurfaceAnimations(!1),this.markMorphing(this.renderedRecord?.element??this.currentItem,this.transitionAnimations),await this.settleAnimations())}animateSlide(forward){const slide=this.renderRoot.querySelector('[part="slide"]');if(!slide)return;const gap="var(--slide-gap, var(--lr-lightbox-slide-gap, var(--lr-space-l)))",from=sign2=>`translateX(calc(${sign2} * (100% + ${gap})))`,spec=sign2=>({keyframes:[{opacity:0,transform:from(sign2)},{opacity:1,transform:"translateX(0)"}],rtlKeyframes:[{opacity:0,transform:from(-sign2)},{opacity:1,transform:"translateX(0)"}],durationProperties:["--lr-lightbox-panel-duration","--lr-duration-base"],easingProperties:["--lr-easing-standard"]}),sign=forward?1:-1,release=this.swipeRelease;this.swipeRelease=0;let motion=spec(sign);if(release){const keyframes=[{opacity:0,transform:`translateX(calc(${this.effectiveDirection==="rtl"?-sign:sign} * (100% + ${gap}) + ${release}px))`},{opacity:1,transform:"translateX(0)"}];motion={...motion,keyframes,rtlKeyframes:keyframes}}const animation=animateRegistered(this,slide,forward?"lightbox.slide.next":"lightbox.slide.previous",this.effectiveDirection,motion);animation&&animation.finished.catch(()=>{})}syncCustomSlide(){const record=this.isConnected&&(this.open||this.hasAttribute("data-closing"))&&this.itemMode?this.itemRecords[this.currentIndex()]:void 0,wanted=record?.type==="custom"&&record.template?record:void 0;if(this.customSlide&&this.customSlide.record.template===wanted?.template&&this.customSlide.record.element===wanted?.element||(this.removeCustomSlide(),!wanted?.template))return;const doc=this.ownerDocument,element=doc.createElement("div");element.slot=CUSTOM_SLIDE_SLOT,element.setAttribute(CUSTOM_SLIDE_ATTRIBUTE,""),wanted.width&&wanted.height&&(element.setAttribute("data-ratio",""),element.style.setProperty("--_lr-lightbox-slide-ratio",String(wanted.width/wanted.height))),element.append(doc.importNode(wanted.template.content,!0)),this.customSlide={record:wanted,element},this.append(element)}removeCustomSlide(){const current=this.customSlide;this.customSlide=void 0,current?.element.remove()}markMorphing(item,animations){const generation=++this.morphGeneration;this.morphingItem&&setItemViewerState(this.morphingItem,"morphing",!1),this.morphingItem=void 0,!(!item||animations.length===0)&&(this.morphingItem=item,setItemViewerState(item,"morphing",!0),Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))).then(()=>{generation===this.morphGeneration&&(setItemViewerState(item,"morphing",!1),this.morphingItem=void 0)}))}applyOpenState(next){const old=this._open;this._open=next,this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}updateLiveRegion(){const count=this.imageCount(),formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveText=count===0?"":this.localize("lightboxImagePosition",void 0,{index:formatter.format(this.currentIndex()+1),total:formatter.format(count)})}captureAnnouncementBaseline(){this.announcementBaseline={index:this.currentIndex(),images:this.activeImages,source:this.imageSource}}willUpdate(changed){if(super.willUpdate(changed),this.sourceBindingCurrent=this.sourceController.update(this.imageSource,this.effectiveLocale),this.toggleAttribute("data-items",this.itemMode),(changed.has("index")||changed.has("open"))&&this.pauseVideos(),(changed.has("index")||changed.has("open")||changed.has("zoomLevel"))&&this.swipe&&this.releaseDrag(!1),(changed.has("index")||changed.has("imageSource")||changed.has("itemsVersion"))&&this.zoomLevel!==1&&(this.zoomLevel=1),this.sourceBindingCurrent&&(changed.has("itemsVersion")||changed.has("images")||changed.has("index")||changed.has("imageSource")||changed.has("sourceState"))){const index=changed.has("index")?void 0:this.index,intent=this.navigationIntent+1;this.syncImages(),index!==void 0&&this.index!==index&&this.navigationIntent===intent&&this.sourceBindingCurrent&&(this.pendingIndexChange=intent)}if(this.sourceBindingCurrent&&this.imageSource!==void 0){this.sourceController.select(this.currentIndex());const count=this.sourceController.count;this.withThumbnails&&count>1&&this.sourceController.requestThumbnails(...this.thumbnailRange(count,this.currentIndex()))}if(this.sourceBindingCurrent||queueDocumentMicrotask(this.ownerDocument,()=>{this.isConnected&&this.sourceState++}),this.sourceBindingCurrent&&(changed.has("index")||changed.has("itemsVersion")||changed.has("images")||changed.has("imageSource")||changed.has("sourceState")||changed.has("strings")||changed.has("locale"))&&this.updateLiveRegion(),changed.has("open"))if(this.open)this.modalSurface.open(()=>this.activateOverlay());else{const hadOverlay=this.overlay!==void 0;this.modalSurface.close(hadOverlay,()=>this.deactivateOverlay(),()=>!this.open)}}updated(changed){super.updated(changed),!(this.announcementBaseline?.index===this.currentIndex()&&this.announcementBaseline.images===this.activeImages&&this.announcementBaseline.source===this.imageSource)&&this.sourceBindingCurrent&&this.open&&this.liveText!==""&&isAccessibilityVisible(this)&&(changed.has("index")||changed.has("itemsVersion")||changed.has("images")||changed.has("imageSource"))&&this.announcements.announcePolite(this.liveText);const sourceError=this.sourceBindingCurrent&&this.imageSource!==void 0&&this.sourceController.state==="error";sourceError||(this.sourceErrorAnnounced=!1),sourceError&&!this.sourceErrorAnnounced&&this.sourceHasRendered&&this.open&&isAccessibilityVisible(this)&&(this.sourceErrorAnnounced=!0,this.announcements.announcePolite(this.localize("imageViewerFailedToLoad"))),this.sourceHasRendered=!0,this.isConnected&&this.sourceBindingCurrent&&this.captureAnnouncementBaseline(),changed.has("open")&&this.open&&(this.modalSurface.show(),this.overlay?.focusInitial());let currentSourceChanged=!1;if(changed.has("images")){const previousImages=changed.get("images"),previousIndex=changed.has("index")?changed.get("index")??0:this.index;currentSourceChanged=previousImages?.[previousImages.length>0?finiteCount(previousIndex,0,previousImages.length-1):0]?.src!==this.images[this.currentIndex()]?.src}const sourceImage=this.imageSource===void 0?void 0:this.sourceController.image;currentSourceChanged||=changed.has("imageSource")||sourceImage!==void 0&&sourceImage!==this.lastSourceImage,this.lastSourceImage=sourceImage;const shownSrc=this.imageSource===void 0?this.activeImages[this.currentIndex()]?.src??"":"";this.itemMode&&changed.has("itemsVersion")&&shownSrc!==this.lastShownSrc&&(currentSourceChanged=!0),this.lastShownSrc=shownSrc,this.open&&(changed.has("index")||currentSourceChanged)&&this.frameEl?.resetView();const current=this.currentIndex(),record=this.itemMode?this.itemRecords[current]:void 0;this.open&&this.firstUpdateDone&&changed.has("index")&&this.renderedIndex!==current&&this.animateSlide(this.effectiveDirection==="rtl"?current<this.renderedIndex:current>this.renderedIndex),changed.has("open")&&this.open&&this.firstUpdateDone&&(this.cancelTransitionAnimations(),this.transitionAnimations=this.startSurfaceAnimations(!0),this.markMorphing(record?.element,this.transitionAnimations));for(const item of this.itemRecords){const active=this.open&&item===record;item.element.toggleAttribute("data-active",active),setItemViewerState(item.element,"active",active)}setCustomState(this.lightboxInternals,"open",this.open),setCustomState(this.lightboxInternals,"zoomed",this.zoomLevel>1);const intent=this.pendingIndexChange;this.pendingIndexChange=void 0,intent===this.navigationIntent&&(this.emit("lr-index-change",{index:this.index}),this.emit("lr-item-change",{index:this.index,previousIndex:this.renderedIndex,item:record?.element??null,previousItem:this.renderedRecord?.element??null})),this.renderedIndex=current,this.renderedRecord=record,this.firstUpdateDone=!0,this.swipeRelease=0,this.syncCustomSlide()}connectedCallback(){super.connectedCallback();const generation=++this.connectionGeneration,connectionDocument=this.ownerDocument;this.addEventListener("click",this.onHostClick),this.syncItems(),typeof MutationObserver=="function"&&(this.itemObserver?.disconnect(),this.itemObserver=new MutationObserver(()=>this.syncItems()),this.itemObserver.observe(this,{childList:!0,subtree:!0})),this.captureAnnouncementBaseline(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),queueDocumentMicrotask(connectionDocument,()=>{this.connectionGeneration===generation&&this.ownerDocument===connectionDocument&&this.isConnected&&this.open&&(this.modalSurface.show(),this.overlay?.focusInitial())}))}disconnectedCallback(){const generation=++this.connectionGeneration,connectionDocument=this.ownerDocument;this.announcementBaseline=void 0,this.sourceErrorAnnounced=!1,this.sourceHasRendered=!1,this.lastSourceImage=void 0,this.removeEventListener("click",this.onHostClick),this.itemObserver?.disconnect(),this.itemObserver=void 0,this.releaseDrag(!1),this.removeCustomSlide(),this.cancelTransitionAnimations(),this.removeAttribute("data-closing"),super.disconnectedCallback(),this.modalSurface.disconnect(),this.overlay?.suspend(),this.open&&queueDocumentMicrotask(connectionDocument,()=>{this.connectionGeneration===generation&&this.ownerDocument===connectionDocument&&!this.isConnected&&this.open&&(this.transitionGeneration++,this.emit("lr-hide",{source:this}),this.applyOpenState(!1),this.emit("lr-close",{reason:"unmount"}),this.emit("lr-after-hide",null))})}activateOverlay(){this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part~="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part~="panel"]')??this;this.closeFrom("escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part="backdrop"]')??this;this.closeFrom("backdrop",backdrop)},preferredInitialFocus:()=>this.shadowRoot?.querySelector('[part="close-button"]')??null,lockScroll:!0,suspendWhenUnrendered:!0}))}deactivateOverlay(){this.overlay?.deactivate(),this.overlay=void 0}constructor(){super(),this.hostDescription=new HostDescriptionController(this,()=>this.renderRoot.querySelector(this.nativeModal.requested?"dialog[data-native-modal-carrier]":'[part~="panel"][role="dialog"]')),this._open=!1,this.navigationIntent=0,this.sourceBindingCurrent=!0,this.sourceState=0,this.sourceController=new LightboxSourceController(this,()=>{this.sourceState++}),this._images=EMPTY_LIGHTBOX_IMAGES,this._fit="actual",this._index=0,this.loop=!1,this.lightDismiss=!1,this.withoutCounter=!1,this.withThumbnails=!1,this.withoutNavigation=!1,this.withoutZoom=!1,this.label="",this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this.accessibleLabel=null,this.slotPresence=new SlotPresenceController(this),this.itemsVersion=0,this.zoomLevel=1,this.itemRecords=[],this.itemImages=EMPTY_LIGHTBOX_IMAGES,this.renderedIndex=0,this.lastShownSrc="",this.firstUpdateDone=!1,this.transitionAnimations=[],this.morphGeneration=0,this.lastItemSignature="",this.onHostClick=event=>{if(event.defaultPrevented||event.button!==0||event.metaKey||event.ctrlKey||event.shiftKey||event.altKey||!this.itemMode)return;const itemTag=tag("lightbox-item"),item=event.composedPath().find(node=>isElement(node)&&node.localName===itemTag);if(!item||item.closest(tag("lightbox"))!==this)return;const position=this.itemRecords.findIndex(record=>record.element===item);position<0||(event.preventDefault(),this.index=position,this.show())},this.toggleZoom=()=>{this.zoomLevel>1?this.frameEl?.resetZoom():this.zoomIn()},this.onZoomChange=event=>{const zoom=event.detail?.zoom;typeof zoom=="number"&&Number.isFinite(zoom)&&(this.zoomLevel=zoom)},this.onSwipeStart=event=>{event.defaultPrevented||event.pointerType==="mouse"||!event.isPrimary||this.imageCount()<2||this.zoomLevel>1||event.composedPath().some(node=>isElement(node)&&node.matches(SWIPE_EXEMPT))||(this.releaseDrag(!1),this.swipe={id:event.pointerId,x:event.clientX,y:event.clientY,dx:0,dragging:!1})},this.onSwipeMove=event=>{const swipe=this.swipe;if(!swipe||swipe.id!==event.pointerId)return;const dx=event.clientX-swipe.x,dy=event.clientY-swipe.y;if(swipe.dx=dx,!swipe.dragging){if(Math.abs(dx)<SWIPE_SLOP||Math.abs(dx)<Math.abs(dy)*1.2)return;swipe.dragging=!0}if(prefersReducedMotion(this))return;const slide=this.slideElement();if(!slide)return;for(const animation of slide.getAnimations())animation.cancel();const offset=this.hasNeighbor(this.swipeIsForward(dx))?dx:dx*SWIPE_EDGE_RESISTANCE;slide.style.transform=`translateX(${offset}px)`,slide.toggleAttribute("data-dragging",!0)},this.onSwipeEnd=event=>{const swipe=this.swipe;if(!swipe||swipe.id!==event.pointerId)return;const dx=event.clientX-swipe.x,dy=event.clientY-swipe.y,forward=this.swipeIsForward(dx);if(!(Math.abs(dx)>=SWIPE_DISTANCE&&Math.abs(dx)>=Math.abs(dy)*1.2&&this.hasNeighbor(forward))){this.releaseDrag(!0);return}this.swipeRelease=swipe.dragging&&!prefersReducedMotion(this)?dx:0,this.releaseDrag(!1),forward?this.next():this.previous(),this.pendingIndexChange===void 0&&(this.swipeRelease=0)},this.onSwipeCancel=event=>{this.swipe?.id===event.pointerId&&this.releaseDrag(!0)},this.swipeRelease=0,this.liveText="",this.lightboxInternals=attachInternalsSafely(this),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.closeFrom("escape",this.renderRoot.querySelector('[part~="panel"]')??this)},onUnexpectedClose:()=>{this.hide().then(()=>{this.open&&this.modalSurface.show()})}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal),this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.sourceErrorAnnounced=!1,this.sourceHasRendered=!1,this.connectionGeneration=0,this.transitionGeneration=0,this.openRequest=new ModalOpenRequest,this.captionId=nextId("lightbox-caption"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part="close-button"]')??this;this.closeFrom("close-button",button)},this.onPanelKeyDown=event=>{if(event.defaultPrevented||shouldIgnoreNavigationKey(event)||event.shiftKey)return;for(const target of event.composedPath()){if(target===this)break;if(isElement(target)&&target.getRootNode()!==this.shadowRoot&&target.matches('a[href], button, [role="button"], [role="link"], [role="slider"], input, select, textarea, [contenteditable]:not([contenteditable="false"])'))return}if(event.composedPath().some(node=>isElement(node)&&node.localName==="video")||keyEventOwnedByInnerControl(event,{container:this,ownerTag:tag("pan-zoom")}))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey?(event.preventDefault(),this.previous()):event.key==="Home"?(event.preventDefault(),this.goTo(0)):event.key==="End"&&(event.preventDefault(),this.goTo(this.imageCount()-1))},repairControlFocusOnUpdate(this,()=>[this.renderRoot.querySelector('[part="close-button"]'),this.renderRoot.querySelector('[part~="frame"]')]),trackScrollRegions(this,()=>{const el=this.renderRoot.querySelector('[part="caption"]');return[el&&{el,role:!1}]})}thumbnailRange(count,current){const size=this.imageSource===void 0?MAX_THUMBNAILS:SOURCE_THUMBNAIL_WINDOW,start=Math.max(0,Math.min(current-Math.floor(size/2),count-size));return[start,Math.min(count,start+size)]}renderThumbnails(count,current){if(!this.withThumbnails||count<2)return nothing;const sourceMode=this.imageSource!==void 0,[start,end]=this.thumbnailRange(count,current),formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),thumbs=[];for(let i=start;i<end;i++){const image=sourceMode?this.sourceController.thumbnailAt(i):this.activeImages[i];if(!image&&!sourceMode)continue;const record=this.itemMode?this.itemRecords[i]:void 0,media=record?record.thumbnail||(record.type==="image"?image?.src:""):image?.thumbnail||image?.src,source=safeMediaSrc(media),active=i===current,position=this.localize("lightboxImagePosition",void 0,{index:formatter.format(i+1),total:formatter.format(count)}),content=source?html`<img src=${source} alt="" loading="lazy" decoding="async" />`:record?.type==="video"?playIcon():html`<span aria-hidden="true">${formatter.format(i+1)}</span>`;thumbs.push(html`<button type="button" part=${active?"thumbnail thumbnail-active":"thumbnail"} aria-label=${image?.alt||position} aria-current=${active?"true":"false"} @click=${()=>this.goTo(i)} >${content}</button>`)}return html`<div part="thumbnails">${thumbs}</div>`}render(){const count=this.imageCount(),current=this.currentIndex(),image=this.imageSource===void 0?count>0?this.activeImages[current]:void 0:this.sourceController.image,record=this.itemMode?this.itemRecords[current]:void 0,isVideo=record?.type==="video",isCustom=record?.type==="custom",mediaSrc=isVideo?safeMediaSrc(image?.src)??"":"",sourceState=this.imageSource===void 0?void 0:this.sourceController.state,label=this.accessibleLabel?.trim()?this.accessibleLabel:(this.label??"").trim()?this.label:this.localize("lightboxLabel"),hasCaption=!!image?.caption,formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),positionText=count>0?this.localize("lightboxImagePosition",void 0,{index:formatter.format(current+1),total:formatter.format(count)}):"",zoomed=this.zoomLevel>1,showZoom=this.itemMode&&!this.withoutZoom&&!isVideo&&!isCustom&&count>0;return html`<slot></slot><div part="surface">${this.nativeModal.render(html`
|
|
2
2
|
<div part="backdrop" @click=${this.onBackdropClick}></div>
|
|
3
3
|
<div part="panel dialog" role=${this.open&&!this.nativeModal.requested?"dialog":nothing} aria-modal=${this.open&&!this.nativeModal.requested?"true":nothing} aria-label=${this.nativeModal.requested?nothing:label} aria-describedby=${hasCaption&&!this.nativeModal.requested?this.captionId:nothing} tabindex="-1" @keydown=${this.onPanelKeyDown} >
|
|
4
4
|
<div part="toolbar">
|
|
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{tag}from"../../../internal/prefix.js";impor
|
|
|
11
11
|
<slot name="close-icon">${closeIcon()}</slot>
|
|
12
12
|
</button>
|
|
13
13
|
</div>
|
|
14
|
-
<div part="stage scroll-container" aria-busy=${sourceState==="loading"?"true":"false"} @pointerdown=${this.onSwipeStart} @pointerup=${this.onSwipeEnd} @pointercancel=${this.onSwipeCancel} >
|
|
14
|
+
<div part="stage scroll-container" aria-busy=${sourceState==="loading"?"true":"false"} @pointerdown=${this.onSwipeStart} @pointermove=${this.onSwipeMove} @pointerup=${this.onSwipeEnd} @pointercancel=${this.onSwipeCancel} >
|
|
15
15
|
${sourceState==="loading"?html`<p part="source-loading">${this.localize("loading")}</p>`:nothing}
|
|
16
16
|
${sourceState==="error"?html`<div part="source-error">${this.localize("imageViewerFailedToLoad")}<button part="source-retry" type="button" @click=${()=>this.sourceController.retry(this.currentIndex())}>${this.localize("retry")}</button></div>`:nothing}
|
|
17
17
|
${count>1&&!this.withoutNavigation?html`
|
|
@@ -21,7 +21,8 @@ import{__decorate}from"tslib";import{tag}from"../../../internal/prefix.js";impor
|
|
|
21
21
|
`:nothing}
|
|
22
22
|
<div part="slide">
|
|
23
23
|
${isVideo?keyed(current,html`<video part="video" controls playsinline preload="metadata" src=${mediaSrc} poster=${ifDefined(record?.thumbnail||void 0)} aria-label=${ifDefined(image?.alt||void 0)} width=${ifDefined(record?.width)} height=${ifDefined(record?.height)} ></video>`):nothing}
|
|
24
|
-
|
|
24
|
+
${isCustom?html`<slot name=${CUSTOM_SLIDE_SLOT}></slot>`:nothing}
|
|
25
|
+
<lr-pan-zoom part="frame image" exportparts="viewport:frame-viewport,content:frame-content,controls:frame-controls" ?hidden=${isVideo||isCustom} .src=${live(isVideo||isCustom?"":image?.src??"")} alt=${image?.alt??""} .fit=${this.fit} .minZoom=${this.withoutZoom?1:this.minZoom} .maxZoom=${this.withoutZoom?1:this.maxZoom} .zoomStep=${this.zoomStep} .accessibleLabel=${positionText||null} @focus=${event=>event.stopPropagation()} @blur=${event=>event.stopPropagation()} @lr-zoom-change=${this.onZoomChange} ></lr-pan-zoom>
|
|
25
26
|
</div>
|
|
26
27
|
${count>1&&!this.withoutNavigation?html`
|
|
27
28
|
<button part="next-button navigation-button navigation-button-next" type="button" aria-label=${this.localize("next")} ?disabled=${!this.loop&¤t===count-1} @click=${this.next} >
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{dialogChrome,dialogOpenHost}from"../../../internal/modal-surface.styles.js";import{activeFill,disabledControl,focusRingShorthand,iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{modalHostStyles}from"../../../internal/native-modal-carrier.styles.js";import{compactContainerQuery}from"../../../internal/container-breakpoints.styles.js";import{inlineSizeContainer}from"../../../internal/layout-fragments.styles.js";const styles=css` :host{--_lr-lightbox-overlay-color:var(--backdrop-color, var(--lr-color-overlay-strong));--_lr-lightbox-control-bg:var(--controls-background, var(--lr-color-neutral));--_lr-lightbox-control-color:var(--controls-color, var(--lr-color-on-neutral));${modalHostStyles} max-inline-size:none;max-block-size:none;${inlineSizeContainer} ${dialogChrome}}${dialogOpenHost} :host([data-closing]){display:flex;pointer-events:none}[part=surface]{display:contents}:host(:not([data-items])) slot:not([name]){display:none}:host([data-items]),:host([data-items][open]),:host([data-items][data-closing]){display:contents;position:static;padding:0}:host([data-items]) [part=surface]{display:none}:host([data-items][open]) [part=surface],:host([data-items][data-closing]) [part=surface]{display:flex;position:fixed;inset:0;z-index:var(--lr-overlay-stack-index,var(--lr-layer-modal));${inlineSizeContainer} ${dialogChrome}}:host([data-items][data-closing]:not([open])) [part=surface]{pointer-events:none}[part=backdrop]{position:absolute;inset:0;background:var(--lr-lightbox-overlay-color,var(--_lr-lightbox-overlay-color));backdrop-filter:var(--backdrop-filter,none)}[part~=panel]{position:relative;display:flex;flex-direction:column;gap:var(--spacing,var(--lr-space-s));inline-size:100%;block-size:100%;min-inline-size:0;min-block-size:0;outline:none}[part=toolbar]{display:flex;align-items:center;flex:0 0 auto;flex-wrap:wrap;gap:var(--lr-space-s)}[part=counter]{display:inline-block;min-inline-size:0;max-inline-size:60%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:var(--lr-space-xs) var(--lr-space-s);border-radius:var(--lr-radius);background:var(--lr-lightbox-control-bg,var(--_lr-lightbox-control-bg));color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color));font-size:var(--lr-font-size-sm)}[part=actions]{display:flex;align-items:center;flex:1 1 0;flex-wrap:wrap;justify-content:flex-end;min-inline-size:0;max-inline-size:100%;gap:var(--lr-space-xs);margin-inline-start:auto}slot[name=actions]::slotted(*){box-sizing:border-box;min-inline-size:0;max-inline-size:100%;overflow-wrap:anywhere}[part=actions][hidden]{display:none}[part=source-retry],[part=zoom-button],[part=close-button],[part~=previous-button],[part~=next-button]{font:inherit;flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;${iconHitTarget} border:none;border-radius:var(--lr-radius-pill);--_lr-lightbox-control-hover-bg:var(--lr-lightbox-control-hover-bg, var(--lr-color-brand-quiet));--_lr-lightbox-control-hover-color:var(--lr-lightbox-control-hover-color, var(--lr-color-brand));background:var(--lr-lightbox-control-bg,var(--_lr-lightbox-control-bg));color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color));cursor:pointer;transition:var(--lr-transition-interactive)}[part=close-button]{margin-inline-start:var(--lr-space-xs)}:where([part=source-retry]):hover,:where([part=zoom-button]):hover,:where([part=close-button]):hover,:where([part~=previous-button]):hover:where(:not(:disabled)),:where([part~=next-button]):hover:where(:not(:disabled)){background:var(--_lr-lightbox-control-hover-bg);color:var(--_lr-lightbox-control-hover-color)}:where([part=source-retry]):active,:where([part=zoom-button]):active,:where([part=close-button]):active,:where([part~=previous-button]):active:where(:not(:disabled)),:where([part~=next-button]):active:where(:not(:disabled)){background:var(--lr-lightbox-control-active-bg,${activeFill("var(--_lr-lightbox-control-hover-bg)")});color:var(--lr-lightbox-control-active-color,var(--_lr-lightbox-control-hover-color))}[part=source-retry]:focus-visible,[part=zoom-button]:focus-visible,[part=close-button]:focus-visible,[part~=previous-button]:focus-visible,[part~=next-button]:focus-visible{${focusRingShorthand}}[part~=previous-button]:disabled,[part~=next-button]:disabled{${disabledControl}}[part=close-button] svg,[part=zoom-button] svg,[part=previous-glyph],[part=next-glyph]{display:block}[part=source-loading],[part=source-error]{position:absolute;inset:var(--lr-space-l);z-index:var(--lr-layer-content);display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:var(--lr-space-s);color:var(--lr-lightbox-status-color,var(--lr-color-on-strong-overlay));overflow-wrap:anywhere}[part=source-retry]{padding-inline:var(--lr-space-s)}[part~=stage]{position:relative;touch-action:pan-y pinch-zoom;flex:1 1 auto;min-inline-size:0;min-block-size:0}[part=slide]{display:block;inline-size:100%;block-size:100%;min-inline-size:0;min-block-size:0;border-radius:var(--media-border-radius,var(--lr-lightbox-media-radius,0));overflow:hidden}lr-pan-zoom[part~=frame]{display:block;inline-size:100%;block-size:100%}lr-pan-zoom[part~=frame][hidden]{display:none}:host([without-zoom]) lr-pan-zoom[part~=frame]::part(controls){display:none}[part=video]{display:block;inline-size:100%;block-size:100%;object-fit:contain;background:var(--lr-lightbox-overlay-color,var(--_lr-lightbox-overlay-color))}[part~=thumbnails]{display:flex;flex:0 0 auto;gap:var(--lr-space-xs);justify-content:center;overflow-x:auto;overflow-y:hidden;padding-block:var(--lr-space-xs)}[part~=thumbnail]{flex:0 0 auto;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;inline-size:var(--thumbnail-size,var(--lr-lightbox-thumbnail-size,var(--lr-size-3-5rem)));block-size:var(--thumbnail-size,var(--lr-lightbox-thumbnail-size,var(--lr-size-3-5rem)));min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);padding:0;overflow:hidden;border:var(--lr-border-width-thin) solid transparent;border-radius:var(--lr-radius);background:var(--lr-lightbox-control-bg,var(--_lr-lightbox-control-bg));color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color));cursor:pointer;opacity:0.7;transition:var(--lr-transition-interactive)}[part~=thumbnail] img{inline-size:100%;block-size:100%;object-fit:cover}[part~=thumbnail]:hover{opacity:1}[part~=thumbnail]:active{opacity:0.85}[part~=thumbnail]:focus-visible{${focusRingShorthand}}[part~=thumbnail-active]{opacity:1;border-color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color))}lr-pan-zoom[part~=frame]::part(base){block-size:100%}lr-pan-zoom[part~=frame]::part(viewport){block-size:100%}[part~=previous-button],[part~=next-button]{position:absolute;inset-block-start:50%;transform:translateY(-50%);z-index:var(--lr-layer-content)}[part~=previous-button]{inset-inline-start:var(--lr-space-s)}[part~=next-button]{inset-inline-end:var(--lr-space-s)}[part=previous-glyph]{transform:rotate(180deg)}[part=next-glyph]{transform:rotate(0deg)}:host(:dir(rtl)) [part=previous-glyph]{transform:rotate(0deg)}:host(:dir(rtl)) [part=next-glyph]{transform:rotate(180deg)}[part=caption]{flex:0 0 auto;margin:0;max-inline-size:100%;max-block-size:var(--lr-size-8rem);overflow-x:hidden;overflow-y:auto;align-self:center;padding:var(--lr-space-xs) var(--lr-space-s);border-radius:var(--lr-radius);background:var(--lr-lightbox-control-bg,var(--_lr-lightbox-control-bg));color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color));text-align:center;overflow-wrap:anywhere}[part=caption]:focus-visible{${focusRingShorthand}}@container ${compactContainerQuery}{[part=counter]{max-inline-size:45%}}`;export{styles};
|
|
1
|
+
import{dialogChrome,dialogOpenHost}from"../../../internal/modal-surface.styles.js";import{activeFill,disabledControl,focusRingShorthand,iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{modalHostStyles}from"../../../internal/native-modal-carrier.styles.js";import{compactContainerQuery}from"../../../internal/container-breakpoints.styles.js";import{inlineSizeContainer}from"../../../internal/layout-fragments.styles.js";const styles=css` :host{--_lr-lightbox-overlay-color:var(--backdrop-color, var(--lr-color-overlay-strong));--_lr-lightbox-control-bg:var(--controls-background, var(--lr-color-neutral));--_lr-lightbox-control-color:var(--controls-color, var(--lr-color-on-neutral));${modalHostStyles} max-inline-size:none;max-block-size:none;${inlineSizeContainer} ${dialogChrome}}${dialogOpenHost} :host([data-closing]){display:flex;pointer-events:none}[part=surface]{display:contents}:host(:not([data-items])) slot:not([name]){display:none}:host([data-items]),:host([data-items][open]),:host([data-items][data-closing]){display:contents;position:static;padding:0}:host([data-items]) [part=surface]{display:none}:host([data-items][open]) [part=surface],:host([data-items][data-closing]) [part=surface]{display:flex;position:fixed;inset:0;z-index:var(--lr-overlay-stack-index,var(--lr-layer-modal));${inlineSizeContainer} ${dialogChrome}}:host([data-items][data-closing]:not([open])) [part=surface]{pointer-events:none}[part=backdrop]{position:absolute;inset:0;background:var(--lr-lightbox-overlay-color,var(--_lr-lightbox-overlay-color));backdrop-filter:var(--backdrop-filter,none)}[part~=panel]{position:relative;display:flex;flex-direction:column;gap:var(--spacing,var(--lr-space-s));inline-size:100%;block-size:100%;min-inline-size:0;min-block-size:0;outline:none}[part=toolbar]{display:flex;align-items:center;flex:0 0 auto;flex-wrap:wrap;gap:var(--lr-space-s)}[part=counter]{display:inline-block;min-inline-size:0;max-inline-size:60%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding:var(--lr-space-xs) var(--lr-space-s);border-radius:var(--lr-radius);background:var(--lr-lightbox-control-bg,var(--_lr-lightbox-control-bg));color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color));font-size:var(--lr-font-size-sm)}[part=actions]{display:flex;align-items:center;flex:1 1 0;flex-wrap:wrap;justify-content:flex-end;min-inline-size:0;max-inline-size:100%;gap:var(--lr-space-xs);margin-inline-start:auto}slot[name=actions]::slotted(*){box-sizing:border-box;min-inline-size:0;max-inline-size:100%;overflow-wrap:anywhere}[part=actions][hidden]{display:none}[part=source-retry],[part=zoom-button],[part=close-button],[part~=previous-button],[part~=next-button]{font:inherit;flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;${iconHitTarget} border:none;border-radius:var(--lr-radius-pill);--_lr-lightbox-control-hover-bg:var(--lr-lightbox-control-hover-bg, var(--lr-color-brand-quiet));--_lr-lightbox-control-hover-color:var(--lr-lightbox-control-hover-color, var(--lr-color-brand));background:var(--lr-lightbox-control-bg,var(--_lr-lightbox-control-bg));color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color));cursor:pointer;transition:var(--lr-transition-interactive)}[part=close-button]{margin-inline-start:var(--lr-space-xs)}:where([part=source-retry]):hover,:where([part=zoom-button]):hover,:where([part=close-button]):hover,:where([part~=previous-button]):hover:where(:not(:disabled)),:where([part~=next-button]):hover:where(:not(:disabled)){background:var(--_lr-lightbox-control-hover-bg);color:var(--_lr-lightbox-control-hover-color)}:where([part=source-retry]):active,:where([part=zoom-button]):active,:where([part=close-button]):active,:where([part~=previous-button]):active:where(:not(:disabled)),:where([part~=next-button]):active:where(:not(:disabled)){background:var(--lr-lightbox-control-active-bg,${activeFill("var(--_lr-lightbox-control-hover-bg)")});color:var(--lr-lightbox-control-active-color,var(--_lr-lightbox-control-hover-color))}[part=source-retry]:focus-visible,[part=zoom-button]:focus-visible,[part=close-button]:focus-visible,[part~=previous-button]:focus-visible,[part~=next-button]:focus-visible{${focusRingShorthand}}[part~=previous-button]:disabled,[part~=next-button]:disabled{${disabledControl}}[part=close-button] svg,[part=zoom-button] svg,[part=previous-glyph],[part=next-glyph]{display:block}[part=source-loading],[part=source-error]{position:absolute;inset:var(--lr-space-l);z-index:var(--lr-layer-content);display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:var(--lr-space-s);color:var(--lr-lightbox-status-color,var(--lr-color-on-strong-overlay));overflow-wrap:anywhere}[part=source-retry]{padding-inline:var(--lr-space-s)}[part~=stage]{position:relative;touch-action:pan-y pinch-zoom;flex:1 1 auto;min-inline-size:0;min-block-size:0}[part=slide]{display:block;inline-size:100%;block-size:100%;min-inline-size:0;min-block-size:0;border-radius:var(--media-border-radius,var(--lr-lightbox-media-radius,0));overflow:hidden}[part=slide][data-dragging]{will-change:transform}slot[name=slide-content]{display:grid;place-items:center;container-type:size;inline-size:100%;block-size:100%}slot[name=slide-content]::slotted(*){box-sizing:border-box;inline-size:100%;block-size:100%;overflow:auto}slot[name=slide-content]::slotted([data-ratio]){inline-size:min(100cqi,100cqb * var(--_lr-lightbox-slide-ratio));block-size:auto;aspect-ratio:var(--_lr-lightbox-slide-ratio)}lr-pan-zoom[part~=frame]{display:block;inline-size:100%;block-size:100%}lr-pan-zoom[part~=frame][hidden]{display:none}:host([without-zoom]) lr-pan-zoom[part~=frame]::part(controls){display:none}[part=video]{display:block;inline-size:100%;block-size:100%;object-fit:contain;background:var(--lr-lightbox-overlay-color,var(--_lr-lightbox-overlay-color))}[part~=thumbnails]{display:flex;flex:0 0 auto;gap:var(--lr-space-xs);justify-content:center;overflow-x:auto;overflow-y:hidden;padding-block:var(--lr-space-xs)}[part~=thumbnail]{flex:0 0 auto;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;inline-size:var(--thumbnail-size,var(--lr-lightbox-thumbnail-size,var(--lr-size-3-5rem)));block-size:var(--thumbnail-size,var(--lr-lightbox-thumbnail-size,var(--lr-size-3-5rem)));min-inline-size:var(--lr-icon-button-size);min-block-size:var(--lr-icon-button-size);padding:0;overflow:hidden;border:var(--lr-border-width-thin) solid transparent;border-radius:var(--lr-radius);background:var(--lr-lightbox-control-bg,var(--_lr-lightbox-control-bg));color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color));cursor:pointer;opacity:0.7;transition:var(--lr-transition-interactive)}[part~=thumbnail] img{inline-size:100%;block-size:100%;object-fit:cover}[part~=thumbnail]:hover{opacity:1}[part~=thumbnail]:active{opacity:0.85}[part~=thumbnail]:focus-visible{${focusRingShorthand}}[part~=thumbnail-active]{opacity:1;border-color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color))}lr-pan-zoom[part~=frame]::part(base){block-size:100%}lr-pan-zoom[part~=frame]::part(viewport){block-size:100%}[part~=previous-button],[part~=next-button]{position:absolute;inset-block-start:50%;transform:translateY(-50%);z-index:var(--lr-layer-content)}[part~=previous-button]{inset-inline-start:var(--lr-space-s)}[part~=next-button]{inset-inline-end:var(--lr-space-s)}[part=previous-glyph]{transform:rotate(180deg)}[part=next-glyph]{transform:rotate(0deg)}:host(:dir(rtl)) [part=previous-glyph]{transform:rotate(0deg)}:host(:dir(rtl)) [part=next-glyph]{transform:rotate(180deg)}[part=caption]{flex:0 0 auto;margin:0;max-inline-size:100%;max-block-size:var(--lr-size-8rem);overflow-x:hidden;overflow-y:auto;align-self:center;padding:var(--lr-space-xs) var(--lr-space-s);border-radius:var(--lr-radius);background:var(--lr-lightbox-control-bg,var(--_lr-lightbox-control-bg));color:var(--lr-lightbox-control-color,var(--_lr-lightbox-control-color));text-align:center;overflow-wrap:anywhere}[part=caption]:focus-visible{${focusRingShorthand}}@container ${compactContainerQuery}{[part=counter]{max-inline-size:45%}}`;export{styles};
|
|
@@ -79,7 +79,7 @@ export interface LyraContextMenuPoint{x:number;y:number;contextElement?:Element;
|
|
|
79
79
|
* @cssprop [--lr-overlay-surface=var(--lr-color-surface-container-high)] - Shared floating-surface fill.
|
|
80
80
|
* @cssprop [--lr-overlay-border=var(--lr-color-border-subtle)] - Shared floating-surface edge
|
|
81
81
|
* colour.
|
|
82
|
-
* @cssprop [--lr-overlay-radius=var(--lr-radius)] - Shared floating-surface corner radius.
|
|
82
|
+
* @cssprop [--lr-overlay-radius=var(--lr-radius-container)] - Shared floating-surface corner radius.
|
|
83
83
|
* @cssprop [--lr-overlay-shadow-anchored=var(--lr-shadow-m)] - Elevation of the anchored popup.
|
|
84
84
|
* @cssprop [--lr-overlay-max-inline-size=var(--lr-size-20rem)] - Maximum inline size fallback of
|
|
85
85
|
* the popup.
|