Skip to content

Instantly share code, notes, and snippets.

@matthewp
Last active October 17, 2021 15:52
Show Gist options
  • Save matthewp/92c4daa6588eaef484c6f389d20d5700 to your computer and use it in GitHub Desktop.
Save matthewp/92c4daa6588eaef484c6f389d20d5700 to your computer and use it in GitHub Desktop.
Haunted State Integration

These are a couple of examples of base class integrations with Haunted. These could be starting points for developing more full fledged mixins.

LitElement

The LitElement version can be used either as a base class, or as a mixin that takes a render function.

import { html } from 'lit-element';
import LitHauntedElement, { litHaunted } from './lit-haunted-element.js';
import { useState } from 'haunted';

class MyHooksElement extends LitHauntedElement {
  render() {
    const [count, setCount] = useState(0);
    
    return html`Count: ${count}`;
  }
}

// OR can be used like so:
const MyHooksElement2 = litHaunted(() => {
  const [count, setCount] = useState(0);
    
  return html`Count: ${count}`;
});

SkateJS

Another integration, this time with SkateJS and Preact.

import { useState } from 'haunted';
import SkateHauntedElement, { html } from './skate-haunted-element.js';

class MyElement extends SkateHauntedElement {
  render() {
    const [count, setCount] = useState(0);

    return html`
      <div>
        <p>A paragraph</p>
        <button type="button" onClick=${() => setCount(count + 1)}>Increment</button>
        
        <p><strong>Count:</strong> ${count}</p>
      </div>
    `;
  }
}

customElements.define('my-element', MyElement);
import { LitElement } from 'lit-element';
import { State } from 'haunted';
export default class LitHauntedElement extends LitElement {
constructor() {
super();
this.hauntedState = new State(() => this.requestUpdate(), this);
}
update(changedProperties) {
this.hauntedState.run(() => super.update(changedProperties));
this.hauntedState.runEffects();
}
}
export const litHaunted = (renderer) => {
return class extends LitHauntedElement {
render() {
return renderer.call(this, this);
}
}
};
import { withComponent } from 'skatejs';
import withPreact from '@skatejs/renderer-preact';
import htm from 'htm';
import { h } from 'preact';
import { State } from 'haunted';
export const html = htm.bind(h);
const Base = withComponent(withPreact());
export default class extends Base {
constructor() {
super();
this.hauntedState = new State(() => this.triggerUpdate(), this);
}
renderer(...args) {
this.hauntedState.run(() => super.renderer(...args));
this.hauntedState.runEffects();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment