@aceshooting/lyra-ui 11.2.0 → 12.1.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 +407 -0
- package/README.md +11 -8
- package/custom-elements.json +1 -1
- package/dist/all.d.ts +1 -0
- package/dist/all.js +1 -1
- package/dist/autoloader.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +0 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +13 -1
- package/dist/components/charts/chart/histogram-bin.d.ts +0 -1
- package/dist/components/charts/chart/histogram-bin.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.d.ts +22 -9
- package/dist/components/charts/chart/lite-chart.class.js +6 -6
- package/dist/components/conversation/code-block/code-block-shared.d.ts +4 -54
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/code-block/shiki-types.d.ts +2 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +0 -3
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +0 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/funnel/funnel.class.d.ts +92 -0
- package/dist/components/data/funnel/funnel.class.js +25 -0
- package/dist/components/data/funnel/funnel.d.ts +1 -0
- package/dist/components/data/funnel/funnel.js +1 -0
- package/dist/components/data/funnel/funnel.styles.d.ts +1 -0
- package/dist/components/data/funnel/funnel.styles.js +127 -0
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +0 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +199 -14
- package/dist/components/data/heatmap/heatmap.class.js +30 -22
- package/dist/components/data/heatmap/heatmap.styles.js +36 -0
- package/dist/components/data/index.d.ts +1 -0
- package/dist/components/data/index.js +1 -1
- package/dist/components/data/table/table.class.d.ts +18 -4
- package/dist/components/data/table/table.class.js +2 -2
- package/dist/components/data/table/table.styles.js +2 -1
- package/dist/components/data/timeline/timeline-cluster.d.ts +1 -0
- package/dist/components/data/timeline/timeline-cluster.js +1 -0
- package/dist/components/data/timeline/timeline-item.class.d.ts +17 -2
- package/dist/components/data/timeline/timeline-item.class.js +13 -2
- package/dist/components/data/timeline/timeline-item.styles.js +65 -0
- package/dist/components/data/timeline/timeline.class.d.ts +83 -27
- package/dist/components/data/timeline/timeline.class.js +3 -3
- package/dist/components/data/timeline/timeline.d.ts +1 -0
- package/dist/components/data/timeline/timeline.js +1 -1
- package/dist/components/data/timeline/timeline.styles.js +14 -0
- package/dist/components/forms/button/button.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +0 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +0 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +7 -1
- package/dist/components/forms/combobox/combobox.class.js +3 -2
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.d.ts +23 -0
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +0 -1
- package/dist/components/forms/input/native-time-input.class.js +1 -1
- package/dist/components/forms/input/time-input-shared.d.ts +2 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +0 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/radio/radio-button.styles.d.ts +0 -1
- package/dist/components/forms/radio/radio-button.styles.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +0 -1
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/radio/radio.class.d.ts +0 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +0 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +0 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +0 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +0 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.d.ts +0 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.d.ts +0 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail-item.class.d.ts +16 -0
- package/dist/components/layout/app-rail/app-rail-item.class.js +4 -4
- package/dist/components/layout/dashboard-grid/layout-internal.d.ts +0 -1
- package/dist/components/layout/dashboard-grid/layout-internal.js +1 -1
- package/dist/components/layout/details/accordion-owner.d.ts +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.d.ts +32 -3
- package/dist/components/layout/filter-bar/filter-bar.class.js +2 -1
- package/dist/components/layout/menu/menu-item.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/layout/widget/widget.class.d.ts +16 -0
- package/dist/components/layout/widget/widget.class.js +2 -2
- package/dist/components/lr-funnel.d.ts +1 -0
- package/dist/components/lr-funnel.js +1 -0
- package/dist/components/media/av-player/av-metadata.d.ts +0 -2
- package/dist/components/media/av-player/av-metadata.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +0 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag-peer-bulk-standard.d.ts +25 -0
- package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -0
- package/dist/components/media/flag/flag.class.d.ts +8 -0
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +4 -1
- package/dist/components/media/map/map.class.d.ts +242 -23
- package/dist/components/media/map/map.class.js +2 -2
- package/dist/components/overlays/chip/chip-group.class.d.ts +16 -0
- package/dist/components/overlays/chip/chip-group.class.js +10 -3
- package/dist/components/overlays/overlay/popover.class.d.ts +7 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +1 -0
- package/dist/components/overlays/overlay/tooltip.class.js +1 -1
- package/dist/components/overlays/progress/progress-shared.d.ts +0 -2
- package/dist/components/overlays/progress/progress-shared.js +1 -1
- package/dist/components/overlays/rating/rating.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.d.ts +10 -9
- package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +0 -4
- package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
- package/dist/components/utility/format/format-options.d.ts +0 -2
- package/dist/components/utility/format/format-options.js +1 -1
- package/dist/components/utility/icon/icon-resource.d.ts +0 -2
- package/dist/components/utility/icon/icon-resource.js +1 -1
- package/dist/components/viewers/archive-viewer/zip-resource-guard.d.ts +2 -1
- package/dist/components/viewers/docx-viewer/docx-resource-guard.d.ts +0 -3
- package/dist/components/viewers/docx-viewer/docx-resource-guard.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-loader.d.ts +2 -1
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.d.ts +0 -3
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-loader.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.d.ts +0 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.d.ts +0 -5
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.js +1 -1
- package/dist/custom-elements-jsx.d.ts +16 -8
- package/dist/events.d.ts +15 -0
- package/dist/internal/accessibility-visibility.d.ts +1 -1
- package/dist/internal/anchor-target.d.ts +1 -3
- package/dist/internal/anchor-target.js +2 -2
- package/dist/internal/anchored-overlay-runtime.d.ts +7 -0
- package/dist/internal/anchored-overlay-runtime.js +1 -0
- package/dist/internal/announcement-text.d.ts +1 -1
- package/dist/internal/ansi.d.ts +0 -4
- package/dist/internal/ansi.js +1 -1
- package/dist/internal/aria-ownership.d.ts +2 -1
- package/dist/internal/autoloader-manifest.js +1 -1
- package/dist/internal/autoloader-tags.d.ts +1 -1
- package/dist/internal/autoloader-tags.js +1 -1
- package/dist/internal/default-strings.generated.d.ts +1 -0
- package/dist/internal/default-strings.generated.js +1 -1
- package/dist/internal/focus-navigation.d.ts +3 -2
- package/dist/internal/form-associated.d.ts +0 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/form-control-labels.d.ts +0 -3
- 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 +7 -14
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/nonmodal-overlay-manager.d.ts +9 -0
- package/dist/internal/nonmodal-overlay-manager.js +1 -0
- package/dist/internal/overlay-manager.d.ts +4 -20
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-stack.d.ts +66 -0
- package/dist/internal/overlay-stack.js +1 -0
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/root-registration-allowlist.d.ts +1 -1
- package/dist/internal/root-registration-allowlist.js +1 -1
- package/dist/internal/text-quote.d.ts +1 -1
- package/dist/lyra.d.ts +5 -4
- package/dist/lyra.js +1 -1
- package/dist/ssr/all.d.ts +1 -0
- package/dist/ssr/all.js +1 -1
- package/dist/ssr.d.ts +4 -4
- package/dist/styles/tokens-root.css +488 -0
- package/dist/svelte.d.ts +17 -8
- package/dist/translations/ar.js +1 -1
- package/dist/translations/de.js +1 -1
- package/dist/translations/es.js +1 -1
- package/dist/translations/fa.js +1 -1
- package/dist/translations/fr.js +1 -1
- package/dist/translations/he.js +1 -1
- package/dist/translations/ja.js +1 -1
- package/dist/translations/pt-BR.js +1 -1
- package/dist/translations/ru.js +1 -1
- package/dist/translations/zh-CN.js +1 -1
- package/dist/utilities/localization.js +1 -1
- package/dist/vue.d.ts +16 -8
- package/llms/components/lr-app-rail-item.md +8 -1
- package/llms/components/lr-app-rail.md +6 -0
- package/llms/components/lr-chip-group.md +7 -0
- package/llms/components/lr-chip.md +7 -0
- package/llms/components/lr-combobox.md +42 -0
- package/llms/components/lr-date-input.md +19 -1
- package/llms/components/lr-date-picker.md +19 -1
- package/llms/components/lr-filter-bar.md +50 -1
- package/llms/components/lr-flag.md +14 -0
- package/llms/components/lr-funnel.md +122 -0
- package/llms/components/lr-heatmap.md +55 -8
- package/llms/components/lr-lite-chart.md +20 -8
- package/llms/components/lr-map.md +109 -22
- package/llms/components/lr-option.md +42 -0
- package/llms/components/lr-popover.md +39 -0
- package/llms/components/lr-table.md +7 -3
- package/llms/components/lr-timeline-item.md +49 -24
- package/llms/components/lr-timeline.md +49 -24
- package/llms/components/lr-widget.md +7 -1
- package/llms/index.md +3 -2
- package/llms/peers.md +1 -1
- package/llms/shared.md +110 -1
- package/llms-full.txt +681 -67
- package/llms.txt +1 -1
- package/package.json +26 -8
- package/vscode-css-data.json +63 -0
- package/vscode-html-data.json +108 -23
- package/web-types.json +32738 -310
|
@@ -1 +1 @@
|
|
|
1
|
-
import{finiteNumber}from"../../../internal/numbers.js";const MAX_LYRA_AV_CUES=1e4,MAX_LYRA_AV_TRACKS=64,MAX_CUE_ID_CHARS=256,MAX_CUE_TEXT_CHARS=1e5,MAX_CUE_SPEAKER_CHARS=4096,MAX_TRACK_SRC_CHARS=16384,MAX_TRACK_LANGUAGE_CHARS=128,MAX_TRACK_LABEL_CHARS=4096,OWNED_AV_METADATA_COLLECTIONS=new WeakSet;function ownedSnapshot(values){const snapshot=Object.freeze(values);return OWNED_AV_METADATA_COLLECTIONS.add(snapshot),snapshot}const EMPTY_LYRA_AV_CUES=ownedSnapshot([]),EMPTY_LYRA_AV_TRACKS=ownedSnapshot([]);function normalizeArray(value,limit,normalize,fallback){try{if(!Array.isArray(value))return fallback;if(OWNED_AV_METADATA_COLLECTIONS.has(value))return value;const result=[],length=Math.min(value.length,limit);for(let index=0;index<length;index+=1)try{const normalized=normalize(value[index]);normalized!==void 0&&result.push(normalized)}catch{}return ownedSnapshot(result)}catch{return fallback}}function snapshotLyraAvCues(value){const seenIds=new Set;return normalizeArray(value,MAX_LYRA_AV_CUES,candidate=>{if(candidate===null||typeof candidate!="object")return;const record=candidate;if(typeof record.cueId!="string"||typeof record.text!="string")return;const cueId=record.cueId.trim();if(!cueId||cueId.length>MAX_CUE_ID_CHARS||seenIds.has(cueId))return;seenIds.add(cueId);const rawStart=record.start,start=Math.max(0,finiteNumber(typeof rawStart=="number"?rawStart:0,0)),rawEnd=record.end,end=typeof rawEnd=="number"&&Number.isFinite(rawEnd)?Math.max(start,rawEnd):void 0,rawSpeaker=record.speaker,speaker=typeof rawSpeaker=="string"?rawSpeaker.slice(0,MAX_CUE_SPEAKER_CHARS):void 0;return Object.freeze({cueId,start,text:record.text.slice(0,MAX_CUE_TEXT_CHARS),...end!==void 0?{end}:{},...speaker!==void 0?{speaker}:{}})},EMPTY_LYRA_AV_CUES)}function snapshotLyraAvTracks(value){return normalizeArray(value,MAX_LYRA_AV_TRACKS,candidate=>{if(candidate===null||typeof candidate!="object")return;const record=candidate;if(!(typeof record.src!="string"||record.kind!=="subtitles"&&record.kind!=="captions"&&record.kind!=="descriptions"||typeof record.srclang!="string"||typeof record.label!="string"))return Object.freeze({src:record.src.slice(0,MAX_TRACK_SRC_CHARS),kind:record.kind,srclang:record.srclang.slice(0,MAX_TRACK_LANGUAGE_CHARS),label:record.label.slice(0,MAX_TRACK_LABEL_CHARS),default:record.default===!0})},EMPTY_LYRA_AV_TRACKS)}function hasSearchableLyraAvCues(cues){return cues.some(cue=>!!(cue.text.trim()||cue.speaker?.trim()))}export{EMPTY_LYRA_AV_CUES,EMPTY_LYRA_AV_TRACKS,
|
|
1
|
+
import{finiteNumber}from"../../../internal/numbers.js";const MAX_LYRA_AV_CUES=1e4,MAX_LYRA_AV_TRACKS=64,MAX_CUE_ID_CHARS=256,MAX_CUE_TEXT_CHARS=1e5,MAX_CUE_SPEAKER_CHARS=4096,MAX_TRACK_SRC_CHARS=16384,MAX_TRACK_LANGUAGE_CHARS=128,MAX_TRACK_LABEL_CHARS=4096,OWNED_AV_METADATA_COLLECTIONS=new WeakSet;function ownedSnapshot(values){const snapshot=Object.freeze(values);return OWNED_AV_METADATA_COLLECTIONS.add(snapshot),snapshot}const EMPTY_LYRA_AV_CUES=ownedSnapshot([]),EMPTY_LYRA_AV_TRACKS=ownedSnapshot([]);function normalizeArray(value,limit,normalize,fallback){try{if(!Array.isArray(value))return fallback;if(OWNED_AV_METADATA_COLLECTIONS.has(value))return value;const result=[],length=Math.min(value.length,limit);for(let index=0;index<length;index+=1)try{const normalized=normalize(value[index]);normalized!==void 0&&result.push(normalized)}catch{}return ownedSnapshot(result)}catch{return fallback}}function snapshotLyraAvCues(value){const seenIds=new Set;return normalizeArray(value,MAX_LYRA_AV_CUES,candidate=>{if(candidate===null||typeof candidate!="object")return;const record=candidate;if(typeof record.cueId!="string"||typeof record.text!="string")return;const cueId=record.cueId.trim();if(!cueId||cueId.length>MAX_CUE_ID_CHARS||seenIds.has(cueId))return;seenIds.add(cueId);const rawStart=record.start,start=Math.max(0,finiteNumber(typeof rawStart=="number"?rawStart:0,0)),rawEnd=record.end,end=typeof rawEnd=="number"&&Number.isFinite(rawEnd)?Math.max(start,rawEnd):void 0,rawSpeaker=record.speaker,speaker=typeof rawSpeaker=="string"?rawSpeaker.slice(0,MAX_CUE_SPEAKER_CHARS):void 0;return Object.freeze({cueId,start,text:record.text.slice(0,MAX_CUE_TEXT_CHARS),...end!==void 0?{end}:{},...speaker!==void 0?{speaker}:{}})},EMPTY_LYRA_AV_CUES)}function snapshotLyraAvTracks(value){return normalizeArray(value,MAX_LYRA_AV_TRACKS,candidate=>{if(candidate===null||typeof candidate!="object")return;const record=candidate;if(!(typeof record.src!="string"||record.kind!=="subtitles"&&record.kind!=="captions"&&record.kind!=="descriptions"||typeof record.srclang!="string"||typeof record.label!="string"))return Object.freeze({src:record.src.slice(0,MAX_TRACK_SRC_CHARS),kind:record.kind,srclang:record.srclang.slice(0,MAX_TRACK_LANGUAGE_CHARS),label:record.label.slice(0,MAX_TRACK_LABEL_CHARS),default:record.default===!0})},EMPTY_LYRA_AV_TRACKS)}function hasSearchableLyraAvCues(cues){return cues.some(cue=>!!(cue.text.trim()||cue.speaker?.trim()))}export{EMPTY_LYRA_AV_CUES,EMPTY_LYRA_AV_TRACKS,hasSearchableLyraAvCues,snapshotLyraAvCues,snapshotLyraAvTracks};
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type PropertyValues, type TemplateResult } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
-
import '../../../internal/form-control-labels.js';
|
|
4
3
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
5
4
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
6
5
|
export type LyraFileInputCapture = '' | 'user' | 'environment';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.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{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const 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"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}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){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,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.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(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.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}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){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);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._disabled&&(this.dropToken++,this.resetDragSession()),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"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),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)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return 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.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(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){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(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 this._files){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()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.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{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const 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"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}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){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,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.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(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.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}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){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);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._disabled&&(this.dropToken++,this.resetDragSession()),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"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),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)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return 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.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(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){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(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 this._files){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()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;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="" />`:html`<span part="file-icon">${fileIcon()}</span>`}
|
|
4
4
|
</span>
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type LyraFlagUrlResolver } from './flag.js';
|
|
2
|
+
/**
|
|
3
|
+
* Register the bulk-resolution `@aceshooting/lyra-flags` resolver through that package's
|
|
4
|
+
* tier-committed `./standard` entry — the pairing of `flag-peer-bulk.js`'s one-shared-fetch
|
|
5
|
+
* batching with `./standard`'s one-tier module graph. Import this entry **instead of**
|
|
6
|
+
* `flag-peer.js` or `flag-peer-bulk.js`, never alongside either: each `setFlagUrlResolver()` call
|
|
7
|
+
* simply replaces the previous resolver, so importing two entries just makes whichever loaded last
|
|
8
|
+
* win.
|
|
9
|
+
*
|
|
10
|
+
* Use it when both conditions hold: the page renders most or all flags at once (a country table, a
|
|
11
|
+
* full locale picker), *and* every `<lr-flag>` stays on the default `fidelity="standard"`.
|
|
12
|
+
* `flag-peer-bulk.js` reaches the same batching through the peer package's root entry, which
|
|
13
|
+
* statically imports all three fidelity tiers' generated loader maps so its `flagUrl()` can honour
|
|
14
|
+
* a per-call variant — so a bundler emits the detailed and compact tiers' whole lazy-chunk graph
|
|
15
|
+
* even though bulk resolution only ever reads the standard-tier eager map. On a real production
|
|
16
|
+
* build with a 156-country flag column, that difference was +15.8MB of emitted assets (+65 detailed
|
|
17
|
+
* SVGs, +31 compact WebPs) that no route rendered.
|
|
18
|
+
*
|
|
19
|
+
* The tradeoff this entry makes in exchange: it is committed to one tier, so `fidelity="compact"`
|
|
20
|
+
* or `fidelity="detailed"` on an individual element resolves to that code's *standard* asset
|
|
21
|
+
* rather than reaching for a tier the registered resolver deliberately does not ship. That is a
|
|
22
|
+
* silent visual no-op, not an error — for per-instance fidelity, import `flag-peer-bulk.js` (bulk,
|
|
23
|
+
* all three tiers) or `flag-peer.js` (per-code lazy, all three tiers) instead.
|
|
24
|
+
*/
|
|
25
|
+
export declare function registerLyraFlagStandardBulkPeer(): Promise<LyraFlagUrlResolver | null>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{loadBulkFlagUrl,setFlagUrlResolver}from"./flag.js";const peerResolver=loadBulkFlagUrl(()=>import("@aceshooting/lyra-flags/standard"));setFlagUrlResolver(peerResolver);async function registerLyraFlagStandardBulkPeer(){return peerResolver}registerLyraFlagStandardBulkPeer();export{registerLyraFlagStandardBulkPeer};
|
|
@@ -62,6 +62,14 @@ export declare function setFlagUrlResolver(value: LyraFlagUrlResolver | Promise<
|
|
|
62
62
|
* Or import `flag-peer-bulk.js` instead of `flag-peer.js` (never both) to get this automatically,
|
|
63
63
|
* registering a resolver backed by one shared `flagUrls()` call — worthwhile only when the page
|
|
64
64
|
* renders most/all flags; a page with a handful pays an unneeded 249-entry fetch.
|
|
65
|
+
* When that page ALSO leaves every `<lr-flag>` on the default `fidelity="standard"`, import
|
|
66
|
+
* `flag-peer-bulk-standard.js` instead: it registers the same bulk resolver through the peer
|
|
67
|
+
* package's tier-committed `@aceshooting/lyra-flags/standard` entry, so the detailed and compact
|
|
68
|
+
* tiers' lazy-chunk graphs never become reachable (measured at +15.8MB of emitted assets on a real
|
|
69
|
+
* production build with a 156-country flag column). It is committed to one tier, so
|
|
70
|
+
* `fidelity="compact"/"detailed"` on an individual element resolves to that code's standard asset
|
|
71
|
+
* — a silent no-op, not an error; use `flag-peer-bulk.js` when per-instance fidelity must be
|
|
72
|
+
* honoured.
|
|
65
73
|
*
|
|
66
74
|
* **Sizing:** the host has no intrinsic `width` — it sizes from `font-size` (`block-size: 1em`,
|
|
67
75
|
* `inline-size` derived from `--lr-flag-aspect-ratio` via CSS `aspect-ratio`), so `<lr-flag>` scales
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadFlagUrl(importFlags){try{const resolver=resolverFromModule(await importFlags());if(resolver)return resolver;throw new TypeError("The flag peer does not expose a callable flagUrl capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function resolverFactoryFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.createFlagUrlResolver;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.createFlagUrlResolver;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadBulkFlagUrl(importFlags){try{const factory=resolverFactoryFromModule(await importFlags());if(factory)return factory();throw new TypeError("The flag peer does not expose a callable createFlagUrlResolver capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;let warnedMissingFlagResolver=!1;function warnMissingFlagResolver(code){warnedMissingFlagResolver||(warnedMissingFlagResolver=!0,console.warn(`<lr-flag> could not resolve the code "${code}" because no flag resolver is registered. Import the optional peer entry once at startup -- import '@aceshooting/lyra-ui/components/media/flag/flag-peer.js' -- and install '@aceshooting/lyra-flags', or pass an already-resolved URL through 'src' instead.`))}function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),warnedMissingFlagResolver=!1,flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){warnMissingFlagResolver(code),this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}function warnFlagPeerMissing(){console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`.")}function warnFlagPeerIncapable(capability){console.warn(`<lr-flag> loaded '@aceshooting/lyra-flags' but it does not expose \`${capability}\`. The package is installed, so this is a version mismatch rather than a missing dependency: upgrade it to a release that provides that capability, and check the peer range in <lr-flag>'s own package metadata for the floor it expects.`)}async function loadFlagUrl(importFlags){let peerModule;try{peerModule=await importFlags()}catch{return warnFlagPeerMissing(),null}try{const resolver=resolverFromModule(peerModule);if(resolver)return resolver}catch{}return warnFlagPeerIncapable("flagUrl"),null}function resolverFactoryFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.createFlagUrlResolver;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.createFlagUrlResolver;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadBulkFlagUrl(importFlags){let peerModule;try{peerModule=await importFlags()}catch{return warnFlagPeerMissing(),null}const factory=resolverFactoryFromModule(peerModule);if(!factory)return warnFlagPeerIncapable("createFlagUrlResolver"),null;try{return factory()}catch{return warnFlagPeerIncapable("createFlagUrlResolver"),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;let warnedMissingFlagResolver=!1;function warnMissingFlagResolver(code){warnedMissingFlagResolver||(warnedMissingFlagResolver=!0,console.warn(`<lr-flag> could not resolve the code "${code}" because no flag resolver is registered. Import the optional peer entry once at startup -- import '@aceshooting/lyra-ui/components/media/flag/flag-peer.js' -- and install '@aceshooting/lyra-flags', or pass an already-resolved URL through 'src' instead.`))}function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),warnedMissingFlagResolver=!1,flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){warnMissingFlagResolver(code),this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
|
|
2
2
|
>${this.fallback?html`<img part="fallback-image" src=${this.fallback} alt=${this.label??""} />`:nothing}</slot
|
|
3
3
|
>`;if(state2.status==="error")return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`;const url=state2.status==="loading"||state2.status==="loaded"?state2.url:void 0;if(!url&&state2.status!=="loading")return html``;const code=this.code,alt=hostAriaLabel(this)??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`
|
|
4
4
|
${state2.status==="loading"?html`
|
|
@@ -1,10 +1,13 @@
|
|
|
1
|
+
import type { Feature } from 'geojson';
|
|
1
2
|
export interface MapLibreGeoJsonSource {
|
|
2
3
|
setData(data: unknown): void;
|
|
3
4
|
/** maplibre-gl 3+ incremental update. Optional because older peers lack it. */
|
|
4
5
|
updateData?(diff: MapLibreGeoJsonDiff): void;
|
|
5
6
|
}
|
|
6
|
-
/** The subset of maplibre-gl's GeoJSON diff this component emits
|
|
7
|
+
/** The subset of maplibre-gl's GeoJSON diff this component emits. */
|
|
7
8
|
export interface MapLibreGeoJsonDiff {
|
|
9
|
+
readonly remove?: readonly (string | number)[];
|
|
10
|
+
readonly add?: readonly Feature[];
|
|
8
11
|
readonly update: readonly {
|
|
9
12
|
readonly id: string | number;
|
|
10
13
|
readonly addOrUpdateProperties: readonly {
|