template.ts
Version:
A powerful, lightweight TypeScript template engine with reactive data binding, conditional rendering, loops, and events
122 lines (121 loc) • 3.17 kB
TypeScript
/**
* TemplateBinder - A lightweight TypeScript template engine
*
* Features:
* - Simple HTML templating with double curly braces {{ }}
* - Looping through arrays with @for directive
* - Dynamic attribute binding with @att:attributeName
* - Event handling with @on:eventName directive
* - Conditional rendering with @if directive
* - Support for nested templates and components
* - Efficient DOM updates - only changed parts are refreshed
*/
type StateValue = any;
type State = Record<string, StateValue>;
type RootElement = Element | ShadowRoot;
export declare class TemplateBinder {
private container;
private state;
private bindings;
private eventBindings;
private conditionalBindings;
private loopBindings;
private originalTemplate;
private stateProxy;
private transitionClass?;
autoUpdate: boolean;
constructor(selectorOrElement: string | RootElement, initialState?: State, transitionClass?: string);
/**
* Bind the template to the state
*/
bind(): void;
/**
* Update the DOM with current state
*/
update(withAnimation?: boolean): void;
/**
* Update elements hierarchically, respecting conditional rendering
*/
private updateHierarchically;
/**
* Check if an element is hidden by any parent with @if
*/
private isElementHiddenByParent;
/**
* Update a single loop binding
*/
private updateSingleLoop;
/**
* Get the state proxy for reactive updates
*/
getState(): State;
/**
* Set a state value
*/
setState(key: string, value: StateValue): void;
/**
* Process the template and extract bindings
*/
private processTemplate;
/**
* Process text bindings with {{ expression }}
*/
private processTextBindings;
/**
* Process attribute bindings @att:attributeName="expression"
*/
private processAttributeBindings;
/**
* Process event bindings @on:eventName="handler"
*/
private processEventBindings;
/**
* Process conditional rendering @if="condition"
*/
private processConditionals;
/**
* Process loops @for="itemsKey"
*/
private processLoops;
/**
* Render the template
*/
private render;
/**
* Create an element for a loop iteration
*/
private createLoopElement;
/**
* Evaluate an expression with the current state
*/
private evaluateExpression;
/**
* Evaluate an expression with a specific context
*/
private evaluateExpressionWithContext;
/**
* Evaluate a condition
*/
private evaluateCondition;
/**
* Evaluate a condition with a specific context
*/
private evaluateConditionWithContext;
/**
* Evaluate JavaScript code with a given context
*/
private evaluateCode;
/**
* Clear all bindings
*/
private clearBindings;
/**
* Apply transition effect to an element when its value updates
*/
private applyTransition;
/**
* Destroy the binder and clean up
*/
destroy(): void;
}
export default TemplateBinder;