Skip to content

poc HookedWebComponent#4137

Draft
SteffenDE wants to merge 1 commit intomainfrom
sd-web-component-class
Draft

poc HookedWebComponent#4137
SteffenDE wants to merge 1 commit intomainfrom
sd-web-component-class

Conversation

@SteffenDE
Copy link
Copy Markdown
Collaborator

I'm not sure how useful this is, but if someone is using web components through classes, this could be a nice abstraction over createHook. Example for Lit:

import { LitElement, html, css } from "lit";
import { customElement, property } from "lit/decorators.js";
import { HookedWebComponent } from "phoenix_live_view";

// Create a base class that combines LitElement with the hook functionality
const HookedLitElement = HookedWebComponent(LitElement);

@customElement("my-counter")
export class MyCounter extends HookedLitElement {

  @property({ type: Number })
  count = 0;

  static styles = css`
    :host {
      display: block;
      padding: 16px;
      border: 2px solid #4f46e5;
      border-radius: 8px;
      font-family: system-ui, sans-serif;
    }
    .counter {
      display: flex;
      align-items: center;
      gap: 16px;
    }
    button {
      padding: 8px 16px;
      font-size: 18px;
      cursor: pointer;
      background: #4f46e5;
      color: white;
      border: none;
      border-radius: 4px;
    }
    button:hover {
      background: #4338ca;
    }
    .value {
      font-size: 24px;
      font-weight: bold;
      min-width: 60px;
      text-align: center;
    }
  `;

  mounted() {
    console.log("MyCounter mounted! Hook is ready:", this.hook);
  }

  updated() {
    console.log("MyCounter updated by LiveView patch");
  }

  private increment() {
    this.count += 1;
    this.hook.pushEvent("increment", {});
  }

  private decrement() {
    this.count -= 1;
    this.hook.pushEvent("decrement", {});
  }

  render() {
    return html`
      <div class="counter">
        <button @click=${this.decrement}>-</button>
        <span class="value">${this.count}</span>
        <button @click=${this.increment}>+</button>
      </div>
    `;
  }
}

@SteffenDE
Copy link
Copy Markdown
Collaborator Author

(Note that the code does not rely on any private LiveView API, so if someone wants to use this, feel free to just copy it!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant