@aceshooting/lyra-ui 23.0.0 → 24.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 +16 -39
- package/README.md +72 -35
- package/custom-elements.json +1 -1
- package/design-tokens.json +1 -1
- package/dist/cli/lyra-rename-ledger.mjs +1 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/cli/migration-contract.mjs +1 -1
- package/dist/cli/migration-renames.mjs +2 -2
- package/dist/cli/migration-transforms.mjs +2 -2
- package/dist/components/agent-tools/approval-queue/approval-queue.class.d.ts +1 -4
- package/dist/components/agent-tools/approval-queue/approval-queue.class.js +1 -3
- package/dist/components/agent-tools/compare-panel/compare-panel.class.d.ts +1 -4
- package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.d.ts +1 -7
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
- package/dist/components/agent-tools/context-inspector/context-inspector.class.d.ts +1 -1
- package/dist/components/agent-tools/evaluation-run/evaluation-run.class.d.ts +2 -5
- package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +1 -3
- package/dist/components/agent-tools/terminal/terminal.class.d.ts +1 -4
- package/dist/components/agent-tools/terminal/terminal.class.js +2 -2
- package/dist/components/agent-tools/tool-approval-dialog/tool-approval-dialog.class.d.ts +1 -7
- package/dist/components/agent-tools/tool-approval-dialog/tool-approval-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.d.ts +1 -4
- package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +1 -3
- package/dist/components/charts/chart/lite-chart-axis-layout.d.ts +13 -0
- package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -0
- package/dist/components/charts/chart/lite-chart.class.d.ts +1 -11
- package/dist/components/charts/chart/lite-chart.class.js +4 -4
- package/dist/components/conversation/agent-workspace/agent-workspace.class.d.ts +13 -3
- package/dist/components/conversation/agent-workspace/agent-workspace.class.js +1 -2
- package/dist/components/conversation/chat-message/chat-message.class.d.ts +3 -9
- package/dist/components/conversation/chat-message/chat-message.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
- package/dist/components/conversation/code-block/code-block-core.class.d.ts +6 -8
- package/dist/components/conversation/code-block/code-block-shared.d.ts +1 -4
- package/dist/components/conversation/code-block/code-block.class.d.ts +4 -6
- package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -3
- package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
- package/dist/components/conversation/markdown/markdown-core.class.d.ts +1 -4
- package/dist/components/conversation/markdown/markdown.class.d.ts +1 -4
- package/dist/components/conversation/message-actions/message-actions.class.d.ts +1 -4
- package/dist/components/conversation/message-actions/message-actions.class.js +1 -1
- package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +1 -4
- package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +2 -5
- package/dist/components/conversation/message-parts/message-parts.class.js +3 -3
- package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +1 -1
- package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +2 -0
- package/dist/components/conversation/streaming-text/streaming-text-core.class.js +0 -1
- package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +2 -0
- package/dist/components/conversation/streaming-text/streaming-text.class.js +0 -1
- package/dist/components/conversation/thread-list/thread-list.class.d.ts +6 -17
- package/dist/components/conversation/thread-list/thread-list.class.js +6 -6
- package/dist/components/data/context-meter/context-meter.class.d.ts +1 -6
- package/dist/components/data/context-meter/context-meter.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.d.ts +0 -1
- package/dist/components/data/data-grid/data-grid.class.js +2 -2
- package/dist/components/data/document-library/document-library.class.d.ts +6 -13
- package/dist/components/data/document-library/document-library.class.js +1 -2
- package/dist/components/data/heatmap/heatmap-grid-navigation.d.ts +7 -0
- package/dist/components/data/heatmap/heatmap-grid-navigation.js +1 -0
- package/dist/components/data/heatmap/heatmap.class.d.ts +3 -23
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/sequence-strip/sequence-strip.class.d.ts +3 -9
- package/dist/components/data/sequence-strip/sequence-strip.class.js +3 -3
- package/dist/components/data/table/table.class.d.ts +5 -14
- package/dist/components/data/table/table.class.js +6 -6
- package/dist/components/forms/button/button.class.d.ts +2 -2
- package/dist/components/forms/button/button.class.js +9 -9
- package/dist/components/forms/combobox/combobox.class.d.ts +1 -4
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- package/dist/components/forms/input/time-input.class.d.ts +1 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +1 -2
- package/dist/components/forms/swatch-picker/swatch-picker.class.d.ts +3 -1
- package/dist/components/forms/swatch-picker/swatch-picker.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail-item.class.d.ts +3 -6
- package/dist/components/layout/app-rail/app-rail-item.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +2 -4
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/app-rail-group/app-rail-group.class.d.ts +2 -6
- package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
- package/dist/components/layout/carousel/carousel.class.d.ts +1 -4
- package/dist/components/layout/carousel/carousel.class.js +2 -2
- package/dist/components/layout/command-palette/command-palette.class.js +1 -1
- package/dist/components/layout/details/details.class.d.ts +2 -4
- package/dist/components/layout/details/details.class.js +1 -1
- package/dist/components/layout/dock-panel/dock-panel.class.d.ts +3 -7
- package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +2 -4
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.d.ts +2 -4
- package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
- package/dist/components/layout/reorder-list/reorder-item.class.d.ts +1 -4
- package/dist/components/layout/reorder-list/reorder-item.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +5 -9
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +5 -5
- package/dist/components/media/av-player/av-player.class.js +3 -3
- package/dist/components/media/file-input/file-input.class.d.ts +3 -6
- package/dist/components/media/file-input/file-input.class.js +3 -3
- package/dist/components/media/lightbox/lightbox.class.d.ts +11 -20
- package/dist/components/media/lightbox/lightbox.class.js +1 -1
- package/dist/components/media/map/map-data-layers.d.ts +20 -0
- package/dist/components/media/map/map-data-layers.js +1 -0
- package/dist/components/media/map/map.class.js +3 -3
- package/dist/components/media/media-time.d.ts +2 -0
- package/dist/components/media/media-time.js +1 -0
- package/dist/components/media/video/video.class.js +5 -5
- package/dist/components/media/video-playlist/video-playlist.class.js +2 -2
- package/dist/components/overlays/callout/callout.class.d.ts +2 -5
- package/dist/components/overlays/callout/callout.class.js +2 -2
- package/dist/components/overlays/dialog/dialog.class.d.ts +4 -7
- package/dist/components/overlays/dialog/dialog.class.js +2 -2
- package/dist/components/overlays/overlay/dropdown.class.d.ts +5 -10
- package/dist/components/overlays/overlay/dropdown.class.js +2 -2
- package/dist/components/overlays/overlay/popover.class.d.ts +2 -3
- package/dist/components/overlays/popup/popup.class.js +1 -1
- package/dist/components/overlays/progress/progress-bar.class.d.ts +1 -4
- package/dist/components/overlays/progress/progress-bar.class.js +2 -2
- package/dist/components/overlays/progress/progress-ring.class.d.ts +1 -4
- package/dist/components/overlays/progress/progress-ring.class.js +2 -2
- package/dist/components/overlays/progress/progress-shared.d.ts +3 -3
- package/dist/components/overlays/progress/progress-shared.js +1 -1
- package/dist/components/overlays/toast/toast-item.class.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +5 -10
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/knowledge-base/knowledge-base.class.d.ts +7 -14
- package/dist/components/retrieval/knowledge-base/knowledge-base.class.js +2 -3
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +2 -8
- package/dist/components/retrieval/memory-panel/memory-panel.class.js +0 -4
- package/dist/components/retrieval/rag-answer/rag-answer.class.js +1 -1
- package/dist/components/utility/export-button/export-button.class.d.ts +6 -10
- package/dist/components/utility/export-button/export-button.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/geojson-view/geojson-view.class.d.ts +1 -1
- package/dist/components/viewers/highlight-layer/highlight-layer-timing.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +4 -4
- package/dist/events.d.ts +17 -78
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/catalog-picker.js +1 -1
- package/dist/internal/css-motion-time.d.ts +7 -0
- package/dist/internal/css-motion-time.js +1 -0
- package/dist/internal/data-state-renderer.d.ts +1 -3
- package/dist/internal/data-state-renderer.js +1 -1
- package/dist/internal/localization-runtime.d.ts +2 -0
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/lyra-element.js +2 -2
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/looks/data.css +1 -1
- package/dist/looks/terminal.css +1 -1
- package/dist/lyra.d.ts +1 -592
- package/dist/lyra.js +1 -1
- package/dist/testing/event-factory.d.ts +2 -2
- package/dist/testing/interaction-drivers.d.ts +5 -3
- package/dist/testing/lyra-tag-event-map.js +1 -1
- package/dist/theme/looks/data.d.ts +1 -1
- package/dist/theme/looks/data.js +1 -1
- package/dist/theme/looks/terminal.d.ts +1 -1
- package/dist/theme/looks/terminal.js +1 -1
- package/dist/theme/theme.d.ts +2 -80
- package/dist/theme/theme.js +1 -1
- package/llms/components/lr-agent-workspace.md +24 -2
- package/llms/components/lr-alert.md +1 -1
- package/llms/components/lr-animation.md +1 -1
- package/llms/components/lr-app-rail.md +8 -10
- package/llms/components/lr-approval-queue.md +2 -4
- package/llms/components/lr-attachment-trigger.md +3 -4
- package/llms/components/lr-badge.md +2 -2
- package/llms/components/lr-button.md +45 -99
- package/llms/components/lr-callout.md +3 -4
- package/llms/components/lr-carousel.md +3 -5
- package/llms/components/lr-chat-message.md +1 -2
- package/llms/components/lr-claim-evidence.md +1 -1
- package/llms/components/lr-code-block-core.md +2 -2
- package/llms/components/lr-code-block.md +5 -6
- package/llms/components/lr-color-picker.md +1 -1
- package/llms/components/lr-combobox.md +5 -6
- package/llms/components/lr-compare-panel.md +2 -4
- package/llms/components/lr-confirm-bar.md +3 -7
- package/llms/components/lr-context-inspector.md +3 -2
- package/llms/components/lr-context-menu.md +2 -2
- package/llms/components/lr-context-meter.md +2 -4
- package/llms/components/lr-copy-button.md +1 -1
- package/llms/components/lr-data-grid.md +4 -7
- package/llms/components/lr-details.md +3 -3
- package/llms/components/lr-dialog.md +4 -6
- package/llms/components/lr-dock-panel.md +5 -6
- package/llms/components/lr-document-library.md +5 -7
- package/llms/components/lr-drawer.md +3 -3
- package/llms/components/lr-dropdown.md +4 -5
- package/llms/components/lr-eval-run.md +3 -5
- package/llms/components/lr-export-button.md +4 -7
- package/llms/components/lr-file-input.md +0 -5
- package/llms/components/lr-funnel.md +1 -1
- package/llms/components/lr-graph.md +3 -7
- package/llms/components/lr-icon.md +1 -1
- package/llms/components/lr-include.md +1 -1
- package/llms/components/lr-input.md +31 -79
- package/llms/components/lr-json-viewer.md +1 -1
- package/llms/components/lr-knowledge-base.md +4 -6
- package/llms/components/lr-knowledge-graph-explorer.md +2 -5
- package/llms/components/lr-known-date.md +1 -1
- package/llms/components/lr-lightbox.md +9 -7
- package/llms/components/lr-lite-chart.md +1 -5
- package/llms/components/lr-markdown-core.md +3 -4
- package/llms/components/lr-markdown.md +3 -5
- package/llms/components/lr-mcp-app.md +1 -1
- package/llms/components/lr-message-actions.md +2 -3
- package/llms/components/lr-message-feedback.md +1 -3
- package/llms/components/lr-message-parts.md +4 -5
- package/llms/components/lr-multi-split.md +8 -7
- package/llms/components/lr-native-time-input.md +1 -1
- package/llms/components/lr-navigation-menu.md +5 -5
- package/llms/components/lr-number-input.md +3 -1
- package/llms/components/lr-otp-input.md +2 -0
- package/llms/components/lr-page.md +1 -1
- package/llms/components/lr-pan-zoom.md +1 -1
- package/llms/components/lr-phone-input.md +3 -1
- package/llms/components/lr-popover.md +2 -2
- package/llms/components/lr-progress-bar.md +3 -5
- package/llms/components/lr-progress-ring.md +5 -7
- package/llms/components/lr-prompt-input.md +1 -1
- package/llms/components/lr-prompt-queue.md +1 -1
- package/llms/components/lr-prompt-studio.md +1 -1
- package/llms/components/lr-rag-eval-dashboard.md +1 -1
- package/llms/components/lr-rating.md +2 -2
- package/llms/components/lr-realtime-session.md +1 -1
- package/llms/components/lr-reorder-item.md +1 -1
- package/llms/components/lr-reorder-list.md +2 -3
- package/llms/components/lr-retrieval-compare.md +1 -1
- package/llms/components/lr-select.md +3 -1
- package/llms/components/lr-selection-toolbar.md +1 -1
- package/llms/components/lr-sequence-strip.md +3 -8
- package/llms/components/lr-span-waterfall.md +1 -1
- package/llms/components/lr-split-panel.md +1 -1
- package/llms/components/lr-streaming-text-core.md +2 -1
- package/llms/components/lr-streaming-text.md +3 -2
- package/llms/components/lr-subagent-panel.md +1 -1
- package/llms/components/lr-swatch-picker.md +7 -6
- package/llms/components/lr-switch.md +3 -1
- package/llms/components/lr-table.md +33 -85
- package/llms/components/lr-terminal.md +2 -5
- package/llms/components/lr-textarea.md +1 -1
- package/llms/components/lr-thread-list.md +8 -14
- package/llms/components/lr-time-input.md +1 -1
- package/llms/components/lr-toggle-group.md +2 -2
- package/llms/components/lr-toggle.md +1 -1
- package/llms/components/lr-tool-approval-dialog.md +4 -7
- package/llms/components/lr-tool-call-block.md +1 -1
- package/llms/components/lr-tool-timeline.md +2 -5
- package/llms/components/lr-video-playlist.md +1 -1
- package/llms/components/lr-video.md +1 -1
- package/llms/components/lr-widget-renderer.md +7 -6
- package/llms/components/lr-zoomable-frame.md +1 -1
- package/llms/index.md +3 -618
- package/llms/migration.md +614 -614
- package/llms/shared/events-and-types.md +32 -31
- package/llms/shared/frameworks-and-ssr.md +7 -3
- package/llms/shared/imports-and-registration.md +22 -22
- package/llms/shared/localization-and-rtl.md +2 -2
- package/llms/shared/native-styles-and-utilities.md +263 -0
- package/llms/shared/styles-and-tokens.md +85 -676
- package/llms/shared/testing-and-utilities.md +12 -11
- package/llms/shared/v23-to-v24-migration.md +167 -0
- package/llms/shared.md +149 -494
- package/llms/tokens.md +3 -3
- package/llms.txt +9 -4
- package/package.json +7 -311
- package/registrations.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
- package/dist/ssr-loader.d.ts +0 -2
- package/dist/ssr-loader.js +0 -1
- package/dist/theme/presets/shadcn.d.ts +0 -22
- package/dist/theme/presets/shadcn.js +0 -1
- package/dist/theme/presets.d.ts +0 -49
- package/dist/theme/presets.js +0 -1
- package/dist/themes/shadcn.css +0 -1
|
@@ -60,8 +60,7 @@ export type LyraFileBackedCapability=Exclude<LyraAttachmentCapability,'camera'|'
|
|
|
60
60
|
* picker. Hidden (`display: none`) by default; exposed as a part only so a consumer can override
|
|
61
61
|
* that with `::part(hidden-input)` in the unlikely case their integration needs to.
|
|
62
62
|
*
|
|
63
|
-
* The host `aria-label` names either trigger shape; an explicit empty value is kept as-is.
|
|
64
|
-
* `accessibleLabel` property is a programmatic fallback that the host `aria-label` wins over.
|
|
63
|
+
* The host `aria-label` names either trigger shape; an explicit empty value is kept as-is.
|
|
65
64
|
* @status stable
|
|
66
65
|
* @since 4.0.0
|
|
67
66
|
*/
|
|
@@ -74,15 +73,12 @@ capabilities:readonly LyraAttachmentCapability[];
|
|
|
74
73
|
/** Native-file-input-style accept string (e.g. `'image/*'` or
|
|
75
74
|
* `'.pdf,.docx'`), forwarded to the hidden file input for the
|
|
76
75
|
* `files`/`image` capabilities — see the class doc for how each uses it. */
|
|
77
|
-
accept:string;
|
|
78
|
-
/**
|
|
79
|
-
*
|
|
80
|
-
get accessibleLabel():string|undefined;set accessibleLabel(value:string|undefined);
|
|
81
|
-
/** The host `aria-label`: names either trigger shape ahead of `accessibleLabel`, by presence, so
|
|
82
|
-
* an explicitly empty value stays empty. */
|
|
76
|
+
accept:string;
|
|
77
|
+
/** The host `aria-label`: names either trigger shape, by presence, so an explicitly empty value
|
|
78
|
+
* stays empty. */
|
|
83
79
|
private hostAccessibleLabel;
|
|
84
80
|
/** Forwards to the internal trigger button(s)' native `title` attribute — a sighted mouse
|
|
85
|
-
* user's hover tooltip, distinct from
|
|
81
|
+
* user's hover tooltip, distinct from the accessible-name (`aria-label`) role.
|
|
86
82
|
* Applies to both the single-capability `[part=trigger]` button and the multi-capability
|
|
87
83
|
* `[part=menu-trigger]` button. Unset (the default): no `title` attribute, unchanged from
|
|
88
84
|
* before this property existed. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{
|
|
1
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{chevronIcon}from"../../../internal/icons.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./attachment-trigger.styles.js";import{falseDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_attachmentAdd,LYRA_DEFAULT_attachmentMenuAudio,LYRA_DEFAULT_attachmentMenuCamera,LYRA_DEFAULT_attachmentMenuFiles,LYRA_DEFAULT_attachmentMenuImage,LYRA_DEFAULT_attachmentTriggerAudio,LYRA_DEFAULT_attachmentTriggerCamera,LYRA_DEFAULT_attachmentTriggerFiles,LYRA_DEFAULT_attachmentTriggerImage,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -25,7 +25,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
25
25
|
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
|
|
26
26
|
<line x1="12" y1="19" x2="12" y2="23"></line>
|
|
27
27
|
<line x1="8" y1="23" x2="16" y2="23"></line>
|
|
28
|
-
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]),MAX_ATTACHMENT_CAPABILITIES=4,ATTACHMENT_CAPABILITY_SCAN_LIMIT=64;function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,ATTACHMENT_CAPABILITY_SCAN_LIMIT);for(let index=0;index<length&&normalized.length<MAX_ATTACHMENT_CAPABILITIES;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.
|
|
28
|
+
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]),MAX_ATTACHMENT_CAPABILITIES=4,ATTACHMENT_CAPABILITY_SCAN_LIMIT=64;function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,ATTACHMENT_CAPABILITY_SCAN_LIMIT);for(let index=0;index<length&&normalized.length<MAX_ATTACHMENT_CAPABILITIES;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.hostAccessibleLabel=null,this.multiple=!1,this.disabled=!1,this.appearance="plain",this.size="m",this.descriptionSyncGeneration=0,this.hasSyncedDescribedByElements=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const OwnerArray=this.ownerDocument.defaultView?.Array??Array,files=Object.freeze(OwnerArray.from(selected));this.emit("lr-files",{capability:this.pendingCapability,files})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get triggerEl(){return this.composedTriggerEl?.control??this.composedTriggerEl}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}updated(changed){super.updated(changed),this.syncTriggerDescription();const composed=this.composedTriggerEl;if(!composed||composed.control)return;const generation=++this.descriptionSyncGeneration;composed.updateComplete.then(()=>{generation!==this.descriptionSyncGeneration||!this.isConnected||this.syncTriggerDescription()})}syncTriggerDescription(){const hostDescribedBy=this.getAttribute("aria-describedby");!hostDescribedBy&&!this.hasSyncedDescribedByElements||(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.triggerEl,hostDescribedBy))}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
|
|
29
29
|
<input
|
|
30
30
|
part="hidden-input"
|
|
31
31
|
type="file"
|
|
@@ -35,7 +35,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
35
35
|
?disabled=${this.disabled}
|
|
36
36
|
@change=${this.onInputChange}
|
|
37
37
|
/>
|
|
38
|
-
`}renderSingleTrigger(capability){const meta=CAPABILITY_META[capability],label=this.hostAccessibleLabel??this.
|
|
38
|
+
`}renderSingleTrigger(capability){const meta=CAPABILITY_META[capability],label=this.hostAccessibleLabel??this.localize(meta.triggerKey);return html`
|
|
39
39
|
<lr-icon-button
|
|
40
40
|
part="trigger"
|
|
41
41
|
exportparts="button:trigger-control"
|
|
@@ -49,7 +49,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
49
49
|
>
|
|
50
50
|
${meta.icon()}
|
|
51
51
|
</lr-icon-button>
|
|
52
|
-
`}renderMenu(){const addLabel=this.localize("attachmentAdd"),accessibleLabel=this.hostAccessibleLabel??
|
|
52
|
+
`}renderMenu(){const addLabel=this.localize("attachmentAdd"),accessibleLabel=this.hostAccessibleLabel??addLabel;return html`
|
|
53
53
|
<lr-dropdown without-arrow
|
|
54
54
|
part="menu"
|
|
55
55
|
@lr-show=${this.stopInternalEvent}
|
|
@@ -84,4 +84,4 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
84
84
|
${single?this.renderSingleTrigger(capabilities[0]):nothing}
|
|
85
85
|
${multi?this.renderMenu():nothing}
|
|
86
86
|
${this.hasFileCapability?this.renderHiddenInput():nothing}
|
|
87
|
-
`}}__decorate([property({attribute:!1})],LyraAttachmentTrigger.prototype,"capabilities",void 0),__decorate([property()],LyraAttachmentTrigger.prototype,"accept",void 0),__decorate([property({attribute
|
|
87
|
+
`}}__decorate([property({attribute:!1})],LyraAttachmentTrigger.prototype,"capabilities",void 0),__decorate([property()],LyraAttachmentTrigger.prototype,"accept",void 0),__decorate([property({attribute:"aria-label"})],LyraAttachmentTrigger.prototype,"hostAccessibleLabel",void 0),__decorate([property({attribute:"trigger-title"})],LyraAttachmentTrigger.prototype,"triggerTitle",void 0),__decorate([property({type:Boolean,reflect:!0,converter:falseDefaultBooleanConverter})],LyraAttachmentTrigger.prototype,"multiple",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraAttachmentTrigger.prototype,"disabled",void 0),__decorate([property({reflect:!0})],LyraAttachmentTrigger.prototype,"appearance",void 0),__decorate([property({reflect:!0})],LyraAttachmentTrigger.prototype,"size",void 0),__decorate([query('input[type="file"]')],LyraAttachmentTrigger.prototype,"inputEl",void 0),__decorate([query("lr-dropdown")],LyraAttachmentTrigger.prototype,"dropdownEl",void 0),__decorate([query('[part="trigger"], [part="menu-trigger"]')],LyraAttachmentTrigger.prototype,"composedTriggerEl",void 0);export{LyraAttachmentTrigger};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{ref}from"lit/directives/ref.js";import{literalSetConverter}from"../../../internal/converters.js";import{LyraElement}from"../../../internal/lyra-element.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{MAX_NATIVE_PLAYBACK_RATE as MAX_PLAYBACK_RATE,MIN_NATIVE_PLAYBACK_RATE as MIN_PLAYBACK_RATE,NativeMediaController,safeNativeMediaSource as safeMediaSrc}from"../../../internal/media-controller.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber,finiteRange}from"../../../internal/numbers.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./av-player.styles.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{resolveBoundedCanvasAllocation}from"../../../internal/canvas.js";import{EMPTY_LYRA_AV_CUES,EMPTY_LYRA_AV_TRACKS,snapshotLyraAvCues,snapshotLyraAvTracks}from"./av-metadata.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_avPlayerFailedToLoad,LYRA_DEFAULT_avPlayerLabel,LYRA_DEFAULT_avPlayerPlaybackRate,LYRA_DEFAULT_avPlayerPosition,LYRA_DEFAULT_avPlayerRateOption,LYRA_DEFAULT_avPlayerTimeline,LYRA_DEFAULT_avPlayerTranscript,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_viewerHighlightLabel}from"../../../internal/default-strings.generated.js";const CONTROLS_SURFACE=literalSetConverter(["regular","clear"],"regular"),TIME_CHANGE_THROTTLE_MS=250,MAX_AV_RATES=32,MAX_AV_PEAKS=65536,MAX_CANVAS_DIMENSION=4096,MAX_CANVAS_PIXELS=8388608,OWNED_AV_COLLECTIONS=new WeakSet,NO_REPORTED_ERROR=Symbol("no-reported-av-error");function ownedSnapshot(values){const snapshot=Object.freeze(values);return OWNED_AV_COLLECTIONS.add(snapshot),snapshot}const EMPTY_RATES=ownedSnapshot([]),DEFAULT_RATES=ownedSnapshot([.75,1,1.25,1.5,2]),EMPTY_CUES=EMPTY_LYRA_AV_CUES,EMPTY_PEAKS=ownedSnapshot([]),EMPTY_TRACKS=EMPTY_LYRA_AV_TRACKS;function normalizeArray(value,limit,normalize,fallback){try{if(!Array.isArray(value))return fallback;if(OWNED_AV_COLLECTIONS.has(value))return value;const result=[],length=Math.min(value.length,limit);for(let index=0;index<length;index++)try{const normalized=normalize(value[index],index);normalized!==void 0&&result.push(normalized)}catch{}return ownedSnapshot(result)}catch{return fallback}}function normalizeRates(value){const seen=new Set;return normalizeArray(value,MAX_AV_RATES,candidate=>{if(!(typeof candidate!="number"||!Number.isFinite(candidate)||candidate<MIN_PLAYBACK_RATE||candidate>MAX_PLAYBACK_RATE||seen.has(candidate)))return seen.add(candidate),candidate},EMPTY_RATES)}function normalizePeaks(value){return normalizeArray(value,MAX_AV_PEAKS,candidate=>typeof candidate=="number"?finiteRange(candidate,0,0,1):void 0,EMPTY_PEAKS)}function positiveFinite(value){const finite=finiteNumber(value,1);return finite>0?finite:1}function waveformPaintPeaks(peaks,maxBars){const barCount=Math.max(1,Math.floor(finiteNumber(maxBars,1)));if(peaks.length<=barCount)return peaks;const finalIndex=peaks.length-1;if(barCount===1)return[finiteRange(peaks[finalIndex],0,0,1)];const result=new Array(barCount),preEndpointBars=barCount-1;for(let barIndex=0;barIndex<preEndpointBars;barIndex+=1){const start=Math.floor(barIndex*finalIndex/preEndpointBars),end=Math.floor((barIndex+1)*finalIndex/preEndpointBars);let peak=0;for(let sampleIndex=start;sampleIndex<end;sampleIndex+=1)peak=Math.max(peak,finiteRange(peaks[sampleIndex],0,0,1));result[barIndex]=peak}return result[preEndpointBars]=finiteRange(peaks[finalIndex],0,0,1),result}
|
|
1
|
+
import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{ref}from"lit/directives/ref.js";import{literalSetConverter}from"../../../internal/converters.js";import{LyraElement}from"../../../internal/lyra-element.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{MAX_NATIVE_PLAYBACK_RATE as MAX_PLAYBACK_RATE,MIN_NATIVE_PLAYBACK_RATE as MIN_PLAYBACK_RATE,NativeMediaController,safeNativeMediaSource as safeMediaSrc}from"../../../internal/media-controller.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{finiteNumber,finiteRange}from"../../../internal/numbers.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{formatMediaTime}from"../media-time.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./av-player.styles.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{resolveBoundedCanvasAllocation}from"../../../internal/canvas.js";import{EMPTY_LYRA_AV_CUES,EMPTY_LYRA_AV_TRACKS,snapshotLyraAvCues,snapshotLyraAvTracks}from"./av-metadata.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_avPlayerFailedToLoad,LYRA_DEFAULT_avPlayerLabel,LYRA_DEFAULT_avPlayerPlaybackRate,LYRA_DEFAULT_avPlayerPosition,LYRA_DEFAULT_avPlayerRateOption,LYRA_DEFAULT_avPlayerTimeline,LYRA_DEFAULT_avPlayerTranscript,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_viewerHighlightLabel}from"../../../internal/default-strings.generated.js";const CONTROLS_SURFACE=literalSetConverter(["regular","clear"],"regular"),TIME_CHANGE_THROTTLE_MS=250,MAX_AV_RATES=32,MAX_AV_PEAKS=65536,MAX_CANVAS_DIMENSION=4096,MAX_CANVAS_PIXELS=8388608,OWNED_AV_COLLECTIONS=new WeakSet,NO_REPORTED_ERROR=Symbol("no-reported-av-error");function ownedSnapshot(values){const snapshot=Object.freeze(values);return OWNED_AV_COLLECTIONS.add(snapshot),snapshot}const EMPTY_RATES=ownedSnapshot([]),DEFAULT_RATES=ownedSnapshot([.75,1,1.25,1.5,2]),EMPTY_CUES=EMPTY_LYRA_AV_CUES,EMPTY_PEAKS=ownedSnapshot([]),EMPTY_TRACKS=EMPTY_LYRA_AV_TRACKS;function normalizeArray(value,limit,normalize,fallback){try{if(!Array.isArray(value))return fallback;if(OWNED_AV_COLLECTIONS.has(value))return value;const result=[],length=Math.min(value.length,limit);for(let index=0;index<length;index++)try{const normalized=normalize(value[index],index);normalized!==void 0&&result.push(normalized)}catch{}return ownedSnapshot(result)}catch{return fallback}}function normalizeRates(value){const seen=new Set;return normalizeArray(value,MAX_AV_RATES,candidate=>{if(!(typeof candidate!="number"||!Number.isFinite(candidate)||candidate<MIN_PLAYBACK_RATE||candidate>MAX_PLAYBACK_RATE||seen.has(candidate)))return seen.add(candidate),candidate},EMPTY_RATES)}function normalizePeaks(value){return normalizeArray(value,MAX_AV_PEAKS,candidate=>typeof candidate=="number"?finiteRange(candidate,0,0,1):void 0,EMPTY_PEAKS)}function positiveFinite(value){const finite=finiteNumber(value,1);return finite>0?finite:1}function waveformPaintPeaks(peaks,maxBars){const barCount=Math.max(1,Math.floor(finiteNumber(maxBars,1)));if(peaks.length<=barCount)return peaks;const finalIndex=peaks.length-1;if(barCount===1)return[finiteRange(peaks[finalIndex],0,0,1)];const result=new Array(barCount),preEndpointBars=barCount-1;for(let barIndex=0;barIndex<preEndpointBars;barIndex+=1){const start=Math.floor(barIndex*finalIndex/preEndpointBars),end=Math.floor((barIndex+1)*finalIndex/preEndpointBars);let peak=0;for(let sampleIndex=start;sampleIndex<end;sampleIndex+=1)peak=Math.max(peak,finiteRange(peaks[sampleIndex],0,0,1));result[barIndex]=peak}return result[preEndpointBars]=finiteRange(peaks[finalIndex],0,0,1),result}class LyraAvPlayerBase extends LyraElement{}class LyraAvPlayer extends DocumentAnchorTarget(LyraAvPlayerBase){static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,avPlayerFailedToLoad:LYRA_DEFAULT_avPlayerFailedToLoad,avPlayerLabel:LYRA_DEFAULT_avPlayerLabel,avPlayerPlaybackRate:LYRA_DEFAULT_avPlayerPlaybackRate,avPlayerPosition:LYRA_DEFAULT_avPlayerPosition,avPlayerRateOption:LYRA_DEFAULT_avPlayerRateOption,avPlayerTimeline:LYRA_DEFAULT_avPlayerTimeline,avPlayerTranscript:LYRA_DEFAULT_avPlayerTranscript,fieldRequired:LYRA_DEFAULT_fieldRequired,viewerHighlightLabel:LYRA_DEFAULT_viewerHighlightLabel}}static{this.styles=[LyraElement.styles,styles,srOnly]}static{this.properties={playbackRate:{type:Number,attribute:"playback-rate",reflect:!0,noAccessor:!0},volume:{type:Number,reflect:!0,noAccessor:!0}}}get playbackRate(){return this._playbackRate}set playbackRate(next){const old=this._playbackRate;this._playbackRate=finiteRange(next,1,MIN_PLAYBACK_RATE,MAX_PLAYBACK_RATE),this.requestUpdate("playbackRate",old)}get volume(){return this._volume}set volume(next){const old=this._volume;this._volume=finiteRange(next,1,0,1),this.requestUpdate("volume",old)}get rates(){return this._rates}set rates(value){const previous=this._rates;this._rates=normalizeRates(value),this.requestUpdate("rates",previous)}get cues(){return this._cues}set cues(value){const previous=this._cues;if(this._cues=snapshotLyraAvCues(value),this._cues!==previous){const starts=[...new Set(this._cues.map(cue=>cue.start))].sort((a,b)=>a-b);this.nextCueStarts=new Map;for(let index=0;index<starts.length;index+=1)this.nextCueStarts.set(starts[index],starts[index+1]??1/0)}this.requestUpdate("cues",previous)}get peaks(){return this._peaks}set peaks(value){const previous=this._peaks;this._peaks=normalizePeaks(value),this.requestUpdate("peaks",previous)}get tracks(){return this._tracks}set tracks(value){const previous=this._tracks;this._tracks=snapshotLyraAvTracks(value),this.requestUpdate("tracks",previous)}constructor(){super(),this.src="",this.name="",this.mimeType="",this.poster="",this.loop=!1,this.muted=!1,this.preload="metadata",this._playbackRate=1,this._volume=1,this.controlsSurface="regular",this._rates=DEFAULT_RATES,this._cues=EMPTY_CUES,this.nextCueStarts=new Map,this._peaks=EMPTY_PEAKS,this._tracks=EMPTY_TRACKS,this.anchorKinds=["time-range"],this.duration=0,this.currentTimeState=0,this.activeCueId=null,this.activeCueIndex=-1,this.searchQuery="",this.searchMatches=[],this.activeSearchIndex=-1,this.metadataLoaded=!1,this.sourceError=!1,this.playbackError=!1,this.mediaController=new NativeMediaController(this,{onEvent:event=>this.onNativeMediaEvent(event)}),this.semanticInternals=attachInternalsSafely(this),this.lastTimeChangeAt=0,this.searchLocale="",this.transcriptLocale="",this.searchMatchIndices=new Set,this.cueKeys=[],this.waveformVisible=!1,this.waveformDirty=!1,this.pendingSeekEmission=null,this.lastEmittedTime=null,this.lastReportedSourceError=NO_REPORTED_ERROR,this.connectionEventBaselinePending=!0,this.onMediaFocus=event=>{relayNativeEvent(this,event)},this.onMediaBlur=event=>{relayNativeEvent(this,event)},this.onWindowResize=()=>this.drawWaveform(),this.canvasRef=el=>{if(!el){this.unbindWaveformResizeObserver();return}this.syncWaveformVisibilityObserver(),this.syncWaveformResizeObserver(),this.drawWaveform()},this.mediaRef=el=>{const media=el?.localName==="audio"||el?.localName==="video"?el:void 0;this.mediaController.attach(media)},this.onPlaybackFailure=error=>{this.playbackError=!0,this.announceRenderError(),this.emit("lr-render-error",{error})},this.onHighlightActivate=(id,start)=>{this.activeHighlightId=id,this.seek(start),this.emit("lr-highlight-activate",{highlightId:id})},this.onTimelineClick=event=>{if(!this.duration)return;const rect=event.currentTarget.getBoundingClientRect();if(rect.width<=0)return;const ratio=Math.min(1,Math.max(0,(event.clientX-rect.left)/rect.width));this.seek(ratio*this.duration)},this.onTimelineKeyDown=event=>{if(!(this.duration>0))return;const delta=event.shiftKey?15:5;switch(event.key){case"ArrowLeft":event.preventDefault(),this.seek(Math.max(0,this.currentTime-delta));break;case"ArrowRight":event.preventDefault(),this.seek(Math.min(this.duration,this.currentTime+delta));break;case"Home":event.preventDefault(),this.seek(0);break;case"End":event.preventDefault(),this.seek(this.duration);break;case" ":event.preventDefault(),this.toggle();break;default:return}},this.cueKey=(_cue,index)=>this.cueKeys[index]??`index:${index}`,this.renderCue=(cue,index)=>{const c=cue,start=this.safeCueStart(c),isActive=this.activeCueIndex===index,isMatch=this.searchMatchIndices.has(index),isActiveMatch=index===this.searchMatches[this.activeSearchIndex],part=["cue",isActive?"cue-current":"",isMatch?"cue-match":"",isActiveMatch?"cue-active-match":""].filter(Boolean).join(" ");return html`<button
|
|
2
2
|
part=${part}
|
|
3
3
|
type="button"
|
|
4
4
|
aria-current=${isActive?"true":"false"}
|
|
@@ -6,7 +6,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,quer
|
|
|
6
6
|
?data-active-match=${isActiveMatch}
|
|
7
7
|
@click=${()=>this.seek(start)}
|
|
8
8
|
>
|
|
9
|
-
<span part="cue-time">${
|
|
9
|
+
<span part="cue-time">${formatMediaTime(start,this.effectiveLocale,"round")}</span>
|
|
10
10
|
${c.speaker?html`<span part="cue-speaker">${c.speaker}</span>`:nothing}
|
|
11
11
|
<span part="cue-text">${c.text}</span>
|
|
12
12
|
</button>`},this.transcriptRenderItem=this.renderCue,new ThemeWatcher(this,()=>{this.peaks.length>0&&this.drawWaveform()})}get mediaEl(){return this.mediaController.element}focus(options){this.mediaEl?.focus(options)}blur(){this.mediaEl?.blur()}click(){this.mediaEl?.click()}get currentTime(){return this.mediaController.currentTime}set currentTime(value){this.mediaController.currentTime=value,this.currentTimeState=this.mediaController.currentTime}detectedKind(){return this.kind==="audio"||this.kind==="video"?this.kind:(this.mimeType??"").startsWith("audio/")?"audio":"video"}get effectivePreload(){return this.preload==="none"||this.preload==="auto"?this.preload:"metadata"}willUpdate(changed){super.willUpdate(changed),changed.has("controlsSurface")&&(this.controlsSurface=CONTROLS_SURFACE.normalizeReflected(this,"controls-surface",this.controlsSurface)),this.semanticInternals.role=hostAriaLabel(this)!==null?"region":null;const mayEmitConnectionTransition=this.isConnected&&!this.connectionEventBaselinePending,locale=this.effectiveLocale;let refreshTranscript=!1;if(changed.has("kind")&&this.kind!==void 0&&this.kind!=="audio"&&this.kind!=="video"&&(this.kind=void 0),changed.has("preload")&&this.preload!==this.effectivePreload&&(this.preload=this.effectivePreload),changed.has("cues")&&(this.rebuildCueKeys(),this.metadataLoaded&&this.reconcileActiveCue()),this.transcriptLocale!==locale&&(this.transcriptLocale=locale,refreshTranscript=!0),this.hasUpdated&&(changed.has("src")||changed.has("kind")||changed.has("mimeType"))&&(this.duration=0,this.currentTimeState=0,this.activeCueId=null,this.activeCueIndex=-1,this.metadataLoaded=!1,this.sourceError=!1,this.playbackError=!1,this.lastTimeChangeAt=0,this.pendingSeekEmission=null,this.lastEmittedTime=null,this.lastReportedSourceError=NO_REPORTED_ERROR,this.mediaController.startGeneration(),changed.has("src")&&this.src&&!safeMediaSrc(this.src))){const error=new TypeError("The media source URL is not allowed.");mayEmitConnectionTransition&&(this.announceRenderError(),this.emit("lr-render-error",{error}))}this.searchQuery&&(changed.has("cues")||this.searchLocale!==locale)&&(this.reconcileSearchMatches(changed.get("cues")),refreshTranscript=!0),refreshTranscript&&this.refreshTranscriptRenderItem()}updated(changed){super.updated(changed),changed.has("playbackRate")&&(this.mediaController.playbackRate=this.playbackRate,changed.get("playbackRate")!==void 0&&this.emit("lr-rate-change",{rate:this.playbackRate})),changed.has("volume")&&(this.mediaController.volume=this.volume),changed.has("muted")&&(this.mediaController.muted=this.muted),changed.has("peaks")&&(this.syncWaveformVisibilityObserver(),this.syncWaveformResizeObserver(),this.drawWaveform()),this.isConnected&&(this.connectionEventBaselinePending=!1)}connectedCallback(){super.connectedCallback(),this.connectionEventBaselinePending=!0,this.syncErrorAnnouncementSink(),this.mediaController.reconnect(),this.bindResizeWindow(),this.syncWaveformVisibilityObserver(),this.syncWaveformResizeObserver(),this.waveformDirty&&this.drawWaveform(),this.requestUpdate()}firstUpdated(changed){super.firstUpdated(changed),this.drawWaveform()}disconnectedCallback(){this.connectionEventBaselinePending=!0,this.mediaController.disconnect(),this.releaseErrorAnnouncementSink(),this.unbindResizeWindow(),this.unbindWaveformResizeObserver(),this.cancelWaveformDrawFrame(),this.waveformDetachedObserverWindow=this.waveformObserverWindow,this.unbindWaveformVisibilityObserver(),this.waveformDirty=this.peaks.length>0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.bindResizeWindow(),this.syncWaveformVisibilityObserver(),this.syncWaveformResizeObserver(),this.isConnected&&this.waveformDirty&&this.drawWaveform()}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}announceRenderError(){this.errorAnnouncementSink?.announce(this.localize("avPlayerFailedToLoad"))}bindResizeWindow(){const nextWindow=this.isConnected?this.ownerDocument.defaultView:null;this.resizeWindow!==nextWindow&&(this.unbindResizeWindow(),this.resizeWindow=nextWindow??void 0,this.resizeWindow?.addEventListener("resize",this.onWindowResize))}unbindResizeWindow(){this.resizeWindow?.removeEventListener("resize",this.onWindowResize),this.resizeWindow=void 0}syncWaveformVisibilityObserver(){const owner=this.isConnected&&this.peaks.length>0?this.ownerDocument.defaultView:null;if(this.waveformIntersectionObserver&&this.waveformObserverWindow===owner)return;const needsFreshSameRealmVisibility=owner!==null&&this.waveformDetachedObserverWindow===owner;if(owner!==null&&(this.waveformDetachedObserverWindow=void 0),this.cancelWaveformDrawFrame(),this.unbindWaveformVisibilityObserver(),!owner)return;const IntersectionObserverCtor=owner.IntersectionObserver;if(!IntersectionObserverCtor){this.waveformVisible=!0;return}needsFreshSameRealmVisibility&&(this.waveformVisible=!1),this.waveformDirty=!0;let observer;observer=new IntersectionObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.waveformIntersectionObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this);!entry||entry.isIntersecting===this.waveformVisible||(this.waveformVisible=entry.isIntersecting,this.waveformVisible?this.waveformDirty&&this.scheduleWaveformDraw():this.cancelWaveformDrawFrame())}),this.waveformObserverWindow=owner,this.waveformIntersectionObserver=observer,observer.observe(this)}unbindWaveformVisibilityObserver(){this.waveformIntersectionObserver?.disconnect(),this.waveformIntersectionObserver=void 0,this.waveformObserverWindow=void 0}syncWaveformResizeObserver(){const target=this.isConnected&&this.peaks.length>0?this.canvasEl:void 0,owner=target?.ownerDocument.defaultView;if(target&&owner&&this.waveformResizeObserver&&this.waveformResizeObserverWindow===owner&&this.waveformResizeTarget===target||(this.unbindWaveformResizeObserver(),!target||!owner||typeof owner.ResizeObserver!="function"))return;let observer;observer=new owner.ResizeObserver(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.waveformResizeObserver!==observer||this.waveformResizeTarget!==target||!entries.some(entry=>entry.target===target))return;const width=positiveFinite(target.clientWidth),height=positiveFinite(target.clientHeight),dpr=positiveFinite(owner.devicePixelRatio),previous=this.lastWaveformAllocation;previous?.target===target&&previous.width===width&&previous.height===height&&previous.dpr===dpr||this.drawWaveform()}),this.waveformResizeObserver=observer,this.waveformResizeObserverWindow=owner,this.waveformResizeTarget=target,observer.observe(target)}unbindWaveformResizeObserver(){this.waveformResizeObserver?.disconnect(),this.waveformResizeObserver=void 0,this.waveformResizeObserverWindow=void 0,this.waveformResizeTarget=void 0,this.lastWaveformAllocation=void 0}play(){return this.mediaController.play()}pause(){this.mediaController.pause()}toggle(){const media=this.mediaEl;if(media?.paused){const generation=this.mediaController.generation;this.play().catch(error=>{!this.isConnected||!this.mediaController.isCurrentGeneration(generation,media)||this.onPlaybackFailure(error)})}else this.pause()}seek(seconds){this.currentTime=seconds,this.emitTimeChange(!0,!0),this.pendingSeekEmission=this.currentTimeState,this.reconcileActiveCue()}async applyAnchor(anchor){return anchor.kind!=="time-range"||!this.metadataLoaded?!1:(this.seek(anchor.start),!0)}onLoadedMetadata(){this.metadataLoaded=!0,this.duration=this.mediaController.duration,this.currentTimeState=this.mediaController.currentTime,this.sourceError=!1,this.playbackError=!1,this.lastReportedSourceError=NO_REPORTED_ERROR,this.reconcileActiveCue(),this.emit("lr-load",{duration:this.duration,kind:this.detectedKind()})}onPlay(){this.playbackError=!1,this.emit("lr-play",null)}onPause(){this.emit("lr-pause",null)}onMediaError(){const error=this.mediaEl?.error??null,identity=error??"native-media-error-without-detail";identity!==this.lastReportedSourceError&&(this.lastReportedSourceError=identity,this.sourceError=!0,this.playbackError=!1,this.announceRenderError(),this.emit("lr-render-error",{error:error??new Error("The media failed to load.")}))}onNativeMediaEvent(event){switch(event.type){case"loadedmetadata":this.onLoadedMetadata();break;case"durationchange":this.duration=this.mediaController.duration,this.reconcileActiveCue();break;case"play":this.onPlay();break;case"pause":this.onPause();break;case"error":this.onMediaError();break;case"volumechange":{const nextVolume=this.mediaController.volume,nextMuted=this.mediaController.muted;this.volume!==nextVolume&&(this.volume=nextVolume),this.muted!==nextMuted&&(this.muted=nextMuted);break}case"ratechange":{const nextRate=this.mediaController.playbackRate;this.playbackRate!==nextRate&&(this.playbackRate=nextRate);break}case"timeupdate":this.onTimeUpdate();break;case"seeked":this.onSeeked();break;default:break}}emitTimeChange(force,allowDuplicate=!1){const now=Date.now();if(!force&&now-this.lastTimeChangeAt<TIME_CHANGE_THROTTLE_MS)return;const nextTime=this.currentTime;this.currentTimeState=nextTime,!(!allowDuplicate&&nextTime===this.lastEmittedTime)&&(this.lastTimeChangeAt=now,this.lastEmittedTime=nextTime,this.emit("lr-time-change",{currentTime:this.currentTimeState}))}onTimeUpdate(){this.emitTimeChange(!1),this.reconcileActiveCue()}reconcileActiveCue(){const time=this.currentTime;let active,activeIndex=-1;this.cues.forEach((cue,index)=>{const start=this.safeCueStart(cue),end=this.safeCueEnd(cue,start);time>=start&&time<end&&(!active||start>=this.safeCueStart(active))&&(active=cue,activeIndex=index)});const nextId=active?.cueId??null;this.setActiveCue(nextId,activeIndex)}setActiveCue(nextId,activeIndex){(nextId!==this.activeCueId||activeIndex!==this.activeCueIndex)&&(this.activeCueId=nextId,this.activeCueIndex=activeIndex,this.emit("lr-cue-change",Object.freeze({cueId:nextId,index:activeIndex})))}onSeeked(){const completedTime=this.currentTime;this.pendingSeekEmission===null||completedTime!==this.pendingSeekEmission?this.emitTimeChange(!0):this.currentTimeState=completedTime,this.pendingSeekEmission=null,this.reconcileActiveCue()}async search(query2){return this.searchQuery=query2,this.reconcileSearchMatches(),this.activeSearchIndex=this.searchMatches.length?0:-1,this.refreshTranscriptRenderItem(),this.emitSearchChange(),await this.revealActiveSearchMatch(),this.searchMatches.length}reconcileSearchMatches(previousCues){const locale=this.effectiveLocale,q=this.searchQuery.trim().toLocaleLowerCase(locale),previousMatchIndex=this.searchMatches[this.activeSearchIndex],previousActiveId=previousCues&&previousMatchIndex!==void 0?previousCues[previousMatchIndex]?.cueId:void 0;if(this.searchMatches=q?this.cues.reduce((acc,cue,index)=>((cue.text.toLocaleLowerCase(locale).includes(q)||(cue.speaker??"").toLocaleLowerCase(locale).includes(q))&&acc.push(index),acc),[]):[],this.searchMatchIndices=new Set(this.searchMatches),this.searchLocale=locale,!this.searchMatches.length){this.activeSearchIndex=-1;return}const retainedPosition=previousActiveId?this.searchMatches.findIndex(index=>this.cues[index]?.cueId===previousActiveId):-1;this.activeSearchIndex=retainedPosition>=0?retainedPosition:Math.min(Math.max(0,this.activeSearchIndex),this.searchMatches.length-1)}async searchNext(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex+1)%this.searchMatches.length,this.refreshTranscriptRenderItem(),this.emitSearchChange(),await this.revealActiveSearchMatch(),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.activeSearchIndex=(this.activeSearchIndex-1+this.searchMatches.length)%this.searchMatches.length,this.refreshTranscriptRenderItem(),this.emitSearchChange(),await this.revealActiveSearchMatch(),!0):!1}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchIndices=new Set,this.activeSearchIndex=-1,this.refreshTranscriptRenderItem(),this.emitSearchChange()}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:!0,activeIndex:this.activeSearchIndex})}async revealActiveSearchMatch(){await this.updateComplete;const list=this.renderRoot.querySelector("lr-virtual-list");if(!list)return;await list.updateComplete;const index=this.searchMatches[this.activeSearchIndex];index!==void 0&&list.scrollToIndex(index,{align:"auto",behavior:"auto"})}drawWaveform(){const canvas=this.canvasEl,ownerWindow=this.ownerDocument.defaultView;if(!this.peaks.length){this.waveformDirty=!1;return}if(!this.isConnected||!canvas||!ownerWindow||!this.waveformVisible){this.waveformDirty=!0;return}this.cancelWaveformDrawFrame(),this.waveformDirty=!1,this.paintWaveform()}paintWaveform(){const canvas=this.canvasEl;if(!canvas||!this.peaks.length)return;const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow)return;const dpr=positiveFinite(ownerWindow.devicePixelRatio),width=positiveFinite(canvas.clientWidth),height=positiveFinite(canvas.clientHeight),allocation=resolveBoundedCanvasAllocation({cssWidth:width,cssHeight:height,desiredScale:dpr,maxDimension:MAX_CANVAS_DIMENSION,maxPixels:MAX_CANVAS_PIXELS});this.lastWaveformAllocation={target:canvas,width,height,dpr},canvas.width=allocation.pixelWidth,canvas.height=allocation.pixelHeight;const ctx=canvas.getContext("2d");if(!ctx)return;const scaleX=allocation.scaleX,scaleY=allocation.scaleY;ctx.setTransform(scaleX,0,0,scaleY,0,0),ctx.clearRect(0,0,width,height);const computed=ownerWindow.getComputedStyle(this),tokenColor=computed.getPropertyValue("--lr-color-brand").trim(),color=ownerWindow.CSS.supports("color",tokenColor)?tokenColor:computed.color;ctx.fillStyle=color;const peaks=waveformPaintPeaks(this.peaks,canvas.width),barWidth=width/peaks.length,physicalPixel=Math.min(barWidth,finiteNumber(1/scaleX,barWidth)),paintedBarWidth=Math.max(physicalPixel,barWidth-physicalPixel);peaks.forEach((peak,i)=>{const barHeight=Math.max(1,finiteRange(peak,0,0,1)*height);ctx.fillRect(i*barWidth,(height-barHeight)/2,paintedBarWidth,barHeight)})}scheduleWaveformDraw(){if(this.waveformDrawFrame)return;const owner=this.ownerDocument.defaultView;if(!owner||!this.isConnected)return;const request={owner,handle:0};request.handle=owner.requestAnimationFrame(()=>{this.waveformDrawFrame===request&&(this.waveformDrawFrame=void 0,this.isConnected&&this.ownerDocument.defaultView===owner&&this.drawWaveform())}),this.waveformDrawFrame=request}cancelWaveformDrawFrame(){const request=this.waveformDrawFrame;request&&request.owner.cancelAnimationFrame(request.handle),this.waveformDrawFrame=void 0}renderMarkers(){if(!this.duration)return nothing;const ranged=this.highlights.filter(h=>h.anchor.kind==="time-range");return ranged.length?html`${ranged.map(h=>{const startSeconds=finiteRange(h.anchor.start,0,0,this.duration),endSeconds=h.anchor.end==null?startSeconds:finiteRange(h.anchor.end,startSeconds,startSeconds,this.duration),start=startSeconds/this.duration*100,end=endSeconds/this.duration*100;return html`<button
|
|
@@ -81,7 +81,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,quer
|
|
|
81
81
|
aria-valuemin="0"
|
|
82
82
|
aria-valuemax=${String(this.duration)}
|
|
83
83
|
aria-valuenow=${String(this.currentTimeState)}
|
|
84
|
-
aria-valuetext=${this.localize("avPlayerPosition",void 0,{current:
|
|
84
|
+
aria-valuetext=${this.localize("avPlayerPosition",void 0,{current:formatMediaTime(this.currentTimeState,this.effectiveLocale,"round"),duration:formatMediaTime(this.duration,this.effectiveLocale,"round")})}
|
|
85
85
|
aria-label=${this.localize("avPlayerTimeline")}
|
|
86
86
|
@click=${this.onTimelineClick}
|
|
87
87
|
@keydown=${this.onTimelineKeyDown}
|
|
@@ -35,7 +35,7 @@ export interface LyraFileInputFilesEvent extends CustomEvent<LyraFileInputFilesD
|
|
|
35
35
|
* @customElement lr-file-input
|
|
36
36
|
* @slot - Custom dropzone content; replaces the localized instruction (`fileInputDefaultLabel`).
|
|
37
37
|
* It does not name the control: the accessible name comes from a host
|
|
38
|
-
* `aria-label
|
|
38
|
+
* `aria-label`, then the form label (`label` or the `label`
|
|
39
39
|
* slot), then the localized instruction -- so icon-only slot content still announces. Slotted
|
|
40
40
|
* text shown without a form label should carry a matching host `aria-label` so the name contains
|
|
41
41
|
* the visible text.
|
|
@@ -210,7 +210,7 @@ directory:boolean;
|
|
|
210
210
|
/** Ignores files pasted from the clipboard into the dropzone, which are otherwise accepted. */
|
|
211
211
|
withoutPaste:boolean;
|
|
212
212
|
/** Form-control label, rendered in `form-control-label` and naming the dropzone button (unless
|
|
213
|
-
* a host `aria-label`
|
|
213
|
+
* a host `aria-label` is set). It never replaces the dropzone instruction --
|
|
214
214
|
* customize that with the `dropzone` slot or the `fileInputDefaultLabel` string. Omitted, `''`
|
|
215
215
|
* and whitespace-only values render identically: no visible label, and the button is named by
|
|
216
216
|
* the instruction. */
|
|
@@ -233,10 +233,7 @@ withError:boolean;size:LyraSize;
|
|
|
233
233
|
* that should trigger live revalidation. A validator that throws fails closed with the generic
|
|
234
234
|
* localized message. Barred (own or fieldset-cascaded `disabled`) exactly like the intrinsic
|
|
235
235
|
* constraint. */
|
|
236
|
-
validators:LyraFileInputValidator[];
|
|
237
|
-
/** Compatibility fallback below the host aria-label, including an explicitly empty host value.
|
|
238
|
-
* @deprecated Use the host aria-label attribute or the native ariaLabel property. */
|
|
239
|
-
get accessibleLabel():string;set accessibleLabel(value:string);
|
|
236
|
+
validators:LyraFileInputValidator[];
|
|
240
237
|
/** The host `aria-label`: names the dropzone ahead of every other source, by presence, so an
|
|
241
238
|
* explicitly empty value stays empty. */
|
|
242
239
|
private hostAccessibleLabel;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";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{srOnly}from"../../../internal/a11y.js";import{warnDeprecatedUsage}from"../../../internal/dev-mode-attribute-warning.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{AggregateFileLimitTracker}from"../../../internal/aggregate-file-limits.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController}from"../../../internal/drop-session-controller.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{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_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,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_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,DEFAULT_MAX_FILES=100,DEFAULT_MAX_TOTAL_SIZE_BYTES=250*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,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,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,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.collectionSupport=collectionSupport}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)}get accessibleLabel(){return this.legacyAccessibleLabel}set accessibleLabel(value){warnDeprecatedUsage(this,"property","accessibleLabel","aria-label"),this.legacyAccessibleLabel=value}constructor(){super(),this.multiple=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,this.directory=!1,this.withoutPaste=!1,this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.legacyAccessibleLabel="",this.hostAccessibleLabel=null,this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.hasSyncedDescribedByElements=!1,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>{const drop=this.dropSession.beginDrop(e);if(!drop)return;const{token,files,folders,overLimit}=drop;if(overLimit&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){this.dropSession.readFolders(folders,token).then(result=>{if(!this.dropSession.isCurrent(token)||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.withoutPaste||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)),installInteractionOnInvalid(this,this.markInteracted),this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.liveDisabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}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=[...valid];const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files.slice(0,1):this.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.disconnectValidatorAttributeObserver(),this.dropSession.reset();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()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.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.hasEffectiveValue&&(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()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),withStaticValidityCheck(this,()=>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.dropSession.reset(),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";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)}get effectiveMaxFiles(){const maxFiles=this.maxFiles;return maxFiles===0||maxFiles===1/0?null:finiteRange(maxFiles>0?maxFiles:NaN,DEFAULT_MAX_FILES,1)}get effectiveMaxTotalSize(){const maxTotalSize=this.maxTotalSize;return maxTotalSize===0||maxTotalSize===1/0?null:finiteRange(maxTotalSize>0?maxTotalSize:NaN,DEFAULT_MAX_TOTAL_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"}totalFileSize(files){let total=0;for(const file of files){const size=file.size;Number.isFinite(size)&&(total+=size)}return total}classify(fileList,isPreview=!1){const limits={maxFiles:this.effectiveMaxFiles,maxTotalSize:this.effectiveMaxTotalSize},tracker=new AggregateFileLimitTracker((this.nonRetaining?0:this._files.length)+finiteCount(this.heldFileCount,0),(this.nonRetaining?0:this.totalFileSize(this._files))+finiteCount(this.heldTotalSize,0));if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"})),...tracker.allowance(limits)};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);if(reason!=="ok"){rejected.push({file:f,reason});continue}const limitReason=tracker.evaluate(f,limits);if(limitReason){rejected.push({file:f,reason:limitReason});continue}files.push(f)}return{files,rejected,...tracker.allowance(limits)}}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});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",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,remainingFiles,remainingTotalSize}=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.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot,remainingFiles,remainingTotalSize}))}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()}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 dropzoneInstruction(){return 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
|
+
import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";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{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteRange}from"../../../internal/numbers.js";import{AggregateFileLimitTracker}from"../../../internal/aggregate-file-limits.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{DropSessionController}from"../../../internal/drop-session-controller.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{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_fileInputRejectedMaxFiles,LYRA_DEFAULT_fileInputRejectedMaxTotalSize,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_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,DEFAULT_MAX_FILES=100,DEFAULT_MAX_TOTAL_SIZE_BYTES=250*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,fileInputRejectedMaxFiles:LYRA_DEFAULT_fileInputRejectedMaxFiles,fileInputRejectedMaxTotalSize:LYRA_DEFAULT_fileInputRejectedMaxTotalSize,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,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.collectionSupport=collectionSupport}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.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.maxFiles=0,this.maxTotalSize=0,this.heldFileCount=0,this.heldTotalSize=0,this.nonRetaining=!1,this.valuePresent=!1,this.directory=!1,this.withoutPaste=!1,this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.hostAccessibleLabel=null,this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.hasSyncedDescribedByElements=!1,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.markInteracted=()=>{this.touched||(this.touched=!0,this.updateValidity(),this.publishCustomStates())},this.onDragEnter=e=>this.dropSession.onDragEnter(e),this.onDragOver=e=>this.dropSession.onDragOver(e),this.onDragLeave=e=>this.dropSession.onDragLeave(e),this.onDrop=e=>{const drop=this.dropSession.beginDrop(e);if(!drop)return;const{token,files,folders,overLimit}=drop;if(overLimit&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){this.dropSession.readFolders(folders,token).then(result=>{if(!this.dropSession.isCurrent(token)||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.withoutPaste||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)),installInteractionOnInvalid(this,this.markInteracted),this.internals.setFormValue(null),this.dropSession=new DropSessionController(this,{isDisabled:()=>this.liveDisabled,previewRejects:items=>this.classify(items,!0).rejected.length>0,onStateChange:()=>{this.dragState=this.dropSession.state,this.publishCustomStates()}})}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}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=[...valid];const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.dropSession.reset(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files.slice(0,1):this.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.disconnectValidatorAttributeObserver(),this.dropSession.reset();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()),(changed.has("valuePresent")||changed.has("nonRetaining"))&&this.updateValidity();const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.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.hasEffectiveValue&&(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()}get hasEffectiveValue(){return this._files.length>0||this.nonRetaining&&this.valuePresent}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",!this.hasEffectiveValue),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),withStaticValidityCheck(this,()=>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.dropSession.reset(),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";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)}get effectiveMaxFiles(){const maxFiles=this.maxFiles;return maxFiles===0||maxFiles===1/0?null:finiteRange(maxFiles>0?maxFiles:NaN,DEFAULT_MAX_FILES,1)}get effectiveMaxTotalSize(){const maxTotalSize=this.maxTotalSize;return maxTotalSize===0||maxTotalSize===1/0?null:finiteRange(maxTotalSize>0?maxTotalSize:NaN,DEFAULT_MAX_TOTAL_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"}totalFileSize(files){let total=0;for(const file of files){const size=file.size;Number.isFinite(size)&&(total+=size)}return total}classify(fileList,isPreview=!1){const limits={maxFiles:this.effectiveMaxFiles,maxTotalSize:this.effectiveMaxTotalSize},tracker=new AggregateFileLimitTracker((this.nonRetaining?0:this._files.length)+finiteCount(this.heldFileCount,0),(this.nonRetaining?0:this.totalFileSize(this._files))+finiteCount(this.heldTotalSize,0));if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"})),...tracker.allowance(limits)};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);if(reason!=="ok"){rejected.push({file:f,reason});continue}const limitReason=tracker.evaluate(f,limits);if(limitReason){rejected.push({file:f,reason:limitReason});continue}files.push(f)}return{files,rejected,...tracker.allowance(limits)}}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});case"maxFiles":return this.localize("fileInputRejectedMaxFiles",void 0,{filename});case"maxTotalSize":return this.localize("fileInputRejectedMaxTotalSize",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,remainingFiles,remainingTotalSize}=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.nonRetaining||(this.files=this.effectiveMultiple?[...this._files,...files]:files),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot,remainingFiles,remainingTotalSize}))}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()}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 dropzoneInstruction(){return 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>
|
|
@@ -13,7 +13,7 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
13
13
|
aria-label=${this.localize("removeWithContext",void 0,{label:file.name})}
|
|
14
14
|
@click=${()=>this.removeFile(index)}
|
|
15
15
|
>${closeIcon()}</button>
|
|
16
|
-
</div>`}render(){const instruction=this.dropzoneInstruction,hasLabel=this.withLabel||this.slotPresence.has("label")||(this.label??"").trim().length>0,
|
|
16
|
+
</div>`}render(){const instruction=this.dropzoneInstruction,hasLabel=this.withLabel||this.slotPresence.has("label")||(this.label??"").trim().length>0,accessibleLabel=this.hostAccessibleLabel,labelledBy=accessibleLabel==null&&hasLabel?"file-input-label":void 0,fallbackAriaLabel=accessibleLabel??(hasLabel?void 0:instruction),hasHint=this.withHint||this.slotPresence.has("hint")||(this.hint??"").length>0,renderedError=this.errorText||this.customError||(this.touched?this.validationMessage:""),hasError=this.withError||this.slotPresence.has("error")||renderedError.length>0,describedBy=[hasError?"file-input-error":"",hasHint?"file-input-hint":""].filter(Boolean).join(" "),invalid=hasError||this.touched&&!this.internals.validity.valid;return html`
|
|
17
17
|
<div part="form-control">
|
|
18
18
|
<label
|
|
19
19
|
id="file-input-label"
|
|
@@ -87,4 +87,4 @@ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/co
|
|
|
87
87
|
?disabled=${this.effectiveDisabled}
|
|
88
88
|
@change=${this.onInputChange}
|
|
89
89
|
/>
|
|
90
|
-
`}}__decorate([property({type:Boolean,reflect:!0})],LyraFileInput.prototype,"multiple",void 0),__decorate([property()],LyraFileInput.prototype,"accept",void 0),__decorate([property()],LyraFileInput.prototype,"capture",void 0),__decorate([property({attribute:!1})],LyraFileInput.prototype,"allowedMimeTypes",null),__decorate([property({attribute:!1})],LyraFileInput.prototype,"forbiddenMimeTypes",null),__decorate([property({type:Number,attribute:"max-file-size"})],LyraFileInput.prototype,"maxFileSize",void 0),__decorate([property({type:Number,attribute:"max-files"})],LyraFileInput.prototype,"maxFiles",void 0),__decorate([property({type:Number,attribute:"max-total-size"})],LyraFileInput.prototype,"maxTotalSize",void 0),__decorate([property({type:Number,attribute:"held-file-count"})],LyraFileInput.prototype,"heldFileCount",void 0),__decorate([property({type:Number,attribute:"held-total-size"})],LyraFileInput.prototype,"heldTotalSize",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"non-retaining"})],LyraFileInput.prototype,"nonRetaining",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"value-present"})],LyraFileInput.prototype,"valuePresent",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraFileInput.prototype,"directory",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"without-paste"})],LyraFileInput.prototype,"withoutPaste",void 0),__decorate([property()],LyraFileInput.prototype,"label",void 0),__decorate([property()],LyraFileInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraFileInput.prototype,"errorText",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraFileInput.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraFileInput.prototype,"withHint",void 0),__decorate([property({type:Boolean,attribute:"with-error"})],LyraFileInput.prototype,"withError",void 0),__decorate([property({reflect:!0})],LyraFileInput.prototype,"size",void 0),__decorate([property({attribute:!1})],LyraFileInput.prototype,"validators",void 0),__decorate([property({attribute
|
|
90
|
+
`}}__decorate([property({type:Boolean,reflect:!0})],LyraFileInput.prototype,"multiple",void 0),__decorate([property()],LyraFileInput.prototype,"accept",void 0),__decorate([property()],LyraFileInput.prototype,"capture",void 0),__decorate([property({attribute:!1})],LyraFileInput.prototype,"allowedMimeTypes",null),__decorate([property({attribute:!1})],LyraFileInput.prototype,"forbiddenMimeTypes",null),__decorate([property({type:Number,attribute:"max-file-size"})],LyraFileInput.prototype,"maxFileSize",void 0),__decorate([property({type:Number,attribute:"max-files"})],LyraFileInput.prototype,"maxFiles",void 0),__decorate([property({type:Number,attribute:"max-total-size"})],LyraFileInput.prototype,"maxTotalSize",void 0),__decorate([property({type:Number,attribute:"held-file-count"})],LyraFileInput.prototype,"heldFileCount",void 0),__decorate([property({type:Number,attribute:"held-total-size"})],LyraFileInput.prototype,"heldTotalSize",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"non-retaining"})],LyraFileInput.prototype,"nonRetaining",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"value-present"})],LyraFileInput.prototype,"valuePresent",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraFileInput.prototype,"directory",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"without-paste"})],LyraFileInput.prototype,"withoutPaste",void 0),__decorate([property()],LyraFileInput.prototype,"label",void 0),__decorate([property()],LyraFileInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraFileInput.prototype,"errorText",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraFileInput.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraFileInput.prototype,"withHint",void 0),__decorate([property({type:Boolean,attribute:"with-error"})],LyraFileInput.prototype,"withError",void 0),__decorate([property({reflect:!0})],LyraFileInput.prototype,"size",void 0),__decorate([property({attribute:!1})],LyraFileInput.prototype,"validators",void 0),__decorate([property({attribute:"aria-label"})],LyraFileInput.prototype,"hostAccessibleLabel",void 0),__decorate([property({attribute:"accepted-message"})],LyraFileInput.prototype,"acceptedMessage",void 0),__decorate([property({attribute:"rejected-message"})],LyraFileInput.prototype,"rejectedMessage",void 0),__decorate([state()],LyraFileInput.prototype,"dragState",void 0),__decorate([state()],LyraFileInput.prototype,"resultStatus",void 0),__decorate([state()],LyraFileInput.prototype,"rejectedFiles",void 0),__decorate([state()],LyraFileInput.prototype,"touched",void 0),__decorate([state()],LyraFileInput.prototype,"validityRevision",void 0),__decorate([query('[part~="base"]')],LyraFileInput.prototype,"baseEl",void 0),__decorate([query('input[type="file"]')],LyraFileInput.prototype,"inputEl",void 0);export{DEFAULT_MAX_FILES,DEFAULT_MAX_FILE_SIZE_BYTES,DEFAULT_MAX_TOTAL_SIZE_BYTES,LyraFileInput};
|
|
@@ -12,7 +12,7 @@ readonly alt?:string;
|
|
|
12
12
|
/** Optional visible caption for this image, rendered in `part="caption"` below the stage. */
|
|
13
13
|
readonly caption?:string;}
|
|
14
14
|
/**
|
|
15
|
-
* Reason a lightbox was dismissed, forwarded as the `lr-
|
|
15
|
+
* Reason a lightbox was dismissed, forwarded as the `lr-close-request` and `lr-close` event detail --
|
|
16
16
|
* 1:1 copy of `<lr-dialog>`'s own `DialogCloseReason` contract. `'escape'` and `'backdrop'`
|
|
17
17
|
* are emitted by the lightbox's own built-in dismiss triggers; `'close-button'` by the built-in
|
|
18
18
|
* close button; `'unmount'` is emitted when the lightbox is removed from the DOM while still
|
|
@@ -20,12 +20,10 @@ readonly caption?:string;}
|
|
|
20
20
|
* to `close()` directly.
|
|
21
21
|
*/
|
|
22
22
|
export type LyraLightboxCloseReason='escape'|'backdrop'|'close-button'|'api'|'unmount'|(string&Record<never,never>);
|
|
23
|
-
/** The
|
|
23
|
+
/** The close affordance, or the lightbox host when removal closes an open instance. */
|
|
24
24
|
export interface LyraLightboxHideDetail{source:Element;}
|
|
25
25
|
/** The affordance that requested lightbox dismissal. */
|
|
26
|
-
export interface LyraLightboxCloseDetail{reason:LyraLightboxCloseReason;}export interface LyraLightboxEventMap{'lr-show':CustomEvent<null>;'lr-after-show':CustomEvent<null>;'lr-hide':CustomEvent<LyraLightboxHideDetail>;'lr-after-hide':CustomEvent<null>;'lr-close-request':CustomEvent<LyraLightboxCloseDetail>;'lr-close':CustomEvent<LyraLightboxCloseDetail>;
|
|
27
|
-
/** @deprecated Use lr-close-request for vetoes and lr-close for accepted dismissal. */
|
|
28
|
-
'lr-lightbox-close':CustomEvent<LyraLightboxCloseReason>;'lr-index-change':CustomEvent<{index:number;}>;
|
|
26
|
+
export interface LyraLightboxCloseDetail{reason:LyraLightboxCloseReason;}export interface LyraLightboxEventMap{'lr-show':CustomEvent<null>;'lr-after-show':CustomEvent<null>;'lr-hide':CustomEvent<LyraLightboxHideDetail>;'lr-after-hide':CustomEvent<null>;'lr-close-request':CustomEvent<LyraLightboxCloseDetail>;'lr-close':CustomEvent<LyraLightboxCloseDetail>;'lr-index-change':CustomEvent<{index:number;}>;
|
|
29
27
|
/** Not emitted by `LyraLightbox` itself -- the embedded `<lr-pan-zoom>` already
|
|
30
28
|
* dispatches this via a composed, bubbling `emit()` call, which continues through this
|
|
31
29
|
* element's own shadow boundary with no re-dispatch needed. Listed here purely for
|
|
@@ -61,11 +59,12 @@ export interface LyraLightboxCloseDetail{reason:LyraLightboxCloseReason;}export
|
|
|
61
59
|
*
|
|
62
60
|
* Lifecycle: `show()` emits cancelable `lr-show` before committing `open=true`, followed by
|
|
63
61
|
* `lr-after-show` after the open panel renders. `hide()`/`close()` and post-render writes to
|
|
64
|
-
* `open=false`
|
|
62
|
+
* `open=false` emits cancelable `lr-hide` and `lr-close-request`, followed by
|
|
65
63
|
* `lr-close` with `{ reason }` after the state commits, and
|
|
66
64
|
* `lr-after-hide` after the closed state renders. A veto leaves the property and reflected
|
|
67
65
|
* attribute synchronized. Initial `open` markup is state rather than a transition and emits no
|
|
68
|
-
* lifecycle events.
|
|
66
|
+
* lifecycle events. Removing an open instance emits non-cancelable `lr-hide`, `lr-close` with
|
|
67
|
+
* reason `unmount`, and `lr-after-hide`; removal cannot be vetoed.
|
|
69
68
|
*
|
|
70
69
|
* **Scope for v1 (deliberate, not oversights):** no default slot / no arbitrary slotted content
|
|
71
70
|
* per image (data-driven via `images` only); no dot-style indicators (a textual counter scales
|
|
@@ -83,21 +82,13 @@ export interface LyraLightboxCloseDetail{reason:LyraLightboxCloseReason;}export
|
|
|
83
82
|
* @customElement lr-lightbox
|
|
84
83
|
* @slot actions - Optional extra toolbar buttons (e.g. download/share/delete), rendered in
|
|
85
84
|
* `part="toolbar"` between the counter and the close button.
|
|
86
|
-
* @event lr-
|
|
85
|
+
* @event lr-hide - Conditionally cancelable visibility event with the close source in its detail:
|
|
86
|
+
* cancelable before a requested close, non-cancelable when an open instance unmounts.
|
|
87
|
+
* @event lr-close-request - Cancelable proposal before dismissal; `detail: { reason }`.
|
|
88
|
+
* Calling `preventDefault()` keeps the lightbox open.
|
|
87
89
|
* @event lr-close - Non-cancelable accepted dismissal with `{ reason }` detail, including unmount.
|
|
88
|
-
* @event lr-lightbox-close - Deprecated: use `lr-close-request` for vetoes and `lr-close` for
|
|
89
|
-
* accepted dismissal. The compatibility event retains its string detail and veto behavior. `detail: LyraLightboxCloseReason`. Cancelable -- a listener
|
|
90
|
-
* calling `preventDefault()` stops the lightbox from closing, for every dismissal path
|
|
91
|
-
* (Escape, backdrop, the built-in close button, or a consumer's own `close()` call). Fired
|
|
92
|
-
* whenever the lightbox is dismissed via Escape, a backdrop click, the built-in close button,
|
|
93
|
-
* a `close()` call, or (with reason `'unmount'`, not cancelable in practice since the element
|
|
94
|
-
* is already being removed) removal from the DOM by anything else while still open.
|
|
95
90
|
* @event lr-show - Cancelable request fired by `show()` before `open` changes.
|
|
96
91
|
* @event lr-after-show - Fired after a successful `show()` has rendered the open panel.
|
|
97
|
-
* @event lr-hide - Cancelable request fired before `lr-lightbox-close`; `detail: { source }`,
|
|
98
|
-
* where `source` is the close button, backdrop, panel (for Escape), or host (for API writes).
|
|
99
|
-
* On removal while already disconnected, the settled notification is non-cancelable because
|
|
100
|
-
* there is no connected state left for a listener to retain.
|
|
101
92
|
* @event lr-after-hide - Fired after a successful `hide()`/`close()` has rendered closed.
|
|
102
93
|
* @event lr-index-change - Fired for `next()`/`previous()`/`goTo()` navigation, including the
|
|
103
94
|
* built-in button and keyboard paths. Not fired when a consumer sets `index`/`images` directly.
|
|
@@ -194,7 +185,7 @@ show():Promise<void>;
|
|
|
194
185
|
hide():Promise<void>;
|
|
195
186
|
/**
|
|
196
187
|
* Close the lightbox and return focus to whatever had it before the lightbox opened. `reason`
|
|
197
|
-
* is forwarded as the `lr-
|
|
188
|
+
* is forwarded as the `lr-close-request` and `lr-close` detail -- built-in triggers pass `'escape'`/
|
|
198
189
|
* `'backdrop'`/`'close-button'`; a consumer's own close affordance (e.g. an `actions`-slotted
|
|
199
190
|
* button) should call this directly with its own reason string.
|
|
200
191
|
*/
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{warnDeprecatedUsage}from"../../../internal/dev-mode-attribute-warning.js";import{LyraElement}from"../../../internal/lyra-element.js";import{DeferredFocusReturn,captureFocusReturnOpener}from"../../../internal/deferred-focus-return.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isAccessibilityVisible,nextId,srOnly}from"../../../internal/a11y.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./lightbox.styles.js";import"../pan-zoom/pan-zoom.class.js";import{LYRA_DEFAULT_close,LYRA_DEFAULT_lightboxImagePosition,LYRA_DEFAULT_lightboxLabel,LYRA_DEFAULT_next,LYRA_DEFAULT_previous}from"../../../internal/default-strings.generated.js";const MAX_LIGHTBOX_IMAGES=1e4,EMPTY_LIGHTBOX_IMAGES=Object.freeze([]);function snapshotLightboxImages(value){try{if(!Array.isArray(value))return EMPTY_LIGHTBOX_IMAGES;const count=Math.min(value.length,MAX_LIGHTBOX_IMAGES),images=[];for(let index=0;index<count;index++)try{const candidate=value[index];if(typeof candidate!="object"||candidate===null)continue;const src=candidate.src;if(typeof src!="string")continue;const alt=candidate.alt,caption=candidate.caption;images.push(Object.freeze({src,...typeof alt=="string"?{alt}:{},...typeof caption=="string"?{caption}:{}}))}catch{}return images.length?Object.freeze(images):EMPTY_LIGHTBOX_IMAGES}catch{return EMPTY_LIGHTBOX_IMAGES}}function ownsNavigationKey(event){for(const target of event.composedPath()){const element=target;if(typeof element.matches=="function"&&(element.localName==="lr-pan-zoom"||element.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="searchbox"], [role="combobox"], [role="spinbutton"], [role="slider"], [role="listbox"], [role="menu"], [role="menuitem"], [role="radio"], [role="radiogroup"], [role="grid"], [role="tree"], [role="tablist"]')))return!0}return!1}function queueDocumentMicrotask(ownerDocument,callback){const ownerWindow=ownerDocument.defaultView;if(ownerWindow){ownerWindow.queueMicrotask(callback);return}Promise.resolve().then(callback)}class LyraLightbox extends LyraElement{constructor(){super(...arguments),this._open=!1,this._images=EMPTY_LIGHTBOX_IMAGES,this._fit="actual",this.index=0,this.loop=!1,this.lightDismiss=!1,this.withoutCounter=!1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this.accessibleLabel=null,this.slotPresence=new SlotPresenceController(this),this.liveText="",this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.closeFrom("escape",this.renderRoot.querySelector('[part="panel"]')??this)},onUnexpectedClose:()=>{this.hide().then(()=>{this.open&&this.nativeModal.show()})}}),this.focusReturnOpener=null,this.deferredFocusReturn=new DeferredFocusReturn,this.connectionGeneration=0,this.transitionGeneration=0,this.captionId=nextId("lightbox-caption"),this.next=()=>this.changeTo(this.currentIndex()+1),this.previous=()=>this.changeTo(this.currentIndex()-1),this.goTo=index=>this.changeTo(index),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part="close-button"]')??this;this.closeFrom("close-button",button)},this.onPanelKeyDown=event=>{if(ownsNavigationKey(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey?(event.preventDefault(),this.previous()):event.key==="Home"?(event.preventDefault(),this.goTo(0)):event.key==="End"&&(event.preventDefault(),this.goTo(this.images.length-1))}}static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,lightboxImagePosition:LYRA_DEFAULT_lightboxImagePosition,lightboxLabel:LYRA_DEFAULT_lightboxLabel,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,srOnly,styles]}get open(){return this._open}set open(next){const normalized=!!next;if(!this.coalesceOpenRequest(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}get images(){return this._images}set images(value){const old=this._images;this._images=snapshotLightboxImages(value),this.requestUpdate("images",old)}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value,"actual"),this.requestUpdate("fit",old)}currentIndex(){const count=this.images.length;return count===0?0:finiteCount(this.index,0,count-1)}syncImages(){const current=this.currentIndex();this.index!==current&&(this.index=current)}changeTo(index){const count=this.images.length;if(count===0||!Number.isFinite(index))return;const requested=finiteInteger(index,0),next=this.loop?(requested%count+count)%count:Math.min(count-1,Math.max(0,requested));next!==this.currentIndex()&&(this.index=next,this.emit("lr-index-change",{index:next}))}async show(){if(this.coalesceOpenRequest(!0)||this._open)return;this.beginOpenRequest(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequestWasSuperseded(!0);if(this.finishOpenRequest(),prevented||superseded){this.syncOpenAttribute();return}this.applyOpenState(!0);const generation=++this.transitionGeneration;await this.updateComplete,generation===this.transitionGeneration&&this._open&&this.emit("lr-after-show",null)}hide(){return this.close("api")}async close(reason="api"){return this.closeFrom(reason,this)}async closeFrom(reason,source){if(this.coalesceOpenRequest(!1)||!this._open)return;if(this.beginOpenRequest(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)){this.finishOpenRequest(),this.syncOpenAttribute();return}if(this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)){this.finishOpenRequest(),this.syncOpenAttribute();return}const event=this.emit("lr-lightbox-close",reason,{cancelable:!0});if(event.defaultPrevented&&warnDeprecatedUsage(this,"event","lr-lightbox-close","lr-close-request"),event.defaultPrevented||this.openRequestWasSuperseded(!1)){this.finishOpenRequest(),this.syncOpenAttribute();return}this.finishOpenRequest(),this.applyOpenState(!1);const generation=++this.transitionGeneration;this.emit("lr-close",{reason}),await this.updateComplete,generation===this.transitionGeneration&&!this._open&&this.emit("lr-after-hide",null)}coalesceOpenRequest(next){return this.openRequestTarget===void 0?!1:(this.openRequestDuringPreflight=next,!0)}beginOpenRequest(next){this.openRequestTarget=next,this.openRequestDuringPreflight=void 0}openRequestWasSuperseded(next){return this.openRequestDuringPreflight!==void 0&&this.openRequestDuringPreflight!==next}finishOpenRequest(){this.openRequestTarget=void 0,this.openRequestDuringPreflight=void 0}applyOpenState(next){const old=this._open;this._open=next,this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}updateLiveRegion(){const count=this.images.length,formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveText=count===0?"":this.localize("lightboxImagePosition",void 0,{index:formatter.format(this.currentIndex()+1),total:formatter.format(count)})}captureAnnouncementBaseline(){this.announcementBaseline={index:this.currentIndex(),images:this.images}}willUpdate(changed){if(super.willUpdate(changed),(changed.has("images")||changed.has("index"))&&this.syncImages(),(changed.has("index")||changed.has("images")||changed.has("strings")||changed.has("locale"))&&this.updateLiveRegion(),changed.has("open"))if(this.open)this.deferredFocusReturn.cancel(),this.focusReturnOpener=captureFocusReturnOpener(this),this.nativeModal.prepare(),this.activateOverlay();else{const hadOverlay=this.overlay!==void 0;this.deactivateOverlay();const opener=this.focusReturnOpener;this.focusReturnOpener=null,hadOverlay&&opener&&this.isConnected&&this.deferredFocusReturn.schedule({host:this,candidates:()=>[opener],isCurrent:()=>!this.open})}}updated(changed){super.updated(changed),!(this.announcementBaseline?.index===this.currentIndex()&&this.announcementBaseline.images===this.images)&&this.open&&this.liveText!==""&&isAccessibilityVisible(this)&&(changed.has("index")||changed.has("images"))&&this.announcementSink?.announce(this.liveText),this.isConnected&&this.captureAnnouncementBaseline(),changed.has("open")&&this.open&&(this.nativeModal.show(),this.overlay?.focusInitial());let currentSourceChanged=!1;if(changed.has("images")){const previousImages=changed.get("images"),previousIndex=changed.has("index")?changed.get("index")??0:this.index;currentSourceChanged=previousImages?.[previousImages.length>0?finiteCount(previousIndex,0,previousImages.length-1):0]?.src!==this.images[this.currentIndex()]?.src}this.open&&(changed.has("index")||currentSourceChanged)&&this.frameEl?.resetView()}connectedCallback(){super.connectedCallback();const generation=++this.connectionGeneration,connectionDocument=this.ownerDocument;this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.captureAnnouncementBaseline(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),queueDocumentMicrotask(connectionDocument,()=>{this.connectionGeneration===generation&&this.ownerDocument===connectionDocument&&this.isConnected&&this.open&&(this.nativeModal.show(),this.overlay?.focusInitial())}))}disconnectedCallback(){const generation=++this.connectionGeneration,connectionDocument=this.ownerDocument;this.announcementSink?.release(),this.announcementSink=void 0,this.announcementBaseline=void 0,super.disconnectedCallback(),this.nativeModal.hide(),this.overlay?.suspend(),this.deferredFocusReturn.cancel(),this.open&&queueDocumentMicrotask(connectionDocument,()=>{this.connectionGeneration===generation&&this.ownerDocument===connectionDocument&&!this.isConnected&&this.open&&(this.transitionGeneration++,this.emit("lr-hide",{source:this}),this.applyOpenState(!1),this.emit("lr-lightbox-close","unmount"),this.emit("lr-close",{reason:"unmount"}),this.emit("lr-after-hide",null))})}activateOverlay(){this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part="panel"]')??this;this.closeFrom("escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part="backdrop"]')??this;this.closeFrom("backdrop",backdrop)},preferredInitialFocus:()=>this.shadowRoot?.querySelector('[part="close-button"]')??null,lockScroll:!0,suspendWhenUnrendered:!0}))}deactivateOverlay(){this.nativeModal.hide(),this.overlay?.deactivate(),this.overlay=void 0}render(){const count=this.images.length,current=this.currentIndex(),image=count>0?this.images[current]:void 0,label=this.accessibleLabel??this.localize("lightboxLabel"),hasCaption=!!image?.caption,formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),positionText=count>0?this.localize("lightboxImagePosition",void 0,{index:formatter.format(current+1),total:formatter.format(count)}):"";return this.nativeModal.render(html`
|
|
1
|
+
import{__decorate}from"tslib";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{DeferredFocusReturn,captureFocusReturnOpener}from"../../../internal/deferred-focus-return.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isAccessibilityVisible,nextId,srOnly}from"../../../internal/a11y.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount,finiteInteger}from"../../../internal/numbers.js";import{normalizeImageFit}from"../../../internal/image-fit.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{styles}from"./lightbox.styles.js";import"../pan-zoom/pan-zoom.class.js";import{LYRA_DEFAULT_close,LYRA_DEFAULT_lightboxImagePosition,LYRA_DEFAULT_lightboxLabel,LYRA_DEFAULT_next,LYRA_DEFAULT_previous}from"../../../internal/default-strings.generated.js";const MAX_LIGHTBOX_IMAGES=1e4,EMPTY_LIGHTBOX_IMAGES=Object.freeze([]);function snapshotLightboxImages(value){try{if(!Array.isArray(value))return EMPTY_LIGHTBOX_IMAGES;const count=Math.min(value.length,MAX_LIGHTBOX_IMAGES),images=[];for(let index=0;index<count;index++)try{const candidate=value[index];if(typeof candidate!="object"||candidate===null)continue;const src=candidate.src;if(typeof src!="string")continue;const alt=candidate.alt,caption=candidate.caption;images.push(Object.freeze({src,...typeof alt=="string"?{alt}:{},...typeof caption=="string"?{caption}:{}}))}catch{}return images.length?Object.freeze(images):EMPTY_LIGHTBOX_IMAGES}catch{return EMPTY_LIGHTBOX_IMAGES}}function ownsNavigationKey(event){for(const target of event.composedPath()){const element=target;if(typeof element.matches=="function"&&(element.localName==="lr-pan-zoom"||element.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="searchbox"], [role="combobox"], [role="spinbutton"], [role="slider"], [role="listbox"], [role="menu"], [role="menuitem"], [role="radio"], [role="radiogroup"], [role="grid"], [role="tree"], [role="tablist"]')))return!0}return!1}function queueDocumentMicrotask(ownerDocument,callback){const ownerWindow=ownerDocument.defaultView;if(ownerWindow){ownerWindow.queueMicrotask(callback);return}Promise.resolve().then(callback)}class LyraLightbox extends LyraElement{constructor(){super(...arguments),this._open=!1,this._images=EMPTY_LIGHTBOX_IMAGES,this._fit="actual",this.index=0,this.loop=!1,this.lightDismiss=!1,this.withoutCounter=!1,this.minZoom=.5,this.maxZoom=4,this.zoomStep=.25,this.accessibleLabel=null,this.slotPresence=new SlotPresenceController(this),this.liveText="",this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.closeFrom("escape",this.renderRoot.querySelector('[part="panel"]')??this)},onUnexpectedClose:()=>{this.hide().then(()=>{this.open&&this.nativeModal.show()})}}),this.focusReturnOpener=null,this.deferredFocusReturn=new DeferredFocusReturn,this.connectionGeneration=0,this.transitionGeneration=0,this.captionId=nextId("lightbox-caption"),this.next=()=>this.changeTo(this.currentIndex()+1),this.previous=()=>this.changeTo(this.currentIndex()-1),this.goTo=index=>this.changeTo(index),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onCloseButtonClick=()=>{const button=this.renderRoot.querySelector('[part="close-button"]')??this;this.closeFrom("close-button",button)},this.onPanelKeyDown=event=>{if(ownsNavigationKey(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey?(event.preventDefault(),this.previous()):event.key==="Home"?(event.preventDefault(),this.goTo(0)):event.key==="End"&&(event.preventDefault(),this.goTo(this.images.length-1))}}static{this.defaultStrings={...super.defaultStrings,close:LYRA_DEFAULT_close,lightboxImagePosition:LYRA_DEFAULT_lightboxImagePosition,lightboxLabel:LYRA_DEFAULT_lightboxLabel,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous}}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,srOnly,styles]}get open(){return this._open}set open(next){const normalized=!!next;if(!this.coalesceOpenRequest(normalized)&&normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.close("api")}}get images(){return this._images}set images(value){const old=this._images;this._images=snapshotLightboxImages(value),this.requestUpdate("images",old)}get fit(){return this._fit}set fit(value){const old=this._fit;this._fit=normalizeImageFit(value,"actual"),this.requestUpdate("fit",old)}currentIndex(){const count=this.images.length;return count===0?0:finiteCount(this.index,0,count-1)}syncImages(){const current=this.currentIndex();this.index!==current&&(this.index=current)}changeTo(index){const count=this.images.length;if(count===0||!Number.isFinite(index))return;const requested=finiteInteger(index,0),next=this.loop?(requested%count+count)%count:Math.min(count-1,Math.max(0,requested));next!==this.currentIndex()&&(this.index=next,this.emit("lr-index-change",{index:next}))}async show(){if(this.coalesceOpenRequest(!0)||this._open)return;this.beginOpenRequest(!0);const prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented,superseded=this.openRequestWasSuperseded(!0);if(this.finishOpenRequest(),prevented||superseded){this.syncOpenAttribute();return}this.applyOpenState(!0);const generation=++this.transitionGeneration;await this.updateComplete,generation===this.transitionGeneration&&this._open&&this.emit("lr-after-show",null)}hide(){return this.close("api")}async close(reason="api"){return this.closeFrom(reason,this)}async closeFrom(reason,source){if(this.coalesceOpenRequest(!1)||!this._open)return;if(this.beginOpenRequest(!1),this.emit("lr-hide",{source},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)){this.finishOpenRequest(),this.syncOpenAttribute();return}if(this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented||this.openRequestWasSuperseded(!1)){this.finishOpenRequest(),this.syncOpenAttribute();return}this.finishOpenRequest(),this.applyOpenState(!1);const generation=++this.transitionGeneration;this.emit("lr-close",{reason}),await this.updateComplete,generation===this.transitionGeneration&&!this._open&&this.emit("lr-after-hide",null)}coalesceOpenRequest(next){return this.openRequestTarget===void 0?!1:(this.openRequestDuringPreflight=next,!0)}beginOpenRequest(next){this.openRequestTarget=next,this.openRequestDuringPreflight=void 0}openRequestWasSuperseded(next){return this.openRequestDuringPreflight!==void 0&&this.openRequestDuringPreflight!==next}finishOpenRequest(){this.openRequestTarget=void 0,this.openRequestDuringPreflight=void 0}applyOpenState(next){const old=this._open;this._open=next,this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}updateLiveRegion(){const count=this.images.length,formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1});this.liveText=count===0?"":this.localize("lightboxImagePosition",void 0,{index:formatter.format(this.currentIndex()+1),total:formatter.format(count)})}captureAnnouncementBaseline(){this.announcementBaseline={index:this.currentIndex(),images:this.images}}willUpdate(changed){if(super.willUpdate(changed),(changed.has("images")||changed.has("index"))&&this.syncImages(),(changed.has("index")||changed.has("images")||changed.has("strings")||changed.has("locale"))&&this.updateLiveRegion(),changed.has("open"))if(this.open)this.deferredFocusReturn.cancel(),this.focusReturnOpener=captureFocusReturnOpener(this),this.nativeModal.prepare(),this.activateOverlay();else{const hadOverlay=this.overlay!==void 0;this.deactivateOverlay();const opener=this.focusReturnOpener;this.focusReturnOpener=null,hadOverlay&&opener&&this.isConnected&&this.deferredFocusReturn.schedule({host:this,candidates:()=>[opener],isCurrent:()=>!this.open})}}updated(changed){super.updated(changed),!(this.announcementBaseline?.index===this.currentIndex()&&this.announcementBaseline.images===this.images)&&this.open&&this.liveText!==""&&isAccessibilityVisible(this)&&(changed.has("index")||changed.has("images"))&&this.announcementSink?.announce(this.liveText),this.isConnected&&this.captureAnnouncementBaseline(),changed.has("open")&&this.open&&(this.nativeModal.show(),this.overlay?.focusInitial());let currentSourceChanged=!1;if(changed.has("images")){const previousImages=changed.get("images"),previousIndex=changed.has("index")?changed.get("index")??0:this.index;currentSourceChanged=previousImages?.[previousImages.length>0?finiteCount(previousIndex,0,previousImages.length-1):0]?.src!==this.images[this.currentIndex()]?.src}this.open&&(changed.has("index")||currentSourceChanged)&&this.frameEl?.resetView()}connectedCallback(){super.connectedCallback();const generation=++this.connectionGeneration,connectionDocument=this.ownerDocument;this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.captureAnnouncementBaseline(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlay(),queueDocumentMicrotask(connectionDocument,()=>{this.connectionGeneration===generation&&this.ownerDocument===connectionDocument&&this.isConnected&&this.open&&(this.nativeModal.show(),this.overlay?.focusInitial())}))}disconnectedCallback(){const generation=++this.connectionGeneration,connectionDocument=this.ownerDocument;this.announcementSink?.release(),this.announcementSink=void 0,this.announcementBaseline=void 0,super.disconnectedCallback(),this.nativeModal.hide(),this.overlay?.suspend(),this.deferredFocusReturn.cancel(),this.open&&queueDocumentMicrotask(connectionDocument,()=>{this.connectionGeneration===generation&&this.ownerDocument===connectionDocument&&!this.isConnected&&this.open&&(this.transitionGeneration++,this.emit("lr-hide",{source:this}),this.applyOpenState(!1),this.emit("lr-close",{reason:"unmount"}),this.emit("lr-after-hide",null))})}activateOverlay(){this.overlay?.isActive()||(this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="panel"]')??null,onEscape:()=>{const panel=this.renderRoot.querySelector('[part="panel"]')??this;this.closeFrom("escape",panel)},onBackdrop:()=>{const backdrop=this.renderRoot.querySelector('[part="backdrop"]')??this;this.closeFrom("backdrop",backdrop)},preferredInitialFocus:()=>this.shadowRoot?.querySelector('[part="close-button"]')??null,lockScroll:!0,suspendWhenUnrendered:!0}))}deactivateOverlay(){this.nativeModal.hide(),this.overlay?.deactivate(),this.overlay=void 0}render(){const count=this.images.length,current=this.currentIndex(),image=count>0?this.images[current]:void 0,label=this.accessibleLabel??this.localize("lightboxLabel"),hasCaption=!!image?.caption,formatter=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:0,useGrouping:!1}),positionText=count>0?this.localize("lightboxImagePosition",void 0,{index:formatter.format(current+1),total:formatter.format(count)}):"";return this.nativeModal.render(html`
|
|
2
2
|
<div part="backdrop" @click=${this.onBackdropClick}></div>
|
|
3
3
|
<div
|
|
4
4
|
part="panel"
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** A normalized numeric point-radius ramp used by a data layer's paint expression. */
|
|
2
|
+
export interface MapDataLayerPointRadius{readonly field:string;readonly stops:readonly(readonly[number,number])[];readonly interpolation:'step'|'linear';readonly fallback:number;}export interface MapDataLayerHeatmapOptions{readonly weightField:string|undefined;readonly weightRange:readonly[number,number]|undefined;readonly stops:readonly(readonly[number,string])[];readonly radius:number|readonly(readonly[number,number])[]|undefined;readonly intensity:number|readonly(readonly[number,number])[]|undefined;}
|
|
3
|
+
/** `['step', input, base, threshold, output, …]`, retaining the admitted stop order. */
|
|
4
|
+
export declare function stepExpression<T>(input:unknown,stops:readonly(readonly[number,T])[]):unknown[];
|
|
5
|
+
/** Builds the category match expression for individual point colors. */
|
|
6
|
+
export declare function pointColorExpression(field:string|undefined,colors:readonly(readonly[string,string])[],fallback:string):string|unknown[];
|
|
7
|
+
/** Builds a guarded numeric line-color ramp, using fallback paint for non-number properties. */
|
|
8
|
+
export declare function lineColorExpression(field:string|undefined,stops:readonly(readonly[number,string])[],fallback:string):string|unknown[];
|
|
9
|
+
/** Builds the cluster count color steps, or returns the layer fallback when there are no stops. */
|
|
10
|
+
export declare function clusterColorExpression(stops:readonly(readonly[number,string])[],fallback:string|(()=>string)):string|unknown[];
|
|
11
|
+
/** Returns the opacity expression used to dim selected point categories. */
|
|
12
|
+
export declare function mutedCategoryOpacityExpression(field:string,categories:readonly string[],opacity:number):unknown[];
|
|
13
|
+
/** Converts a normalized scalar or ramp radius to MapLibre's data expression. */
|
|
14
|
+
export declare function pointRadiusExpression(radius:number|MapDataLayerPointRadius):number|unknown[];
|
|
15
|
+
/** `heatmap-weight` for the authored field, or undefined to keep MapLibre's default weight of 1. */
|
|
16
|
+
export declare function heatmapWeightExpression(options:MapDataLayerHeatmapOptions|undefined):unknown[]|undefined;
|
|
17
|
+
/** Normalizes a scalar-or-zoom-stop paint value to a bounded MapLibre expression. */
|
|
18
|
+
export declare function heatmapZoomValue(value:number|readonly(readonly[number,number])[]|undefined,fallback:number,min:number,max:number):number|unknown[];
|
|
19
|
+
/** Prepends the transparent density-zero floor needed when an authored heatmap starts above zero. */
|
|
20
|
+
export declare function heatmapColorExpression(authoredStops:readonly(readonly[number,string])[],fallbackStops:readonly(readonly[number,string])[]|(()=>readonly(readonly[number,string])[])):unknown[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{finiteRange}from"../../../internal/numbers.js";function stepExpression(input,stops){const expression=["step",input,stops[0][1]];for(const[threshold,output]of stops)expression.push(threshold,output);return expression}function pointColorExpression(field,colors,fallback){return field&&colors.length?["match",["get",field],...colors.flatMap(([value,color])=>[value,color]),fallback]:fallback}function lineColorExpression(field,stops,fallback){return!field||stops.length<2?fallback:["case",["==",["typeof",["get",field]],"number"],["interpolate",["linear"],["number",["get",field]],...stops.flatMap(([value,color])=>[value,color])],fallback]}function clusterColorExpression(stops,fallback){return stops.length?stepExpression(["get","point_count"],stops):typeof fallback=="function"?fallback():fallback}function mutedCategoryOpacityExpression(field,categories,opacity){return["match",["get",field],...categories.flatMap(value=>[value,opacity]),1]}function pointRadiusExpression(radius){if(typeof radius=="number")return radius;const input=["number",["get",radius.field],0];let domainInput=input,stops=radius.stops;if(radius.interpolation==="linear"&&!Number.isFinite(stops.at(-1)[0]-stops[0][0])){if(stops=stops.map(([value,output2])=>[value/2,output2]),stops.some(([value],index)=>index>0&&value<=stops[index-1][0]))return radius.fallback;domainInput=["/",input,2]}const output=stops.length===1?stops[0][1]:radius.interpolation==="linear"?["interpolate",["linear"],domainInput,...stops.flat()]:stepExpression(input,stops);return["case",["all",["==",["typeof",["get",radius.field]],"number"],[">=",input,-Number.MAX_VALUE],["<=",input,Number.MAX_VALUE]],output,radius.fallback]}function heatmapWeightExpression(options){const field=options?.weightField??"";if(!field)return;const min=options?.weightRange?.[0]??Number.NaN,max=options?.weightRange?.[1]??Number.NaN;return!Number.isFinite(min)||!Number.isFinite(max)||min>=max?["get",field]:["interpolate",["linear"],["get",field],min,0,max,1]}function heatmapZoomValue(value,fallback,min,max){if(typeof value=="number"||value===void 0)return finiteRange(typeof value=="number"?value:Number.NaN,fallback,min,max);const stops=value.map(([zoom,output])=>[zoom,finiteRange(output,fallback,min,max)]);if(stops.length===0)return fallback;if(stops.length===1)return stops[0][1];const expression=["interpolate",["linear"],["zoom"]];for(const[zoom,output]of stops)expression.push(zoom,output);return expression}function heatmapColorExpression(authoredStops,fallbackStops){const withFloor=stops=>stops.length&&stops[0][0]>0?[[0,"rgba(0, 0, 0, 0)"],...stops]:stops,authored=withFloor(authoredStops),ramp=authored.length>=2?authored:withFloor(typeof fallbackStops=="function"?fallbackStops():fallbackStops),expression=["interpolate",["linear"],["heatmap-density"]];for(const[density,color]of ramp)expression.push(density,color);return expression}export{clusterColorExpression,heatmapColorExpression,heatmapWeightExpression,heatmapZoomValue,lineColorExpression,mutedCategoryOpacityExpression,pointColorExpression,pointRadiusExpression,stepExpression};
|