Spooky Ghost Haunted Docs Toggle darkmode

Hooks: useController

Reuse existing ReactiveControllers in your haunted component without adding @lit/reactive-element to your bundle.

import { component, html, useController, useEffect } from 'haunted'

import { MouseController } from './mouse-controller.js';

function TrackMouse(element) {
  const { pos, down } = useController(host => new MouseController(host));

  useEffect(() => {
    const x = pos.x - element.clientLeft;
    const y = pos.y - element.clientTop;
    if (x > element.clientWidth || y > element.clientHeight) return;
    const hue = Math.floor((x / element.clientWidth) * 360);
    const saturation = 100 - Math.floor((y / element.clientHeight) * 100);
    element.style.setProperty('--x', `${x}px`);
    element.style.setProperty('--y', `${y}px`);
    element.style.setProperty('--hue', hue);
    element.style.setProperty('--saturation', `${saturation}%`);
    element.style.setProperty('--loupe-border-color', down ? 'white' : 'black');
    if (down) {
      element.color = getComputedStyle(element.shadowRoot.getElementById('loupe')).getPropertyValue('background-color');
      element.shadowRoot.getElementById('alert').textContent = element.color;
      element.shadowRoot.getElementById('alert').setAttribute("aria-hidden", "false");
      element.dispatchEvent(new CustomEvent('pick'));
  }, [pos, down]);

  return html`
    <link rel="stylesheet" href="color-picker.css">
    <div id="loupe" role="button" aria-label="color picker"></div>
    <div id="alert" role="alert" aria-hidden="true"></div>

customElements.define('use-controller', component(TrackMouse));



Creates and stores a stateful ReactiveController instance and provides it with a ReactiveControllerHost that drives the controller lifecycle.

Use this hook to convert a ReactiveController into a Haunted hook.



<C extends ReactiveController>(host: ReactiveControllerHost) => C

A function that creates a controller instance. This function is given a HauntedControllerHost to pass to the controller. The create function is only called once per component.




import { useController } from 'haunted/lib/use-controller';