aboutsummaryrefslogtreecommitdiff
path: root/src/runtime.ffi.mjs
blob: 45b05bfee8cc1128286d3c6ea8f591281d890925 (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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import { Empty } from "./gleam.mjs";
import { map as result_map } from "../gleam_stdlib/gleam/result.mjs";

export function morph(prev, curr, dispatch, parent) {
  if (curr[3]) {
    return prev?.nodeType === 1 &&
      prev.nodeName === curr[0].toUpperCase() &&
      prev.namespaceURI === curr[3]
      ? morphElement(prev, curr, curr[3], dispatch, parent)
      : createElement(prev, curr, curr[3], dispatch, parent);
  }

  if (curr[2]) {
    return prev?.nodeType === 1 && prev.nodeName === curr[0].toUpperCase()
      ? morphElement(prev, curr, null, dispatch, parent)
      : createElement(prev, curr, null, dispatch, parent);
  }

  if (typeof curr?.[0] === "string") {
    return prev?.nodeType === 3
      ? morphText(prev, curr)
      : createText(prev, curr);
  }

  return document.createComment(
    [
      "[internal lustre error] I couldn't work out how to render this element. This",
      "function should only be called internally by lustre's runtime: if you think",
      "this is an error, please open an issue at",
      "https://github.com/hayleigh-dot-dev/gleam-lustre/issues/new",
    ].join(" ")
  );
}

// ELEMENTS --------------------------------------------------------------------

function createElement(prev, curr, ns, dispatch, parent = null) {
  const el = ns
    ? document.createElementNS(ns, curr[0])
    : document.createElement(curr[0]);

  el.$lustre = {};

  let attr = curr[1];
  let dangerousUnescapedHtml = "";

  while (attr.head) {
    if (attr.head[0] === "class") {
      morphAttr(el, attr.head[0], `${el.className} ${attr.head[1]}`);
    } else if (attr.head[0] === "style") {
      morphAttr(el, attr.head[0], `${el.style.cssText} ${attr.head[1]}`);
    } else if (attr.head[0] === "dangerous-unescaped-html") {
      dangerousUnescapedHtml += attr.head[1];
    } else {
      morphAttr(el, attr.head[0], attr.head[1], dispatch);
    }

    attr = attr.tail;
  }

  if (customElements.get(curr[0])) {
    el._slot = curr[2];
  } else if (curr[0] === "slot") {
    let child = new Empty();
    let parentWithSlot = parent;

    while (parentWithSlot) {
      if (parentWithSlot._slot) {
        child = parentWithSlot._slot;
        break;
      } else {
        parentWithSlot = parentWithSlot.parentNode;
      }
    }

    while (child.head) {
      el.appendChild(morph(null, child.head, dispatch, el));
      child = child.tail;
    }
  } else if (dangerousUnescapedHtml) {
    el.innerHTML = dangerousUnescapedHtml;
  } else {
    let child = curr[2];
    while (child.head) {
      el.appendChild(morph(null, child.head, dispatch, el));
      child = child.tail;
    }
  }

  if (prev) prev.replaceWith(el);

  return el;
}

function morphElement(prev, curr, ns, dispatch, parent) {
  const prevAttrs = prev.attributes;
  const currAttrs = new Map();

  // This can happen if we're morphing an existing DOM element that *wasn't*
  // initially created by lustre.
  prev.$lustre ??= {};

  let currAttr = curr[1];
  while (currAttr.head) {
    if (currAttr.head[0] === "class" && currAttrs.has("class")) {
      currAttrs.set(
        currAttr.head[0],
        `${currAttrs.get("class")} ${currAttr.head[1]}`
      );
    } else if (currAttr.head[0] === "style" && currAttrs.has("style")) {
      currAttrs.set(
        currAttr.head[0],
        `${currAttrs.get("style")} ${currAttr.head[1]}`
      );
    } else if (
      currAttr.head[0] === "dangerous-unescaped-html" &&
      currAttrs.has("dangerous-unescaped-html")
    ) {
      currAttrs.set(
        currAttr.head[0],
        `${currAttrs.get("dangerous-unescaped-html")} ${currAttr.head[1]}`
      );
    } else {
      currAttrs.set(currAttr.head[0], currAttr.head[1]);
    }

    currAttr = currAttr.tail;
  }

  for (const { name, value: prevValue } of prevAttrs) {
    if (!currAttrs.has(name)) {
      prev.removeAttribute(name);
    } else {
      const value = currAttrs.get(name);

      if (value !== prevValue) {
        morphAttr(prev, name, value, dispatch);
        currAttrs.delete(name);
      }
    }
  }

  for (const [name, value] of currAttrs) {
    morphAttr(prev, name, value, dispatch);
  }

  if (customElements.get(curr[0])) {
    prev._slot = curr[2];
  } else if (curr[0] === "slot") {
    let prevChild = prev.firstChild;
    let currChild = new Empty();
    let parentWithSlot = parent;

    while (parentWithSlot) {
      if (parentWithSlot._slot) {
        currChild = parentWithSlot._slot;
        break;
      } else {
        parentWithSlot = parentWithSlot.parentNode;
      }
    }

    while (prevChild) {
      if (currChild.head) {
        morph(prevChild, currChild.head, dispatch, prev);
        currChild = currChild.tail;
      }

      prevChild = prevChild.nextSibling;
    }

    while (currChild.head) {
      prev.appendChild(morph(null, currChild.head, dispatch, prev));
      currChild = currChild.tail;
    }
  } else if (currAttrs.has("dangerous-unescaped-html")) {
    prev.innerHTML = currAttrs.get("dangerous-unescaped-html");
  } else {
    let prevChild = prev.firstChild;
    let currChild = curr[2];

    while (prevChild) {
      if (currChild.head) {
        const next = prevChild.nextSibling;
        morph(prevChild, currChild.head, dispatch, prev);
        currChild = currChild.tail;
        prevChild = next;
      } else {
        const next = prevChild.nextSibling;
        prevChild.remove();
        prevChild = next;
      }
    }

    while (currChild.head) {
      prev.appendChild(morph(null, currChild.head, dispatch, prev));
      currChild = currChild.tail;
    }
  }

  return prev;
}

// ATTRIBUTES ------------------------------------------------------------------

function morphAttr(el, name, value, dispatch) {
  switch (typeof value) {
    case "string":
      if (el.getAttribute(name) !== value) el.setAttribute(name, value);
      if (value === "") el.removeAttribute(name);
      if (name === "value" && el.value !== value) el.value = value;
      break;

    // Event listeners need to be handled slightly differently because we need
    // to be able to support custom events. We
    case name.startsWith("on") && "function": {
      if (el.$lustre[name] === value) break;

      const event = name.slice(2).toLowerCase();
      const handler = (e) => result_map(value(e), dispatch);

      if (el.$lustre[`${name}Handler`]) {
        el.removeEventListener(event, el.$lustre[`${name}Handler`]);
      }

      el.addEventListener(event, handler);

      el.$lustre[name] = value;
      el.$lustre[`${name}Handler`] = handler;

      break;
    }

    default:
      el[name] = value;
  }
}

// TEXT ------------------------------------------------------------------------

function createText(prev, curr) {
  const el = document.createTextNode(curr[0]);

  if (prev) prev.replaceWith(el);
  return el;
}

function morphText(prev, curr) {
  const prevValue = prev.nodeValue;
  const currValue = curr[0];

  if (!currValue) {
    prev?.remove();
    return null;
  }

  if (prevValue !== currValue) prev.nodeValue = currValue;

  return prev;
}