social-kit / test / helpers / fake-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
/**
 * Minimal DOM stub for the chip/toast/sheet smoke tests (test/dom.test.mjs) —
 * just enough surface for the kit's DOM glue: createElement, appendChild,
 * remove, classList, addEventListener + a manual dispatch, setAttribute, and
 * a tiny innerHTML parser + querySelector that understand exactly the flat
 * markup the kit renders (tags with class attributes, no text nodes). Not a
 * DOM; a tripwire for advanced-rename breakage in the DOM paths the vector
 * suite can't reach.
 */

const VOID_TAGS = new Set(["input", "br", "img"]);

export class FakeElement {
  constructor(tagName) {
    this.tagName = tagName.toUpperCase();
    this.children = [];
    this.parent = null;
    this.className = "";
    this.textContent = "";
    this.title = "";
    this.attrs = {};
    this.listeners = new Map();
    this.value = "";
    this.placeholder = "";
    this.disabled = false;
    this.type = "";
    this.href = "";
    const self = this;
    this.classList = {
      toggle(cls, on) {
        const has = self.classNames().includes(cls);
        const want = on === undefined ? !has : !!on;
        const list = self.classNames().filter((c) => c !== cls);
        if (want) list.push(cls);
        self.className = list.join(" ");
        return want;
      },
      add(cls) {
        this.toggle(cls, true);
      },
      contains(cls) {
        return self.classNames().includes(cls);
      },
    };
  }

  classNames() {
    return this.className.split(/\s+/).filter((c) => c.length > 0);
  }

  set innerHTML(markup) {
    this.children = [];
    const re = /<(\/?)([a-zA-Z0-9]+)((?:\s+[a-zA-Z-]+(?:="[^"]*")?)*)\s*\/?>/g;
    const stack = [this];
    let m;
    while ((m = re.exec(markup)) !== null) {
      const [, closing, rawTag, rawAttrs] = m;
      const tag = rawTag.toLowerCase();
      if (closing) {
        if (stack.length > 1) stack.pop();
        continue;
      }
      const el = new FakeElement(tag);
      for (const am of rawAttrs.matchAll(/([a-zA-Z-]+)(?:="([^"]*)")?/g)) {
        const [, name, value] = am;
        if (name === "class") el.className = value ?? "";
        else if (name === "type") el.type = value ?? "";
        else el.attrs[name] = value ?? "";
      }
      stack[stack.length - 1].appendChild(el);
      if (!VOID_TAGS.has(tag)) stack.push(el);
    }
  }

  get innerHTML() {
    return this.children.map((c) => `<${c.tagName.toLowerCase()}>`).join("");
  }

  appendChild(el) {
    if (el.parent) el.remove();
    el.parent = this;
    this.children.push(el);
    return el;
  }

  remove() {
    if (this.parent) {
      this.parent.children = this.parent.children.filter((c) => c !== this);
      this.parent = null;
    }
  }

  addEventListener(type, cb) {
    if (!this.listeners.has(type)) this.listeners.set(type, []);
    this.listeners.get(type).push(cb);
  }

  removeEventListener(type, cb) {
    const l = this.listeners.get(type);
    if (l) this.listeners.set(type, l.filter((x) => x !== cb));
  }

  /** Test helper: fire an event at this element (no bubbling). */
  dispatch(type, evt = {}) {
    for (const cb of this.listeners.get(type) ?? []) cb({ target: this, ...evt });
  }

  setAttribute(name, value) {
    this.attrs[name] = String(value);
  }

  getAttribute(name) {
    return this.attrs[name] ?? null;
  }

  focus() {}

  matches(selector) {
    const m = selector.match(/^([a-zA-Z0-9]*)((?:\.[A-Za-z0-9_-]+)*)$/);
    if (!m) return false;
    const [, tag, classPart] = m;
    if (tag && this.tagName !== tag.toUpperCase()) return false;
    const classes = classPart.split(".").filter((c) => c.length > 0);
    return classes.every((c) => this.classNames().includes(c));
  }

  querySelector(selector) {
    for (const el of this.walk()) {
      if (el.matches(selector)) return el;
    }
    return null;
  }

  querySelectorAll(selector) {
    return [...this.walk()].filter((el) => el.matches(selector));
  }

  *walk() {
    for (const c of this.children) {
      yield c;
      yield* c.walk();
    }
  }
}

/** Install window/document/navigator/localStorage/fetch/location stubs. */
export function installFakeDom() {
  const document = {
    head: new FakeElement("head"),
    body: new FakeElement("body"),
    visibilityState: "visible",
    createElement: (tag) => new FakeElement(tag),
    querySelector(selector) {
      return this.head.querySelector(selector) ?? this.body.querySelector(selector);
    },
    addEventListener() {},
    removeEventListener() {},
  };
  const timers = [];
  const window = {
    setTimeout: (fn, ms) => {
      const t = setTimeout(fn, ms);
      t.unref?.();
      timers.push(t);
      return t;
    },
    setInterval: (fn, ms) => {
      const t = setInterval(fn, ms);
      t.unref?.();
      timers.push(t);
      return t;
    },
    clearTimeout,
    clearInterval,
    addEventListener() {},
    removeEventListener() {},
  };
  const location = {
    href: "https://game1.ardegazu.ro/#room",
    host: "game1.ardegazu.ro",
    hash: "#room",
    reloaded: 0,
    reload() {
      this.reloaded++;
    },
  };
  const store = new Map();
  const localStorage = {
    getItem: (k) => (store.has(k) ? store.get(k) : null),
    setItem: (k, v) => void store.set(k, String(v)),
    removeItem: (k) => void store.delete(k),
  };
  const navigator = {}; // no share, no clipboard — the fallback paths
  const fetch = () => Promise.reject(new Error("offline test env"));

  // defineProperty: some of these exist on globalThis as getter-only accessors
  for (const [name, value] of Object.entries({ document, window, location, localStorage, navigator, fetch })) {
    Object.defineProperty(globalThis, name, { value, configurable: true, writable: true });
  }
  return { document, window, location, localStorage, navigator, timers };
}

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/social-kit.git