CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-stencil--core

A comprehensive web component compiler that transforms TypeScript and JSX code into standards-compliant web components with complete development toolchain.

75

1.44x
Overview
Eval results
Files

runtime-utilities.mddocs/

Runtime Utilities

Runtime functions for asset management, mode handling, task scheduling, and component utilities. These utilities provide essential runtime functionality for Stencil components and applications.

Capabilities

Asset Management

Functions for managing asset paths and resources in Stencil applications.

/**
 * Get the base path to where assets can be found
 * @param path - Asset path to resolve
 * @returns Full asset path with base URL
 */
function getAssetPath(path: string): string;

/**
 * Set the base path where assets can be found
 * @param path - Base asset path to set
 * @returns The set path
 */
function setAssetPath(path: string): string;

Usage Examples:

import { getAssetPath, setAssetPath } from '@stencil/core';

// Set asset path for custom elements build
setAssetPath(import.meta.url);

// Get asset path for use in component
export class MyComponent {
  render() {
    return (
      <div>
        <img src={getAssetPath('./assets/logo.png')} alt="Logo" />
      </div>
    );
  }
}

Mode Management

Functions for handling style modes and environment-specific styling.

/**
 * Get the current mode for style resolution
 * @param ref - Reference to get mode for
 * @returns Current mode or undefined
 */
function getMode<T = string | undefined>(ref: any): T;

/**
 * Set the mode resolution handler
 * @param handler - Function to resolve mode for elements
 */
function setMode(handler: ResolutionHandler): void;

type ResolutionHandler = (elm: HTMLElement) => string | undefined | null;

Usage Examples:

import { setMode, getMode } from '@stencil/core';

// Set mode resolver based on theme attribute
setMode((elm) => {
  return elm.closest('[theme]')?.getAttribute('theme') || 'default';
});

// Use mode in component
export class MyComponent {
  componentDidLoad() {
    const currentMode = getMode(this.el);
    console.log('Current mode:', currentMode);
  }
}

Build Conditionals

Constants for build-time feature detection and conditional compilation.

/**
 * Build-time conditionals for feature detection
 */
interface UserBuildConditionals {
  /** Whether running in development mode */
  isDev: boolean;
  /** Whether running in browser environment */
  isBrowser: boolean;
  /** Whether running in server environment */
  isServer: boolean;
  /** Whether running in testing environment */
  isTesting: boolean;
}

/**
 * Build conditionals object
 */
declare const Build: UserBuildConditionals;

/**
 * Environment variables from stencil.config.ts
 */
declare const Env: { [prop: string]: string | undefined };

Usage Examples:

import { Build, Env } from '@stencil/core';

export class MyComponent {
  componentDidLoad() {
    if (Build.isDev) {
      console.log('Development mode active');
    }
    
    if (Build.isBrowser) {
      // Browser-specific code
      window.addEventListener('resize', this.handleResize);
    }
    
    if (Build.isServer) {
      // Server-side rendering code
      this.setupSSRDefaults();
    }
    
    // Use environment variables
    const apiUrl = Env.API_URL || 'https://api.example.com';
  }
}

Task Scheduling

Functions for scheduling DOM read and write operations to optimize performance.

/**
 * Schedule a DOM-write task for optimal performance
 * @param task - Callback to execute during write phase
 */
function writeTask(task: RafCallback): void;

/**
 * Schedule a DOM-read task for optimal performance
 * @param task - Callback to execute during read phase
 */
function readTask(task: RafCallback): void;

interface RafCallback {
  (timeStamp: number): void;
}

/**
 * Task queue API for advanced scheduling
 */
interface QueueApi {
  /** Schedule a callback for next tick */
  tick: (cb: RafCallback) => void;
  /** Schedule a DOM read task */
  read: (cb: RafCallback) => void;
  /** Schedule a DOM write task */
  write: (cb: RafCallback) => void;
  /** Clear all queued tasks */
  clear?: () => void;
  /** Flush all queued tasks immediately */
  flush?: (cb?: () => void) => void;
}

Usage Examples:

import { writeTask, readTask } from '@stencil/core';

export class MyComponent {
  @Element() el: HTMLElement;
  
  updateLayout() {
    // First read DOM properties
    readTask(() => {
      const rect = this.el.getBoundingClientRect();
      const scrollTop = window.scrollY;
      
      // Then write DOM changes
      writeTask(() => {
        this.el.style.transform = `translateY(${scrollTop}px)`;
        this.el.style.width = `${rect.width}px`;
      });
    });
  }
  
  @Listen('scroll', { target: 'window' })
  handleScroll() {
    this.updateLayout();
  }
}

Component Utilities

Utilities for working with component instances and lifecycle management.

/**
 * Get Stencil element reference from any reference
 * @param ref - Reference to get element for
 * @returns HTMLStencilElement instance
 */
function getElement(ref: any): HTMLStencilElement;

/**
 * Force a component to re-render
 * @param ref - Component reference to force update
 */
function forceUpdate(ref: any): void;

/**
 * Get the current rendering reference
 * @returns Current rendering reference
 */
function getRenderingRef(): any;

/**
 * Enhanced HTML element with Stencil capabilities
 */
interface HTMLStencilElement extends HTMLElement {
  /** Promise that resolves when component is ready */
  componentOnReady(): Promise<HTMLStencilElement>;
}

Usage Examples:

import { getElement, forceUpdate } from '@stencil/core';

export class MyComponent {
  @Element() el: HTMLElement;
  private data: any[] = [];
  
  async componentDidLoad() {
    const stencilEl = getElement(this.el);
    await stencilEl.componentOnReady();
    console.log('Component is ready');
  }
  
  @Method()
  async updateData(newData: any[]) {
    this.data = newData;
    // Force re-render with new data
    forceUpdate(this);
  }
  
  @Method()
  async refresh() {
    // Force component to re-render
    forceUpdate(this.el);
  }
}

Platform Configuration

Functions for configuring platform-specific behavior and security settings.

/**
 * Set Content Security Policy nonce for dynamic styles and scripts
 * @param nonce - Nonce value for CSP
 */
function setNonce(nonce: string): void;

/**
 * Set global error handler for unhandled exceptions
 * @param handler - Error handler function
 */
function setErrorHandler(handler: ErrorHandler): void;

type ErrorHandler = (err: any, element?: HTMLElement) => void;

/**
 * Set platform-specific helper functions
 * @param helpers - Platform helper functions
 */
function setPlatformHelpers(helpers: PlatformHelpers): void;

interface PlatformHelpers {
  /** Jump function for task scheduling */
  jmp?: (c: any) => any;
  /** RequestAnimationFrame implementation */
  raf?: (c: any) => number;
  /** Add event listener implementation */
  ael?: (el: any, eventName: string, listener: any, options: any) => void;
  /** Remove event listener implementation */
  rel?: (el: any, eventName: string, listener: any, options: any) => void;
  /** Create custom event implementation */
  ce?: (eventName: string, opts?: any) => any;
}

Usage Examples:

import { setNonce, setErrorHandler, setPlatformHelpers } from '@stencil/core';

// Set CSP nonce for dynamic styles
setNonce('abc123xyz');

// Set global error handler
setErrorHandler((error, element) => {
  console.error('Stencil component error:', error);
  if (element) {
    console.error('Error occurred in element:', element.tagName);
  }
  
  // Send to error reporting service
  errorReportingService.report(error, {
    component: element?.tagName,
    url: window.location.href
  });
});

// Set custom platform helpers for non-standard environments
setPlatformHelpers({
  raf: (callback) => {
    // Custom RAF implementation for non-browser environments
    return customScheduler.schedule(callback);
  },
  ael: (el, eventName, listener, options) => {
    // Custom event listener implementation
    customEventSystem.addEventListener(el, eventName, listener, options);
  }
});

Virtual DOM Utilities

The render function for manually rendering virtual DOM trees.

/**
 * Render a virtual DOM tree to a container element
 * @param vnode - Virtual DOM tree to render
 * @param container - Container element to render into
 */
function render(vnode: VNode, container: Element): void;

Usage Example:

import { render, h } from '@stencil/core';

// Render virtual DOM tree to specific container
const vnode = (
  <div>
    <h1>Hello, World!</h1>
    <p>This is rendered with the render function</p>
  </div>
);

const container = document.getElementById('app');
render(vnode, container);

// Or using h() function directly
const vnodeWithH = h('div', null, [
  h('h1', null, 'Hello, World!'),
  h('p', null, 'This is rendered with h() and render()')
]);

render(vnodeWithH, container);

Performance Utilities

Utilities for performance monitoring and optimization.

/**
 * Performance monitoring for component operations
 */
interface PerformanceEntry {
  name: string;
  startTime: number;
  duration: number;
}

/**
 * Custom elements define options for performance tuning
 */
interface CustomElementsDefineOptions {
  /** Components to exclude from definition */
  exclude?: string[];
  /** Resources URL for assets */
  resourcesUrl?: string;
  /** Use synchronous queue for updates */
  syncQueue?: boolean;
  /** Transform tag names during definition */
  transformTagName?: (tagName: string) => string;
  /** Custom jump function */
  jmp?: (c: Function) => any;
  /** Custom RAF function */
  raf?: (c: FrameRequestCallback) => number;
  /** Custom add event listener */
  ael?: (
    el: EventTarget,
    eventName: string,
    listener: EventListenerOrEventListenerObject,
    options: boolean | AddEventListenerOptions,
  ) => void;
  /** Custom remove event listener */
  rel?: (
    el: EventTarget,
    eventName: string,
    listener: EventListenerOrEventListenerObject,
    options: boolean | AddEventListenerOptions,
  ) => void;
  /** Custom create event */
  ce?: (eventName: string, opts?: any) => CustomEvent;
}

Usage Example:

// Custom elements definition with performance options
const defineOptions: CustomElementsDefineOptions = {
  // Exclude certain components from auto-definition
  exclude: ['my-heavy-component'],
  
  // Use synchronous queue for immediate updates
  syncQueue: true,
  
  // Transform tag names for compatibility
  transformTagName: (tagName) => {
    return tagName.replace(/^my-/, 'custom-');
  }
};

Install with Tessl CLI

npx tessl i tessl/npm-stencil--core

docs

build-configuration.md

compiler-api.md

component-development.md

development-server.md

index.md

runtime-utilities.md

testing-utilities.md

tile.json