/**
 * @license
 * Copyright 2021 Google LLC
 * SPDX-License-Identifier: BSD-3-Clause
 */
import{html as t,noChange as i}from"../../lit/index.js";import{directive as e,PartType as s}from"../../lit/directive.js";import{AsyncDirective as r}from"../../lit/async-directive.js";import{repeat as n}from"../../lit/directives/repeat.js";import{Virtualizer as o}from"./Virtualizer.js";export{virtualizerRef}from"./Virtualizer.js";export const defaultKeyFunction=t=>t;export const defaultRenderItem=(i,e)=>t`${e}: ${JSON.stringify(i,null,2)}`;export const virtualize=e(class VirtualizeDirective extends r{constructor(t){if(super(t),this._virtualizer=null,this._first=0,this._last=-1,this._renderItem=(t,i)=>defaultRenderItem(t,i+this._first),this._keyFunction=(t,i)=>defaultKeyFunction(t,this._first),this._items=[],t.type!==s.CHILD)throw new Error("The virtualize directive can only be used in child expressions")}render(t){t&&this._setFunctions(t);const i=[];if(this._first>=0&&this._last>=this._first)for(let t=this._first;t<=this._last;t++)i.push(this._items[t]);return n(i,this._keyFunction,this._renderItem)}update(t,[e]){this._setFunctions(e);const s=this._items!==e.items;return this._items=e.items||[],this._virtualizer?this._updateVirtualizerConfig(t,e):this._initialize(t,e),s?i:this.render()}async _updateVirtualizerConfig(t,i){if(!await this._virtualizer.updateLayoutConfig(i.layout||{})){const e=t.parentNode;this._makeVirtualizer(e,i)}this._virtualizer.items=this._items}_setFunctions(t){const{renderItem:i,keyFunction:e}=t;i&&(this._renderItem=(t,e)=>i(t,e+this._first)),e&&(this._keyFunction=(t,i)=>e(t,i+this._first))}_makeVirtualizer(t,i){this._virtualizer&&this._virtualizer.disconnected();const{layout:e,scroller:s,items:r}=i;this._virtualizer=new o({hostElement:t,layout:e,scroller:s}),this._virtualizer.items=r,this._virtualizer.connected()}_initialize(t,i){const e=t.parentNode;e&&1===e.nodeType&&(e.addEventListener("rangeChanged",(t=>{this._first=t.first,this._last=t.last,this.setValue(this.render())})),this._makeVirtualizer(e,i))}disconnected(){this._virtualizer?.disconnected()}reconnected(){this._virtualizer?.connected()}});