aboutsummaryrefslogtreecommitdiff
path: root/src/server-component.mjs
blob: 855ff9d6a14fd9fc585d0f95bc1d3b30e1d64f14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
// Note that this path is relative to the built Gleam project, not the source files
// in `src/`. This particular module is not used by the Lustre package itself, but
// is instead bundled and made available to package users in the `priv/` directory.
//
// It makes obvious sense to co-locate the source with the rest of the package
// source code, but if we use relative imports here the bundle will fail because
// `vdom.ffi.mjs` is importing things from the Gleam standard library and expects
// to be placed in the `build/dev/javascript/lustre/` directory.
//
import * as Constants from "../build/dev/javascript/lustre/lustre/internals/constants.mjs";
import { patch, morph } from "../build/dev/javascript/lustre/vdom.ffi.mjs";

export class LustreServerComponent extends HTMLElement {
  static get observedAttributes() {
    return ["route"];
  }

  #observer = null;
  #root = null;
  #socket = null;
  #shadow = null;
  #stylesOffset = 0;

  constructor() {
    super();

    this.#shadow = this.attachShadow({ mode: "closed" });
    this.#observer = new MutationObserver((mutations) => {
      const changed = [];

      for (const mutation of mutations) {
        if (mutation.type === "attributes") {
          const { attributeName: name, oldValue: prev } = mutation;
          const next = this.getAttribute(name);

          if (prev !== next) {
            try {
              changed.push([name, JSON.parse(next)]);
            } catch {
              changed.push([name, next]);
            }
          }
        }
      }

      if (changed.length) {
        this.#socket?.send(JSON.stringify([Constants.attrs, changed]));
      }
    });
  }

  connectedCallback() {
    for (const link of document.querySelectorAll("link")) {
      if (link.rel === "stylesheet") {
        this.#shadow.appendChild(link.cloneNode(true));
        this.#stylesOffset++;
      }
    }

    for (const style of document.querySelectorAll("style")) {
      this.#shadow.appendChild(style.cloneNode(true));
      this.#stylesOffset++;
    }

    this.#root = document.createElement("div");
    this.#shadow.appendChild(this.#root);
  }

  attributeChangedCallback(name, prev, next) {
    switch (name) {
      case "route": {
        if (!next) {
          this.#socket?.close();
          this.#socket = null;
        } else if (prev !== next) {
          const id = this.getAttribute("id");
          const route = next + (id ? `?id=${id}` : "");
          const protocol = window.location.protocol === "https:" ? "wss" : "ws";

          this.#socket?.close();
          this.#socket = new WebSocket(
            `${protocol}://${window.location.host}${route}`,
          );
          this.#socket.addEventListener("message", (message) =>
            this.messageReceivedCallback(message),
          );
        }
      }
    }
  }

  messageReceivedCallback({ data }) {
    const [kind, ...payload] = JSON.parse(data);

    switch (kind) {
      case Constants.diff:
        return this.diff(payload);

      case Constants.emit:
        return this.emit(payload);

      case Constants.init:
        return this.init(payload);
    }
  }

  init([attrs, vdom]) {
    const initial = [];

    for (const attr of attrs) {
      if (attr in this) {
        initial.push([attr, this[attr]]);
      } else if (this.hasAttribute(attr)) {
        initial.push([attr, this.getAttribute(attr)]);
      }

      Object.defineProperty(this, attr, {
        get() {
          return this[`_${attr}`] ?? this.getAttribute(attr);
        },
        set(value) {
          const prev = this[attr];

          if (typeof value === "string") {
            this.setAttribute(attr, value);
          } else {
            this[`_${attr}`] = value;
          }

          if (prev !== value) {
            this.#socket?.send(
              JSON.stringify([Constants.attrs, [[attr, value]]]),
            );
          }
        },
      });
    }

    this.#observer.observe(this, {
      attributeFilter: attrs,
      attributeOldValue: true,
      attributes: true,
      characterData: false,
      characterDataOldValue: false,
      childList: false,
      subtree: false,
    });

    this.morph(vdom);

    if (initial.length) {
      this.#socket?.send(JSON.stringify([Constants.attrs, initial]));
    }
  }

  morph(vdom) {
    this.#root = morph(this.#root, vdom, (handler) => (event) => {
      const data = JSON.parse(this.getAttribute("data-lustre-data") || "{}");
      const msg = handler(event);

      msg.data = merge(data, msg.data);

      this.#socket?.send(JSON.stringify([Constants.event, msg.tag, msg.data]));
    });
  }

  diff([diff]) {
    this.#root = patch(
      this.#root,
      diff,
      (handler) => (event) => {
        const msg = handler(event);
        this.#socket?.send(
          JSON.stringify([Constants.event, msg.tag, msg.data]),
        );
      },
      this.#stylesOffset,
    );
  }

  emit([event, data]) {
    this.dispatchEvent(new CustomEvent(event, { detail: data }));
  }

  disconnectedCallback() {
    this.#socket?.close();
  }

  get adoptedStyleSheets() {
    return this.#shadow.adoptedStyleSheets;
  }

  set adoptedStyleSheets(value) {
    this.#shadow.adoptedStyleSheets = value;
  }
}

window.customElements.define("lustre-server-component", LustreServerComponent);

// UTILS -----------------------------------------------------------------------

function merge(target, source) {
  for (const key in source) {
    if (source[key] instanceof Object)
      Object.assign(source[key], merge(target[key], source[key]));
  }

  Object.assign(target || {}, source);
  return target;
}