board / client / test / harness / dom.mjs
  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
/**
 * The minimum browser surface board's modules touch at import time and in the
 * code paths the vectors cover: localStorage, IndexedDB (fake-indexeddb),
 * `document` (i18n's hydrateHtml runs at module load), `window`, `navigator`,
 * plus the sliver of `<canvas>` the text layout in app/canvas.ts measures with.
 *
 * Deliberately tiny and honest: every stub either behaves like the real thing
 * for the operations under test, or throws. A stub that silently returns
 * `undefined` where the browser returns data is how a fixture ends up encoding
 * the harness's bug (dev/docs/CLJS.md).
 *
 * Canon: chat/client/test/harness/dom.mjs, plus the pointer/canvas additions a
 * whiteboard needs.
 */
// Pinned before the first Date use: app/boards.ts's default board label goes
// through Intl (`fmtDate`), so an unpinned zone would make the fixtures depend
// on the machine that generated them.
process.env.TZ = "UTC";

import "fake-indexeddb/auto";

class MemStorage {
  constructor() {
    this._m = new Map();
  }
  get length() {
    return this._m.size;
  }
  key(i) {
    return [...this._m.keys()][i] ?? null;
  }
  getItem(k) {
    return this._m.has(String(k)) ? this._m.get(String(k)) : null;
  }
  setItem(k, v) {
    this._m.set(String(k), String(v));
  }
  removeItem(k) {
    this._m.delete(String(k));
  }
  clear() {
    this._m.clear();
  }
  snapshot() {
    return Object.fromEntries([...this._m.entries()].sort(([a], [b]) => (a < b ? -1 : 1)));
  }
}

/** Node's `querySelectorAll` needs to exist and return nothing (i18n hydrate). */
const emptyList = [];

function mkEl(tag = "div") {
  const el = {
    tagName: String(tag).toUpperCase(),
    lang: "en",
    hidden: false,
    className: "",
    textContent: "",
    innerHTML: "",
    value: "",
    title: "",
    type: "",
    placeholder: "",
    isContentEditable: false,
    contentEditable: "",
    children: [],
    style: {
      _p: {},
      setProperty(k, v) {
        this._p[k] = v;
      },
    },
    dataset: {},
    classList: {
      _s: new Set(),
      add(...c) {
        c.forEach((x) => this._s.add(x));
      },
      remove(...c) {
        c.forEach((x) => this._s.delete(x));
      },
      toggle(c, on) {
        if (on === undefined) this._s.has(c) ? this._s.delete(c) : this._s.add(c);
        else if (on) this._s.add(c);
        else this._s.delete(c);
      },
      contains(c) {
        return this._s.has(c);
      },
    },
    querySelectorAll: () => emptyList,
    querySelector: () => null,
    appendChild(x) {
      this.children.push(x);
      return x;
    },
    append(...xs) {
      xs.forEach((x) => this.children.push(x));
    },
    replaceChildren() {},
    insertBefore(x) {
      this.children.push(x);
      return x;
    },
    removeChild(x) {
      return x;
    },
    setAttribute() {},
    getAttribute: () => null,
    addEventListener() {},
    removeEventListener() {},
    remove() {},
    focus() {},
    select() {},
    click() {},
    setPointerCapture() {},
    releasePointerCapture() {},
    getBoundingClientRect: () => ({ left: 0, top: 0, right: 800, bottom: 600, width: 800, height: 600 }),
  };
  if (String(tag) === "canvas") {
    el.width = 0;
    el.height = 0;
    el.getContext = () => mkCtx();
    el.toBlob = (cb) => cb(null);
  }
  return el;
}

/**
 * A CanvasRenderingContext2D that records nothing and measures text as
 * 0.6 em/char. Text layout is the only place a measurement feeds a VALUE the
 * vectors record (layoutText's line breaks), so the metric must be a stated
 * constant rather than a platform font metric — otherwise the fixture would
 * encode whichever fonts the generating machine had.
 */
export function mkCtx() {
  const noop = () => {};
  return {
    font: "",
    fillStyle: "",
    strokeStyle: "",
    lineWidth: 1,
    lineCap: "",
    lineJoin: "",
    textAlign: "",
    textBaseline: "",
    globalAlpha: 1,
    measureText(s) {
      const m = /^(\d+(?:\.\d+)?)px/.exec(this.font);
      const size = m ? Number(m[1]) : 10;
      return { width: String(s).length * size * 0.6 };
    },
    setTransform: noop,
    save: noop,
    restore: noop,
    beginPath: noop,
    closePath: noop,
    moveTo: noop,
    lineTo: noop,
    quadraticCurveTo: noop,
    arcTo: noop,
    ellipse: noop,
    rect: noop,
    clip: noop,
    fill: noop,
    stroke: noop,
    fillRect: noop,
    strokeRect: noop,
    clearRect: noop,
    fillText: noop,
    drawImage: noop,
    setLineDash: noop,
  };
}

export const localStorageStub = new MemStorage();

export function installDom() {
  const g = globalThis;
  g.localStorage = localStorageStub;
  g.sessionStorage = new MemStorage();
  if (!g.document) {
    const docEl = mkEl("html");
    g.document = {
      documentElement: docEl,
      head: { appendChild() {} },
      body: mkEl("body"),
      title: "board",
      visibilityState: "visible",
      hasFocus: () => true,
      querySelectorAll: () => emptyList,
      querySelector: () => null,
      getElementById: () => null,
      createElement: (tag) => mkEl(tag),
      createDocumentFragment: () => mkEl("fragment"),
      createTextNode: (t) => ({ nodeValue: t }),
      createRange: () => ({ selectNodeContents() {}, collapse() {} }),
      execCommand() {},
      addEventListener() {},
      removeEventListener() {},
    };
  }
  if (!g.window) {
    g.window = g;
    g.window.addEventListener = () => {};
    g.window.removeEventListener = () => {};
    g.window.visualViewport = null;
    g.window.setTimeout = setTimeout;
    g.window.clearTimeout = clearTimeout;
    g.window.innerWidth = 800;
    g.window.innerHeight = 600;
    g.window.getSelection = () => null;
  }
  if (!g.navigator) g.navigator = {};
  if (!g.navigator.languages) {
    Object.defineProperty(g.navigator, "languages", { value: ["en-US", "en"], configurable: true });
  }
  if (!g.navigator.language) {
    Object.defineProperty(g.navigator, "language", { value: "en-US", configurable: true });
  }
  if (!g.matchMedia) g.matchMedia = () => ({ matches: false, addEventListener: () => {} });
  if (!g.devicePixelRatio) g.devicePixelRatio = 1;
  if (!g.requestAnimationFrame) g.requestAnimationFrame = (fn) => setTimeout(() => fn(0), 0);
  if (!g.ResizeObserver) g.ResizeObserver = class { observe() {} disconnect() {} };
  // node-forge (reached through helia -> auto-tls -> acme-client) does
  // `new URL(window.location.href)` at module init, so `href` must be a real
  // absolute URL — an incomplete location stub throws ERR_INVALID_URL and the
  // whole harness dies before a single fixture is written.
  if (!g.location) {
    g.location = {
      href: "https://board.ardegazu.ro/",
      origin: "https://board.ardegazu.ro",
      protocol: "https:",
      host: "board.ardegazu.ro",
      hostname: "board.ardegazu.ro",
      pathname: "/",
      search: "",
      hash: "",
      reload() {},
      replace() {},
    };
  }
  if (!g.history) g.history = { replaceState() {}, pushState() {} };
  return { localStorage: localStorageStub };
}

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/board.git