element-vir
Version:
Heroic. Reactive. Declarative. Type safe. Web components without compromise.
65 lines (64 loc) • 2.18 kB
TypeScript
import { AsyncDirective, type ChildPart, type DirectiveResult, type PartInfo } from '../../lit-exports/all-lit-exports.js';
/**
* Implementation for {@link keyedCache}.
*
* @category Internal
*/
declare class KeyedCacheDirective extends AsyncDirective {
private readonly cache;
private currentKey;
constructor(partInfo: PartInfo);
/** Render the value. */
render(_key: PropertyKey, value: unknown): unknown[];
/** Update the template based on the cache key. */
update(containerPart: ChildPart, [key, value,]: [
PropertyKey,
unknown
]): unknown[];
/** Handle disconnection. */
disconnected(): void;
/** Handle reconnection. */
reconnected(): void;
/** Clear the cache. */
protected clearCache(): void;
}
/**
* Caches rendered DOM by a user-provided key. When the key changes, the current DOM is stored and
* the previously cached DOM for the new key is restored (if any). This preserves DOM state (such as
* typed input values) across key switches.
*
* Unlike `cache`, which distinguishes templates by their structure, `keyedCache` distinguishes them
* by an arbitrary key, allowing multiple instances of the same template to maintain independent DOM
* state.
*
* Note: cached DOM is stored in a `Map` keyed by the provided key. Entries are not automatically
* garbage collected, so avoid using dynamically generated keys that are never reused.
*
* @category Directives
* @example
*
* ```ts
* import {html, defineElement, keyedCache} from 'element-vir';
*
* const MyElement = defineElement()({
* tagName: 'my-element',
* stateInit: {
* activeTab: 'tab-a',
* },
* render({state}) {
* return html`
* <div>
* ${keyedCache(
* state.activeTab,
* html`
* <input placeholder="Type here..." />
* `,
* )}
* </div>
* `;
* },
* });
* ```
*/
export declare const keyedCache: (key: PropertyKey, value: unknown) => DirectiveResult<typeof KeyedCacheDirective>;
export type { KeyedCacheDirective };