CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-microsoft--fast-element

A library for constructing Web Components

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

html-templates.mddocs/

HTML Templates

Template system using tagged template literals with efficient compilation, directive support, and reactive binding capabilities for building dynamic HTML content.

Capabilities

HTML Template Tag

Tagged template literal function for creating reactive HTML templates with binding expressions and directives.

/**
 * Transforms a template literal string into a ViewTemplate
 * @param strings - The string fragments that are interpolated with the values
 * @param values - The values that are interpolated with the string fragments
 * @returns A ViewTemplate instance
 */
function html<TSource = any, TParent = any>(
  strings: TemplateStringsArray,
  ...values: TemplateValue<TSource, TParent>[]
): ViewTemplate<TSource, TParent>;

/**
 * Template tag interface with additional utilities
 */
interface HTMLTemplateTag {
  <TSource = any, TParent = any>(
    strings: TemplateStringsArray,
    ...values: TemplateValue<TSource, TParent>[]
  ): ViewTemplate<TSource, TParent>;
  
  /** Creates partial HTML directive for template composition */
  partial(html: string): InlineTemplateDirective;
}

/**
 * Types that can be interpolated into templates
 */
type TemplateValue<TSource, TParent = any> =
  | Expression<TSource, any, TParent>
  | Binding<TSource, any, TParent>
  | HTMLDirective
  | CaptureType<TSource, TParent>;

Usage Examples:

import { FASTElement, customElement, html, attr } from "@microsoft/fast-element";

// Basic template with bindings
const template = html<MyElement>`
  <div class="container">
    <h1>${x => x.title}</h1>
    <p>${x => x.description}</p>
    <button @click="${x => x.handleClick}">
      ${x => x.buttonText}
    </button>
  </div>
`;

// Template with conditional content
const conditionalTemplate = html<UserCard>`
  <div class="user-card">
    <h2>${x => x.name}</h2>
    ${x => x.showEmail ? html`<p>${x => x.email}</p>` : ""}
    ${x => x.avatar ? html`<img src="${x => x.avatar}" alt="Avatar">` : ""}
  </div>
`;

// Template composition with partials
const headerPartial = html.partial(`
  <header class="app-header">
    <nav>Navigation</nav>
  </header>
`);

const mainTemplate = html`
  ${headerPartial}
  <main>
    <slot></slot>
  </main>
`;

@customElement({
  name: "my-element",
  template
})
export class MyElement extends FASTElement {
  @attr title: string = "Hello World";
  @attr description: string = "A sample element";
  @attr buttonText: string = "Click me";
  
  handleClick() {
    console.log("Button clicked!");
  }
}

ViewTemplate Class

Core template class that manages HTML content, compilation, and view creation with support for both element and synthetic views.

/**
 * A template capable of creating HTMLView instances or rendering directly to DOM
 */
class ViewTemplate<TSource = any, TParent = any> 
  implements ElementViewTemplate<TSource, TParent>, SyntheticViewTemplate<TSource, TParent> {
  
  /** The html representing what this template will instantiate */
  readonly html: string | HTMLTemplateElement;
  
  /** The directives that will be connected to placeholders in the html */
  readonly factories: Record<string, ViewBehaviorFactory>;
  
  /**
   * Creates an instance of ViewTemplate
   * @param html - The html string or template element
   * @param factories - The directive factories
   * @param policy - The security policy for compilation
   */
  constructor(
    html: string | HTMLTemplateElement,
    factories?: Record<string, ViewBehaviorFactory>,
    policy?: DOMPolicy
  );
  
  /** Creates an HTMLView instance based on this template definition */
  create(hostBindingTarget?: Element): HTMLView<TSource, TParent>;
  
  /** Returns a directive that can inline the template */
  inline(): CaptureType<TSource, TParent>;
  
  /**
   * Sets the DOMPolicy for this template
   * @param policy - The policy to associate with this template
   * @returns The modified template instance
   */
  withPolicy(policy: DOMPolicy): this;
  
  /**
   * Creates an HTMLView from this template, binds it to the source, and appends it to the host
   * @param source - The data source to bind the template to
   * @param host - The Element where the template will be rendered
   * @param hostBindingTarget - An HTML element to target the host bindings at
   */
  render(
    source: TSource,
    host: Node,
    hostBindingTarget?: Element
  ): HTMLView<TSource, TParent>;
  
  /**
   * Creates a template based on static strings and dynamic values
   * @param strings - The static strings to create the template with
   * @param values - The dynamic values to create the template with
   * @param policy - The DOMPolicy to associate with the template
   * @returns A ViewTemplate
   */
  static create<TSource = any, TParent = any>(
    strings: string[],
    values: TemplateValue<TSource, TParent>[],
    policy?: DOMPolicy
  ): ViewTemplate<TSource, TParent>;
}

Usage Examples:

import { ViewTemplate, html, DOMPolicy } from "@microsoft/fast-element";

// Create template manually
const manualTemplate = new ViewTemplate(
  `<div class="manual">\${0}</div>`,
  {
    "0": /* factory */
  }
);

// Create with security policy
const secureTemplate = html`
  <div innerHTML="${x => x.userContent}"></div>
`.withPolicy(myDOMPolicy);

// Render template directly
const view = template.render(
  { title: "Hello", content: "World" },
  document.body
);

// Create reusable view
const reusableView = template.create();
reusableView.bind({ title: "Dynamic" });
reusableView.appendTo(container);

// Template composition
const childTemplate = html`<span>${x => x.text}</span>`;
const parentTemplate = html`
  <div class="parent">
    ${childTemplate.inline()}
  </div>
`;

Element View Template

Specialized template interface for custom elements with host binding support and element-specific rendering capabilities.

/**
 * A template capable of creating views specifically for rendering custom elements
 */
interface ElementViewTemplate<TSource = any, TParent = any> {
  /**
   * Creates an ElementView instance based on this template definition
   * @param hostBindingTarget - The element that host behaviors will be bound to
   */
  create(hostBindingTarget: Element): ElementView<TSource, TParent>;

  /**
   * Creates an HTMLView from this template, binds it to the source, and appends it to the host
   * @param source - The data source to bind the template to
   * @param host - The Node where the template will be rendered
   * @param hostBindingTarget - An HTML element to target the host bindings at
   */
  render(
    source: TSource,
    host: Node,
    hostBindingTarget?: Element
  ): ElementView<TSource, TParent>;
}

/**
 * Hydratable version of element view template for SSR scenarios
 */
interface HydratableElementViewTemplate<TSource = any, TParent = any>
  extends ElementViewTemplate<TSource, TParent> {
  /**
   * Hydrates an element view from server-rendered content
   * @param firstChild - First child node of the hydration range
   * @param lastChild - Last child node of the hydration range  
   * @param hostBindingTarget - The element that host behaviors will be bound to
   */
  hydrate(
    firstChild: Node,
    lastChild: Node,
    hostBindingTarget?: Element
  ): ElementView<TSource, TParent>;
}

Synthetic View Template

Template interface for creating views not connected to custom elements, useful for dynamic content and template fragments.

/**
 * A template capable of rendering views not specifically connected to custom elements
 */
interface SyntheticViewTemplate<TSource = any, TParent = any> {
  /** Creates a SyntheticView instance based on this template definition */
  create(): SyntheticView<TSource, TParent>;

  /** Returns a directive that can inline the template */
  inline(): CaptureType<TSource, TParent>;
}

/**
 * Hydratable version of synthetic view template for SSR scenarios
 */
interface HydratableSyntheticViewTemplate<TSource = any, TParent = any>
  extends SyntheticViewTemplate {
  /**
   * Hydrates a synthetic view from server-rendered content
   * @param firstChild - First child node of the hydration range
   * @param lastChild - Last child node of the hydration range
   */
  hydrate(firstChild: Node, lastChild: Node): SyntheticView<TSource, TParent>;
}

Usage Examples:

import { html, SyntheticViewTemplate } from "@microsoft/fast-element";

// Synthetic template for dynamic content
const dynamicContent: SyntheticViewTemplate<DataItem> = html`
  <div class="dynamic-item">
    <h3>${x => x.title}</h3>
    <p>${x => x.description}</p>
  </div>
`;

// Create and use synthetic view
const syntheticView = dynamicContent.create();
syntheticView.bind(dataItem);
syntheticView.appendTo(container);

// Inline synthetic template
const listTemplate = html`
  <ul class="item-list">
    ${repeat(x => x.items, dynamicContent.inline())}
  </ul>
`;

Template Compilation System

System for compiling templates into efficient view factories with directive resolution and binding optimization.

/**
 * The result of a template compilation operation
 */
interface HTMLTemplateCompilationResult<TSource = any, TParent = any> {
  /**
   * Creates a view instance
   * @param hostBindingTarget - The host binding target for the view
   */
  createView(hostBindingTarget?: Element): HTMLView<TSource, TParent>;

  /** Compiled view behavior factories */
  readonly factories: CompiledViewBehaviorFactory[];
}

/**
 * Strategy for compiling templates
 */
interface CompilationStrategy {
  /**
   * Compiles a template
   * @param template - The template to compile
   * @param factories - The directive factories
   * @param policy - The DOM security policy
   */
  compile<TSource = any, TParent = any>(
    template: string | HTMLTemplateElement,
    factories: Record<string, ViewBehaviorFactory>,
    policy?: DOMPolicy
  ): HTMLTemplateCompilationResult<TSource, TParent>;
}

/**
 * Template compiler utilities
 */
const Compiler: {
  /**
   * Compiles a template into a compilation result
   * @param html - The HTML template string or element
   * @param factories - The directive factories
   * @param policy - The DOM security policy
   */
  compile<TSource = any, TParent = any>(
    html: string | HTMLTemplateElement,
    factories: Record<string, ViewBehaviorFactory>,
    policy?: DOMPolicy
  ): HTMLTemplateCompilationResult<TSource, TParent>;
};

Usage Examples:

import { Compiler, html, ViewTemplate } from "@microsoft/fast-element";

// Manual compilation
const result = Compiler.compile(
  '<div>${0}</div>',
  { "0": bindingFactory },
  domPolicy
);

// Create view from compilation result
const view = result.createView();
view.bind(source);

// Custom compilation strategy
class MyCompilationStrategy implements CompilationStrategy {
  compile(template, factories, policy) {
    // Custom compilation logic
    return Compiler.compile(template, factories, policy);
  }
}

Inline Template Directive

Directive for composing templates by inlining HTML content with associated behavior factories.

/**
 * Inlines a template into another template
 */
class InlineTemplateDirective implements HTMLDirective {
  /** An empty template partial */
  static readonly empty: InlineTemplateDirective;
  
  /**
   * Creates an instance of InlineTemplateDirective
   * @param html - The HTML template string to inline
   * @param factories - The behavior factories associated with the template
   */
  constructor(
    html: string,
    factories?: Record<string, ViewBehaviorFactory>
  );
  
  /**
   * Creates HTML to be used within a template
   * @param add - Can be used to add behavior factories to a template
   */
  createHTML(add: AddViewBehaviorFactory): string;
}

Usage Examples:

import { html, InlineTemplateDirective } from "@microsoft/fast-element";

// Create partial template
const buttonPartial = html.partial(`
  <button class="btn" type="button">
    <slot></slot>
  </button>
`);

// Use partial in main template
const formTemplate = html`
  <form>
    <input type="text" placeholder="Enter text">
    ${buttonPartial}
  </form>
`;

// Manual inline directive
const customInline = new InlineTemplateDirective(
  `<div class="custom">\${0}</div>`,
  { "0": someFactory }
);

const containerTemplate = html`
  <section>
    ${customInline}
  </section>
`;

Markup Parsing

Utilities for parsing and processing HTML markup during template compilation.

/**
 * Markup parsing and processing utilities
 */
const Markup: {
  /** Interpolation start marker */
  interpolationStart: string;
  
  /** Interpolation end marker */
  interpolationEnd: string;
  
  /**
   * Creates a placeholder for directive interpolation
   * @param index - The interpolation index
   */
  createPlaceholder(index: number): string;
};

/**
 * Template parser utilities
 */
const Parser: {
  /**
   * Parses template markup
   * @param html - The HTML template string
   * @param factories - The directive factories
   */
  parse(
    html: string,
    factories: Record<string, ViewBehaviorFactory>
  ): DocumentFragment;
};

Types

/**
 * Marker interface for capturing template types
 */
interface CaptureType<TSource, TParent> {}

/**
 * Template options for compilation behavior
 */
interface TemplateOptions {
  /** Template compilation strategy */
  strategy?: CompilationStrategy;
}

/**
 * View behavior factory interface
 */
interface ViewBehaviorFactory {
  /** Unique identifier for the factory */
  id?: string;
  
  /**
   * Creates a view behavior
   * @param targets - The targets for the behavior
   */
  createBehavior(targets: ViewBehaviorTargets): ViewBehavior;
}

/**
 * Compiled view behavior factory with additional metadata
 */
interface CompiledViewBehaviorFactory extends ViewBehaviorFactory {
  /** Target node ID in the compiled template */
  targetNodeId?: string;
  
  /** Target tag name */
  targetTagName?: string | null;
}

docs

attributes.md

context-system.md

css-styling.md

data-binding.md

dependency-injection.md

html-templates.md

index.md

observable-system.md

ssr-hydration.md

state-management.md

template-directives.md

testing-utilities.md

utilities.md

web-components.md

tile.json