@aceshooting/lyra-ui 8.0.0 → 8.2.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.
Files changed (61) hide show
  1. package/CHANGELOG.md +199 -17
  2. package/custom-elements.json +1 -1
  3. package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
  4. package/dist/components/agent-tools/terminal/terminal.class.js +2 -2
  5. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +5 -0
  6. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  7. package/dist/components/charts/chart/chart.class.js +1 -1
  8. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -0
  9. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  10. package/dist/components/conversation/widget-renderer/widget-renderer.class.js +1 -1
  11. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  12. package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
  13. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +4 -0
  14. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  15. package/dist/components/data/query-builder/query-builder.class.js +2 -2
  16. package/dist/components/data/table/table.class.js +2 -2
  17. package/dist/components/data/table/table.styles.js +8 -3
  18. package/dist/components/data/tree/tree-item.styles.js +11 -3
  19. package/dist/components/data/tree/tree.class.d.ts +11 -0
  20. package/dist/components/data/tree/tree.class.js +1 -1
  21. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +3 -0
  22. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  23. package/dist/components/forms/icon-button/icon-button.class.js +1 -1
  24. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -0
  25. package/dist/components/forms/locale-picker/locale-picker.class.js +4 -3
  26. package/dist/components/forms/locale-picker/locale-picker.styles.js +4 -0
  27. package/dist/components/forms/radio/radio-group.class.d.ts +3 -0
  28. package/dist/components/forms/radio/radio-group.class.js +1 -1
  29. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +3 -0
  30. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  31. package/dist/components/forms/switch/switch.styles.js +9 -0
  32. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  33. package/dist/components/media/avatar/avatar.class.js +2 -2
  34. package/dist/components/media/flag/flag.class.js +2 -2
  35. package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
  36. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
  37. package/dist/components/utility/icon/icon.class.js +1 -1
  38. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  39. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  40. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +3 -2
  41. package/dist/components/viewers/page-rail/page-rail.class.js +2 -0
  42. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  43. package/dist/internal/anchor-target.js +1 -1
  44. package/dist/internal/package-metadata.d.ts +1 -1
  45. package/dist/internal/package-metadata.js +1 -1
  46. package/dist/internal/safe-svg.d.ts +13 -0
  47. package/dist/internal/safe-svg.js +1 -0
  48. package/dist/testing/happy-dom-shims.d.ts +4 -0
  49. package/dist/testing/happy-dom-shims.js +1 -1
  50. package/llms/components/lr-attachment-chip.md +18 -10
  51. package/llms/components/lr-checkbox-group.md +2 -0
  52. package/llms/components/lr-graph-query-builder.md +3 -1
  53. package/llms/components/lr-locale-picker.md +6 -4
  54. package/llms/components/lr-radio-group.md +3 -1
  55. package/llms/components/lr-rubric-form.md +2 -0
  56. package/llms/components/lr-tool-param-form.md +3 -0
  57. package/llms/peers.md +3 -3
  58. package/llms-full.txt +36 -15
  59. package/package.json +9 -8
  60. package/vscode-html-data.json +7 -7
  61. package/web-types.json +8 -8
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{finiteRange}from"../../../internal/numbers.js";import{LyraElement}from"../../../internal/lyra-element.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./mcp-app.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_mcpAppLabel,LYRA_DEFAULT_mcpAppLoading,LYRA_DEFAULT_mcpAppUnavailable,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";function record(value){return value&&typeof value==="object"&&!Array.isArray(value)?value:null}function cspSources(values){return(values??[]).flatMap(value=>{try{const url=new URL(value);return url.protocol==="https:"||url.protocol==="http:"?[url.origin]:[]}catch{return[]}})}function buildCsp(csp){const resources=cspSources(csp?.resourceDomains);const connections=cspSources(csp?.connectDomains);const frames=cspSources(csp?.frameDomains);return[`default-src 'none'`,`script-src 'unsafe-inline'`,`style-src 'unsafe-inline'`,`img-src data: blob: ${resources.join(" ")}`.trim(),`font-src data: ${resources.join(" ")}`.trim(),`media-src data: blob: ${resources.join(" ")}`.trim(),`connect-src ${connections.length?connections.join(" "):"'none'"}`,`frame-src ${frames.length?frames.join(" "):"'none'"}`,`base-uri 'none'`,`form-action 'none'`].join("; ")}function withCsp(htmlSource,csp){const meta=`<meta http-equiv="Content-Security-Policy" content="${buildCsp(csp)}">`;return/<head(?:\s[^>]*)?>/i.test(htmlSource)?htmlSource.replace(/<head(?:\s[^>]*)?>/i,head=>`${head}${meta}`):`${meta}${htmlSource}`}function permissionPolicy(permissions){const enabled=[permissions?.camera?"camera":"",permissions?.microphone?"microphone":"",permissions?.geolocation?"geolocation":"",permissions?.clipboardRead?"clipboard-read":"",permissions?.clipboardWrite?"clipboard-write":""].filter(Boolean);return enabled.map(permission=>`${permission} *`).join("; ")}class LyraMcpApp extends LyraElement{constructor(){super(...arguments);this.resource=null;this.height=320;this.maxHeight=800;this.label="";this.accessibleLabel=null;this.loaded=false;this.frameHeight=320;this.frameGeneration=0;this.suppressNextResourceAnnouncement=true;this.onMessage=event=>{if(event.currentTarget!==this.messageWindow)return;if(!this.frame?.contentWindow||event.source!==this.frame.contentWindow)return;const expectedOrigin=this.expectedOrigin();if(expectedOrigin&&event.origin!==expectedOrigin)return;const message=record(event.data);if(message?.["channel"]!=="lyra-mcp-app"||message["version"]!==1||typeof message["type"]!=="string")return;switch(message["type"]){case"resize":{const requested=typeof message["height"]==="number"?message["height"]:this.height;const height=finiteRange(requested,this.height,120,finiteRange(this.maxHeight,800,120,1e4));this.frameHeight=height;this.emit("lr-mcp-resize",{height});break}case"tool-call":if(typeof message["name"]==="string"){this.emit("lr-mcp-tool-call",{requestId:typeof message["requestId"]==="string"?message["requestId"]:void 0,name:message["name"],args:message["args"]})}break;case"send-message":this.emit("lr-mcp-send-message",{message:message["message"]});break;case"open-link":if(typeof message["href"]==="string")this.emit("lr-mcp-open-link",{href:message["href"]});break;case"log":this.emit("lr-mcp-log",{level:typeof message["level"]==="string"?message["level"]:"info",value:message["value"]});break}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,mcpAppLabel:LYRA_DEFAULT_mcpAppLabel,mcpAppLoading:LYRA_DEFAULT_mcpAppLoading,mcpAppUnavailable:LYRA_DEFAULT_mcpAppUnavailable,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles]}resourceAvailable(resource){return Boolean(resource&&(resource.html||safeMediaSrc(resource.src)))}syncAnnouncementSinks(){if(!this.isConnected)return;const heldDocument=this.loadingAnnouncementSink?.element.ownerDocument;if(heldDocument===this.ownerDocument&&this.errorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;this.loadingAnnouncementSink?.release();this.errorAnnouncementSink?.release();this.loadingAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}connectedCallback(){super.connectedCallback();this.syncAnnouncementSinks();if(this.hasUpdated){this.suppressNextResourceAnnouncement=true;this.requestUpdate()}this.bindMessageWindow()}disconnectedCallback(){this.unbindMessageWindow();this.loaded=false;this.loadingAnnouncementSink?.release();this.errorAnnouncementSink?.release();this.loadingAnnouncementSink=void 0;this.errorAnnouncementSink=void 0;this.suppressNextResourceAnnouncement=true;super.disconnectedCallback()}adoptedCallback(){this.syncAnnouncementSinks();this.bindMessageWindow()}bindMessageWindow(){const nextWindow=this.isConnected?this.ownerDocument.defaultView:null;if(this.messageWindow===nextWindow)return;this.unbindMessageWindow();this.messageWindow=nextWindow??void 0;this.messageWindow?.addEventListener("message",this.onMessage)}unbindMessageWindow(){this.messageWindow?.removeEventListener("message",this.onMessage);this.messageWindow=void 0}willUpdate(changed){if(changed.has("resource")){if(this.hasUpdated&&!this.suppressNextResourceAnnouncement){const wasAvailable=this.resourceAvailable(changed.get("resource"));const isAvailable=this.resourceAvailable(this.resource);if(isAvailable)this.loadingAnnouncementSink?.announce(this.localize("mcpAppLoading"));else if(wasAvailable)this.errorAnnouncementSink?.announce(this.localize("mcpAppUnavailable"))}this.loaded=false;this.frameGeneration++}if(changed.has("resource")||changed.has("height")||changed.has("maxHeight")){this.frameHeight=finiteRange(this.height,320,120,finiteRange(this.maxHeight,800,120,1e4))}}updated(_changed){this.suppressNextResourceAnnouncement=false}expectedOrigin(){if(this.resource?.html)return"null";const src=safeMediaSrc(this.resource?.src);if(!src)return null;return"null"}onLoad(){this.loaded=true;this.emit("lr-mcp-ready",{uri:this.resource?.uri??""});this.postHostContext({resource:{uri:this.resource?.uri,metadata:this.resource?.metadata},locale:this.effectiveLocale,direction:this.effectiveDirection})}post(message){const target=this.frame?.contentWindow;if(!target)return;const origin=this.expectedOrigin();target.postMessage(message,origin==="null"?"*":origin??"*")}postHostContext(context){this.post({channel:"lyra-mcp-app",version:1,type:"host-context",context})}postToolResult(requestId,result,error){this.post({channel:"lyra-mcp-app",version:1,type:"tool-result",requestId,...result!==void 0?{result}:{},...error?{error}:{}})}render(){const resource=this.resource;const src=safeMediaSrc(resource?.src);const valid=Boolean(resource&&(resource.html||src));const label=this.accessibleLabel||this.label||resource?.title||this.localize("mcpAppLabel");if(!valid){return html`<div part="base"><p part="error">${this.localize("mcpAppUnavailable")}</p></div>`}return html`<div part="base">
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{keyed}from"lit/directives/keyed.js";import{finiteRange}from"../../../internal/numbers.js";import{LyraElement}from"../../../internal/lyra-element.js";import{safeLinkHref,safeMediaSrc}from"../../../internal/safe-url.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{styles}from"./mcp-app.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_mcpAppLabel,LYRA_DEFAULT_mcpAppLoading,LYRA_DEFAULT_mcpAppUnavailable,LYRA_DEFAULT_open}from"../../../internal/default-strings.generated.js";function record(value){return value&&typeof value==="object"&&!Array.isArray(value)?value:null}function cspSources(values){return(values??[]).flatMap(value=>{try{const url=new URL(value);return url.protocol==="https:"||url.protocol==="http:"?[url.origin]:[]}catch{return[]}})}function buildCsp(csp){const resources=cspSources(csp?.resourceDomains);const connections=cspSources(csp?.connectDomains);const frames=cspSources(csp?.frameDomains);return[`default-src 'none'`,`script-src 'unsafe-inline'`,`style-src 'unsafe-inline'`,`img-src data: blob: ${resources.join(" ")}`.trim(),`font-src data: ${resources.join(" ")}`.trim(),`media-src data: blob: ${resources.join(" ")}`.trim(),`connect-src ${connections.length?connections.join(" "):"'none'"}`,`frame-src ${frames.length?frames.join(" "):"'none'"}`,`base-uri 'none'`,`form-action 'none'`].join("; ")}function withCsp(htmlSource,csp){const meta=`<meta http-equiv="Content-Security-Policy" content="${buildCsp(csp)}">`;return/<head(?:\s[^>]*)?>/i.test(htmlSource)?htmlSource.replace(/<head(?:\s[^>]*)?>/i,head=>`${head}${meta}`):`${meta}${htmlSource}`}function permissionPolicy(permissions){const enabled=[permissions?.camera?"camera":"",permissions?.microphone?"microphone":"",permissions?.geolocation?"geolocation":"",permissions?.clipboardRead?"clipboard-read":"",permissions?.clipboardWrite?"clipboard-write":""].filter(Boolean);return enabled.map(permission=>`${permission} *`).join("; ")}class LyraMcpApp extends LyraElement{constructor(){super(...arguments);this.resource=null;this.height=320;this.maxHeight=800;this.label="";this.accessibleLabel=null;this.loaded=false;this.frameHeight=320;this.frameGeneration=0;this.suppressNextResourceAnnouncement=true;this.onMessage=event=>{if(event.currentTarget!==this.messageWindow)return;if(!this.frame?.contentWindow||event.source!==this.frame.contentWindow)return;const expectedOrigin=this.expectedOrigin();if(expectedOrigin&&event.origin!==expectedOrigin)return;const message=record(event.data);if(message?.["channel"]!=="lyra-mcp-app"||message["version"]!==1||typeof message["type"]!=="string")return;switch(message["type"]){case"resize":{const requested=typeof message["height"]==="number"?message["height"]:this.height;const height=finiteRange(requested,this.height,120,finiteRange(this.maxHeight,800,120,1e4));this.frameHeight=height;this.emit("lr-mcp-resize",{height});break}case"tool-call":if(typeof message["name"]==="string"){this.emit("lr-mcp-tool-call",{requestId:typeof message["requestId"]==="string"?message["requestId"]:void 0,name:message["name"],args:message["args"]})}break;case"send-message":this.emit("lr-mcp-send-message",{message:message["message"]});break;case"open-link":{const href=safeLinkHref(message["href"]);if(href)this.emit("lr-mcp-open-link",{href})}break;case"log":this.emit("lr-mcp-log",{level:typeof message["level"]==="string"?message["level"]:"info",value:message["value"]});break}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,mcpAppLabel:LYRA_DEFAULT_mcpAppLabel,mcpAppLoading:LYRA_DEFAULT_mcpAppLoading,mcpAppUnavailable:LYRA_DEFAULT_mcpAppUnavailable,open:LYRA_DEFAULT_open}}static{this.styles=[LyraElement.styles,styles]}resourceAvailable(resource){return Boolean(resource&&(resource.html||safeMediaSrc(resource.src)))}syncAnnouncementSinks(){if(!this.isConnected)return;const heldDocument=this.loadingAnnouncementSink?.element.ownerDocument;if(heldDocument===this.ownerDocument&&this.errorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;this.loadingAnnouncementSink?.release();this.errorAnnouncementSink?.release();this.loadingAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}connectedCallback(){super.connectedCallback();this.syncAnnouncementSinks();if(this.hasUpdated){this.suppressNextResourceAnnouncement=true;this.requestUpdate()}this.bindMessageWindow()}disconnectedCallback(){this.unbindMessageWindow();this.loaded=false;this.loadingAnnouncementSink?.release();this.errorAnnouncementSink?.release();this.loadingAnnouncementSink=void 0;this.errorAnnouncementSink=void 0;this.suppressNextResourceAnnouncement=true;super.disconnectedCallback()}adoptedCallback(){this.syncAnnouncementSinks();this.bindMessageWindow()}bindMessageWindow(){const nextWindow=this.isConnected?this.ownerDocument.defaultView:null;if(this.messageWindow===nextWindow)return;this.unbindMessageWindow();this.messageWindow=nextWindow??void 0;this.messageWindow?.addEventListener("message",this.onMessage)}unbindMessageWindow(){this.messageWindow?.removeEventListener("message",this.onMessage);this.messageWindow=void 0}willUpdate(changed){if(changed.has("resource")){if(this.hasUpdated&&!this.suppressNextResourceAnnouncement){const wasAvailable=this.resourceAvailable(changed.get("resource"));const isAvailable=this.resourceAvailable(this.resource);if(isAvailable)this.loadingAnnouncementSink?.announce(this.localize("mcpAppLoading"));else if(wasAvailable)this.errorAnnouncementSink?.announce(this.localize("mcpAppUnavailable"))}this.loaded=false;this.frameGeneration++}if(changed.has("resource")||changed.has("height")||changed.has("maxHeight")){this.frameHeight=finiteRange(this.height,320,120,finiteRange(this.maxHeight,800,120,1e4))}}updated(_changed){this.suppressNextResourceAnnouncement=false}expectedOrigin(){if(this.resource?.html)return"null";const src=safeMediaSrc(this.resource?.src);if(!src)return null;return"null"}onLoad(){this.loaded=true;this.emit("lr-mcp-ready",{uri:this.resource?.uri??""});this.postHostContext({resource:{uri:this.resource?.uri,metadata:this.resource?.metadata},locale:this.effectiveLocale,direction:this.effectiveDirection})}post(message){const target=this.frame?.contentWindow;if(!target)return;const origin=this.expectedOrigin();target.postMessage(message,origin==="null"?"*":origin??"*")}postHostContext(context){this.post({channel:"lyra-mcp-app",version:1,type:"host-context",context})}postToolResult(requestId,result,error){this.post({channel:"lyra-mcp-app",version:1,type:"tool-result",requestId,...result!==void 0?{result}:{},...error?{error}:{}})}render(){const resource=this.resource;const src=safeMediaSrc(resource?.src);const valid=Boolean(resource&&(resource.html||src));const label=this.accessibleLabel||this.label||resource?.title||this.localize("mcpAppLabel");if(!valid){return html`<div part="base"><p part="error">${this.localize("mcpAppUnavailable")}</p></div>`}return html`<div part="base">
2
2
  ${this.loaded?nothing:html`<p part="loading">${this.localize("mcpAppLoading")}</p>`}
3
3
  ${keyed(this.frameGeneration,html`<iframe
4
4
  part="frame"
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{srOnly}from"../../../internal/a11y.js";import{Announcer,acquireAnnouncementSink}from"../../../internal/announcer.js";import{createAnsiParser}from"../../../internal/ansi.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{styles}from"./terminal.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_details,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_jumpToLatest,LYRA_DEFAULT_open,LYRA_DEFAULT_terminalDownload,LYRA_DEFAULT_terminalHighlightLine,LYRA_DEFAULT_terminalLabel}from"../../../internal/default-strings.generated.js";const EMPTY_CELL_STYLES={bold:false,dim:false,italic:false,underline:false,inverse:false};const ANNOUNCE_THROTTLE_MS=10;const MAX_SEARCH_MATCHES=1e4;const TONE_BACKGROUND_VAR={accent:"var(--lr-terminal-highlight-accent-bg, var(--lr-color-brand-quiet))",success:"var(--lr-terminal-highlight-success-bg, var(--lr-color-success-quiet))",warning:"var(--lr-terminal-highlight-warning-bg, var(--lr-color-warning-quiet))",danger:"var(--lr-terminal-highlight-danger-bg, var(--lr-color-danger-quiet))",neutral:"var(--lr-terminal-highlight-neutral-bg, var(--lr-color-surface))"};function plainTextOfLine(line){return line.cells.map(c=>c.char).join("")}function groupCells(cells){const segments=[];for(const cell of cells){const last=segments[segments.length-1];if(last&&stylesEqual(last.styles,cell.styles)){last.text+=cell.char}else{segments.push({text:cell.char,styles:cell.styles})}}return segments}function stylesEqual(a,b){return a.bold===b.bold&&a.dim===b.dim&&a.italic===b.italic&&a.underline===b.underline&&a.inverse===b.inverse&&a.fg===b.fg&&a.bg===b.bg}class LyraTerminal extends LyraElement{constructor(){super(...arguments);this.content="";this.maxScrollback=5e3;this.follow=true;this.wrap=true;this.copyable=true;this.downloadable=false;this.filename="terminal.log";this.announceOutput=false;this.accessibleLabel="";this.highlights=[];this.activeHighlightId=null;this.anchorKinds=["line-range"];this.lines=[];this.scrollTargetLineNumber=null;this.justCopied=false;this.buffer=[];this.lineSeq=0;this.column=0;this.ansiParser=createAnsiParser();this.pendingAnnounceText="";this.announcer=new Announcer({throttleMs:ANNOUNCE_THROTTLE_MS,onFlush:text=>{this.pendingAnnounceText="";this.sink?.announce(text);if(this.announceRegionEl)this.announceRegionEl.textContent=text}});this.searchQuery="";this.searchMatches=[];this.searchActiveIndex=-1;this.jumpToLatest=()=>{this.follow=true;this.emit("lr-follow-change",{following:true});this.scrollToBottom()};this.onLineKeyDown=(e,h)=>{if(e.key==="Enter"||e.key===" "){e.preventDefault();this.activateHighlight(h)}};this.onCopy=()=>{const text=this.getPlainText();const ownerWindow=this.ownerDocument.defaultView;try{void ownerWindow?.navigator.clipboard?.writeText(text)?.catch(()=>{})}catch{}this.emit("lr-copy",{text});this.justCopied=true;this.clearCopyTimeout();if(!ownerWindow)return;this.copyTimeoutWindow=ownerWindow;this.copyTimeoutId=ownerWindow.setTimeout(()=>{this.copyTimeoutId=void 0;this.copyTimeoutWindow=void 0;this.justCopied=false},1500)};this.onDownload=()=>{const filename=this.filename||"terminal.log";if(this.emit("lr-download",{filename},{cancelable:true}).defaultPrevented)return;const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow)return;const blob=new ownerWindow.Blob([this.getPlainText()],{type:"text/plain"});const url=ownerWindow.URL.createObjectURL(blob);const a=this.ownerDocument.createElement("a");a.href=url;a.download=filename;a.click();ownerWindow.setTimeout(()=>ownerWindow.URL.revokeObjectURL(url),5e3)};this.onVisibleRangeChanged=e=>{e.stopPropagation();const atBottom=this.lines.length===0||e.detail.end>=this.lines.length-1;if(atBottom!==this.follow){this.follow=atBottom;this.emit("lr-follow-change",{following:atBottom})}};this.onViewportKeyDown=e=>{if(e.key==="End")this.jumpToLatest()};this.onViewportPointerUp=()=>{const shadowGetSelection=root=>root?.getSelection?.();const listShadow=this.renderRoot.querySelector("lr-virtual-list")?.shadowRoot;const selection=shadowGetSelection(listShadow)??shadowGetSelection(this.shadowRoot)??this.ownerDocument.getSelection();const text=selection?.toString()??"";if(!selection||selection.isCollapsed||text==="")return;const lineNumberOf=node=>{let el=node;while(el){if(el.nodeType===1){const attr=el.getAttribute("data-line-number");if(attr!==null)return Number(attr)}el=el.parentNode??el.host??null}return null};const startLine=lineNumberOf(selection.anchorNode);const endLine=lineNumberOf(selection.focusNode);const anchor=startLine!==null&&endLine!==null?{kind:"line-range",start:Math.min(startLine,endLine),end:Math.max(startLine,endLine)}:null;let rects=[];try{rects=[...selection.getRangeAt(0).getClientRects()]}catch{rects=[]}this.emit("lr-text-select",{text,anchor,rects})};this.renderLine=(line,highlightOwnerLines)=>{const isMatchLine=this.searchMatches.some(m=>m.lineNumber===line.number);const isActiveMatchLine=this.searchMatches[this.searchActiveIndex]?.lineNumber===line.number;const highlight=this.highlightForLine(line.number);const highlightOwner=highlight&&highlightOwnerLines.get(highlight)===line.number?highlight:void 0;const tone=highlight?.tone;const lineText=plainTextOfLine(line).trim();const lineLabel=lineText||this.localize("terminalHighlightLine",void 0,{line:getNumberFormat(this.effectiveLocale).format(line.number)});const highlightLabel=highlightOwner?.label?[this.localize("highlightWithLabel",void 0,{label:highlightOwner.label}),lineLabel].join(this.localize("accessibleLabelSeparator")):lineLabel;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{srOnly}from"../../../internal/a11y.js";import{Announcer,acquireAnnouncementSink}from"../../../internal/announcer.js";import{createAnsiParser}from"../../../internal/ansi.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{styles}from"./terminal.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_accessibleLabelSeparator,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_details,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_jumpToLatest,LYRA_DEFAULT_open,LYRA_DEFAULT_terminalDownload,LYRA_DEFAULT_terminalHighlightLine,LYRA_DEFAULT_terminalLabel}from"../../../internal/default-strings.generated.js";const EMPTY_CELL_STYLES={bold:false,dim:false,italic:false,underline:false,inverse:false};const ANNOUNCE_THROTTLE_MS=10;const MAX_SEARCH_MATCHES=1e4;const TONE_BACKGROUND_VAR={accent:"var(--lr-terminal-highlight-accent-bg, var(--lr-color-brand-quiet))",success:"var(--lr-terminal-highlight-success-bg, var(--lr-color-success-quiet))",warning:"var(--lr-terminal-highlight-warning-bg, var(--lr-color-warning-quiet))",danger:"var(--lr-terminal-highlight-danger-bg, var(--lr-color-danger-quiet))",neutral:"var(--lr-terminal-highlight-neutral-bg, var(--lr-color-surface))"};function plainTextOfLine(line){return line.cells.map(c=>c.char).join("")}function groupCells(cells){const segments=[];for(const cell of cells){const last=segments[segments.length-1];if(last&&stylesEqual(last.styles,cell.styles)){last.text+=cell.char}else{segments.push({text:cell.char,styles:cell.styles})}}return segments}function stylesEqual(a,b){return a.bold===b.bold&&a.dim===b.dim&&a.italic===b.italic&&a.underline===b.underline&&a.inverse===b.inverse&&a.fg===b.fg&&a.bg===b.bg}class LyraTerminal extends LyraElement{constructor(){super(...arguments);this.content="";this.maxScrollback=5e3;this.follow=true;this.wrap=true;this.copyable=true;this.downloadable=false;this.filename="terminal.log";this.announceOutput=false;this.accessibleLabel="";this.highlights=[];this.activeHighlightId=null;this.anchorKinds=["line-range"];this.lines=[];this.scrollTargetLineNumber=null;this.justCopied=false;this.buffer=[];this.lineSeq=0;this.column=0;this.ansiParser=createAnsiParser();this.pendingAnnounceText="";this.announcer=new Announcer({throttleMs:ANNOUNCE_THROTTLE_MS,onFlush:text=>{this.pendingAnnounceText="";this.sink?.announce(text);if(this.announceRegionEl)this.announceRegionEl.textContent=text}});this.searchQuery="";this.searchMatches=[];this.searchActiveIndex=-1;this.jumpToLatest=()=>{this.follow=true;this.emit("lr-follow-change",{following:true});this.scrollToBottom()};this.onLineKeyDown=(e,h)=>{if(e.key==="Enter"||e.key===" "){e.preventDefault();this.activateHighlight(h)}};this.onCopy=()=>{const text=this.getPlainText();const ownerWindow=this.ownerDocument.defaultView;try{void ownerWindow?.navigator.clipboard?.writeText(text)?.catch(()=>{})}catch{}this.emit("lr-copy",{text});this.justCopied=true;this.clearCopyTimeout();if(!ownerWindow)return;this.copyTimeoutWindow=ownerWindow;this.copyTimeoutId=ownerWindow.setTimeout(()=>{this.copyTimeoutId=void 0;this.copyTimeoutWindow=void 0;this.justCopied=false},1500)};this.onDownload=()=>{const filename=this.filename||"terminal.log";if(this.emit("lr-download",{filename},{cancelable:true}).defaultPrevented)return;const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow)return;const blob=new ownerWindow.Blob([this.getPlainText()],{type:"text/plain"});const url=ownerWindow.URL.createObjectURL(blob);const a=this.ownerDocument.createElement("a");a.href=url;a.download=filename;a.click();ownerWindow.setTimeout(()=>ownerWindow.URL.revokeObjectURL(url),5e3)};this.onVisibleRangeChanged=e=>{e.stopPropagation();const atBottom=this.lines.length===0||e.detail.end>=this.lines.length-1;if(atBottom!==this.follow){this.follow=atBottom;this.emit("lr-follow-change",{following:atBottom})}};this.onViewportKeyDown=e=>{if(e.key==="End")this.jumpToLatest()};this.onViewportPointerUp=()=>{const shadowGetSelection=root=>root?.getSelection?.();const listShadow=this.renderRoot.querySelector("lr-virtual-list")?.shadowRoot;const selection=shadowGetSelection(listShadow)??shadowGetSelection(this.shadowRoot)??this.ownerDocument.getSelection();const text=selection?.toString()??"";if(!selection||selection.isCollapsed||text==="")return;const lineNumberOf=node=>{let el=node;while(el){if(el.nodeType===1){const attr=el.getAttribute("data-line-number");if(attr!==null)return Number(attr)}el=el.parentNode??el.host??null}return null};const startLine=lineNumberOf(selection.anchorNode);const endLine=lineNumberOf(selection.focusNode);const anchor=startLine!==null&&endLine!==null?{kind:"line-range",start:Math.min(startLine,endLine),end:Math.max(startLine,endLine)}:null;let rects=[];try{rects=[...selection.getRangeAt(0).getClientRects()]}catch{rects=[]}this.emit("lr-text-select",{text,anchor,rects})};this.renderLine=(line,highlightOwnerLines)=>{const isMatchLine=this.searchMatches.some(m=>m.lineNumber===line.number);const isActiveMatchLine=this.searchMatches[this.searchActiveIndex]?.lineNumber===line.number;const highlight=this.highlightForLine(line.number);const highlightOwner=highlight&&highlightOwnerLines.get(highlight)===line.number?highlight:void 0;const tone=highlight?.tone;const lineText=plainTextOfLine(line).trim();const lineLabel=lineText||this.localize("terminalHighlightLine",void 0,{line:getNumberFormat(this.effectiveLocale).format(line.number)});const highlightLabel=highlightOwner?.label?[this.localize("highlightWithLabel",void 0,{label:highlightOwner.label}),lineLabel].join(this.localize("accessibleLabelSeparator")):lineLabel;return html`
2
2
  <div
3
3
  part="line"
4
4
  dir="ltr"
@@ -13,7 +13,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
13
13
  @click=${highlightOwner?()=>this.activateHighlight(highlightOwner):nothing}
14
14
  @keydown=${highlightOwner?e=>this.onLineKeyDown(e,highlightOwner):nothing}
15
15
  >${groupCells(line.cells).map(seg=>html`<span style=${styleMap(this.segmentStyle(seg.styles))}>${seg.text}</span>`)}</div>
16
- `}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,details:LYRA_DEFAULT_details,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,jumpToLatest:LYRA_DEFAULT_jumpToLatest,open:LYRA_DEFAULT_open,terminalDownload:LYRA_DEFAULT_terminalDownload,terminalHighlightLine:LYRA_DEFAULT_terminalHighlightLine,terminalLabel:LYRA_DEFAULT_terminalLabel}}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}connectedCallback(){super.connectedCallback();const ownerWindow=this.ownerDocument.defaultView;if(ownerWindow)this.announcer.setTimerHost(ownerWindow);this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){super.disconnectedCallback();this.clearCopyTimeout();this.justCopied=false;this.cancelPendingAnnouncement();this.sink?.release();this.sink=void 0}adoptedCallback(){const ownerWindow=this.ownerDocument.defaultView;if(ownerWindow)this.announcer.setTimerHost(ownerWindow)}firstUpdated(){this.announceRegionEl=this.renderRoot.querySelector('[part="announcer"]')??void 0}willUpdate(changed){if(changed.has("content")){const previousSearch=this.searchState();this.cancelPendingAnnouncement();this.resetBuffer();this.writeInternal(this.content,false);this.emitSearchChangeIfChanged(previousSearch)}if(changed.has("maxScrollback"))this.trimScrollback();if(changed.has("announceOutput")&&!this.announceOutput)this.cancelPendingAnnouncement()}resetBuffer(){this.ansiParser.reset();this.buffer=[];this.lineSeq=0;this.column=0;this.lines=[];this.scrollTargetLineNumber=null;this.searchQuery="";this.searchMatches=[];this.searchActiveIndex=-1}appendLine(){this.buffer.push({number:++this.lineSeq,cells:[]});this.trimScrollback(false);this.column=0}trimScrollback(notifySearch=true){const previousSearch=this.searchState();const max=Math.max(1,finiteCount(this.maxScrollback,5e3));let trimmed=false;while(this.buffer.length>max){this.buffer.shift();trimmed=true}if(!trimmed)return;this.lines=[...this.buffer];if(this.searchQuery)this.recomputeSearchMatches();if(this.scrollTargetLineNumber!==null&&!this.buffer.some(line=>line.number===this.scrollTargetLineNumber)){this.scrollTargetLineNumber=this.buffer[0]?.number??null}if(notifySearch)this.emitSearchChangeIfChanged(previousSearch)}putChar(ch,styles2){if(this.buffer.length===0)this.appendLine();const line=this.buffer[this.buffer.length-1];if(this.column<line.cells.length){line.cells[this.column]={char:ch,styles:styles2}}else{while(line.cells.length<this.column)line.cells.push({char:" ",styles:EMPTY_CELL_STYLES});line.cells.push({char:ch,styles:styles2})}this.column++}applyChunk(text,styles2){for(const ch of text){if(ch==="\n")this.appendLine();else if(ch==="\r")this.column=0;else if(ch==="\b")this.column=Math.max(0,this.column-1);else if(ch===" ")this.column=(Math.floor(this.column/8)+1)*8;else this.putChar(ch,styles2)}}writeInternal(raw,notifySearch=true){const previousSearch=this.searchState();if(raw!==""){const segments=this.ansiParser.push(raw);for(const seg of segments)this.applyChunk(seg.text,seg.styles)}this.lines=[...this.buffer];if(this.searchQuery)this.recomputeSearchMatches();if(this.follow){const last=this.buffer[this.buffer.length-1];this.scrollTargetLineNumber=last?last.number:null}if(this.hasUpdated&&this.announceOutput&&raw!==""){this.pendingAnnounceText+=(this.pendingAnnounceText?"\n":"")+raw;this.announcer.announce(this.pendingAnnounceText)}if(notifySearch)this.emitSearchChangeIfChanged(previousSearch)}write(chunk){this.writeInternal(chunk)}clear(){const previousSearch=this.searchState();this.cancelPendingAnnouncement();this.resetBuffer();this.emitSearchChangeIfChanged(previousSearch)}getPlainText(){return this.buffer.map(plainTextOfLine).join("\n")}scrollToBottom(){const last=this.buffer[this.buffer.length-1];this.scrollTargetLineNumber=last?last.number:null}recomputeSearchMatches(){this.searchMatches=[];if(!this.searchQuery)return;const needle=this.searchQuery.toLocaleLowerCase(this.effectiveLocale);for(const line of this.buffer){const haystack=plainTextOfLine(line).toLocaleLowerCase(this.effectiveLocale);let from=0;for(;;){const idx=haystack.indexOf(needle,from);if(idx<0)break;this.searchMatches.push({lineNumber:line.number});if(this.searchMatches.length>=MAX_SEARCH_MATCHES)break;from=idx+needle.length}if(this.searchMatches.length>=MAX_SEARCH_MATCHES)break}if(this.searchActiveIndex>=this.searchMatches.length){this.searchActiveIndex=this.searchMatches.length>0?0:-1}}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,activeIndex:this.searchActiveIndex})}searchState(){return{query:this.searchQuery,matchCount:this.searchMatches.length,activeIndex:this.searchActiveIndex}}emitSearchChangeIfChanged(previous){if(previous.query!==this.searchQuery||previous.matchCount!==this.searchMatches.length||previous.activeIndex!==this.searchActiveIndex){this.emitSearchChange()}}jumpToActiveMatch(){const match=this.searchMatches[this.searchActiveIndex];if(!match)return;if(this.follow){this.follow=false;this.emit("lr-follow-change",{following:false})}this.scrollTargetLineNumber=match.lineNumber}async search(query){const previousSearch=this.searchState();this.searchQuery=query;this.recomputeSearchMatches();this.searchActiveIndex=this.searchMatches.length>0?0:-1;this.emitSearchChangeIfChanged(previousSearch);if(this.searchActiveIndex>=0)this.jumpToActiveMatch();await this.updateComplete;return this.searchMatches.length}async searchNext(){if(this.searchMatches.length===0)return false;const previousSearch=this.searchState();this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length;this.emitSearchChangeIfChanged(previousSearch);this.jumpToActiveMatch();return true}async searchPrevious(){if(this.searchMatches.length===0)return false;const previousSearch=this.searchState();this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length;this.emitSearchChangeIfChanged(previousSearch);this.jumpToActiveMatch();return true}clearSearch(){const previousSearch=this.searchState();this.searchQuery="";this.searchMatches=[];this.searchActiveIndex=-1;this.emitSearchChangeIfChanged(previousSearch);this.requestUpdate()}highlightForLine(lineNumber){return this.highlights.find(h=>h.anchor.kind==="line-range"&&lineNumber>=h.anchor.start&&lineNumber<=(h.anchor.end??h.anchor.start))}resolvedHighlightOwnerLines(){const owners=new Map;for(const line of this.lines){const highlight=this.highlightForLine(line.number);if(highlight&&!owners.has(highlight))owners.set(highlight,line.number)}return owners}activateHighlight(h){this.activeHighlightId=h.id;this.emit("lr-highlight-activate",{id:h.id})}async scrollToAnchor(target){let start;if(typeof target==="string"){const highlight=this.highlights.find(h=>h.id===target);if(highlight?.anchor.kind==="line-range")start=highlight.anchor.start}else if(target.kind==="line-range"){start=target.start}if(start===void 0)return false;const found=this.buffer.some(line=>line.number===start);if(!found)return false;if(this.follow){this.follow=false;this.emit("lr-follow-change",{following:false})}this.scrollTargetLineNumber=start;await this.updateComplete;return true}clearCopyTimeout(){if(this.copyTimeoutId!==void 0)this.copyTimeoutWindow?.clearTimeout(this.copyTimeoutId);this.copyTimeoutId=void 0;this.copyTimeoutWindow=void 0}cancelPendingAnnouncement(){this.pendingAnnounceText="";this.announcer.cancel();if(this.announceRegionEl)this.announceRegionEl.textContent=""}lineStateStyle(highlight,interactive,isMatchLine,isActiveMatchLine){return{cursor:interactive?"pointer":"",outline:isMatchLine?`var(--lr-size-2px) solid ${isActiveMatchLine?"var(--lr-terminal-search-active-outline-color, var(--lr-color-brand))":"var(--lr-terminal-search-outline-color, var(--lr-color-warning))"}`:"",background:highlight?.tone?TONE_BACKGROUND_VAR[highlight.tone]:""}}segmentStyle(s){const fg=s.fg??"var(--lr-color-text)";const bg=s.bg??"transparent";return{"font-weight":s.bold?"bold":"normal",opacity:s.dim?"0.7":"1","font-style":s.italic?"italic":"normal","text-decoration":s.underline?"underline":"none",color:s.inverse?bg:fg,"background-color":s.inverse?fg:bg}}render(){const hasToolbar=this.copyable||this.downloadable;const ariaLabel=this.accessibleLabel||this.localize("terminalLabel");const highlightOwnerLines=this.resolvedHighlightOwnerLines();return html`
16
+ `}}static{this.defaultStrings={...super.defaultStrings,accessibleLabelSeparator:LYRA_DEFAULT_accessibleLabelSeparator,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,details:LYRA_DEFAULT_details,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,jumpToLatest:LYRA_DEFAULT_jumpToLatest,open:LYRA_DEFAULT_open,terminalDownload:LYRA_DEFAULT_terminalDownload,terminalHighlightLine:LYRA_DEFAULT_terminalHighlightLine,terminalLabel:LYRA_DEFAULT_terminalLabel}}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}connectedCallback(){super.connectedCallback();const ownerWindow=this.ownerDocument.defaultView;if(ownerWindow)this.announcer.setTimerHost(ownerWindow);this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){super.disconnectedCallback();this.clearCopyTimeout();this.justCopied=false;this.cancelPendingAnnouncement();this.sink?.release();this.sink=void 0}adoptedCallback(){const ownerWindow=this.ownerDocument.defaultView;if(ownerWindow)this.announcer.setTimerHost(ownerWindow)}firstUpdated(){this.announceRegionEl=this.renderRoot.querySelector('[part="announcer"]')??void 0}willUpdate(changed){if(changed.has("content")){const previousSearch=this.searchState();this.cancelPendingAnnouncement();this.resetBuffer();this.writeInternal(this.content,false);this.emitSearchChangeIfChanged(previousSearch)}if(changed.has("maxScrollback"))this.trimScrollback();if(changed.has("announceOutput")&&!this.announceOutput)this.cancelPendingAnnouncement()}resetBuffer(){this.ansiParser.reset();this.buffer=[];this.lineSeq=0;this.column=0;this.lines=[];this.scrollTargetLineNumber=null;this.searchQuery="";this.searchMatches=[];this.searchActiveIndex=-1}appendLine(){this.buffer.push({number:++this.lineSeq,cells:[]});this.trimScrollback(false);this.column=0}trimScrollback(notifySearch=true){const previousSearch=this.searchState();const max=Math.max(1,finiteCount(this.maxScrollback,5e3));let trimmed=false;while(this.buffer.length>max){this.buffer.shift();trimmed=true}if(!trimmed)return;this.lines=[...this.buffer];if(this.searchQuery)this.recomputeSearchMatches();if(this.scrollTargetLineNumber!==null&&!this.buffer.some(line=>line.number===this.scrollTargetLineNumber)){this.scrollTargetLineNumber=this.buffer[0]?.number??null}if(notifySearch)this.emitSearchChangeIfChanged(previousSearch)}putChar(ch,styles2){if(this.buffer.length===0)this.appendLine();const line=this.buffer[this.buffer.length-1];if(this.column<line.cells.length){line.cells[this.column]={char:ch,styles:styles2}}else{while(line.cells.length<this.column)line.cells.push({char:" ",styles:EMPTY_CELL_STYLES});line.cells.push({char:ch,styles:styles2})}this.column++}applyChunk(text,styles2){for(const ch of text){if(ch==="\n")this.appendLine();else if(ch==="\r")this.column=0;else if(ch==="\b")this.column=Math.max(0,this.column-1);else if(ch===" ")this.column=(Math.floor(this.column/8)+1)*8;else this.putChar(ch,styles2)}}writeInternal(raw,notifySearch=true){const previousSearch=this.searchState();if(raw!==""){const segments=this.ansiParser.push(raw);for(const seg of segments)this.applyChunk(seg.text,seg.styles)}this.lines=[...this.buffer];if(this.searchQuery)this.recomputeSearchMatches();if(this.follow){const last=this.buffer[this.buffer.length-1];this.scrollTargetLineNumber=last?last.number:null}if(this.hasUpdated&&this.announceOutput&&raw!==""){this.pendingAnnounceText+=(this.pendingAnnounceText?"\n":"")+raw;this.announcer.announce(this.pendingAnnounceText)}if(notifySearch)this.emitSearchChangeIfChanged(previousSearch)}write(chunk){this.writeInternal(chunk)}clear(){const previousSearch=this.searchState();this.cancelPendingAnnouncement();this.resetBuffer();this.emitSearchChangeIfChanged(previousSearch)}getPlainText(){return this.buffer.map(plainTextOfLine).join("\n")}scrollToBottom(){const last=this.buffer[this.buffer.length-1];this.scrollTargetLineNumber=last?last.number:null}recomputeSearchMatches(){this.searchMatches=[];if(!this.searchQuery)return;const needle=this.searchQuery.toLocaleLowerCase(this.effectiveLocale);for(const line of this.buffer){const haystack=plainTextOfLine(line).toLocaleLowerCase(this.effectiveLocale);let from=0;for(;;){const idx=haystack.indexOf(needle,from);if(idx<0)break;this.searchMatches.push({lineNumber:line.number});if(this.searchMatches.length>=MAX_SEARCH_MATCHES)break;from=idx+needle.length}if(this.searchMatches.length>=MAX_SEARCH_MATCHES)break}if(this.searchActiveIndex>=this.searchMatches.length){this.searchActiveIndex=this.searchMatches.length>0?0:-1}}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,activeIndex:this.searchActiveIndex})}searchState(){return{query:this.searchQuery,matchCount:this.searchMatches.length,activeIndex:this.searchActiveIndex}}emitSearchChangeIfChanged(previous){if(previous.query!==this.searchQuery||previous.matchCount!==this.searchMatches.length||previous.activeIndex!==this.searchActiveIndex){this.emitSearchChange()}}jumpToActiveMatch(){const match=this.searchMatches[this.searchActiveIndex];if(!match)return;if(this.follow){this.follow=false;this.emit("lr-follow-change",{following:false})}this.scrollTargetLineNumber=match.lineNumber}async search(query){const previousSearch=this.searchState();this.searchQuery=query;this.recomputeSearchMatches();this.searchActiveIndex=this.searchMatches.length>0?0:-1;this.emitSearchChangeIfChanged(previousSearch);if(this.searchActiveIndex>=0)this.jumpToActiveMatch();await this.updateComplete;return this.searchMatches.length}async searchNext(){if(this.searchMatches.length===0)return false;const previousSearch=this.searchState();this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length;this.emitSearchChangeIfChanged(previousSearch);this.jumpToActiveMatch();return true}async searchPrevious(){if(this.searchMatches.length===0)return false;const previousSearch=this.searchState();this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length;this.emitSearchChangeIfChanged(previousSearch);this.jumpToActiveMatch();return true}clearSearch(){const previousSearch=this.searchState();this.searchQuery="";this.searchMatches=[];this.searchActiveIndex=-1;this.emitSearchChangeIfChanged(previousSearch);this.requestUpdate()}highlightForLine(lineNumber){return this.highlights.find(h=>h.anchor.kind==="line-range"&&lineNumber>=h.anchor.start&&lineNumber<=(h.anchor.end??h.anchor.start))}resolvedHighlightOwnerLines(){const owners=new Map;for(const line of this.lines){const highlight=this.highlightForLine(line.number);if(highlight&&!owners.has(highlight))owners.set(highlight,line.number)}return owners}activateHighlight(h){this.activeHighlightId=h.id;this.emit("lr-highlight-activate",{id:h.id})}async scrollToAnchor(target){let start;if(typeof target==="string"){const highlight=this.highlights.find(h=>h.id===target);if(highlight?.anchor.kind==="line-range")start=highlight.anchor.start}else if(target.kind==="line-range"){start=target.start}if(start===void 0)return false;const found=this.buffer.some(line=>line.number===start);if(!found)return false;if(this.follow){this.follow=false;this.emit("lr-follow-change",{following:false})}this.scrollTargetLineNumber=start;await this.updateComplete;return true}clearCopyTimeout(){if(this.copyTimeoutId!==void 0)this.copyTimeoutWindow?.clearTimeout(this.copyTimeoutId);this.copyTimeoutId=void 0;this.copyTimeoutWindow=void 0}cancelPendingAnnouncement(){this.pendingAnnounceText="";this.announcer.cancel();if(this.announceRegionEl)this.announceRegionEl.textContent=""}lineStateStyle(highlight,interactive,isMatchLine,isActiveMatchLine){return{cursor:interactive?"pointer":"",outline:isMatchLine?`var(--lr-size-2px) solid ${isActiveMatchLine?"var(--lr-terminal-search-active-outline-color, var(--lr-color-brand))":"var(--lr-terminal-search-outline-color, var(--lr-color-warning))"}`:"",background:highlight?.tone?TONE_BACKGROUND_VAR[highlight.tone]:""}}segmentStyle(s){const fg=sanitizeCssColor(s.fg)??"var(--lr-color-text)";const bg=sanitizeCssColor(s.bg)??"transparent";return{"font-weight":s.bold?"bold":"normal",opacity:s.dim?"0.7":"1","font-style":s.italic?"italic":"normal","text-decoration":s.underline?"underline":"none",color:s.inverse?bg:fg,"background-color":s.inverse?fg:bg}}render(){const hasToolbar=this.copyable||this.downloadable;const ariaLabel=this.accessibleLabel||this.localize("terminalLabel");const highlightOwnerLines=this.resolvedHighlightOwnerLines();return html`
17
17
  <div part="base">
18
18
  <div part="announcer" class="sr-only" aria-hidden="true"></div>
19
19
  ${hasToolbar?html`
@@ -221,6 +221,11 @@ export declare class LyraToolParamForm extends LyraElement<LyraToolParamFormEven
221
221
  private firstInvalidField;
222
222
  private get missingRequiredKeys();
223
223
  private firstMissingPropertyError;
224
+ private focusFirstControl;
225
+ /** Forwards host clicks to the first rendered form field so the component behaves like a regular
226
+ * control from caller code and event re-dispatch paths.
227
+ */
228
+ click(): void;
224
229
  connectedCallback(): void;
225
230
  disconnectedCallback(): void;
226
231
  /** `value`, with any property missing from it filled in from `schema`'s own `default` — see the class doc. */
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./tool-param-form.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/checkbox/checkbox.class.js";import{getListFormat}from"../../../internal/intl-cache.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldMustBeBoolean,LYRA_DEFAULT_fieldMustBeInteger,LYRA_DEFAULT_fieldMustBeNumber,LYRA_DEFAULT_fieldMustBeOneOf,LYRA_DEFAULT_fieldMustBeString,LYRA_DEFAULT_fieldMustEqual,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_schemaMustBeObject,LYRA_DEFAULT_schemaPropertiesMustBeFlat,LYRA_DEFAULT_toolParamMissingProperty,LYRA_DEFAULT_unsupportedFieldType,LYRA_DEFAULT_valueMustBeSerializable}from"../../../internal/default-strings.generated.js";const EMPTY_SCHEMA={type:"object",properties:{}};function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraToolParamForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldMustBeBoolean:LYRA_DEFAULT_fieldMustBeBoolean,fieldMustBeInteger:LYRA_DEFAULT_fieldMustBeInteger,fieldMustBeNumber:LYRA_DEFAULT_fieldMustBeNumber,fieldMustBeOneOf:LYRA_DEFAULT_fieldMustBeOneOf,fieldMustBeString:LYRA_DEFAULT_fieldMustBeString,fieldMustEqual:LYRA_DEFAULT_fieldMustEqual,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,schemaMustBeObject:LYRA_DEFAULT_schemaMustBeObject,schemaPropertiesMustBeFlat:LYRA_DEFAULT_schemaPropertiesMustBeFlat,toolParamMissingProperty:LYRA_DEFAULT_toolParamMissingProperty,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType,valueMustBeSerializable:LYRA_DEFAULT_valueMustBeSerializable}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},schema:{attribute:false,noAccessor:true},value:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this._errors={};this._formError="";this.showFormError=false;this.touchedFields=new Set;this.baseId=nextId("tool-param-form");this._fieldsetDisabled=false;this._name="";this._schema=EMPTY_SCHEMA;this._value={};this._effectiveValue={};this._validityFlags={};this._disabled=false;this.hasInteracted=false;this.visibleErrorSnapshot=new Map;this.suppressNextErrorAnnouncement=true;this.stopNestedControlEvent=e=>{e.stopPropagation()};this.onFieldFocus=()=>{this.emit("focus")};this.onFieldBlur=()=>{this.emit("blur")};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.syncFormState()}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}[VALIDITY_ANCHOR](){const field=this.firstInvalidField();if(field){const input=field.querySelector("input.control");if(input)return input;for(const child of field.children){const anchor=resolveValidityAnchor(child);if(anchor)return anchor}}return this.firstMissingPropertyError()}firstInvalidField(){if(!this.renderRoot)return void 0;const fields=Array.from(this.renderRoot.querySelectorAll('[part="field"]'));for(const key of Object.keys(this._errors)){const field=fields.find(candidate=>candidate.dataset["key"]===key);if(field)return field}return void 0}get missingRequiredKeys(){const properties=this.schemaProperties;return this.requiredKeys.filter(key=>!Object.prototype.hasOwnProperty.call(properties,key)&&Boolean(this._errors[key]))}firstMissingPropertyError(){if(!this.renderRoot)return void 0;const errors=Array.from(this.renderRoot.querySelectorAll('[part="error"][data-missing-property]'));for(const key of Object.keys(this._errors)){const error=errors.find(candidate=>candidate.dataset["key"]===key);if(error)return error}return void 0}connectedCallback(){super.connectedCallback();if(this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument){this.errorAnnouncementSink?.release();this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}if(this.hasUpdated){this.suppressNextErrorAnnouncement=true;this.requestUpdate()}this.syncFormState()}disconnectedCallback(){super.disconnectedCallback();this.errorAnnouncementSink?.release();this.errorAnnouncementSink=void 0;this.suppressNextErrorAnnouncement=true}get effectiveValue(){return{...this._effectiveValue}}get schemaProperties(){const properties=this.schema?.properties;return properties!==null&&typeof properties==="object"&&!Array.isArray(properties)?properties:{}}get requiredKeys(){const required=this.schema?.required;return Array.isArray(required)?required.filter(key=>typeof key==="string"):[]}resolveEffectiveValue(){const props=this.schemaProperties;const out={...this.value};for(const[key,prop]of Object.entries(props)){if(!Object.prototype.hasOwnProperty.call(this.value,key)&&prop.default!==void 0){Object.defineProperty(out,key,{configurable:true,enumerable:true,writable:true,value:prop.default})}}return out}get schema(){return this._schema}set schema(next){const old=this._schema;this._schema=next??EMPTY_SCHEMA;this.syncFormState();this.requestUpdate("schema",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??{};this.syncFormState();this.requestUpdate("value",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.applyValidity();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}get formError(){return this._formError}computeValidation(effective){const props=this.schemaProperties;const required=new Set(this.requiredKeys);const out={};const flags={};const addError=(key,message)=>{Object.defineProperty(out,key,{configurable:true,enumerable:true,writable:true,value:message})};for(const[key,prop]of Object.entries(props)){const type=prop?.type;if(type!=="string"&&type!=="number"&&type!=="integer"&&type!=="boolean"){addError(key,this.localize("unsupportedFieldType",void 0,{type:String(type)}));flags.customError=true;continue}const present=Object.prototype.hasOwnProperty.call(effective,key)&&effective[key]!==void 0;if(!present){if(required.has(key)){addError(key,this.localize("fieldRequired"));flags.valueMissing=true}continue}const v=effective[key];if(type==="string"&&typeof v!=="string"){addError(key,this.localize("fieldMustBeString"));flags.typeMismatch=true;continue}if(type==="number"&&(typeof v!=="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeNumber"));flags.typeMismatch=true;continue}if(type==="integer"&&(typeof v!=="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeInteger"));flags.typeMismatch=true;continue}if(type==="integer"&&!Number.isInteger(v)){addError(key,this.localize("fieldMustBeInteger"));flags.stepMismatch=true;continue}if(type==="boolean"&&typeof v!=="boolean"){addError(key,this.localize("fieldMustBeBoolean"));flags.typeMismatch=true;continue}if(type==="string"&&Array.isArray(prop.enum)&&!prop.enum.includes(v)){addError(key,this.localize("fieldMustBeOneOf",void 0,{values:getListFormat(this.effectiveLocale,{style:"long",type:"disjunction"}).format(prop.enum)}));flags.customError=true;continue}if(prop.const!==void 0&&v!==prop.const){addError(key,this.localize("fieldMustEqual",void 0,{value:JSON.stringify(prop.const)}));flags.customError=true}}for(const key of required){if(Object.prototype.hasOwnProperty.call(props,key))continue;if(!Object.prototype.hasOwnProperty.call(effective,key)||effective[key]===void 0){addError(key,this.localize("fieldRequired"));flags.valueMissing=true}}return{errors:out,flags}}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])}if(this._formError)this.showFormError=true;const valid=this.internals.reportValidity();if(!valid&&!this.firstInvalidField()&&this.missingRequiredKeys.length>0){void this.updateComplete.then(()=>{const error=this.firstMissingPropertyError();this.validityController.refreshAnchor();error?.focus()})}return valid}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidityCustomStates()}formResetCallback(){this.hasInteracted=false;this.value={};this.touchedFields=new Set;this.showFormError=false}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)){restored=parsed}}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.applyValidity();this.requestUpdate()}schemaShapeError(){const schema=this.schema;if(schema===null||typeof schema!=="object"||schema.type!=="object"){return this.localize("schemaMustBeObject")}const properties=schema.properties;if(properties===null||typeof properties!=="object"||Array.isArray(properties)){return this.localize("schemaPropertiesMustBeFlat")}return""}serializeEffectiveValue(effective){const serialized=JSON.stringify(effective,(_key,value)=>{if(typeof value==="number"&&!Number.isFinite(value)){throw new TypeError("Non-finite numbers are not JSON values.")}return value});if(typeof serialized!=="string")throw new TypeError("Value did not serialize to JSON.");return serialized}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncInternals(formValue){this.internals.setFormValue(formValue,formValue);this.applyValidity()}applyValidity(){if(!this.validityController)return;if(this.barredFromValidation||Object.keys(this._validityFlags).length===0){this.validityController.setValidity({})}else{const firstMessage=Object.values(this._errors)[0]??this._formError;this.validityController.setValidity(this._validityFlags,firstMessage)}this.syncValidityCustomStates()}syncValidityCustomStates(){syncValidityStates(this.internals,{required:this.requiredKeys.length>0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}syncFormState(){let effective={};let errors={};let flags={};let formError="";let formValue=null;try{formError=this.schemaShapeError();effective=this.resolveEffectiveValue();const validation=this.computeValidation(effective);errors=validation.errors;flags=validation.flags;formValue=this.serializeEffectiveValue(effective)}catch{formError=this.localize("valueMustBeSerializable");formValue=null}if(formError){flags.customError=true;formValue=null}this._effectiveValue=effective;if(JSON.stringify(this._errors)!==JSON.stringify(errors))this._errors=errors;this._formError=formError;this._validityFlags=flags;this.syncInternals(formValue)}updated(changed){if(changed.has("value")||changed.has("schema")||changed.has("_errors")||changed.has("_formError")){const valid=Object.keys(this._errors).length===0&&this._formError==="";const key=JSON.stringify({valid,errors:this._errors,formError:this._formError});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}const nestedUpdates=Array.from(this.firstInvalidField()?.children??[]).filter(element=>typeof element[VALIDITY_ANCHOR]==="function").map(element=>element.updateComplete).filter(update=>update!==void 0);if(nestedUpdates.length>0){void Promise.all(nestedUpdates).then(()=>this.validityController.refreshAnchor())}}const currentErrors=new Map;for(const node of this.renderRoot.querySelectorAll('[part="error"]')){const fieldKey=node.closest('[part~="field"]')?.dataset["key"];const key=node.dataset["key"]??fieldKey??"form";const text=node.textContent?.trim()??"";if(text)currentErrors.set(key,text)}if(!this.suppressNextErrorAnnouncement){const freshMessages=[];for(const[key,text]of currentErrors){if(this.visibleErrorSnapshot.get(key)!==text&&!freshMessages.includes(text)){freshMessages.push(text)}}if(freshMessages.length>0)this.errorAnnouncementSink?.announce(freshMessages.join(" "))}this.visibleErrorSnapshot=currentErrors;this.suppressNextErrorAnnouncement=false}setFieldValue(key,val){if(this.effectiveDisabled)return;this.hasInteracted=true;this.value={...this.value,[key]:val};this.emit("lr-input",{value:this.effectiveValue})}markTouched(key){this.hasInteracted=true;this.syncValidityCustomStates();if(this.touchedFields.has(key))return;this.touchedFields=new Set(this.touchedFields).add(key)}onTextInput(key,e){this.setFieldValue(key,e.target.value)}onNumberInput(key,e){const raw=e.target;const n=raw.valueAsNumber;this.setFieldValue(key,Number.isNaN(n)?void 0:n)}onSelectChange(key,e){e.stopPropagation();this.setFieldValue(key,e.target.value)}onCheckboxChange(key,e){e.stopPropagation();this.setFieldValue(key,e.detail.checked)}renderControl(key,prop,fieldId,label,required,describedBy,errorMessage,effective){if(prop.type==="string"&&prop.enum&&prop.enum.length>0){return html`<lr-select
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,resolveValidityAnchor,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./tool-param-form.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/option.class.js";import"../../forms/checkbox/checkbox.class.js";import{getListFormat}from"../../../internal/intl-cache.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldMustBeBoolean,LYRA_DEFAULT_fieldMustBeInteger,LYRA_DEFAULT_fieldMustBeNumber,LYRA_DEFAULT_fieldMustBeOneOf,LYRA_DEFAULT_fieldMustBeString,LYRA_DEFAULT_fieldMustEqual,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_schemaMustBeObject,LYRA_DEFAULT_schemaPropertiesMustBeFlat,LYRA_DEFAULT_toolParamMissingProperty,LYRA_DEFAULT_unsupportedFieldType,LYRA_DEFAULT_valueMustBeSerializable}from"../../../internal/default-strings.generated.js";const EMPTY_SCHEMA={type:"object",properties:{}};function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraToolParamForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldMustBeBoolean:LYRA_DEFAULT_fieldMustBeBoolean,fieldMustBeInteger:LYRA_DEFAULT_fieldMustBeInteger,fieldMustBeNumber:LYRA_DEFAULT_fieldMustBeNumber,fieldMustBeOneOf:LYRA_DEFAULT_fieldMustBeOneOf,fieldMustBeString:LYRA_DEFAULT_fieldMustBeString,fieldMustEqual:LYRA_DEFAULT_fieldMustEqual,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,schemaMustBeObject:LYRA_DEFAULT_schemaMustBeObject,schemaPropertiesMustBeFlat:LYRA_DEFAULT_schemaPropertiesMustBeFlat,toolParamMissingProperty:LYRA_DEFAULT_toolParamMissingProperty,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType,valueMustBeSerializable:LYRA_DEFAULT_valueMustBeSerializable}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},schema:{attribute:false,noAccessor:true},value:{attribute:false,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this._errors={};this._formError="";this.showFormError=false;this.touchedFields=new Set;this.baseId=nextId("tool-param-form");this._fieldsetDisabled=false;this._name="";this._schema=EMPTY_SCHEMA;this._value={};this._effectiveValue={};this._validityFlags={};this._disabled=false;this.hasInteracted=false;this.visibleErrorSnapshot=new Map;this.suppressNextErrorAnnouncement=true;this.stopNestedControlEvent=e=>{e.stopPropagation()};this.onFieldFocus=()=>{this.emit("focus")};this.onFieldBlur=()=>{this.emit("blur")};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.syncFormState()}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}[VALIDITY_ANCHOR](){const field=this.firstInvalidField();if(field){const input=field.querySelector("input.control");if(input)return input;for(const child of field.children){const anchor=resolveValidityAnchor(child);if(anchor)return anchor}}return this.firstMissingPropertyError()}firstInvalidField(){if(!this.renderRoot)return void 0;const fields=Array.from(this.renderRoot.querySelectorAll('[part="field"]'));for(const key of Object.keys(this._errors)){const field=fields.find(candidate=>candidate.dataset["key"]===key);if(field)return field}return void 0}get missingRequiredKeys(){const properties=this.schemaProperties;return this.requiredKeys.filter(key=>!Object.prototype.hasOwnProperty.call(properties,key)&&Boolean(this._errors[key]))}firstMissingPropertyError(){if(!this.renderRoot)return void 0;const errors=Array.from(this.renderRoot.querySelectorAll('[part="error"][data-missing-property]'));for(const key of Object.keys(this._errors)){const error=errors.find(candidate=>candidate.dataset["key"]===key);if(error)return error}return void 0}focusFirstControl(){if(!this.renderRoot)return;const firstField=this.renderRoot.querySelector('[part="field"]');if(!firstField)return;const control=firstField.querySelector("input.control")||firstField.querySelector("lr-select")||firstField.querySelector("lr-checkbox");control?.focus()}click(){if(this.effectiveDisabled)return;this.focusFirstControl()}connectedCallback(){super.connectedCallback();if(this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument){this.errorAnnouncementSink?.release();this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}if(this.hasUpdated){this.suppressNextErrorAnnouncement=true;this.requestUpdate()}this.syncFormState()}disconnectedCallback(){super.disconnectedCallback();this.errorAnnouncementSink?.release();this.errorAnnouncementSink=void 0;this.suppressNextErrorAnnouncement=true}get effectiveValue(){return{...this._effectiveValue}}get schemaProperties(){const properties=this.schema?.properties;return properties!==null&&typeof properties==="object"&&!Array.isArray(properties)?properties:{}}get requiredKeys(){const required=this.schema?.required;return Array.isArray(required)?required.filter(key=>typeof key==="string"):[]}resolveEffectiveValue(){const props=this.schemaProperties;const out={...this.value};for(const[key,prop]of Object.entries(props)){if(!Object.prototype.hasOwnProperty.call(this.value,key)&&prop.default!==void 0){Object.defineProperty(out,key,{configurable:true,enumerable:true,writable:true,value:prop.default})}}return out}get schema(){return this._schema}set schema(next){const old=this._schema;this._schema=next??EMPTY_SCHEMA;this.syncFormState();this.requestUpdate("schema",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??{};this.syncFormState();this.requestUpdate("value",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.applyValidity();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}get formError(){return this._formError}computeValidation(effective){const props=this.schemaProperties;const required=new Set(this.requiredKeys);const out={};const flags={};const addError=(key,message)=>{Object.defineProperty(out,key,{configurable:true,enumerable:true,writable:true,value:message})};for(const[key,prop]of Object.entries(props)){const type=prop?.type;if(type!=="string"&&type!=="number"&&type!=="integer"&&type!=="boolean"){addError(key,this.localize("unsupportedFieldType",void 0,{type:String(type)}));flags.customError=true;continue}const present=Object.prototype.hasOwnProperty.call(effective,key)&&effective[key]!==void 0;if(!present){if(required.has(key)){addError(key,this.localize("fieldRequired"));flags.valueMissing=true}continue}const v=effective[key];if(type==="string"&&typeof v!=="string"){addError(key,this.localize("fieldMustBeString"));flags.typeMismatch=true;continue}if(type==="number"&&(typeof v!=="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeNumber"));flags.typeMismatch=true;continue}if(type==="integer"&&(typeof v!=="number"||!Number.isFinite(v))){addError(key,this.localize("fieldMustBeInteger"));flags.typeMismatch=true;continue}if(type==="integer"&&!Number.isInteger(v)){addError(key,this.localize("fieldMustBeInteger"));flags.stepMismatch=true;continue}if(type==="boolean"&&typeof v!=="boolean"){addError(key,this.localize("fieldMustBeBoolean"));flags.typeMismatch=true;continue}if(type==="string"&&Array.isArray(prop.enum)&&!prop.enum.includes(v)){addError(key,this.localize("fieldMustBeOneOf",void 0,{values:getListFormat(this.effectiveLocale,{style:"long",type:"disjunction"}).format(prop.enum)}));flags.customError=true;continue}if(prop.const!==void 0&&v!==prop.const){addError(key,this.localize("fieldMustEqual",void 0,{value:JSON.stringify(prop.const)}));flags.customError=true}}for(const key of required){if(Object.prototype.hasOwnProperty.call(props,key))continue;if(!Object.prototype.hasOwnProperty.call(effective,key)||effective[key]===void 0){addError(key,this.localize("fieldRequired"));flags.valueMissing=true}}return{errors:out,flags}}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)])}if(this._formError)this.showFormError=true;const valid=this.internals.reportValidity();if(!valid&&!this.firstInvalidField()&&this.missingRequiredKeys.length>0){void this.updateComplete.then(()=>{const error=this.firstMissingPropertyError();this.validityController.refreshAnchor();error?.focus()})}return valid}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncValidityCustomStates()}formResetCallback(){this.hasInteracted=false;this.value={};this.touchedFields=new Set;this.showFormError=false}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed)){restored=parsed}}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.applyValidity();this.requestUpdate()}schemaShapeError(){const schema=this.schema;if(schema===null||typeof schema!=="object"||schema.type!=="object"){return this.localize("schemaMustBeObject")}const properties=schema.properties;if(properties===null||typeof properties!=="object"||Array.isArray(properties)){return this.localize("schemaPropertiesMustBeFlat")}return""}serializeEffectiveValue(effective){const serialized=JSON.stringify(effective,(_key,value)=>{if(typeof value==="number"&&!Number.isFinite(value)){throw new TypeError("Non-finite numbers are not JSON values.")}return value});if(typeof serialized!=="string")throw new TypeError("Value did not serialize to JSON.");return serialized}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncInternals(formValue){this.internals.setFormValue(formValue,formValue);this.applyValidity()}applyValidity(){if(!this.validityController)return;if(this.barredFromValidation||Object.keys(this._validityFlags).length===0){this.validityController.setValidity({})}else{const firstMessage=Object.values(this._errors)[0]??this._formError;this.validityController.setValidity(this._validityFlags,firstMessage)}this.syncValidityCustomStates()}syncValidityCustomStates(){syncValidityStates(this.internals,{required:this.requiredKeys.length>0,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}syncFormState(){let effective={};let errors={};let flags={};let formError="";let formValue=null;try{formError=this.schemaShapeError();effective=this.resolveEffectiveValue();const validation=this.computeValidation(effective);errors=validation.errors;flags=validation.flags;formValue=this.serializeEffectiveValue(effective)}catch{formError=this.localize("valueMustBeSerializable");formValue=null}if(formError){flags.customError=true;formValue=null}this._effectiveValue=effective;if(JSON.stringify(this._errors)!==JSON.stringify(errors))this._errors=errors;this._formError=formError;this._validityFlags=flags;this.syncInternals(formValue)}updated(changed){if(changed.has("value")||changed.has("schema")||changed.has("_errors")||changed.has("_formError")){const valid=Object.keys(this._errors).length===0&&this._formError==="";const key=JSON.stringify({valid,errors:this._errors,formError:this._formError});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}const nestedUpdates=Array.from(this.firstInvalidField()?.children??[]).filter(element=>typeof element[VALIDITY_ANCHOR]==="function").map(element=>element.updateComplete).filter(update=>update!==void 0);if(nestedUpdates.length>0){void Promise.all(nestedUpdates).then(()=>this.validityController.refreshAnchor())}}const currentErrors=new Map;for(const node of this.renderRoot.querySelectorAll('[part="error"]')){const fieldKey=node.closest('[part~="field"]')?.dataset["key"];const key=node.dataset["key"]??fieldKey??"form";const text=node.textContent?.trim()??"";if(text)currentErrors.set(key,text)}if(!this.suppressNextErrorAnnouncement){const freshMessages=[];for(const[key,text]of currentErrors){if(this.visibleErrorSnapshot.get(key)!==text&&!freshMessages.includes(text)){freshMessages.push(text)}}if(freshMessages.length>0)this.errorAnnouncementSink?.announce(freshMessages.join(" "))}this.visibleErrorSnapshot=currentErrors;this.suppressNextErrorAnnouncement=false}setFieldValue(key,val){if(this.effectiveDisabled)return;this.hasInteracted=true;this.value={...this.value,[key]:val};this.emit("lr-input",{value:this.effectiveValue})}markTouched(key){this.hasInteracted=true;this.syncValidityCustomStates();if(this.touchedFields.has(key))return;this.touchedFields=new Set(this.touchedFields).add(key)}onTextInput(key,e){this.setFieldValue(key,e.target.value)}onNumberInput(key,e){const raw=e.target;const n=raw.valueAsNumber;this.setFieldValue(key,Number.isNaN(n)?void 0:n)}onSelectChange(key,e){e.stopPropagation();this.setFieldValue(key,e.target.value)}onCheckboxChange(key,e){e.stopPropagation();this.setFieldValue(key,e.detail.checked)}renderControl(key,prop,fieldId,label,required,describedBy,errorMessage,effective){if(prop.type==="string"&&prop.enum&&prop.enum.length>0){return html`<lr-select
2
2
  id=${fieldId}
3
3
  .label=${label}
4
4
  .hint=${prop.description??""}
@@ -92,4 +92,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
92
92
  ${this.hasCustomDataTable()?nothing:this.renderDataTable()}
93
93
  </div>
94
94
  </div>
95
- `}get showsLegend(){return this.legend&&!this.withoutLegend}}__decorate([property({converter:{fromAttribute:value=>normalizeChartType(value)}})],LyraChart.prototype,"type",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"labels",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"datasets",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"legend",void 0);__decorate([property()],LyraChart.prototype,"description",void 0);__decorate([property()],LyraChart.prototype,"grid",void 0);__decorate([property({attribute:"index-axis"})],LyraChart.prototype,"indexAxis",void 0);__decorate([property()],LyraChart.prototype,"label",void 0);__decorate([property({attribute:"legend-position"})],LyraChart.prototype,"legendPosition",void 0);__decorate([property({type:Number})],LyraChart.prototype,"max",void 0);__decorate([property({type:Number})],LyraChart.prototype,"min",void 0);__decorate([property({type:Array})],LyraChart.prototype,"plugins",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"valueFormatter",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"area",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"zoom",void 0);__decorate([property()],LyraChart.prototype,"height",void 0);__decorate([property({attribute:"x-label"})],LyraChart.prototype,"xLabel",void 0);__decorate([property({attribute:"y-label"})],LyraChart.prototype,"yLabel",void 0);__decorate([property({attribute:"y2-label"})],LyraChart.prototype,"y2Label",void 0);__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraChart.prototype,"beginAtZero",void 0);__decorate([property({attribute:"accessible-label"})],LyraChart.prototype,"accessibleLabel",void 0);__decorate([property({attribute:"accessible-description"})],LyraChart.prototype,"accessibleDescription",void 0);__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraChart.prototype,"showDataTable",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"horizontal",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"stacked",void 0);__decorate([property({type:Boolean,attribute:"without-animation",reflect:true})],LyraChart.prototype,"withoutAnimation",void 0);__decorate([property({type:Boolean,attribute:"without-legend",reflect:true})],LyraChart.prototype,"withoutLegend",void 0);__decorate([property({type:Boolean,attribute:"without-tooltip",reflect:true})],LyraChart.prototype,"withoutTooltip",void 0);__decorate([property({type:Boolean,attribute:"data-labels"})],LyraChart.prototype,"dataLabels",void 0);__decorate([property({type:Boolean,attribute:"stack-totals"})],LyraChart.prototype,"stackTotals",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"config",void 0);__decorate([state()],LyraChart.prototype,"slottedConfig",void 0);__decorate([state()],LyraChart.prototype,"loading",void 0);__decorate([state()],LyraChart.prototype,"loadFailed",void 0);__decorate([state()],LyraChart.prototype,"zoomed",void 0);__decorate([state()],LyraChart.prototype,"visible",void 0);__decorate([query("canvas")],LyraChart.prototype,"canvasEl",void 0);__decorate([state()],LyraChart.prototype,"autoLegendPosition",void 0);__decorate([state()],LyraChart.prototype,"keyboardDatumAnnouncement",void 0);function lockChartType(ctor,value){Object.defineProperty(ctor.prototype,"type",{configurable:true,enumerable:true,get(){return value},set(_v){}})}export{LyraChart,lockChartType,seriesPalette2 as seriesPalette};
95
+ `}get showsLegend(){return this.legend&&!this.withoutLegend}}__decorate([property({converter:{fromAttribute:value=>normalizeChartType(value)}})],LyraChart.prototype,"type",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"labels",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"datasets",void 0);__decorate([property({type:Boolean,converter:trueDefaultBooleanConverter})],LyraChart.prototype,"legend",void 0);__decorate([property()],LyraChart.prototype,"description",void 0);__decorate([property()],LyraChart.prototype,"grid",void 0);__decorate([property({attribute:"index-axis"})],LyraChart.prototype,"indexAxis",void 0);__decorate([property()],LyraChart.prototype,"label",void 0);__decorate([property({attribute:"legend-position"})],LyraChart.prototype,"legendPosition",void 0);__decorate([property({type:Number})],LyraChart.prototype,"max",void 0);__decorate([property({type:Number})],LyraChart.prototype,"min",void 0);__decorate([property({type:Array})],LyraChart.prototype,"plugins",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"valueFormatter",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"area",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"zoom",void 0);__decorate([property()],LyraChart.prototype,"height",void 0);__decorate([property({attribute:"x-label"})],LyraChart.prototype,"xLabel",void 0);__decorate([property({attribute:"y-label"})],LyraChart.prototype,"yLabel",void 0);__decorate([property({attribute:"y2-label"})],LyraChart.prototype,"y2Label",void 0);__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraChart.prototype,"beginAtZero",void 0);__decorate([property({attribute:"accessible-label"})],LyraChart.prototype,"accessibleLabel",void 0);__decorate([property({attribute:"accessible-description"})],LyraChart.prototype,"accessibleDescription",void 0);__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraChart.prototype,"showDataTable",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"horizontal",void 0);__decorate([property({type:Boolean})],LyraChart.prototype,"stacked",void 0);__decorate([property({type:Boolean,attribute:"without-animation",reflect:true})],LyraChart.prototype,"withoutAnimation",void 0);__decorate([property({type:Boolean,attribute:"without-legend",reflect:true})],LyraChart.prototype,"withoutLegend",void 0);__decorate([property({type:Boolean,attribute:"without-tooltip",reflect:true})],LyraChart.prototype,"withoutTooltip",void 0);__decorate([property({type:Boolean,attribute:"data-labels"})],LyraChart.prototype,"dataLabels",void 0);__decorate([property({type:Boolean,attribute:"stack-totals"})],LyraChart.prototype,"stackTotals",void 0);__decorate([property({attribute:false})],LyraChart.prototype,"config",void 0);__decorate([state()],LyraChart.prototype,"slottedConfig",void 0);__decorate([state()],LyraChart.prototype,"loading",void 0);__decorate([state()],LyraChart.prototype,"loadFailed",void 0);__decorate([state()],LyraChart.prototype,"zoomed",void 0);__decorate([state()],LyraChart.prototype,"visible",void 0);__decorate([query("canvas")],LyraChart.prototype,"canvasEl",void 0);__decorate([state()],LyraChart.prototype,"autoLegendPosition",void 0);__decorate([state()],LyraChart.prototype,"keyboardDatumAnnouncement",void 0);function lockChartType(ctor,value){Object.defineProperty(ctor.prototype,"type",{configurable:true,enumerable:true,get(){return value},set(_v){}})}export{LyraChart,lockChartType,seriesPalette2 as seriesPalette};
@@ -64,6 +64,11 @@ export declare class LyraSelectionToolbar extends LyraElement<LyraSelectionToolb
64
64
  private onToolbarFocusIn;
65
65
  private onToolbarKeyDown;
66
66
  private actionPartNames;
67
+ /** Coerces a caller-supplied `rect` to finite geometry before it reaches any style sink --
68
+ * `rect` is typed `DOMRectReadOnly`, but TS cannot enforce that across the property boundary,
69
+ * and `coordinates()` feeds a `styleMap()` whose first commit serializes the whole `style`
70
+ * value as one string (see `sanitizeSwatchColor`'s doc comment for why that matters). */
71
+ private safeRect;
67
72
  private coordinates;
68
73
  private updateToolbarPosition;
69
74
  private startPositioning;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{styles}from"./selection-toolbar.styles.js";import{LYRA_DEFAULT_copy,LYRA_DEFAULT_open,LYRA_DEFAULT_selectionAsk,LYRA_DEFAULT_selectionCite,LYRA_DEFAULT_selectionQuote,LYRA_DEFAULT_selectionToolbarLabel}from"../../../internal/default-strings.generated.js";const ACTION_KEYS={ask:"selectionAsk",quote:"selectionQuote",cite:"selectionCite",copy:"copy"};class LyraSelectionToolbar extends LyraElement{constructor(){super(...arguments);this.open=false;this.text="";this.anchor=null;this.rect=null;this.actions=["ask","quote","cite","copy"];this.label="";this.accessibleLabel=null;this.activeActionIndex=0;this.lifecycleGeneration=0;this.positioningGeneration=0;this.rovingGeneration=0;this.onToolbarFocusIn=event=>{const buttons=this.actionButtons();const path=event.composedPath();const index=buttons.findIndex(button=>path.includes(button));if(index>=0)void this.syncRovingStops(index)};this.onToolbarKeyDown=event=>{const buttons=this.actionButtons();if(buttons.length===0)return;const forward=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";const backward=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let next;if(event.key===forward)next=(this.activeActionIndex+1)%buttons.length;else if(event.key===backward)next=(this.activeActionIndex-1+buttons.length)%buttons.length;else if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else return;event.preventDefault();const generation=this.lifecycleGeneration;const owner=this.ownerDocument.defaultView;void this.syncRovingStops(next).then(button=>{if(!button||!this.isCurrentLifecycle(generation,owner)||!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.renderRoot.contains(button))return;button.focus()})};this.updateToolbarPosition=()=>{const toolbar=this.toolbar;const view=this.ownerDocument.defaultView;if(!toolbar||!view)return;const edge=8;const gap=8;const rect=this.rect??new view.DOMRect(view.innerWidth/2,0,0,0);const width=toolbar.offsetWidth;const height=toolbar.offsetHeight;const desiredInline=rect.left+rect.width/2;const desiredLeft=desiredInline-width/2;const maxLeft=Math.max(edge,view.innerWidth-width-edge);const left=Math.min(maxLeft,Math.max(edge,desiredLeft));const above=rect.top-height-gap;const below=rect.bottom+gap;const desiredTop=above>=edge?above:below;const maxTop=Math.max(edge,view.innerHeight-height-edge);const top=Math.min(maxTop,Math.max(edge,desiredTop));const logicalInline=this.effectiveDirection==="rtl"?view.innerWidth-desiredInline:desiredInline;toolbar.style.setProperty("--lr-selection-toolbar-inline-start",`${logicalInline}px`);toolbar.style.setProperty("--lr-selection-toolbar-block-start",`${rect.top}px`);toolbar.style.setProperty("--lr-selection-toolbar-inline-shift",`${left-(desiredInline-width/2)}px`);toolbar.style.setProperty("--lr-selection-toolbar-block-shift",`${top-(rect.top-height)}px`);toolbar.toggleAttribute("data-positioned",true)}}static{this.defaultStrings={...super.defaultStrings,copy:LYRA_DEFAULT_copy,open:LYRA_DEFAULT_open,selectionAsk:LYRA_DEFAULT_selectionAsk,selectionCite:LYRA_DEFAULT_selectionCite,selectionQuote:LYRA_DEFAULT_selectionQuote,selectionToolbarLabel:LYRA_DEFAULT_selectionToolbarLabel}}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback();if(this.hasUpdated)this.syncOpenLifecycle()}disconnectedCallback(){this.lifecycleGeneration++;this.rovingGeneration++;this.retirePositioning();this.overlay?.suspend();super.disconnectedCallback()}adoptedCallback(){this.lifecycleGeneration++;this.rovingGeneration++;this.retirePositioning()}updated(changed){if(changed.has("open")||changed.has("text"))this.syncOpenLifecycle();if(this.open&&this.text&&(changed.has("rect")||changed.has("actions"))){this.updateToolbarPosition()}if(this.open&&this.text&&(changed.has("open")||changed.has("text")||changed.has("actions"))){void this.syncRovingStops()}}syncOpenLifecycle(){if(!this.isConnected){this.retirePositioning();this.overlay?.deactivate();this.overlay=void 0;return}if(!this.open||!this.text){this.retirePositioning();this.overlay?.deactivate();this.overlay=void 0;return}if(this.overlay?.isActive()){this.overlay.resume()}else{this.overlay=activateOverlay({host:this,panel:()=>this.toolbar??null,onEscape:()=>this.dismiss(),modal:false,trapFocus:false})}this.startPositioning()}dismiss(){if(!this.open)return;this.open=false;this.emit("lr-dismiss")}async activate(action){const text=this.text;const anchor=this.anchor;const generation=this.lifecycleGeneration;const owner=this.isConnected?this.ownerDocument.defaultView:null;if(action==="copy"&&owner?.navigator.clipboard?.writeText){try{await owner.navigator.clipboard.writeText(text)}catch(error){if(!this.isCurrentLifecycle(generation,owner))return;this.emit("lr-copy-error",{error})}}if(!this.isCurrentLifecycle(generation,owner))return;this.emit("lr-selection-action",{action,text,anchor})}isCurrentLifecycle(generation,owner){return generation===this.lifecycleGeneration&&this.isConnected&&this.ownerDocument.defaultView===owner}actionButtons(){return[...this.renderRoot.querySelectorAll("lr-button[data-action]")]}async syncRovingStops(preferredIndex=this.activeActionIndex){const generation=this.lifecycleGeneration;const owner=this.ownerDocument.defaultView;const request=++this.rovingGeneration;if(!owner||!this.isConnected)return void 0;const buttons=this.actionButtons();await Promise.all(buttons.map(button=>button.updateComplete));if(request!==this.rovingGeneration||!this.isCurrentLifecycle(generation,owner)||buttons.some(button=>!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.renderRoot.contains(button)))return void 0;if(buttons.length===0)return void 0;this.activeActionIndex=Math.min(Math.max(0,preferredIndex),buttons.length-1);buttons.forEach((button,index)=>{const inner=button.shadowRoot?.querySelector('[part~="base"]');if(inner)inner.tabIndex=index===this.activeActionIndex?0:-1});return buttons[this.activeActionIndex]}actionPartNames(action){const parts=["action"];switch(action){case"ask":parts.push("action-ask");break;case"quote":parts.push("action-quote");break;case"cite":parts.push("action-cite");break;case"copy":parts.push("action-copy");break}return parts.join(" ")}coordinates(){const viewportWidth=this.ownerDocument.defaultView?.innerWidth??0;const desiredInline=this.rect?this.rect.left+this.rect.width/2:viewportWidth/2;const block=this.rect?.top??0;return{"--lr-selection-toolbar-inline-start":`${this.effectiveDirection==="rtl"?viewportWidth-desiredInline:desiredInline}px`,"--lr-selection-toolbar-block-start":`${block}px`}}startPositioning(){this.retirePositioning();const toolbar=this.toolbar;const view=this.ownerDocument.defaultView;if(!toolbar||!view||!this.isConnected)return;const generation=this.positioningGeneration;const update=()=>{if(generation!==this.positioningGeneration||!this.isConnected||this.ownerDocument.defaultView!==view||this.toolbar!==toolbar)return;this.updateToolbarPosition()};const observer=typeof view.ResizeObserver==="undefined"?void 0:new view.ResizeObserver(update);observer?.observe(toolbar);view.addEventListener("resize",update);view.visualViewport?.addEventListener("resize",update);view.visualViewport?.addEventListener("scroll",update);update();this.stopPositioning=()=>{observer?.disconnect();view.removeEventListener("resize",update);view.visualViewport?.removeEventListener("resize",update);view.visualViewport?.removeEventListener("scroll",update)}}retirePositioning(){this.positioningGeneration++;const stop=this.stopPositioning;this.stopPositioning=void 0;stop?.()}render(){if(!this.open||!this.text)return html`${nothing}`;const label=this.accessibleLabel||this.label||this.localize("selectionToolbarLabel");return html`<div
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteNumber}from"../../../internal/numbers.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{styles}from"./selection-toolbar.styles.js";import{LYRA_DEFAULT_copy,LYRA_DEFAULT_open,LYRA_DEFAULT_selectionAsk,LYRA_DEFAULT_selectionCite,LYRA_DEFAULT_selectionQuote,LYRA_DEFAULT_selectionToolbarLabel}from"../../../internal/default-strings.generated.js";const ACTION_KEYS={ask:"selectionAsk",quote:"selectionQuote",cite:"selectionCite",copy:"copy"};class LyraSelectionToolbar extends LyraElement{constructor(){super(...arguments);this.open=false;this.text="";this.anchor=null;this.rect=null;this.actions=["ask","quote","cite","copy"];this.label="";this.accessibleLabel=null;this.activeActionIndex=0;this.lifecycleGeneration=0;this.positioningGeneration=0;this.rovingGeneration=0;this.onToolbarFocusIn=event=>{const buttons=this.actionButtons();const path=event.composedPath();const index=buttons.findIndex(button=>path.includes(button));if(index>=0)void this.syncRovingStops(index)};this.onToolbarKeyDown=event=>{const buttons=this.actionButtons();if(buttons.length===0)return;const forward=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";const backward=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let next;if(event.key===forward)next=(this.activeActionIndex+1)%buttons.length;else if(event.key===backward)next=(this.activeActionIndex-1+buttons.length)%buttons.length;else if(event.key==="Home")next=0;else if(event.key==="End")next=buttons.length-1;else return;event.preventDefault();const generation=this.lifecycleGeneration;const owner=this.ownerDocument.defaultView;void this.syncRovingStops(next).then(button=>{if(!button||!this.isCurrentLifecycle(generation,owner)||!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.renderRoot.contains(button))return;button.focus()})};this.updateToolbarPosition=()=>{const toolbar=this.toolbar;const view=this.ownerDocument.defaultView;if(!toolbar||!view)return;const edge=8;const gap=8;const rect=this.safeRect(this.rect??new view.DOMRect(view.innerWidth/2,0,0,0));const width=toolbar.offsetWidth;const height=toolbar.offsetHeight;const desiredInline=rect.left+rect.width/2;const desiredLeft=desiredInline-width/2;const maxLeft=Math.max(edge,view.innerWidth-width-edge);const left=Math.min(maxLeft,Math.max(edge,desiredLeft));const above=rect.top-height-gap;const below=rect.bottom+gap;const desiredTop=above>=edge?above:below;const maxTop=Math.max(edge,view.innerHeight-height-edge);const top=Math.min(maxTop,Math.max(edge,desiredTop));const logicalInline=this.effectiveDirection==="rtl"?view.innerWidth-desiredInline:desiredInline;toolbar.style.setProperty("--lr-selection-toolbar-inline-start",`${logicalInline}px`);toolbar.style.setProperty("--lr-selection-toolbar-block-start",`${rect.top}px`);toolbar.style.setProperty("--lr-selection-toolbar-inline-shift",`${left-(desiredInline-width/2)}px`);toolbar.style.setProperty("--lr-selection-toolbar-block-shift",`${top-(rect.top-height)}px`);toolbar.toggleAttribute("data-positioned",true)}}static{this.defaultStrings={...super.defaultStrings,copy:LYRA_DEFAULT_copy,open:LYRA_DEFAULT_open,selectionAsk:LYRA_DEFAULT_selectionAsk,selectionCite:LYRA_DEFAULT_selectionCite,selectionQuote:LYRA_DEFAULT_selectionQuote,selectionToolbarLabel:LYRA_DEFAULT_selectionToolbarLabel}}static{this.styles=[LyraElement.styles,styles]}connectedCallback(){super.connectedCallback();if(this.hasUpdated)this.syncOpenLifecycle()}disconnectedCallback(){this.lifecycleGeneration++;this.rovingGeneration++;this.retirePositioning();this.overlay?.suspend();super.disconnectedCallback()}adoptedCallback(){this.lifecycleGeneration++;this.rovingGeneration++;this.retirePositioning()}updated(changed){if(changed.has("open")||changed.has("text"))this.syncOpenLifecycle();if(this.open&&this.text&&(changed.has("rect")||changed.has("actions"))){this.updateToolbarPosition()}if(this.open&&this.text&&(changed.has("open")||changed.has("text")||changed.has("actions"))){void this.syncRovingStops()}}syncOpenLifecycle(){if(!this.isConnected){this.retirePositioning();this.overlay?.deactivate();this.overlay=void 0;return}if(!this.open||!this.text){this.retirePositioning();this.overlay?.deactivate();this.overlay=void 0;return}if(this.overlay?.isActive()){this.overlay.resume()}else{this.overlay=activateOverlay({host:this,panel:()=>this.toolbar??null,onEscape:()=>this.dismiss(),modal:false,trapFocus:false})}this.startPositioning()}dismiss(){if(!this.open)return;this.open=false;this.emit("lr-dismiss")}async activate(action){const text=this.text;const anchor=this.anchor;const generation=this.lifecycleGeneration;const owner=this.isConnected?this.ownerDocument.defaultView:null;if(action==="copy"&&owner?.navigator.clipboard?.writeText){try{await owner.navigator.clipboard.writeText(text)}catch(error){if(!this.isCurrentLifecycle(generation,owner))return;this.emit("lr-copy-error",{error})}}if(!this.isCurrentLifecycle(generation,owner))return;this.emit("lr-selection-action",{action,text,anchor})}isCurrentLifecycle(generation,owner){return generation===this.lifecycleGeneration&&this.isConnected&&this.ownerDocument.defaultView===owner}actionButtons(){return[...this.renderRoot.querySelectorAll("lr-button[data-action]")]}async syncRovingStops(preferredIndex=this.activeActionIndex){const generation=this.lifecycleGeneration;const owner=this.ownerDocument.defaultView;const request=++this.rovingGeneration;if(!owner||!this.isConnected)return void 0;const buttons=this.actionButtons();await Promise.all(buttons.map(button=>button.updateComplete));if(request!==this.rovingGeneration||!this.isCurrentLifecycle(generation,owner)||buttons.some(button=>!button.isConnected||button.ownerDocument!==this.ownerDocument||!this.renderRoot.contains(button)))return void 0;if(buttons.length===0)return void 0;this.activeActionIndex=Math.min(Math.max(0,preferredIndex),buttons.length-1);buttons.forEach((button,index)=>{const inner=button.shadowRoot?.querySelector('[part~="base"]');if(inner)inner.tabIndex=index===this.activeActionIndex?0:-1});return buttons[this.activeActionIndex]}actionPartNames(action){const parts=["action"];switch(action){case"ask":parts.push("action-ask");break;case"quote":parts.push("action-quote");break;case"cite":parts.push("action-cite");break;case"copy":parts.push("action-copy");break}return parts.join(" ")}safeRect(rect){return{left:finiteNumber(rect.left,0),top:finiteNumber(rect.top,0),width:finiteNumber(rect.width,0),bottom:finiteNumber(rect.bottom,0)}}coordinates(){const viewportWidth=this.ownerDocument.defaultView?.innerWidth??0;const rect=this.rect?this.safeRect(this.rect):void 0;const desiredInline=rect?rect.left+rect.width/2:viewportWidth/2;const block=rect?.top??0;return{"--lr-selection-toolbar-inline-start":`${this.effectiveDirection==="rtl"?viewportWidth-desiredInline:desiredInline}px`,"--lr-selection-toolbar-block-start":`${block}px`}}startPositioning(){this.retirePositioning();const toolbar=this.toolbar;const view=this.ownerDocument.defaultView;if(!toolbar||!view||!this.isConnected)return;const generation=this.positioningGeneration;const update=()=>{if(generation!==this.positioningGeneration||!this.isConnected||this.ownerDocument.defaultView!==view||this.toolbar!==toolbar)return;this.updateToolbarPosition()};const observer=typeof view.ResizeObserver==="undefined"?void 0:new view.ResizeObserver(update);observer?.observe(toolbar);view.addEventListener("resize",update);view.visualViewport?.addEventListener("resize",update);view.visualViewport?.addEventListener("scroll",update);update();this.stopPositioning=()=>{observer?.disconnect();view.removeEventListener("resize",update);view.visualViewport?.removeEventListener("resize",update);view.visualViewport?.removeEventListener("scroll",update)}}retirePositioning(){this.positioningGeneration++;const stop=this.stopPositioning;this.stopPositioning=void 0;stop?.()}render(){if(!this.open||!this.text)return html`${nothing}`;const label=this.accessibleLabel||this.label||this.localize("selectionToolbarLabel");return html`<div
2
2
  part="toolbar"
3
3
  role="toolbar"
4
4
  aria-label=${label}
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,render}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{styles}from"./widget-renderer.styles.js";import{resolveTree}from"./resolve.js";import{getDefaultWidgetTypeRegistry}from"./registry.js";const GAP_TOKEN={s:"var(--lr-space-s)",m:"var(--lr-space-m)",l:"var(--lr-space-l)"};const JUSTIFY_VALUE={start:"flex-start",center:"center",end:"flex-end",between:"space-between"};class LyraWidgetRenderer extends LyraElement{constructor(){super(...arguments);this.tree=null;this.document=null;this.resolved=null;this.warned=new Set;this.elements=new Map;this.actionHandlers=new WeakMap;this.bindingHandlers=new WeakMap;this.assignedProps=new WeakMap;this.initialProps=new WeakMap}static{this.styles=[LyraElement.styles,styles]}willUpdate(changed){if(!this.hasUpdated||changed.has("tree")||changed.has("document")||changed.has("state")||changed.has("registry")){if(this.document!==null&&this.document.version!=="1"){this.resolved=null;this.emit("lr-render-error",{error:new Error("lr-widget-renderer: unsupported document version")});return}const registry=this.registry??getDefaultWidgetTypeRegistry();const root=this.document?.root??this.tree;const next=resolveTree(root,{registry,warned:this.warned,state:this.state??this.document?.state});if(root!=null&&next===null){this.emit("lr-render-error",{error:new Error("lr-widget-renderer: tree resolved to nothing renderable")})}this.resolved=next}}updated(){this.pruneElementCache()}collectMappedKeys(node,out){if(!node||node.kind==="text")return;if(node.kind==="mapped")out.add(node.identityKey);for(const child of node.children)this.collectMappedKeys(child,out)}pruneElementCache(){const live=new Set;this.collectMappedKeys(this.resolved,live);for(const[key,el]of this.elements){if(live.has(key))continue;const state2=this.actionHandlers.get(el);if(state2)el.removeEventListener(state2.event,state2.handler);for(const binding of this.bindingHandlers.get(el)??[]){el.removeEventListener(binding.event,binding.handler)}this.elements.delete(key)}}builtinStyle(node){const gap=typeof node.props["gap"]==="string"?GAP_TOKEN[node.props["gap"]]:void 0;const align=typeof node.props["align"]==="string"?node.props["align"]:void 0;const justifyRaw=typeof node.props["justify"]==="string"?node.props["justify"]:void 0;const justify=justifyRaw?JUSTIFY_VALUE[justifyRaw]:void 0;return{display:"flex","flex-direction":node.kind==="builtin-row"?"row":"column","flex-wrap":node.kind==="builtin-row"?"wrap":"nowrap",...gap?{gap}:{},...align?{"align-items":align}:{},...justify?{"justify-content":justify}:{}}}syncActionHandler(el,node){const existing=this.actionHandlers.get(el);if(existing){el.removeEventListener(existing.event,existing.handler);this.actionHandlers.delete(el)}if(node.actionEvent){const handler=e=>{e.stopPropagation();if(node.actionId!==void 0){this.emit("lr-widget-action",{actionId:node.actionId,payload:node.payload})}};el.addEventListener(node.actionEvent,handler);this.actionHandlers.set(el,{event:node.actionEvent,handler})}}syncBindingHandlers(el,node){for(const existing of this.bindingHandlers.get(el)??[]){el.removeEventListener(existing.event,existing.handler)}const states=[];for(const binding of node.bindings){if(!binding.event)continue;const handler=event=>{event.stopPropagation();const detail=event.detail;const detailValue=detail&&typeof detail==="object"&&"value"in detail?detail.value:void 0;const value=detailValue??el[binding.prop];this.emit("lr-widget-state-change",{path:binding.path,value,nodeId:node.key,prop:binding.prop})};el.addEventListener(binding.event,handler);states.push({event:binding.event,handler})}this.bindingHandlers.set(el,states)}getOrCreateElement(node){if(!node.tag)return null;const existing=this.elements.get(node.identityKey);const el=existing&&existing.tagName.toLowerCase()===node.tag?existing:document.createElement(node.tag);if(el!==existing)this.elements.set(node.identityKey,el);const previousKeys=this.assignedProps.get(el)??new Set;const initialValues=this.initialProps.get(el)??new Map;const nextKeys=new Set(Object.keys(node.props));for(const key of previousKeys){if(!nextKeys.has(key)){el[key]=initialValues.get(key)}}for(const[k,v]of Object.entries(node.props)){if(!initialValues.has(k)){initialValues.set(k,el[k])}el[k]=v}this.assignedProps.set(el,nextKeys);this.initialProps.set(el,initialValues);const slotValue=node.slot??"";if(el.getAttribute("slot")!==slotValue){if(slotValue)el.setAttribute("slot",slotValue);else el.removeAttribute("slot")}this.syncActionHandler(el,node);this.syncBindingHandlers(el,node);render(html`${repeat(node.children,child=>this.renderIdentity(child),child=>this.renderChildValue(child))}`,el,{host:this});return el}renderIdentity(node){return node.kind==="text"?`text:${node.key}`:node.identityKey}renderChildValue(node){if(node.kind==="text"){return html`<span class="widget-text" slot=${node.slot??nothing}>${node.text}</span>`}if(node.kind==="mapped"){return this.getOrCreateElement(node)??nothing}const part=node.kind==="builtin-row"?"row":node.kind==="builtin-col"?"col":"text";return html`<div part=${part} style=${styleMap(this.builtinStyle(node))} slot=${node.slot??nothing}>
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,render}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{styles}from"./widget-renderer.styles.js";import{resolveTree}from"./resolve.js";import{getDefaultWidgetTypeRegistry}from"./registry.js";const GAP_TOKEN={s:"var(--lr-space-s)",m:"var(--lr-space-m)",l:"var(--lr-space-l)"};const JUSTIFY_VALUE={start:"flex-start",center:"center",end:"flex-end",between:"space-between"};const ALIGN_VALUE={start:"flex-start","flex-start":"flex-start",center:"center",end:"flex-end","flex-end":"flex-end",stretch:"stretch",baseline:"baseline","self-start":"self-start","self-end":"self-end","first baseline":"first baseline","last baseline":"last baseline",normal:"normal"};function sanitizeAlignValue(value){return ALIGN_VALUE[value.trim().toLowerCase()]}class LyraWidgetRenderer extends LyraElement{constructor(){super(...arguments);this.tree=null;this.document=null;this.resolved=null;this.warned=new Set;this.elements=new Map;this.actionHandlers=new WeakMap;this.bindingHandlers=new WeakMap;this.assignedProps=new WeakMap;this.initialProps=new WeakMap}static{this.styles=[LyraElement.styles,styles]}willUpdate(changed){if(!this.hasUpdated||changed.has("tree")||changed.has("document")||changed.has("state")||changed.has("registry")){if(this.document!==null&&this.document.version!=="1"){this.resolved=null;this.emit("lr-render-error",{error:new Error("lr-widget-renderer: unsupported document version")});return}const registry=this.registry??getDefaultWidgetTypeRegistry();const root=this.document?.root??this.tree;const next=resolveTree(root,{registry,warned:this.warned,state:this.state??this.document?.state});if(root!=null&&next===null){this.emit("lr-render-error",{error:new Error("lr-widget-renderer: tree resolved to nothing renderable")})}this.resolved=next}}updated(){this.pruneElementCache()}collectMappedKeys(node,out){if(!node||node.kind==="text")return;if(node.kind==="mapped")out.add(node.identityKey);for(const child of node.children)this.collectMappedKeys(child,out)}pruneElementCache(){const live=new Set;this.collectMappedKeys(this.resolved,live);for(const[key,el]of this.elements){if(live.has(key))continue;const state2=this.actionHandlers.get(el);if(state2)el.removeEventListener(state2.event,state2.handler);for(const binding of this.bindingHandlers.get(el)??[]){el.removeEventListener(binding.event,binding.handler)}this.elements.delete(key)}}builtinStyle(node){const gap=typeof node.props["gap"]==="string"?GAP_TOKEN[node.props["gap"]]:void 0;const align=typeof node.props["align"]==="string"?sanitizeAlignValue(node.props["align"]):void 0;const justifyRaw=typeof node.props["justify"]==="string"?node.props["justify"]:void 0;const justify=justifyRaw?JUSTIFY_VALUE[justifyRaw]:void 0;return{display:"flex","flex-direction":node.kind==="builtin-row"?"row":"column","flex-wrap":node.kind==="builtin-row"?"wrap":"nowrap",...gap?{gap}:{},...align?{"align-items":align}:{},...justify?{"justify-content":justify}:{}}}syncActionHandler(el,node){const existing=this.actionHandlers.get(el);if(existing){el.removeEventListener(existing.event,existing.handler);this.actionHandlers.delete(el)}if(node.actionEvent){const handler=e=>{e.stopPropagation();if(node.actionId!==void 0){this.emit("lr-widget-action",{actionId:node.actionId,payload:node.payload})}};el.addEventListener(node.actionEvent,handler);this.actionHandlers.set(el,{event:node.actionEvent,handler})}}syncBindingHandlers(el,node){for(const existing of this.bindingHandlers.get(el)??[]){el.removeEventListener(existing.event,existing.handler)}const states=[];for(const binding of node.bindings){if(!binding.event)continue;const handler=event=>{event.stopPropagation();const detail=event.detail;const detailValue=detail&&typeof detail==="object"&&"value"in detail?detail.value:void 0;const value=detailValue??el[binding.prop];this.emit("lr-widget-state-change",{path:binding.path,value,nodeId:node.key,prop:binding.prop})};el.addEventListener(binding.event,handler);states.push({event:binding.event,handler})}this.bindingHandlers.set(el,states)}getOrCreateElement(node){if(!node.tag)return null;const existing=this.elements.get(node.identityKey);const el=existing&&existing.tagName.toLowerCase()===node.tag?existing:document.createElement(node.tag);if(el!==existing)this.elements.set(node.identityKey,el);const previousKeys=this.assignedProps.get(el)??new Set;const initialValues=this.initialProps.get(el)??new Map;const nextKeys=new Set(Object.keys(node.props));for(const key of previousKeys){if(!nextKeys.has(key)){el[key]=initialValues.get(key)}}for(const[k,v]of Object.entries(node.props)){if(!initialValues.has(k)){initialValues.set(k,el[k])}el[k]=v}this.assignedProps.set(el,nextKeys);this.initialProps.set(el,initialValues);const slotValue=node.slot??"";if(el.getAttribute("slot")!==slotValue){if(slotValue)el.setAttribute("slot",slotValue);else el.removeAttribute("slot")}this.syncActionHandler(el,node);this.syncBindingHandlers(el,node);render(html`${repeat(node.children,child=>this.renderIdentity(child),child=>this.renderChildValue(child))}`,el,{host:this});return el}renderIdentity(node){return node.kind==="text"?`text:${node.key}`:node.identityKey}renderChildValue(node){if(node.kind==="text"){return html`<span class="widget-text" slot=${node.slot??nothing}>${node.text}</span>`}if(node.kind==="mapped"){return this.getOrCreateElement(node)??nothing}const part=node.kind==="builtin-row"?"row":node.kind==="builtin-col"?"col":"text";return html`<div part=${part} style=${styleMap(this.builtinStyle(node))} slot=${node.slot??nothing}>
2
2
  ${node.kind==="builtin-text"?node.props["value"]??nothing:nothing}
3
3
  ${repeat(node.children,child=>this.renderIdentity(child),child=>this.renderChildValue(child))}
4
4
  </div>`}render(){return html`<div part="base">${this.resolved?this.renderChildValue(this.resolved):nothing}</div>`}}__decorate([property({attribute:false})],LyraWidgetRenderer.prototype,"tree",void 0);__decorate([property({attribute:false})],LyraWidgetRenderer.prototype,"document",void 0);__decorate([property({attribute:false})],LyraWidgetRenderer.prototype,"state",void 0);__decorate([property({attribute:false})],LyraWidgetRenderer.prototype,"registry",void 0);__decorate([state()],LyraWidgetRenderer.prototype,"resolved",void 0);export{LyraWidgetRenderer};
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{resolveCssLength}from"../../../internal/css-length.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteDuration,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{srOnly}from"../../../internal/a11y.js";import{aggregateValues,columnId,columnValue,filterRows,pathValue,rowsAsDelimited,searchRows,sortRows}from"./data-grid-processing.js";import{styles}from"./data-grid.styles.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_next,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationFirstPage,LYRA_DEFAULT_paginationJumpToPage,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_paginationLastPage,LYRA_DEFAULT_previous,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_tableFilterLabel}from"../../../internal/default-strings.generated.js";export*from"./data-grid-types.js";const selectableConverter={fromAttribute(value){if(value===null)return"none";if(value===""||value==="multiple")return"multiple";return value==="single"||value==="none"?value:"none"},toAttribute(value){if(value==="none")return null;return value===""||value==="multiple"?"":value}};const INTERACTIVE_SELECTOR='button, a[href], input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"]), [role="button"], [role="checkbox"], [role="radio"]';const VIRTUALIZATION_THRESHOLD=80;const VIRTUAL_OVERSCAN=5;function isKey(value){return typeof value==="string"||typeof value==="number"&&Number.isFinite(value)}function keysEqual(left,right){return typeof left===typeof right&&left===right}function arrayHasKey(keys,key){return keys.some(candidate=>keysEqual(candidate,key))}function isElementValue(value){if(value===null||typeof value!=="object")return false;const candidate=value;return candidate.nodeType===1&&typeof candidate.closest==="function"}function valueControl(value){if(!isElementValue(value)||typeof value.value!=="string")return null;return value}function checkableControl(value){if(!isElementValue(value)||typeof value.checked!=="boolean")return null;return value}function dateText(value){try{const timestamp=Date.prototype.getTime.call(value);return Number.isFinite(timestamp)?Date.prototype.toISOString.call(value):""}catch{return void 0}}function humanizeIdentifier(value,locale){const intlLocale=resolveIntlLocale(locale);return value.replaceAll(/[._-]+/gu," ").replaceAll(/([a-z\d])([A-Z])/gu,"$1 $2").replace(/^./u,first=>first.toLocaleUpperCase(intlLocale))}function safeText(value){if(value===null||value===void 0)return"";if(typeof value==="object"){const serializedDate=dateText(value);if(serializedDate!==void 0)return serializedDate}if(Array.isArray(value))return value.map(safeText).join(", ");if(typeof value==="object"){try{return JSON.stringify(value,(_key,nested)=>typeof nested==="bigint"?nested.toString():nested)??""}catch{return""}}return String(value)}function normalizedGroupBy(value){if(Array.isArray(value))return value.map(entry=>entry.trim()).filter(Boolean);return value?.split(/[\s,]+/u).map(entry=>entry.trim()).filter(Boolean)??[]}class LyraDataGrid extends LyraElement{constructor(){super(...arguments);this.appearance="outlined";this.childRows=null;this.columnOrder=[];this.columns=[];this.data=[];this.dataSource=null;this.expandedKeys=[];this.filterDebounce=250;this.filterFromLeafRows=false;this.filters=[];this.groupBy=null;this.label=null;this.loading=false;this.maxMultiSort=0;this.page=0;this.pageSize=20;this.pageSizeOptions=[10,20,50,100];this.paginate=false;this.pinnable=false;this.reorderable=false;this.resizable=false;this.rowClass=null;this.rowDetail=null;this.rowKey=null;this.searchFn=null;this.searchTerm="";this.selectable="none";this.selectableRows=null;this.selectedKeys=[];this.server=false;this.size="m";this.sort=[];this.sortDescFirst=false;this.striped=false;this.total=-1;this.withColumnMenu=false;this.withColumnsMenu=false;this.withoutSortRemoval=false;this.withSearch=false;this.columnWidths=new Map;this.columnVisibility=new Map;this.columnPinning=new Map;this.activeFilterColumn=null;this.columnsMenuOpen=false;this.activeColumnMenu=null;this.liveText="";this.bodyScrollTop=0;this.viewportHeight=0;this.focusedRow=-1;this.focusedColumn=0;this.dragGhost="";this.requestGeneration=0;this.ownsLoadingState=false;this.lastSelectedIndex=-1;this.isMounting=true}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,menuLabel:LYRA_DEFAULT_menuLabel,next:LYRA_DEFAULT_next,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,paginationFirstPage:LYRA_DEFAULT_paginationFirstPage,paginationJumpToPage:LYRA_DEFAULT_paginationJumpToPage,paginationLabel:LYRA_DEFAULT_paginationLabel,paginationLastPage:LYRA_DEFAULT_paginationLastPage,previous:LYRA_DEFAULT_previous,resizeColumn:LYRA_DEFAULT_resizeColumn,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showAllColumns:LYRA_DEFAULT_showAllColumns,tableFilterLabel:LYRA_DEFAULT_tableFilterLabel}}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}get filteredCount(){return this.processedClientRows.length}get pageCount(){const size=this.safePageSize;if(size===0)return 0;if(!this.usesServerData&&normalizedGroupBy(this.groupBy).length>0){const groups=this.topLevelGroupBuckets(this.processedClientRows).length;return groups<=0?0:Math.ceil(groups/size)}const count=this.safeTotal>=0?this.safeTotal:this.filteredCount;return count<=0?0:Math.ceil(count/size)}get selectedRows(){return this.allSourceRows.filter((row,index)=>arrayHasKey(this.selectedKeys,this.keyForRow(row,index)))}set selectedRows(next){const source=this.allSourceRows;const candidates=Array.isArray(next)?next:[];const rows=candidates.filter((row,index)=>source.includes(row)&&candidates.indexOf(row)===index);const limited=this.selectionMode==="single"?rows.slice(0,1):rows;this.selectedKeys=limited.map(row=>this.keyForRow(row,source.indexOf(row)))}connectedCallback(){super.connectedCallback();this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});if(this.dataSource)this.scheduleServerRequest(false)}disconnectedCallback(){this.requestGeneration+=1;this.requestController?.abort();this.requestController=void 0;if(this.ownsLoadingState)this.loading=false;this.ownsLoadingState=false;this.cancelRequestTimer();this.resizeSession=void 0;this.activeFilterColumn=null;this.activeColumnMenu=null;this.columnsMenuOpen=false;this.dragGhost="";this.sink?.release();this.sink=void 0;super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed);if(this.hasUpdated&&changed.has("loading")&&this.loading){this.announce(this.localize("loading"))}const sourceReplaced=changed.has("dataSource")&&changed.get("dataSource")!==void 0;const serverDisabled=changed.has("server")&&!this.usesServerData;if((sourceReplaced||serverDisabled)&&(this.requestController||this.requestTimer!==void 0)){this.requestGeneration+=1;this.requestController?.abort();this.requestController=void 0;this.cancelRequestTimer();if(this.ownsLoadingState)this.loading=false;this.ownsLoadingState=false}if(changed.has("columns"))this.handleColumnsChange();if(!this.usesServerData&&(changed.has("data")||changed.has("rowKey")||changed.has("childRows")||changed.has("server")||changed.has("dataSource"))){const validKeys=this.allSourceRows.map((row,index)=>this.keyForRow(row,index));const selectedKeys=this.selectedKeys.filter(key=>validKeys.some(candidate=>keysEqual(candidate,key)));if(selectedKeys.length!==this.selectedKeys.length||selectedKeys.some((key,index)=>!keysEqual(key,this.selectedKeys[index]))){this.selectedKeys=selectedKeys}this.lastSelectedIndex=-1}if(this.paginate&&(changed.has("data")||changed.has("filters")||changed.has("searchTerm")||changed.has("groupBy")||changed.has("pageSize")||changed.has("total")||changed.has("server")||changed.has("dataSource"))){const lastPage=Math.max(0,this.pageCount-1);this.page=finiteInteger(this.page,0,0,lastPage)}if(changed.has("data")||changed.has("columns")||changed.has("filters")||changed.has("searchTerm")||changed.has("sort")||changed.has("expandedKeys")||changed.has("groupBy")||changed.has("page")||changed.has("pageSize")||changed.has("paginate")||changed.has("childRows")){this.focusedRow=finiteInteger(this.focusedRow,-1,-1,Math.max(-1,this.displayItems.length-1));this.focusedColumn=finiteInteger(this.focusedColumn,0,0,Math.max(0,this.visibleColumns.length-1))}}updated(changed){if(changed.has("dataSource")&&this.dataSource)this.scheduleServerRequest(false);const requestRelevant=changed.has("sort")||changed.has("filters")||changed.has("searchTerm")||changed.has("page")||changed.has("pageSize")||changed.has("server");if(requestRelevant&&(this.server||this.dataSource)){const delayed=changed.has("filters")||changed.has("searchTerm");this.scheduleServerRequest(delayed)}this.isMounting=false}announce(text){this.sink?.announce(text);this.liveText=text}get usesServerData(){return this.server||this.dataSource!==null}get safePage(){return finiteCount(this.page)}get safePageSize(){return finiteCount(this.pageSize)}get safeTotal(){return this.total===-1?-1:finiteCount(this.total)}get allSourceRows(){const result=[];const visit=rows=>{for(const row of rows){result.push(row);visit(this.childrenFor(row))}};visit(this.data);return result}get orderedColumns(){const entries=this.columns.map((column,naturalIndex)=>({column,id:columnId(column,naturalIndex),naturalIndex}));if(this.columnOrder.length===0)return entries;const rank=new Map(this.columnOrder.map((id,index)=>[id,index]));return entries.sort((left,right)=>{const leftRank=rank.get(left.id);const rightRank=rank.get(right.id);if(leftRank===void 0&&rightRank===void 0)return left.naturalIndex-right.naturalIndex;if(leftRank===void 0)return 1;if(rightRank===void 0)return-1;return leftRank-rightRank})}get visibleColumns(){const entries=this.orderedColumns.filter(({column,id})=>this.columnVisibility.get(id)??column.hidden!==true);const rank=(side,id)=>{const ordered=this.orderedColumns.filter(entry=>this.getColumnPin(entry.id)===side);return ordered.findIndex(entry=>entry.id===id)};return entries.sort((left,right)=>{const leftPin=this.getColumnPin(left.id);const rightPin=this.getColumnPin(right.id);if(leftPin===rightPin)return 0;if(leftPin==="left")return-1;if(rightPin==="left")return 1;if(leftPin==="right")return 1;if(rightPin==="right")return-1;return rank("left",left.id)-rank("right",right.id)})}get processedClientRows(){if(this.usesServerData)return[...this.data];if(this.childRows){const included=this.data.filter(row=>this.rowMatches(row)||this.filterFromLeafRows&&this.hasMatchingDescendant(row));return sortRows(included,this.columns,this.sort,this.effectiveLocale)}const filtered=filterRows(this.data,this.columns,this.filters,this.effectiveLocale);const searched=searchRows(filtered,this.columns,this.searchTerm,this.effectiveLocale,this.searchFn);return sortRows(searched,this.columns,this.sort,this.effectiveLocale)}childrenFor(row){const children=typeof this.childRows==="function"?this.childRows(row):this.childRows?pathValue(row,this.childRows):void 0;return Array.isArray(children)?children:[]}keyForRow(row,index){const candidate=this.rowKey?pathValue(row,this.rowKey):void 0;return isKey(candidate)?candidate:index}renderedColumnElements(columnId2,role){const prefix=role?`[role="${role}"]`:"";const ownerCss=this.ownerDocument.defaultView?.CSS;const escape=ownerCss?.escape;if(typeof escape==="function"){try{const matches=[...this.renderRoot.querySelectorAll(`${prefix}[data-column-id="${escape.call(ownerCss,columnId2)}"]`)];if(matches.length>0)return matches}catch{}}return[...this.renderRoot.querySelectorAll(`${prefix}[data-column-id]`)].filter(element=>element.getAttribute("data-column-id")===columnId2)}computedToken(name){if(!this.isConnected)return"";const owner=this.ownerDocument.defaultView;if(!owner||typeof owner.getComputedStyle!=="function")return"";try{return owner.getComputedStyle(this).getPropertyValue(name).trim()}catch{return""}}autoSizeColumn(columnId2){const cells=this.renderedColumnElements(columnId2);if(cells.length===0)return;let width=0;for(const cell of cells)width=Math.max(width,cell.scrollWidth);const entry=this.orderedColumns.find(({id})=>id===columnId2);if(!entry)return;const minimum=finiteRange(entry.column.minWidth??0,0,0);const maximum=finiteRange(entry.column.maxWidth??Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,minimum);this.setColumnWidth(columnId2,finiteRange(width,minimum,minimum,maximum),false)}autoSizeColumns(){for(const{id}of this.visibleColumns)this.autoSizeColumn(id)}collapseAllRows(){this.expandedKeys=[]}collapseRow(key){this.expandedKeys=this.expandedKeys.filter(candidate=>!keysEqual(candidate,key))}copySelectedRows(options={}){const rowsToCopy=this.selectedRows.length>0?this.selectedRows:this.getProcessedRows();const format=options.format??"tsv";const text=this.delimitedRows(rowsToCopy,{...options,delimiter:format==="csv"?",":" "});this.writeClipboard(text);if(!this.isMounting)this.announce(this.localize("copied"));return rowsToCopy.length}expandAllRows(){const keys=[];this.allSourceRows.forEach((row,index)=>{if(this.childrenFor(row).length>0||this.rowDetail)keys.push(this.keyForRow(row,index))});for(const group of this.groupItems(this.processedClientRows))keys.push(group.key);this.expandedKeys=keys}expandRow(key){if(!arrayHasKey(this.expandedKeys,key))this.expandedKeys=[...this.expandedKeys,key]}exportDataAsCsv(options={}){const text=this.getDataAsCsv(options);const ownerDocument=this.ownerDocument;const owner=ownerDocument.defaultView;if(!owner||typeof owner.URL.createObjectURL!=="function")return;const url=owner.URL.createObjectURL(new owner.Blob([text],{type:"text/csv;charset=utf-8"}));try{const anchor=ownerDocument.createElement("a");anchor.href=url;const legacyFileName=options.filename;anchor.download=options.fileName||legacyFileName||"data.csv";anchor.hidden=true;ownerDocument.body?.append(anchor);anchor.click();anchor.remove()}finally{owner.URL.revokeObjectURL(url)}}focus(options={}){const selector=this.focusedRow<0?`[role="columnheader"][data-column-position="${this.focusedColumn}"]`:`[role="gridcell"][data-row-position="${this.focusedRow}"][data-column-position="${this.focusedColumn}"]`;this.renderRoot.querySelector(selector)?.focus(options)}getColumnFacets(columnId2){const uniqueValues=new Map;if(this.usesServerData)return{uniqueValues};const entry=this.orderedColumns.find(({id})=>id===columnId2);if(!entry)return{uniqueValues};const otherFilters=this.filters.filter(filter=>filter.id!==columnId2);const rows=searchRows(filterRows(this.data,this.columns,otherFilters,this.effectiveLocale),this.columns,this.searchTerm,this.effectiveLocale,this.searchFn);let minimum=Number.POSITIVE_INFINITY;let maximum=Number.NEGATIVE_INFINITY;for(const row of rows){const value=columnValue(entry.column,row);uniqueValues.set(value,(uniqueValues.get(value)??0)+1);const number=typeof value==="number"?value:Number(value);if(Number.isFinite(number)){minimum=Math.min(minimum,number);maximum=Math.max(maximum,number)}}return Number.isFinite(minimum)&&Number.isFinite(maximum)?{uniqueValues,minMax:[minimum,maximum]}:{uniqueValues}}getColumnPin(columnId2){if(this.columnPinning.has(columnId2))return this.columnPinning.get(columnId2)??false;return this.orderedColumns.find(({id})=>id===columnId2)?.column.pinned??false}getDataAsCsv(options={}){return this.delimitedRows(this.getProcessedRows(),options)}getProcessedRows(){return[...this.processedClientRows]}getVisibleRows(){const rows=this.processedClientRows;if(!this.paginate||this.usesServerData)return[...rows];const size=this.safePageSize;if(size===0)return[];const start=this.safePage*size;if(normalizedGroupBy(this.groupBy).length>0){return this.topLevelGroupBuckets(rows).slice(start,start+size).flatMap(bucket=>bucket.rows)}return rows.slice(start,start+size)}getState(){return{order:[...this.columnOrder],widths:Object.fromEntries(this.columnWidths),visibility:Object.fromEntries(this.columnVisibility),pinning:Object.fromEntries(this.columnPinning),sort:this.sort.map(item=>({...item})),filters:this.filters.map(item=>({...item})),search:this.searchTerm,selectedKeys:[...this.selectedKeys],expandedKeys:[...this.expandedKeys],page:this.safePage,pageSize:this.safePageSize}}handleColumnsChange(){const valid=new Set(this.columns.map((column,index)=>columnId(column,index)));const natural=[...valid];const order=this.columnOrder.filter(id=>valid.has(id));for(const id of natural)if(!order.includes(id))order.push(id);if(this.columnOrder.length>0&&order.join("\0")!==this.columnOrder.join("\0")){this.columnOrder=order}const widths=[...this.columnWidths].filter(([id])=>valid.has(id));const visibility=[...this.columnVisibility].filter(([id])=>valid.has(id));const pinning=[...this.columnPinning].filter(([id])=>valid.has(id));if(widths.length!==this.columnWidths.size)this.columnWidths=new Map(widths);if(visibility.length!==this.columnVisibility.size)this.columnVisibility=new Map(visibility);if(pinning.length!==this.columnPinning.size)this.columnPinning=new Map(pinning)}handlePageChange(){this.applyPageChange(this.safePage)}applyPageChange(value){let requested;if(typeof value==="number")requested=value;else requested=Number(valueControl(value?.currentTarget)?.value??this.safePage);const last=Math.max(0,this.pageCount-1);const next=finiteInteger(requested,this.safePage,0,last);this.page=next;this.emit("lr-page-change",{page:next,pageSize:this.safePageSize})}handleSearchTermChange(){this.applySearchTermChange(this.searchTerm)}applySearchTermChange(value){const next=typeof value==="string"?value:valueControl(value?.currentTarget)?.value??this.searchTerm;this.searchTerm=next;if(this.page!==0)this.page=0}pinColumn(columnId2,side){if(!this.orderedColumns.some(({id})=>id===columnId2))return;const next=new Map(this.columnPinning);next.set(columnId2,side);this.columnPinning=next}async reload(){const owner=this.ownerDocument.defaultView;if(!this.isConnected||!owner||!this.usesServerData)return;this.cancelRequestTimer();await this.loadServerData(owner)}resetColumns(){this.columnOrder=[];this.columnWidths=new Map;this.columnVisibility=new Map;this.columnPinning=new Map}resetState(){this.resetColumns();this.sort=[];this.filters=[];this.searchTerm="";this.expandedKeys=[]}scrollToIndex(index,options={}){const rows=this.getVisibleRows();if(rows.length===0)return;const target=finiteInteger(index,0,0,rows.length-1);const rendered=this.renderRoot?.querySelector(`[part~="row"][data-visible-index="${target}"]`);if(rendered){rendered.scrollIntoView({block:options.align??"nearest"});return}const body=this.bodyElement;if(!body)return;const rowHeight=this.resolvedRowHeight;let top=target*rowHeight;if(options.align==="center")top-=(body.clientHeight-rowHeight)/2;else if(options.align==="end")top-=body.clientHeight-rowHeight;body.scrollTo({top:Math.max(0,top)})}setState(state2){const known=new Set(this.columns.map((column,index)=>columnId(column,index)));if(state2.order)this.columnOrder=state2.order.filter(id=>known.has(id));if(state2.widths)this.columnWidths=this.validColumnMap(state2.widths,known,width=>finiteRange(width,0,0));if(state2.visibility)this.columnVisibility=this.validColumnMap(state2.visibility,known,Boolean);if(state2.pinning)this.columnPinning=this.validColumnMap(state2.pinning,known,side=>side==="left"||side==="right"?side:false);if(state2.sort)this.sort=state2.sort.filter(item=>known.has(item.id)).map(item=>({id:item.id,desc:Boolean(item.desc)}));if(state2.filters)this.filters=state2.filters.filter(item=>known.has(item.id)).map(item=>({...item}));if(state2.search!==void 0)this.searchTerm=state2.search;if(state2.selectedKeys)this.selectedKeys=state2.selectedKeys.filter(isKey);if(state2.expandedKeys)this.expandedKeys=state2.expandedKeys.filter(isKey);if(state2.page!==void 0)this.page=finiteCount(state2.page);if(state2.pageSize!==void 0)this.pageSize=finiteCount(state2.pageSize)}sizeColumnsToFit(){const body=this.bodyElement;if(!body||this.visibleColumns.length===0)return;const selectionWidth=this.selectionEnabled?resolveCssLength(this.computedToken("--lr-icon-button-size"),this)??0:0;const available=Math.max(0,body.clientWidth-selectionWidth);const flexible=this.visibleColumns.filter(({column})=>column.flex!==0);if(flexible.length===0)return;const totalFlex=flexible.reduce((sum,{column})=>sum+finiteRange(column.flex??1,1,0),0)||flexible.length;const next=new Map(this.columnWidths);for(const{column,id}of flexible){const share=available*(finiteRange(column.flex??1,1,0)/totalFlex);const minimum=finiteRange(column.minWidth??0,0,0);const maximum=finiteRange(column.maxWidth??Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,minimum);next.set(id,finiteRange(share,minimum,minimum,maximum))}this.columnWidths=next}toggleColumn(columnId2,visible){if(!this.orderedColumns.some(({id})=>id===columnId2))return;const next=new Map(this.columnVisibility);next.set(columnId2,visible);this.columnVisibility=next;this.focusedColumn=finiteInteger(this.focusedColumn,0,0,Math.max(0,this.visibleColumns.length-1))}validColumnMap(record,known,convert){const result=new Map;for(const[id,value]of Object.entries(record))if(known.has(id))result.set(id,convert(value));return result}delimitedRows(rows,options){const active=this.visibleColumns.map(({column,id})=>({...column,id,value:row=>{const raw=columnValue(column,row);const formatted=column.formatter?.(raw,row);return typeof formatted==="string"?formatted:raw},hidden:false}));return rowsAsDelimited(rows,active,options)}writeClipboard(text){const ownerDocument=this.ownerDocument;const owner=ownerDocument.defaultView;if(!owner)return;try{const clipboard=owner.navigator.clipboard;if(typeof clipboard?.writeText==="function"){void clipboard.writeText(text).catch(()=>void 0);return}}catch{}if(!ownerDocument.body)return;const textarea=ownerDocument.createElement("textarea");textarea.value=text;textarea.style.position="fixed";textarea.style.opacity="0";ownerDocument.body.append(textarea);try{textarea.select();ownerDocument.execCommand?.("copy")}finally{textarea.remove()}}setColumnWidth(columnIdValue,width,emit,finished=true){const entry=this.orderedColumns.find(({id})=>id===columnIdValue);if(!entry)return;const minimum=finiteRange(entry.column.minWidth??0,0,0);const maximum=finiteRange(entry.column.maxWidth??Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,minimum);const safeWidth=finiteRange(width,minimum,minimum,maximum);const next=new Map(this.columnWidths);next.set(columnIdValue,safeWidth);this.columnWidths=next;if(emit)this.emit("lr-column-resize",{columnId:columnIdValue,width:safeWidth,finished})}cancelRequestTimer(){const timer=this.requestTimer;this.requestTimer=void 0;if(timer)timer.owner.clearTimeout(timer.handle)}scheduleServerRequest(delayed){const owner=this.ownerDocument.defaultView;if(!this.isConnected||!owner||!this.usesServerData)return;this.cancelRequestTimer();const delay=delayed?finiteDuration(this.filterDebounce,250):0;let handle=0;handle=owner.setTimeout(()=>{if(this.requestTimer?.owner!==owner||this.requestTimer.handle!==handle||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.requestTimer=void 0;void this.loadServerData(owner)},delay);this.requestTimer={owner,handle}}async loadServerData(owner){if(!this.isConnected||this.ownerDocument.defaultView!==owner||!this.usesServerData)return;this.requestController?.abort();const AbortControllerCtor=owner.AbortController;this.requestController=typeof AbortControllerCtor==="function"?new AbortControllerCtor:void 0;const generation=++this.requestGeneration;const request={sort:this.sort.map(item=>({...item})),filters:this.filters.map(item=>({...item})),search:this.searchTerm,page:this.safePage,pageSize:this.safePageSize,signal:this.requestController?.signal};this.emit("request",request);this.emit("lr-data-request",request);if(!this.dataSource)return;this.ownsLoadingState=true;this.loading=true;try{const response=await this.dataSource(request);if(generation!==this.requestGeneration||request.signal?.aborted||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.data=Array.isArray(response.rows)?response.rows:[];this.total=finiteCount(response.total);this.loading=false;this.ownsLoadingState=false}catch(error){if(generation!==this.requestGeneration||request.signal?.aborted||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.loading=false;this.ownsLoadingState=false;this.emit("lr-data-error",{error,request})}}get selectionMode(){if(this.selectable===""||this.selectable==="multiple")return"multiple";return this.selectable}get selectionEnabled(){return this.selectionMode!=="none"}rowIsSelectable(row){return this.selectionEnabled&&(this.selectableRows?.(row)??true)}rowMatches(row){return filterRows([row],this.columns,this.filters,this.effectiveLocale).length>0&&searchRows([row],this.columns,this.searchTerm,this.effectiveLocale,this.searchFn).length>0}processedChildrenFor(row){const children=this.childrenFor(row);if(children.length===0||this.usesServerData)return children;const included=children.filter(child=>{if(this.rowMatches(child))return true;return this.filterFromLeafRows&&this.hasMatchingDescendant(child)});return sortRows(included,this.columns,this.sort,this.effectiveLocale)}hasMatchingDescendant(row){return this.childrenFor(row).some(child=>this.rowMatches(child)||this.hasMatchingDescendant(child))}get pageRows(){return this.getVisibleRows()}get currentPageSelectableRows(){const result=[];const visited=new Set;const visit=pageRows=>{for(const row of pageRows){if(visited.has(row))continue;visited.add(row);const sourceIndex=this.allSourceRows.indexOf(row);const key=this.keyForRow(row,sourceIndex<0?result.length:sourceIndex);if(this.rowIsSelectable(row))result.push({row,key});visit(this.childrenFor(row))}};visit(this.pageRows);return result}groupKey(parent,id,value){return`group:${parent}:${id}:${typeof value}:${safeText(value)}`}topLevelGroupBuckets(rows){const field=normalizedGroupBy(this.groupBy)[0];if(!field)return[];const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return[];const buckets=new Map;for(const row of rows){const value=columnValue(entry.column,row);const bucket=buckets.get(value)??[];bucket.push(row);buckets.set(value,bucket)}return[...buckets].map(([value,bucketRows])=>({value,rows:bucketRows}))}groupItems(rows){const fields=normalizedGroupBy(this.groupBy);if(fields.length===0||this.usesServerData)return[];const result=[];const visit=(groupRows,depth,parent)=>{const field=fields[depth];if(!field)return;const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return;const buckets=new Map;for(const row of groupRows){const value=columnValue(entry.column,row);const bucket=buckets.get(value)??[];bucket.push(row);buckets.set(value,bucket)}for(const[value,bucket]of buckets){const key=this.groupKey(parent,entry.id,value);result.push({kind:"group",key,value,columnId:entry.id,rows:bucket,depth});if(depth+1<fields.length)visit(bucket,depth+1,key)}};visit(rows,0,"root");return result}get displayItems(){const groups=normalizedGroupBy(this.groupBy);if(groups.length>0&&!this.usesServerData)return this.groupedDisplayItems(this.pageRows,groups,0,"root");const result=[];const sourceRows=this.allSourceRows;const visit=(rows,depth)=>{for(const row of rows){const sourceIndex=sourceRows.indexOf(row);const safeIndex=sourceIndex<0?result.length:sourceIndex;const key=this.keyForRow(row,safeIndex);result.push({kind:"row",row,key,depth,sourceIndex:safeIndex});if(arrayHasKey(this.expandedKeys,key))visit(this.processedChildrenFor(row),depth+1)}};visit(this.pageRows,0);return result}groupedDisplayItems(rows,fields,depth,parent){const field=fields[depth];if(!field)return[];const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return rows.map((row,index)=>({kind:"row",row,key:this.keyForRow(row,index),depth,sourceIndex:index}));const buckets=new Map;for(const row of rows){const value=columnValue(entry.column,row);const bucket=buckets.get(value)??[];bucket.push(row);buckets.set(value,bucket)}const result=[];for(const[value,bucket]of buckets){const key=this.groupKey(parent,entry.id,value);result.push({kind:"group",key,value,columnId:entry.id,rows:bucket,depth});if(!arrayHasKey(this.expandedKeys,key))continue;if(depth+1<fields.length)result.push(...this.groupedDisplayItems(bucket,fields,depth+1,key));else{for(const row of bucket){const sourceIndex=this.allSourceRows.indexOf(row);result.push({kind:"row",row,key:this.keyForRow(row,Math.max(0,sourceIndex)),depth:depth+1,sourceIndex:Math.max(0,sourceIndex)})}}}return result}get resolvedRowHeight(){const raw=this.computedToken("--row-height");return finiteRange(resolveCssLength(raw,this)??56,56,1)}get virtualWindow(){const items=this.displayItems;const disable=items.length<VIRTUALIZATION_THRESHOLD||Boolean(this.childRows)||Boolean(this.rowDetail)||normalizedGroupBy(this.groupBy).length>0||this.computedToken("--max-height")==="none";if(disable)return{items,start:0,end:items.length};const height=this.resolvedRowHeight;const visibleCount=Math.max(1,Math.ceil((this.viewportHeight||height*10)/height));const start=Math.min(Math.max(0,items.length-visibleCount),Math.max(0,Math.floor(this.bodyScrollTop/height)-VIRTUAL_OVERSCAN));const end=Math.min(items.length,start+visibleCount+VIRTUAL_OVERSCAN*2);return{items:items.slice(start,end),start,end}}get gridTemplate(){const columns=this.visibleColumns.map(({column,id})=>{const width=this.columnWidths.get(id)??column.width;if(width!==void 0&&Number.isFinite(width)&&width>0)return`${width}px`;const minimum=Number.isFinite(column.minWidth)&&(column.minWidth??0)>0?`${column.minWidth}px`:"var(--lr-size-7rem)";const maximum=Number.isFinite(column.maxWidth)&&(column.maxWidth??0)>0?`${column.maxWidth}px`:`${finiteRange(column.flex??1,1,0)}fr`;return`minmax(${minimum}, ${maximum})`});if(this.selectionEnabled)columns.unshift("var(--lr-icon-button-size)");return columns.length>0?columns.join(" "):"minmax(var(--lr-size-7rem), 1fr)"}columnStyle(column,id){const side=this.getColumnPin(id);const pinOffset=side?this.pinOffset(id,side):0;return{...side?{"--pin-offset":`${pinOffset}px`}:{},...column.width&&!this.columnWidths.has(id)?{"--column-authored-width":`${column.width}px`}:{}}}estimatedColumnWidth(column,id){const explicit=this.columnWidths.get(id)??column.width;if(explicit!==void 0)return finiteRange(explicit,112,0);const raw=this.computedToken("--lr-size-7rem");return finiteRange(resolveCssLength(raw,this)??112,112,0)}pinOffset(id,side){const entries=this.visibleColumns;const index=entries.findIndex(entry=>entry.id===id);if(index<0)return 0;const subset=side==="left"?entries.slice(0,index):entries.slice(index+1);return subset.filter(entry=>this.getColumnPin(entry.id)===side).reduce((sum,entry)=>sum+this.estimatedColumnWidth(entry.column,entry.id),0)}columnLabel(column,id){return column.label??humanizeIdentifier(column.field??id,this.effectiveLocale)}columnIsSortable(column){return column.sortable!==false&&Boolean(column.field||column.value)}sortFor(id){const index=this.sort.findIndex(item=>item.id===id);return{state:index>=0?this.sort[index]:void 0,index}}activateSort(id,additive){const entry=this.orderedColumns.find(item=>item.id===id);if(!entry||!this.columnIsSortable(entry.column))return;const existing=this.sortFor(id).state;const descendingFirst=entry.column.sortDescFirst??this.sortDescFirst;let replacement;if(!existing)replacement={id,desc:descendingFirst};else if(existing.desc===descendingFirst)replacement={id,desc:!descendingFirst};else if(this.withoutSortRemoval)replacement={id,desc:descendingFirst};let next=additive?this.sort.filter(item=>item.id!==id):[];if(replacement)next.push(replacement);const limit=finiteCount(this.maxMultiSort);if(limit>0&&next.length>limit)next=next.slice(next.length-limit);this.sort=next;this.page=0;this.emit("lr-sort-change",{sort:this.sort.map(item=>({...item}))})}onHeaderClick(event,id){const target=event.target;const interactive=isElementValue(target)?target.closest(INTERACTIVE_SELECTOR):null;if(interactive&&interactive!==event.currentTarget)return;this.activateSort(id,event.shiftKey)}onFilterInput(event,id){const control=valueControl(event.currentTarget);if(!control)return;const value=control.value;const next=this.filters.filter(filter=>filter.id!==id);if(value)next.push({id,value});this.filters=next;this.page=0;this.emit("lr-filter-change",{filters:next.map(filter=>({...filter}))})}onBodyScroll(event){const target=event.currentTarget;if(!isElementValue(target)||typeof target.scrollTop!=="number"||typeof target.clientHeight!=="number")return;this.bodyScrollTop=target.scrollTop;this.viewportHeight=target.clientHeight}onCellClick(event,item,column,index){const target=event.target;const interactive=isElementValue(target)?target.closest(INTERACTIVE_SELECTOR):null;if(interactive&&interactive!==event.currentTarget&&isElementValue(event.currentTarget)&&event.currentTarget.contains(interactive))return;this.emit("lr-cell-click",{column,value:columnValue(column,item.row),row:item.row,index})}emitCellContextMenu(originalEvent,item,column,index){const detail={column,value:columnValue(column,item.row),row:item.row,index,originalEvent};const emitted=this.emit("lr-cell-contextmenu",detail,{cancelable:true});if(emitted.defaultPrevented)originalEvent.preventDefault()}descendantRows(row){const result=[];const visit=parent=>{for(const child of this.childrenFor(parent)){result.push(child);visit(child)}};visit(row);return result}setRowSelected(item,selected,event){if(!this.rowIsSelectable(item.row))return;const selectableItems=this.displayItems.filter(candidate=>candidate.kind==="row"&&this.rowIsSelectable(candidate.row));const position=selectableItems.findIndex(candidate=>keysEqual(candidate.key,item.key));let affected=[item];if(event?.shiftKey&&this.selectionMode==="multiple"&&this.lastSelectedIndex>=0){const from=Math.min(this.lastSelectedIndex,position);const to=Math.max(this.lastSelectedIndex,position);affected=selectableItems.slice(from,to+1)}const descendants=this.selectionMode==="multiple"?affected.flatMap(candidate=>this.descendantRows(candidate.row)):[];const keys=[...affected.map(candidate=>candidate.key),...descendants.map((row,index)=>{const sourceIndex=this.allSourceRows.indexOf(row);return this.keyForRow(row,sourceIndex<0?index:sourceIndex)})];let next=this.selectionMode==="single"?[]:[...this.selectedKeys];for(const key of keys){next=next.filter(candidate=>!keysEqual(candidate,key));if(selected)next.push(key)}this.selectedKeys=next;this.lastSelectedIndex=position;this.emitSelection()}selectCurrentPage(selected){const pageKeys=this.currentPageSelectableRows.map(item=>item.key);let next=this.selectedKeys.filter(key=>!pageKeys.some(pageKey=>keysEqual(pageKey,key)));if(selected)next=[...next,...pageKeys];this.selectedKeys=next;this.emitSelection()}emitSelection(){const selectedKeys=[...this.selectedKeys];const selectedRows=[...this.selectedRows];this.emit("lr-row-select",{selectedKeys,selectedRows})}rowSelectionState(item){const own=arrayHasKey(this.selectedKeys,item.key);const descendants=this.descendantRows(item.row);if(descendants.length===0)return{checked:own,indeterminate:false};const selected=descendants.filter((row,index)=>{const sourceIndex=this.allSourceRows.indexOf(row);return arrayHasKey(this.selectedKeys,this.keyForRow(row,sourceIndex<0?index:sourceIndex))}).length;const checked=own&&selected===descendants.length;return{checked,indeterminate:!checked&&(own||selected>0)}}toggleRowExpanded(item,emitUserEvent){const expanded=arrayHasKey(this.expandedKeys,item.key);if(expanded)this.collapseRow(item.key);else this.expandRow(item.key);if(emitUserEvent){this.emit(expanded?"lr-row-collapse":"lr-row-expand",{key:item.key,row:item.row})}}toggleGroupExpanded(item){if(arrayHasKey(this.expandedKeys,item.key))this.collapseRow(item.key);else this.expandRow(item.key)}moveColumn(id,delta,emitUserEvent){const order=this.orderedColumns.map(entry=>entry.id);const from=order.indexOf(id);if(from<0)return;const to=finiteInteger(from+delta,from,0,order.length-1);if(from===to)return;order.splice(from,1);order.splice(to,0,id);this.columnOrder=order;if(emitUserEvent)this.emit("lr-column-move",{columnOrder:[...order],columnId:id,finished:true})}onDragStart(event,id){const entry=this.orderedColumns.find(item=>item.id===id);if(!entry||!(this.reorderable||entry.column.movable)){event.preventDefault();return}event.dataTransfer?.setData("text/plain",id);if(event.dataTransfer)event.dataTransfer.effectAllowed="move";this.dragGhost=this.columnLabel(entry.column,id)}onDrop(event,targetId){event.preventDefault();const sourceId=event.dataTransfer?.getData("text/plain");this.dragGhost="";if(!sourceId||sourceId===targetId)return;const order=this.orderedColumns.map(entry=>entry.id);const source=order.indexOf(sourceId);const target=order.indexOf(targetId);if(source<0||target<0)return;order.splice(source,1);order.splice(target,0,sourceId);this.columnOrder=order;this.emit("lr-column-move",{columnOrder:[...order],columnId:sourceId,finished:true})}onResizeStart(event,id){const entry=this.orderedColumns.find(item=>item.id===id);if(!entry||!(this.resizable||entry.column.resizable))return;const header=this.renderedColumnElements(id,"columnheader")[0];this.resizeSession={columnId:id,startClientX:event.clientX,startWidth:header?.getBoundingClientRect().width??this.estimatedColumnWidth(entry.column,id),pointerId:event.pointerId};try{event.currentTarget.setPointerCapture?.(event.pointerId)}catch{}event.preventDefault()}onResizeMove(event){const session=this.resizeSession;if(!session||event.pointerId!==session.pointerId)return;const direction=this.effectiveDirection==="rtl"?-1:1;this.setColumnWidth(session.columnId,session.startWidth+(event.clientX-session.startClientX)*direction,true,false)}onResizeEnd(event){const session=this.resizeSession;if(!session||event.pointerId!==session.pointerId)return;const width=this.columnWidths.get(session.columnId)??session.startWidth;this.resizeSession=void 0;try{event.currentTarget.releasePointerCapture?.(event.pointerId)}catch{}this.emit("lr-column-resize",{columnId:session.columnId,width,finished:true})}onResizeKey(event,id){if(!event.altKey||event.key!=="ArrowLeft"&&event.key!=="ArrowRight")return;const entry=this.orderedColumns.find(item=>item.id===id);if(!entry)return;const logical=(event.key==="ArrowRight"?1:-1)*(this.effectiveDirection==="rtl"?-1:1);const current=this.columnWidths.get(id)??this.estimatedColumnWidth(entry.column,id);this.setColumnWidth(id,current+logical*10,true,true);event.preventDefault()}onPageSizeChange(event){const control=valueControl(event.currentTarget);if(!control)return;this.pageSize=finiteCount(Number(control.value));this.page=0;this.emit("lr-page-change",{page:0,pageSize:this.safePageSize})}focusCell(row,column){const rowLimit=Math.max(-1,this.displayItems.length-1);const columnLimit=Math.max(0,this.visibleColumns.length-1);this.focusedRow=finiteInteger(row,this.focusedRow,-1,rowLimit);this.focusedColumn=finiteInteger(column,this.focusedColumn,0,columnLimit);let pendingScrollTop;if(this.focusedRow>=0){const selector=`[role="gridcell"][data-row-position="${this.focusedRow}"]`;if(!this.renderRoot.querySelector(selector)){const top=this.focusedRow*this.resolvedRowHeight;pendingScrollTop=top;this.bodyScrollTop=top;if(this.bodyElement)this.bodyElement.scrollTop=top}}void this.updateComplete.then(()=>{if(pendingScrollTop!==void 0&&this.bodyElement){this.bodyElement.scrollTop=pendingScrollTop}this.focus()})}onGridKeyDown(event,rowPosition,columnPosition,item,column,columnIdValue){const target=event.target;if(isElementValue(target)&&target!==event.currentTarget&&target.closest(INTERACTIVE_SELECTOR)){return}const rtlMultiplier=this.effectiveDirection==="rtl"?-1:1;if(event.ctrlKey&&event.key.toLowerCase()==="a"&&this.selectionMode==="multiple"){this.selectCurrentPage(true);event.preventDefault();return}if(event.ctrlKey&&event.key.toLowerCase()==="c"){this.copySelectedRows();event.preventDefault();return}if(event.shiftKey&&event.key==="F10"&&item&&column){this.emitCellContextMenu(event,item,column,rowPosition);return}const headerEntry=columnIdValue?this.orderedColumns.find(entry=>entry.id===columnIdValue):void 0;if(rowPosition<0&&columnIdValue&&headerEntry&&(this.reorderable||headerEntry.column.movable)&&event.shiftKey&&!event.altKey&&(event.key==="ArrowLeft"||event.key==="ArrowRight")){const delta=(event.key==="ArrowRight"?1:-1)*rtlMultiplier;this.moveColumn(columnIdValue,delta,true);event.preventDefault();return}if(rowPosition<0&&columnIdValue&&headerEntry&&(this.resizable||headerEntry.column.resizable)&&event.altKey){this.onResizeKey(event,columnIdValue);if(event.defaultPrevented)return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){const delta=(event.key==="ArrowRight"?1:-1)*rtlMultiplier;this.focusCell(rowPosition,columnPosition+delta);event.preventDefault()}else if(event.key==="ArrowUp"){this.focusCell(rowPosition-1,columnPosition);event.preventDefault()}else if(event.key==="ArrowDown"){this.focusCell(rowPosition+1,columnPosition);event.preventDefault()}else if(event.key==="Home"){this.focusCell(event.ctrlKey?-1:rowPosition,0);event.preventDefault()}else if(event.key==="End"){this.focusCell(event.ctrlKey?this.displayItems.length-1:rowPosition,this.visibleColumns.length-1);event.preventDefault()}else if(event.key==="PageUp"||event.key==="PageDown"){const delta=event.key==="PageDown"?this.safePageSize||10:-(this.safePageSize||10);this.focusCell(rowPosition+delta,columnPosition);event.preventDefault()}else if(event.key==="Enter"){if(rowPosition<0&&columnIdValue)this.activateSort(columnIdValue,event.shiftKey);else if(item&&column)this.emit("lr-cell-click",{column,value:columnValue(column,item.row),row:item.row,index:rowPosition});event.preventDefault()}else if(event.key===" "&&item){const selected=!arrayHasKey(this.selectedKeys,item.key);this.setRowSelected(item,selected,event);event.preventDefault()}}setGroupSelected(group,selected){const eligible=group.rows.filter(row=>this.rowIsSelectable(row));const groupKeys=eligible.map((row,index)=>{const sourceIndex=this.allSourceRows.indexOf(row);return this.keyForRow(row,sourceIndex<0?index:sourceIndex)});let next=this.selectedKeys.filter(key=>!groupKeys.some(groupKey=>keysEqual(groupKey,key)));if(selected)next=[...next,...groupKeys];this.selectedKeys=next;this.emitSelection()}userPinColumn(id,side){this.pinColumn(id,side);this.emit("lr-column-pin",{columnId:id,side})}userToggleColumn(id,visible){this.toggleColumn(id,visible);this.emit("lr-column-visibility-change",{columnId:id,visible})}renderToolbar(){if(!this.withSearch&&!this.withColumnsMenu)return nothing;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{resolveCssLength}from"../../../internal/css-length.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteCount,finiteDuration,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{srOnly}from"../../../internal/a11y.js";import{aggregateValues,columnId,columnValue,filterRows,pathValue,rowsAsDelimited,searchRows,sortRows}from"./data-grid-processing.js";import{styles}from"./data-grid.styles.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_loading,LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_next,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_paginationFirstPage,LYRA_DEFAULT_paginationJumpToPage,LYRA_DEFAULT_paginationLabel,LYRA_DEFAULT_paginationLastPage,LYRA_DEFAULT_previous,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_tableFilterLabel}from"../../../internal/default-strings.generated.js";export*from"./data-grid-types.js";const selectableConverter={fromAttribute(value){if(value===null)return"none";if(value===""||value==="multiple")return"multiple";return value==="single"||value==="none"?value:"none"},toAttribute(value){if(value==="none")return null;return value===""||value==="multiple"?"":value}};const INTERACTIVE_SELECTOR='button, a[href], input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"]), [role="button"], [role="checkbox"], [role="radio"]';const VIRTUALIZATION_THRESHOLD=80;const VIRTUAL_OVERSCAN=5;function isKey(value){return typeof value==="string"||typeof value==="number"&&Number.isFinite(value)}function keysEqual(left,right){return typeof left===typeof right&&left===right}function arrayHasKey(keys,key){return keys.some(candidate=>keysEqual(candidate,key))}function isElementValue(value){if(value===null||typeof value!=="object")return false;const candidate=value;return candidate.nodeType===1&&typeof candidate.closest==="function"}function valueControl(value){if(!isElementValue(value)||typeof value.value!=="string")return null;return value}function checkableControl(value){if(!isElementValue(value)||typeof value.checked!=="boolean")return null;return value}function dateText(value){try{const timestamp=Date.prototype.getTime.call(value);return Number.isFinite(timestamp)?Date.prototype.toISOString.call(value):""}catch{return void 0}}function humanizeIdentifier(value,locale){const intlLocale=resolveIntlLocale(locale);return value.replaceAll(/[._-]+/gu," ").replaceAll(/([a-z\d])([A-Z])/gu,"$1 $2").replace(/^./u,first=>first.toLocaleUpperCase(intlLocale))}function safeText(value){if(value===null||value===void 0)return"";if(typeof value==="object"){const serializedDate=dateText(value);if(serializedDate!==void 0)return serializedDate}if(Array.isArray(value))return value.map(safeText).join(", ");if(typeof value==="object"){try{return JSON.stringify(value,(_key,nested)=>typeof nested==="bigint"?nested.toString():nested)??""}catch{return""}}return String(value)}function normalizedGroupBy(value){if(Array.isArray(value))return value.map(entry=>entry.trim()).filter(Boolean);return value?.split(/[\s,]+/u).map(entry=>entry.trim()).filter(Boolean)??[]}class LyraDataGrid extends LyraElement{constructor(){super(...arguments);this.appearance="outlined";this.childRows=null;this.columnOrder=[];this.columns=[];this.data=[];this.dataSource=null;this.expandedKeys=[];this.filterDebounce=250;this.filterFromLeafRows=false;this.filters=[];this.groupBy=null;this.label=null;this.loading=false;this.maxMultiSort=0;this.page=0;this.pageSize=20;this.pageSizeOptions=[10,20,50,100];this.paginate=false;this.pinnable=false;this.reorderable=false;this.resizable=false;this.rowClass=null;this.rowDetail=null;this.rowKey=null;this.searchFn=null;this.searchTerm="";this.selectable="none";this.selectableRows=null;this.selectedKeys=[];this.server=false;this.size="m";this.sort=[];this.sortDescFirst=false;this.striped=false;this.total=-1;this.withColumnMenu=false;this.withColumnsMenu=false;this.withoutSortRemoval=false;this.withSearch=false;this.columnWidths=new Map;this.columnVisibility=new Map;this.columnPinning=new Map;this.activeFilterColumn=null;this.columnsMenuOpen=false;this.activeColumnMenu=null;this.liveText="";this.bodyScrollTop=0;this.viewportHeight=0;this.focusedRow=-1;this.focusedColumn=0;this.dragGhost="";this.requestGeneration=0;this.ownsLoadingState=false;this.lastSelectedIndex=-1;this.isMounting=true}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,loading:LYRA_DEFAULT_loading,menuLabel:LYRA_DEFAULT_menuLabel,next:LYRA_DEFAULT_next,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,paginationFirstPage:LYRA_DEFAULT_paginationFirstPage,paginationJumpToPage:LYRA_DEFAULT_paginationJumpToPage,paginationLabel:LYRA_DEFAULT_paginationLabel,paginationLastPage:LYRA_DEFAULT_paginationLastPage,previous:LYRA_DEFAULT_previous,resizeColumn:LYRA_DEFAULT_resizeColumn,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showAllColumns:LYRA_DEFAULT_showAllColumns,tableFilterLabel:LYRA_DEFAULT_tableFilterLabel}}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}get filteredCount(){return this.processedClientRows.length}get pageCount(){const size=this.safePageSize;if(size===0)return 0;if(!this.usesServerData&&normalizedGroupBy(this.groupBy).length>0){const groups=this.topLevelGroupBuckets(this.processedClientRows).length;return groups<=0?0:Math.ceil(groups/size)}const count=this.safeTotal>=0?this.safeTotal:this.filteredCount;return count<=0?0:Math.ceil(count/size)}get selectedRows(){return this.allSourceRows.filter((row,index)=>arrayHasKey(this.selectedKeys,this.keyForRow(row,index)))}set selectedRows(next){const source=this.allSourceRows;const candidates=Array.isArray(next)?next:[];const rows=candidates.filter((row,index)=>source.includes(row)&&candidates.indexOf(row)===index);const limited=this.selectionMode==="single"?rows.slice(0,1):rows;this.selectedKeys=limited.map(row=>this.keyForRow(row,source.indexOf(row)))}connectedCallback(){super.connectedCallback();this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this});if(this.dataSource)this.scheduleServerRequest(false)}disconnectedCallback(){this.requestGeneration+=1;this.requestController?.abort();this.requestController=void 0;if(this.ownsLoadingState)this.loading=false;this.ownsLoadingState=false;this.cancelRequestTimer();this.resizeSession=void 0;this.activeFilterColumn=null;this.activeColumnMenu=null;this.columnsMenuOpen=false;this.dragGhost="";this.sink?.release();this.sink=void 0;super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed);if(this.hasUpdated&&changed.has("loading")&&this.loading){this.announce(this.localize("loading"))}const sourceReplaced=changed.has("dataSource")&&changed.get("dataSource")!==void 0;const serverDisabled=changed.has("server")&&!this.usesServerData;if((sourceReplaced||serverDisabled)&&(this.requestController||this.requestTimer!==void 0)){this.requestGeneration+=1;this.requestController?.abort();this.requestController=void 0;this.cancelRequestTimer();if(this.ownsLoadingState)this.loading=false;this.ownsLoadingState=false}if(changed.has("columns"))this.handleColumnsChange();if(!this.usesServerData&&(changed.has("data")||changed.has("rowKey")||changed.has("childRows")||changed.has("server")||changed.has("dataSource"))){const validKeys=this.allSourceRows.map((row,index)=>this.keyForRow(row,index));const selectedKeys=this.selectedKeys.filter(key=>validKeys.some(candidate=>keysEqual(candidate,key)));if(selectedKeys.length!==this.selectedKeys.length||selectedKeys.some((key,index)=>!keysEqual(key,this.selectedKeys[index]))){this.selectedKeys=selectedKeys}this.lastSelectedIndex=-1}if(this.paginate&&(changed.has("data")||changed.has("filters")||changed.has("searchTerm")||changed.has("groupBy")||changed.has("pageSize")||changed.has("total")||changed.has("server")||changed.has("dataSource"))){const lastPage=Math.max(0,this.pageCount-1);this.page=finiteInteger(this.page,0,0,lastPage)}if(changed.has("data")||changed.has("columns")||changed.has("filters")||changed.has("searchTerm")||changed.has("sort")||changed.has("expandedKeys")||changed.has("groupBy")||changed.has("page")||changed.has("pageSize")||changed.has("paginate")||changed.has("childRows")){this.focusedRow=finiteInteger(this.focusedRow,-1,-1,Math.max(-1,this.displayItems.length-1));this.focusedColumn=finiteInteger(this.focusedColumn,0,0,Math.max(0,this.visibleColumns.length-1))}}updated(changed){if(changed.has("dataSource")&&this.dataSource)this.scheduleServerRequest(false);const requestRelevant=changed.has("sort")||changed.has("filters")||changed.has("searchTerm")||changed.has("page")||changed.has("pageSize")||changed.has("server");if(requestRelevant&&(this.server||this.dataSource)){const delayed=changed.has("filters")||changed.has("searchTerm");this.scheduleServerRequest(delayed)}this.isMounting=false}announce(text){this.sink?.announce(text);this.liveText=text}get usesServerData(){return this.server||this.dataSource!==null}get safePage(){return finiteCount(this.page)}get safePageSize(){return finiteCount(this.pageSize)}get safeTotal(){return this.total===-1?-1:finiteCount(this.total)}get allSourceRows(){const result=[];const visit=rows=>{for(const row of rows){result.push(row);visit(this.childrenFor(row))}};visit(this.data);return result}get orderedColumns(){const entries=this.columns.map((column,naturalIndex)=>({column,id:columnId(column,naturalIndex),naturalIndex}));if(this.columnOrder.length===0)return entries;const rank=new Map(this.columnOrder.map((id,index)=>[id,index]));return entries.sort((left,right)=>{const leftRank=rank.get(left.id);const rightRank=rank.get(right.id);if(leftRank===void 0&&rightRank===void 0)return left.naturalIndex-right.naturalIndex;if(leftRank===void 0)return 1;if(rightRank===void 0)return-1;return leftRank-rightRank})}get visibleColumns(){const entries=this.orderedColumns.filter(({column,id})=>this.columnVisibility.get(id)??column.hidden!==true);const rank=(side,id)=>{const ordered=this.orderedColumns.filter(entry=>this.getColumnPin(entry.id)===side);return ordered.findIndex(entry=>entry.id===id)};return entries.sort((left,right)=>{const leftPin=this.getColumnPin(left.id);const rightPin=this.getColumnPin(right.id);if(leftPin===rightPin)return 0;if(leftPin==="left")return-1;if(rightPin==="left")return 1;if(leftPin==="right")return 1;if(rightPin==="right")return-1;return rank("left",left.id)-rank("right",right.id)})}get processedClientRows(){if(this.usesServerData)return[...this.data];if(this.childRows){const included=this.data.filter(row=>this.rowMatches(row)||this.filterFromLeafRows&&this.hasMatchingDescendant(row));return sortRows(included,this.columns,this.sort,this.effectiveLocale)}const filtered=filterRows(this.data,this.columns,this.filters,this.effectiveLocale);const searched=searchRows(filtered,this.columns,this.searchTerm,this.effectiveLocale,this.searchFn);return sortRows(searched,this.columns,this.sort,this.effectiveLocale)}childrenFor(row){const children=typeof this.childRows==="function"?this.childRows(row):this.childRows?pathValue(row,this.childRows):void 0;return Array.isArray(children)?children:[]}keyForRow(row,index){const candidate=this.rowKey?pathValue(row,this.rowKey):void 0;return isKey(candidate)?candidate:index}renderedColumnElements(columnId2,role){const prefix=role?`[role="${role}"]`:"";const ownerCss=this.ownerDocument.defaultView?.CSS;const escape=ownerCss?.escape;if(typeof escape==="function"){try{const matches=[...this.renderRoot.querySelectorAll(`${prefix}[data-column-id="${escape.call(ownerCss,columnId2)}"]`)];if(matches.length>0)return matches}catch{}}return[...this.renderRoot.querySelectorAll(`${prefix}[data-column-id]`)].filter(element=>element.getAttribute("data-column-id")===columnId2)}computedToken(name){if(!this.isConnected)return"";const owner=this.ownerDocument.defaultView;if(!owner||typeof owner.getComputedStyle!=="function")return"";try{return owner.getComputedStyle(this).getPropertyValue(name).trim()}catch{return""}}autoSizeColumn(columnId2){const cells=this.renderedColumnElements(columnId2);if(cells.length===0)return;let width=0;for(const cell of cells)width=Math.max(width,cell.scrollWidth);const entry=this.orderedColumns.find(({id})=>id===columnId2);if(!entry)return;const minimum=finiteRange(entry.column.minWidth??0,0,0);const maximum=finiteRange(entry.column.maxWidth??Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,minimum);this.setColumnWidth(columnId2,finiteRange(width,minimum,minimum,maximum),false)}autoSizeColumns(){for(const{id}of this.visibleColumns)this.autoSizeColumn(id)}collapseAllRows(){this.expandedKeys=[]}collapseRow(key){this.expandedKeys=this.expandedKeys.filter(candidate=>!keysEqual(candidate,key))}copySelectedRows(options={}){const rowsToCopy=this.selectedRows.length>0?this.selectedRows:this.getProcessedRows();const format=options.format??"tsv";const text=this.delimitedRows(rowsToCopy,{...options,delimiter:format==="csv"?",":" "});this.writeClipboard(text);if(!this.isMounting)this.announce(this.localize("copied"));return rowsToCopy.length}expandAllRows(){const keys=[];this.allSourceRows.forEach((row,index)=>{if(this.childrenFor(row).length>0||this.rowDetail)keys.push(this.keyForRow(row,index))});for(const group of this.groupItems(this.processedClientRows))keys.push(group.key);this.expandedKeys=keys}expandRow(key){if(!arrayHasKey(this.expandedKeys,key))this.expandedKeys=[...this.expandedKeys,key]}exportDataAsCsv(options={}){const text=this.getDataAsCsv(options);const ownerDocument=this.ownerDocument;const owner=ownerDocument.defaultView;if(!owner||typeof owner.URL.createObjectURL!=="function")return;const url=owner.URL.createObjectURL(new owner.Blob([text],{type:"text/csv;charset=utf-8"}));try{const anchor=ownerDocument.createElement("a");anchor.href=url;const legacyFileName=options.filename;anchor.download=options.fileName||legacyFileName||"data.csv";anchor.hidden=true;ownerDocument.body?.append(anchor);anchor.click();anchor.remove()}finally{owner.URL.revokeObjectURL(url)}}focus(options={}){const selector=this.focusedRow<0?`[role="columnheader"][data-column-position="${this.focusedColumn}"]`:`[role="gridcell"][data-row-position="${this.focusedRow}"][data-column-position="${this.focusedColumn}"]`;this.renderRoot.querySelector(selector)?.focus(options)}getColumnFacets(columnId2){const uniqueValues=new Map;if(this.usesServerData)return{uniqueValues};const entry=this.orderedColumns.find(({id})=>id===columnId2);if(!entry)return{uniqueValues};const otherFilters=this.filters.filter(filter=>filter.id!==columnId2);const rows=searchRows(filterRows(this.data,this.columns,otherFilters,this.effectiveLocale),this.columns,this.searchTerm,this.effectiveLocale,this.searchFn);let minimum=Number.POSITIVE_INFINITY;let maximum=Number.NEGATIVE_INFINITY;for(const row of rows){const value=columnValue(entry.column,row);uniqueValues.set(value,(uniqueValues.get(value)??0)+1);const number=typeof value==="number"?value:Number(value);if(Number.isFinite(number)){minimum=Math.min(minimum,number);maximum=Math.max(maximum,number)}}return Number.isFinite(minimum)&&Number.isFinite(maximum)?{uniqueValues,minMax:[minimum,maximum]}:{uniqueValues}}getColumnPin(columnId2){if(this.columnPinning.has(columnId2))return this.columnPinning.get(columnId2)??false;return this.orderedColumns.find(({id})=>id===columnId2)?.column.pinned??false}getDataAsCsv(options={}){return this.delimitedRows(this.getProcessedRows(),options)}getProcessedRows(){return[...this.processedClientRows]}getVisibleRows(){const rows=this.processedClientRows;if(!this.paginate||this.usesServerData)return[...rows];const size=this.safePageSize;if(size===0)return[];const start=this.safePage*size;if(normalizedGroupBy(this.groupBy).length>0){return this.topLevelGroupBuckets(rows).slice(start,start+size).flatMap(bucket=>bucket.rows)}return rows.slice(start,start+size)}getState(){return{order:[...this.columnOrder],widths:Object.fromEntries(this.columnWidths),visibility:Object.fromEntries(this.columnVisibility),pinning:Object.fromEntries(this.columnPinning),sort:this.sort.map(item=>({...item})),filters:this.filters.map(item=>({...item})),search:this.searchTerm,selectedKeys:[...this.selectedKeys],expandedKeys:[...this.expandedKeys],page:this.safePage,pageSize:this.safePageSize}}handleColumnsChange(){const valid=new Set(this.columns.map((column,index)=>columnId(column,index)));const natural=[...valid];const order=this.columnOrder.filter(id=>valid.has(id));for(const id of natural)if(!order.includes(id))order.push(id);if(this.columnOrder.length>0&&order.join("\0")!==this.columnOrder.join("\0")){this.columnOrder=order}const widths=[...this.columnWidths].filter(([id])=>valid.has(id));const visibility=[...this.columnVisibility].filter(([id])=>valid.has(id));const pinning=[...this.columnPinning].filter(([id])=>valid.has(id));if(widths.length!==this.columnWidths.size)this.columnWidths=new Map(widths);if(visibility.length!==this.columnVisibility.size)this.columnVisibility=new Map(visibility);if(pinning.length!==this.columnPinning.size)this.columnPinning=new Map(pinning)}handlePageChange(){this.applyPageChange(this.safePage)}applyPageChange(value){let requested;if(typeof value==="number")requested=value;else requested=Number(valueControl(value?.currentTarget)?.value??this.safePage);const last=Math.max(0,this.pageCount-1);const next=finiteInteger(requested,this.safePage,0,last);this.page=next;this.emit("lr-page-change",{page:next,pageSize:this.safePageSize})}handleSearchTermChange(){this.applySearchTermChange(this.searchTerm)}applySearchTermChange(value){const next=typeof value==="string"?value:valueControl(value?.currentTarget)?.value??this.searchTerm;this.searchTerm=next;if(this.page!==0)this.page=0}pinColumn(columnId2,side){if(!this.orderedColumns.some(({id})=>id===columnId2))return;const next=new Map(this.columnPinning);next.set(columnId2,side);this.columnPinning=next}async reload(){const owner=this.ownerDocument.defaultView;if(!this.isConnected||!owner||!this.usesServerData)return;this.cancelRequestTimer();await this.loadServerData(owner)}resetColumns(){this.columnOrder=[];this.columnWidths=new Map;this.columnVisibility=new Map;this.columnPinning=new Map}resetState(){this.resetColumns();this.sort=[];this.filters=[];this.searchTerm="";this.expandedKeys=[]}scrollToIndex(index,options={}){const rows=this.getVisibleRows();if(rows.length===0)return;const target=finiteInteger(index,0,0,rows.length-1);const rendered=this.renderRoot?.querySelector(`[part~="row"][data-visible-index="${target}"]`);if(rendered){rendered.scrollIntoView({block:options.align??"nearest"});return}const body=this.bodyElement;if(!body)return;const rowHeight=this.resolvedRowHeight;let top=target*rowHeight;if(options.align==="center")top-=(body.clientHeight-rowHeight)/2;else if(options.align==="end")top-=body.clientHeight-rowHeight;body.scrollTo({top:Math.max(0,top)})}setState(state2){const known=new Set(this.columns.map((column,index)=>columnId(column,index)));if(state2.order)this.columnOrder=state2.order.filter(id=>known.has(id));if(state2.widths)this.columnWidths=this.validColumnMap(state2.widths,known,width=>finiteRange(width,0,0));if(state2.visibility)this.columnVisibility=this.validColumnMap(state2.visibility,known,Boolean);if(state2.pinning)this.columnPinning=this.validColumnMap(state2.pinning,known,side=>side==="left"||side==="right"?side:false);if(state2.sort)this.sort=state2.sort.filter(item=>known.has(item.id)).map(item=>({id:item.id,desc:Boolean(item.desc)}));if(state2.filters)this.filters=state2.filters.filter(item=>known.has(item.id)).map(item=>({...item}));if(state2.search!==void 0)this.searchTerm=state2.search;if(state2.selectedKeys)this.selectedKeys=state2.selectedKeys.filter(isKey);if(state2.expandedKeys)this.expandedKeys=state2.expandedKeys.filter(isKey);if(state2.page!==void 0)this.page=finiteCount(state2.page);if(state2.pageSize!==void 0)this.pageSize=finiteCount(state2.pageSize)}sizeColumnsToFit(){const body=this.bodyElement;if(!body||this.visibleColumns.length===0)return;const selectionWidth=this.selectionEnabled?resolveCssLength(this.computedToken("--lr-icon-button-size"),this)??0:0;const available=Math.max(0,body.clientWidth-selectionWidth);const flexible=this.visibleColumns.filter(({column})=>column.flex!==0);if(flexible.length===0)return;const totalFlex=flexible.reduce((sum,{column})=>sum+finiteRange(column.flex??1,1,0),0)||flexible.length;const next=new Map(this.columnWidths);for(const{column,id}of flexible){const share=available*(finiteRange(column.flex??1,1,0)/totalFlex);const minimum=finiteRange(column.minWidth??0,0,0);const maximum=finiteRange(column.maxWidth??Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,minimum);next.set(id,finiteRange(share,minimum,minimum,maximum))}this.columnWidths=next}toggleColumn(columnId2,visible){if(!this.orderedColumns.some(({id})=>id===columnId2))return;const next=new Map(this.columnVisibility);next.set(columnId2,visible);this.columnVisibility=next;this.focusedColumn=finiteInteger(this.focusedColumn,0,0,Math.max(0,this.visibleColumns.length-1))}validColumnMap(record,known,convert){const result=new Map;for(const[id,value]of Object.entries(record))if(known.has(id))result.set(id,convert(value));return result}delimitedRows(rows,options){const active=this.visibleColumns.map(({column,id})=>({...column,id,value:row=>{const raw=columnValue(column,row);const formatted=column.formatter?.(raw,row);return typeof formatted==="string"?formatted:raw},hidden:false}));return rowsAsDelimited(rows,active,options)}writeClipboard(text){const ownerDocument=this.ownerDocument;const owner=ownerDocument.defaultView;if(!owner)return;try{const clipboard=owner.navigator.clipboard;if(typeof clipboard?.writeText==="function"){void clipboard.writeText(text).catch(()=>void 0);return}}catch{}if(!ownerDocument.body)return;const textarea=ownerDocument.createElement("textarea");textarea.value=text;textarea.style.position="fixed";textarea.style.opacity="0";ownerDocument.body.append(textarea);try{textarea.select();ownerDocument.execCommand?.("copy")}finally{textarea.remove()}}setColumnWidth(columnIdValue,width,emit,finished=true){const entry=this.orderedColumns.find(({id})=>id===columnIdValue);if(!entry)return;const minimum=finiteRange(entry.column.minWidth??0,0,0);const maximum=finiteRange(entry.column.maxWidth??Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,minimum);const safeWidth=finiteRange(width,minimum,minimum,maximum);const next=new Map(this.columnWidths);next.set(columnIdValue,safeWidth);this.columnWidths=next;if(emit)this.emit("lr-column-resize",{columnId:columnIdValue,width:safeWidth,finished})}cancelRequestTimer(){const timer=this.requestTimer;this.requestTimer=void 0;if(timer)timer.owner.clearTimeout(timer.handle)}scheduleServerRequest(delayed){const owner=this.ownerDocument.defaultView;if(!this.isConnected||!owner||!this.usesServerData)return;this.cancelRequestTimer();const delay=delayed?finiteDuration(this.filterDebounce,250):0;let handle=0;handle=owner.setTimeout(()=>{if(this.requestTimer?.owner!==owner||this.requestTimer.handle!==handle||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.requestTimer=void 0;void this.loadServerData(owner)},delay);this.requestTimer={owner,handle}}async loadServerData(owner){if(!this.isConnected||this.ownerDocument.defaultView!==owner||!this.usesServerData)return;this.requestController?.abort();const AbortControllerCtor=owner.AbortController;this.requestController=typeof AbortControllerCtor==="function"?new AbortControllerCtor:void 0;const generation=++this.requestGeneration;const request={sort:this.sort.map(item=>({...item})),filters:this.filters.map(item=>({...item})),search:this.searchTerm,page:this.safePage,pageSize:this.safePageSize,signal:this.requestController?.signal};this.emit("request",request);this.emit("lr-data-request",request);if(!this.dataSource)return;this.ownsLoadingState=true;this.loading=true;try{const response=await this.dataSource(request);if(generation!==this.requestGeneration||request.signal?.aborted||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.data=Array.isArray(response.rows)?response.rows:[];this.total=finiteCount(response.total);this.loading=false;this.ownsLoadingState=false}catch(error){if(generation!==this.requestGeneration||request.signal?.aborted||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.loading=false;this.ownsLoadingState=false;this.emit("lr-data-error",{error,request})}}get selectionMode(){if(this.selectable===""||this.selectable==="multiple")return"multiple";return this.selectable}get selectionEnabled(){return this.selectionMode!=="none"}rowIsSelectable(row){return this.selectionEnabled&&(this.selectableRows?.(row)??true)}rowMatches(row){return filterRows([row],this.columns,this.filters,this.effectiveLocale).length>0&&searchRows([row],this.columns,this.searchTerm,this.effectiveLocale,this.searchFn).length>0}processedChildrenFor(row){const children=this.childrenFor(row);if(children.length===0||this.usesServerData)return children;const included=children.filter(child=>{if(this.rowMatches(child))return true;return this.filterFromLeafRows&&this.hasMatchingDescendant(child)});return sortRows(included,this.columns,this.sort,this.effectiveLocale)}hasMatchingDescendant(row){return this.childrenFor(row).some(child=>this.rowMatches(child)||this.hasMatchingDescendant(child))}get pageRows(){return this.getVisibleRows()}get currentPageSelectableRows(){const result=[];const visited=new Set;const visit=pageRows=>{for(const row of pageRows){if(visited.has(row))continue;visited.add(row);const sourceIndex=this.allSourceRows.indexOf(row);const key=this.keyForRow(row,sourceIndex<0?result.length:sourceIndex);if(this.rowIsSelectable(row))result.push({row,key});visit(this.childrenFor(row))}};visit(this.pageRows);return result}groupKey(parent,id,value){return`group:${parent}:${id}:${typeof value}:${safeText(value)}`}topLevelGroupBuckets(rows){const field=normalizedGroupBy(this.groupBy)[0];if(!field)return[];const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return[];const buckets=new Map;for(const row of rows){const value=columnValue(entry.column,row);const bucket=buckets.get(value)??[];bucket.push(row);buckets.set(value,bucket)}return[...buckets].map(([value,bucketRows])=>({value,rows:bucketRows}))}groupItems(rows){const fields=normalizedGroupBy(this.groupBy);if(fields.length===0||this.usesServerData)return[];const result=[];const visit=(groupRows,depth,parent)=>{const field=fields[depth];if(!field)return;const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return;const buckets=new Map;for(const row of groupRows){const value=columnValue(entry.column,row);const bucket=buckets.get(value)??[];bucket.push(row);buckets.set(value,bucket)}for(const[value,bucket]of buckets){const key=this.groupKey(parent,entry.id,value);result.push({kind:"group",key,value,columnId:entry.id,rows:bucket,depth});if(depth+1<fields.length)visit(bucket,depth+1,key)}};visit(rows,0,"root");return result}get displayItems(){const groups=normalizedGroupBy(this.groupBy);if(groups.length>0&&!this.usesServerData)return this.groupedDisplayItems(this.pageRows,groups,0,"root");const result=[];const sourceRows=this.allSourceRows;const visit=(rows,depth)=>{for(const row of rows){const sourceIndex=sourceRows.indexOf(row);const safeIndex=sourceIndex<0?result.length:sourceIndex;const key=this.keyForRow(row,safeIndex);result.push({kind:"row",row,key,depth,sourceIndex:safeIndex});if(arrayHasKey(this.expandedKeys,key))visit(this.processedChildrenFor(row),depth+1)}};visit(this.pageRows,0);return result}groupedDisplayItems(rows,fields,depth,parent){const field=fields[depth];if(!field)return[];const entry=this.orderedColumns.find(({id,column})=>id===field||column.field===field);if(!entry)return rows.map((row,index)=>({kind:"row",row,key:this.keyForRow(row,index),depth,sourceIndex:index}));const buckets=new Map;for(const row of rows){const value=columnValue(entry.column,row);const bucket=buckets.get(value)??[];bucket.push(row);buckets.set(value,bucket)}const result=[];for(const[value,bucket]of buckets){const key=this.groupKey(parent,entry.id,value);result.push({kind:"group",key,value,columnId:entry.id,rows:bucket,depth});if(!arrayHasKey(this.expandedKeys,key))continue;if(depth+1<fields.length)result.push(...this.groupedDisplayItems(bucket,fields,depth+1,key));else{for(const row of bucket){const sourceIndex=this.allSourceRows.indexOf(row);result.push({kind:"row",row,key:this.keyForRow(row,Math.max(0,sourceIndex)),depth:depth+1,sourceIndex:Math.max(0,sourceIndex)})}}}return result}get resolvedRowHeight(){const raw=this.computedToken("--row-height");return finiteRange(resolveCssLength(raw,this)??56,56,1)}get virtualWindow(){const items=this.displayItems;const disable=items.length<VIRTUALIZATION_THRESHOLD||Boolean(this.childRows)||Boolean(this.rowDetail)||normalizedGroupBy(this.groupBy).length>0||this.computedToken("--max-height")==="none";if(disable)return{items,start:0,end:items.length};const height=this.resolvedRowHeight;const visibleCount=Math.max(1,Math.ceil((this.viewportHeight||height*10)/height));const start=Math.min(Math.max(0,items.length-visibleCount),Math.max(0,Math.floor(this.bodyScrollTop/height)-VIRTUAL_OVERSCAN));const end=Math.min(items.length,start+visibleCount+VIRTUAL_OVERSCAN*2);return{items:items.slice(start,end),start,end}}get gridTemplate(){const columns=this.visibleColumns.map(({column,id})=>{const width=this.columnWidths.get(id)??column.width;if(width!==void 0&&Number.isFinite(width)&&width>0)return`${width}px`;const minimum=Number.isFinite(column.minWidth)&&(column.minWidth??0)>0?`${column.minWidth}px`:"var(--lr-size-7rem)";const maximum=Number.isFinite(column.maxWidth)&&(column.maxWidth??0)>0?`${column.maxWidth}px`:`${finiteRange(column.flex??1,1,0)}fr`;return`minmax(${minimum}, ${maximum})`});if(this.selectionEnabled)columns.unshift("var(--lr-icon-button-size)");return columns.length>0?columns.join(" "):"minmax(var(--lr-size-7rem), 1fr)"}columnStyle(column,id){const side=this.getColumnPin(id);const pinOffset=side?this.pinOffset(id,side):0;return{...side?{"--pin-offset":`${pinOffset}px`}:{},...Number.isFinite(column.width)&&(column.width??0)>0&&!this.columnWidths.has(id)?{"--column-authored-width":`${column.width}px`}:{}}}estimatedColumnWidth(column,id){const explicit=this.columnWidths.get(id)??column.width;if(explicit!==void 0)return finiteRange(explicit,112,0);const raw=this.computedToken("--lr-size-7rem");return finiteRange(resolveCssLength(raw,this)??112,112,0)}pinOffset(id,side){const entries=this.visibleColumns;const index=entries.findIndex(entry=>entry.id===id);if(index<0)return 0;const subset=side==="left"?entries.slice(0,index):entries.slice(index+1);return subset.filter(entry=>this.getColumnPin(entry.id)===side).reduce((sum,entry)=>sum+this.estimatedColumnWidth(entry.column,entry.id),0)}columnLabel(column,id){return column.label??humanizeIdentifier(column.field??id,this.effectiveLocale)}columnIsSortable(column){return column.sortable!==false&&Boolean(column.field||column.value)}sortFor(id){const index=this.sort.findIndex(item=>item.id===id);return{state:index>=0?this.sort[index]:void 0,index}}activateSort(id,additive){const entry=this.orderedColumns.find(item=>item.id===id);if(!entry||!this.columnIsSortable(entry.column))return;const existing=this.sortFor(id).state;const descendingFirst=entry.column.sortDescFirst??this.sortDescFirst;let replacement;if(!existing)replacement={id,desc:descendingFirst};else if(existing.desc===descendingFirst)replacement={id,desc:!descendingFirst};else if(this.withoutSortRemoval)replacement={id,desc:descendingFirst};let next=additive?this.sort.filter(item=>item.id!==id):[];if(replacement)next.push(replacement);const limit=finiteCount(this.maxMultiSort);if(limit>0&&next.length>limit)next=next.slice(next.length-limit);this.sort=next;this.page=0;this.emit("lr-sort-change",{sort:this.sort.map(item=>({...item}))})}onHeaderClick(event,id){const target=event.target;const interactive=isElementValue(target)?target.closest(INTERACTIVE_SELECTOR):null;if(interactive&&interactive!==event.currentTarget)return;this.activateSort(id,event.shiftKey)}onFilterInput(event,id){const control=valueControl(event.currentTarget);if(!control)return;const value=control.value;const next=this.filters.filter(filter=>filter.id!==id);if(value)next.push({id,value});this.filters=next;this.page=0;this.emit("lr-filter-change",{filters:next.map(filter=>({...filter}))})}onBodyScroll(event){const target=event.currentTarget;if(!isElementValue(target)||typeof target.scrollTop!=="number"||typeof target.clientHeight!=="number")return;this.bodyScrollTop=target.scrollTop;this.viewportHeight=target.clientHeight}onCellClick(event,item,column,index){const target=event.target;const interactive=isElementValue(target)?target.closest(INTERACTIVE_SELECTOR):null;if(interactive&&interactive!==event.currentTarget&&isElementValue(event.currentTarget)&&event.currentTarget.contains(interactive))return;this.emit("lr-cell-click",{column,value:columnValue(column,item.row),row:item.row,index})}emitCellContextMenu(originalEvent,item,column,index){const detail={column,value:columnValue(column,item.row),row:item.row,index,originalEvent};const emitted=this.emit("lr-cell-contextmenu",detail,{cancelable:true});if(emitted.defaultPrevented)originalEvent.preventDefault()}descendantRows(row){const result=[];const visit=parent=>{for(const child of this.childrenFor(parent)){result.push(child);visit(child)}};visit(row);return result}setRowSelected(item,selected,event){if(!this.rowIsSelectable(item.row))return;const selectableItems=this.displayItems.filter(candidate=>candidate.kind==="row"&&this.rowIsSelectable(candidate.row));const position=selectableItems.findIndex(candidate=>keysEqual(candidate.key,item.key));let affected=[item];if(event?.shiftKey&&this.selectionMode==="multiple"&&this.lastSelectedIndex>=0){const from=Math.min(this.lastSelectedIndex,position);const to=Math.max(this.lastSelectedIndex,position);affected=selectableItems.slice(from,to+1)}const descendants=this.selectionMode==="multiple"?affected.flatMap(candidate=>this.descendantRows(candidate.row)):[];const keys=[...affected.map(candidate=>candidate.key),...descendants.map((row,index)=>{const sourceIndex=this.allSourceRows.indexOf(row);return this.keyForRow(row,sourceIndex<0?index:sourceIndex)})];let next=this.selectionMode==="single"?[]:[...this.selectedKeys];for(const key of keys){next=next.filter(candidate=>!keysEqual(candidate,key));if(selected)next.push(key)}this.selectedKeys=next;this.lastSelectedIndex=position;this.emitSelection()}selectCurrentPage(selected){const pageKeys=this.currentPageSelectableRows.map(item=>item.key);let next=this.selectedKeys.filter(key=>!pageKeys.some(pageKey=>keysEqual(pageKey,key)));if(selected)next=[...next,...pageKeys];this.selectedKeys=next;this.emitSelection()}emitSelection(){const selectedKeys=[...this.selectedKeys];const selectedRows=[...this.selectedRows];this.emit("lr-row-select",{selectedKeys,selectedRows})}rowSelectionState(item){const own=arrayHasKey(this.selectedKeys,item.key);const descendants=this.descendantRows(item.row);if(descendants.length===0)return{checked:own,indeterminate:false};const selected=descendants.filter((row,index)=>{const sourceIndex=this.allSourceRows.indexOf(row);return arrayHasKey(this.selectedKeys,this.keyForRow(row,sourceIndex<0?index:sourceIndex))}).length;const checked=own&&selected===descendants.length;return{checked,indeterminate:!checked&&(own||selected>0)}}toggleRowExpanded(item,emitUserEvent){const expanded=arrayHasKey(this.expandedKeys,item.key);if(expanded)this.collapseRow(item.key);else this.expandRow(item.key);if(emitUserEvent){this.emit(expanded?"lr-row-collapse":"lr-row-expand",{key:item.key,row:item.row})}}toggleGroupExpanded(item){if(arrayHasKey(this.expandedKeys,item.key))this.collapseRow(item.key);else this.expandRow(item.key)}moveColumn(id,delta,emitUserEvent){const order=this.orderedColumns.map(entry=>entry.id);const from=order.indexOf(id);if(from<0)return;const to=finiteInteger(from+delta,from,0,order.length-1);if(from===to)return;order.splice(from,1);order.splice(to,0,id);this.columnOrder=order;if(emitUserEvent)this.emit("lr-column-move",{columnOrder:[...order],columnId:id,finished:true})}onDragStart(event,id){const entry=this.orderedColumns.find(item=>item.id===id);if(!entry||!(this.reorderable||entry.column.movable)){event.preventDefault();return}event.dataTransfer?.setData("text/plain",id);if(event.dataTransfer)event.dataTransfer.effectAllowed="move";this.dragGhost=this.columnLabel(entry.column,id)}onDrop(event,targetId){event.preventDefault();const sourceId=event.dataTransfer?.getData("text/plain");this.dragGhost="";if(!sourceId||sourceId===targetId)return;const order=this.orderedColumns.map(entry=>entry.id);const source=order.indexOf(sourceId);const target=order.indexOf(targetId);if(source<0||target<0)return;order.splice(source,1);order.splice(target,0,sourceId);this.columnOrder=order;this.emit("lr-column-move",{columnOrder:[...order],columnId:sourceId,finished:true})}onResizeStart(event,id){const entry=this.orderedColumns.find(item=>item.id===id);if(!entry||!(this.resizable||entry.column.resizable))return;const header=this.renderedColumnElements(id,"columnheader")[0];this.resizeSession={columnId:id,startClientX:event.clientX,startWidth:header?.getBoundingClientRect().width??this.estimatedColumnWidth(entry.column,id),pointerId:event.pointerId};try{event.currentTarget.setPointerCapture?.(event.pointerId)}catch{}event.preventDefault()}onResizeMove(event){const session=this.resizeSession;if(!session||event.pointerId!==session.pointerId)return;const direction=this.effectiveDirection==="rtl"?-1:1;this.setColumnWidth(session.columnId,session.startWidth+(event.clientX-session.startClientX)*direction,true,false)}onResizeEnd(event){const session=this.resizeSession;if(!session||event.pointerId!==session.pointerId)return;const width=this.columnWidths.get(session.columnId)??session.startWidth;this.resizeSession=void 0;try{event.currentTarget.releasePointerCapture?.(event.pointerId)}catch{}this.emit("lr-column-resize",{columnId:session.columnId,width,finished:true})}onResizeKey(event,id){if(!event.altKey||event.key!=="ArrowLeft"&&event.key!=="ArrowRight")return;const entry=this.orderedColumns.find(item=>item.id===id);if(!entry)return;const logical=(event.key==="ArrowRight"?1:-1)*(this.effectiveDirection==="rtl"?-1:1);const current=this.columnWidths.get(id)??this.estimatedColumnWidth(entry.column,id);this.setColumnWidth(id,current+logical*10,true,true);event.preventDefault()}onPageSizeChange(event){const control=valueControl(event.currentTarget);if(!control)return;this.pageSize=finiteCount(Number(control.value));this.page=0;this.emit("lr-page-change",{page:0,pageSize:this.safePageSize})}focusCell(row,column){const rowLimit=Math.max(-1,this.displayItems.length-1);const columnLimit=Math.max(0,this.visibleColumns.length-1);this.focusedRow=finiteInteger(row,this.focusedRow,-1,rowLimit);this.focusedColumn=finiteInteger(column,this.focusedColumn,0,columnLimit);let pendingScrollTop;if(this.focusedRow>=0){const selector=`[role="gridcell"][data-row-position="${this.focusedRow}"]`;if(!this.renderRoot.querySelector(selector)){const top=this.focusedRow*this.resolvedRowHeight;pendingScrollTop=top;this.bodyScrollTop=top;if(this.bodyElement)this.bodyElement.scrollTop=top}}void this.updateComplete.then(()=>{if(pendingScrollTop!==void 0&&this.bodyElement){this.bodyElement.scrollTop=pendingScrollTop}this.focus()})}onGridKeyDown(event,rowPosition,columnPosition,item,column,columnIdValue){const target=event.target;if(isElementValue(target)&&target!==event.currentTarget&&target.closest(INTERACTIVE_SELECTOR)){return}const rtlMultiplier=this.effectiveDirection==="rtl"?-1:1;if(event.ctrlKey&&event.key.toLowerCase()==="a"&&this.selectionMode==="multiple"){this.selectCurrentPage(true);event.preventDefault();return}if(event.ctrlKey&&event.key.toLowerCase()==="c"){this.copySelectedRows();event.preventDefault();return}if(event.shiftKey&&event.key==="F10"&&item&&column){this.emitCellContextMenu(event,item,column,rowPosition);return}const headerEntry=columnIdValue?this.orderedColumns.find(entry=>entry.id===columnIdValue):void 0;if(rowPosition<0&&columnIdValue&&headerEntry&&(this.reorderable||headerEntry.column.movable)&&event.shiftKey&&!event.altKey&&(event.key==="ArrowLeft"||event.key==="ArrowRight")){const delta=(event.key==="ArrowRight"?1:-1)*rtlMultiplier;this.moveColumn(columnIdValue,delta,true);event.preventDefault();return}if(rowPosition<0&&columnIdValue&&headerEntry&&(this.resizable||headerEntry.column.resizable)&&event.altKey){this.onResizeKey(event,columnIdValue);if(event.defaultPrevented)return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){const delta=(event.key==="ArrowRight"?1:-1)*rtlMultiplier;this.focusCell(rowPosition,columnPosition+delta);event.preventDefault()}else if(event.key==="ArrowUp"){this.focusCell(rowPosition-1,columnPosition);event.preventDefault()}else if(event.key==="ArrowDown"){this.focusCell(rowPosition+1,columnPosition);event.preventDefault()}else if(event.key==="Home"){this.focusCell(event.ctrlKey?-1:rowPosition,0);event.preventDefault()}else if(event.key==="End"){this.focusCell(event.ctrlKey?this.displayItems.length-1:rowPosition,this.visibleColumns.length-1);event.preventDefault()}else if(event.key==="PageUp"||event.key==="PageDown"){const delta=event.key==="PageDown"?this.safePageSize||10:-(this.safePageSize||10);this.focusCell(rowPosition+delta,columnPosition);event.preventDefault()}else if(event.key==="Enter"){if(rowPosition<0&&columnIdValue)this.activateSort(columnIdValue,event.shiftKey);else if(item&&column)this.emit("lr-cell-click",{column,value:columnValue(column,item.row),row:item.row,index:rowPosition});event.preventDefault()}else if(event.key===" "&&item){const selected=!arrayHasKey(this.selectedKeys,item.key);this.setRowSelected(item,selected,event);event.preventDefault()}}setGroupSelected(group,selected){const eligible=group.rows.filter(row=>this.rowIsSelectable(row));const groupKeys=eligible.map((row,index)=>{const sourceIndex=this.allSourceRows.indexOf(row);return this.keyForRow(row,sourceIndex<0?index:sourceIndex)});let next=this.selectedKeys.filter(key=>!groupKeys.some(groupKey=>keysEqual(groupKey,key)));if(selected)next=[...next,...groupKeys];this.selectedKeys=next;this.emitSelection()}userPinColumn(id,side){this.pinColumn(id,side);this.emit("lr-column-pin",{columnId:id,side})}userToggleColumn(id,visible){this.toggleColumn(id,visible);this.emit("lr-column-visibility-change",{columnId:id,visible})}renderToolbar(){if(!this.withSearch&&!this.withColumnsMenu)return nothing;return html`
2
2
  <div part="toolbar">
3
3
  ${this.withSearch?html`
4
4
  <input