File size: 5,092 Bytes
96bdf6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Window } from 'happy-dom';
import { act, type ReactNode } from 'react';
import { createRoot, type Root } from 'react-dom/client';

const clientDomGlobalNames = [
    'window',
    'document',
    'navigator',
    'location',
    'history',
    'Element',
    'HTMLElement',
    'HTMLButtonElement',
    'HTMLInputElement',
    'HTMLTextAreaElement',
    'Node',
    'NodeFilter',
    'DocumentFragment',
    'Event',
    'MouseEvent',
    'KeyboardEvent',
    'FocusEvent',
    'PointerEvent',
    'CustomEvent',
    'MutationObserver',
    'ResizeObserver',
    'getComputedStyle',
    'requestAnimationFrame',
    'cancelAnimationFrame',
    'IS_REACT_ACT_ENVIRONMENT'
] as const;

type ClientDomGlobalName = (typeof clientDomGlobalNames)[number];

type ClientDomRenderer = {
    container: HTMLDivElement;
    render: (node: ReactNode) => Promise<void>;
    click: (element: HTMLElement) => Promise<void>;
    cleanup: () => Promise<void>;
};

function setClientDomGlobals(window: Window): Map<ClientDomGlobalName, PropertyDescriptor | undefined> {
    const descriptors = new Map<ClientDomGlobalName, PropertyDescriptor | undefined>();
    const values: Record<ClientDomGlobalName, unknown> = {
        window,
        document: window.document,
        navigator: window.navigator,
        location: window.location,
        history: window.history,
        Element: window.Element,
        HTMLElement: window.HTMLElement,
        HTMLButtonElement: window.HTMLButtonElement,
        HTMLInputElement: window.HTMLInputElement,
        HTMLTextAreaElement: window.HTMLTextAreaElement,
        Node: window.Node,
        NodeFilter: window.NodeFilter,
        DocumentFragment: window.DocumentFragment,
        Event: window.Event,
        MouseEvent: window.MouseEvent,
        KeyboardEvent: window.KeyboardEvent,
        FocusEvent: window.FocusEvent,
        PointerEvent: window.PointerEvent,
        CustomEvent: window.CustomEvent,
        MutationObserver: window.MutationObserver,
        ResizeObserver: window.ResizeObserver,
        getComputedStyle: window.getComputedStyle.bind(window),
        requestAnimationFrame: window.requestAnimationFrame.bind(window),
        cancelAnimationFrame: window.cancelAnimationFrame.bind(window),
        IS_REACT_ACT_ENVIRONMENT: true
    };

    for (const name of clientDomGlobalNames) {
        descriptors.set(name, Object.getOwnPropertyDescriptor(globalThis, name));
        Object.defineProperty(globalThis, name, {
            configurable: true,
            writable: true,
            value: values[name]
        });
    }

    return descriptors;
}

function restoreClientDomGlobals(descriptors: Map<ClientDomGlobalName, PropertyDescriptor | undefined>) {
    for (const name of clientDomGlobalNames) {
        const descriptor = descriptors.get(name);
        if (descriptor) {
            Object.defineProperty(globalThis, name, descriptor);
        } else {
            Reflect.deleteProperty(globalThis, name);
        }
    }
}

function dispatchClientDomEvent(element: HTMLElement, event: unknown) {
    element.dispatchEvent(event as Event);
}

export async function renderInClientDom(node: ReactNode): Promise<ClientDomRenderer> {
    const window = new Window({ url: 'http://localhost' });
    const descriptors = setClientDomGlobals(window);
    const happyDomContainer = window.document.createElement('div');
    window.document.body.append(happyDomContainer);
    const container = happyDomContainer as unknown as HTMLDivElement;
    const root: Root = createRoot(container);
    let cleanedUp = false;

    const render = async (nextNode: ReactNode) => {
        await act(async () => {
            root.render(nextNode);
        });
    };

    const cleanup = async () => {
        if (cleanedUp) {
            return;
        }

        cleanedUp = true;
        try {
            await act(async () => {
                root.unmount();
            });
        } finally {
            container.remove();
            try {
                await window.happyDOM.close();
            } finally {
                restoreClientDomGlobals(descriptors);
            }
        }
    };

    try {
        await render(node);
    } catch (error) {
        await cleanup();
        throw error;
    }

    return {
        container,
        render,
        click: async (element) => {
            await act(async () => {
                dispatchClientDomEvent(
                    element,
                    new window.PointerEvent('pointerdown', { bubbles: true, button: 0, buttons: 1 })
                );
                dispatchClientDomEvent(
                    element,
                    new window.MouseEvent('mousedown', { bubbles: true, button: 0, buttons: 1 })
                );
                dispatchClientDomEvent(element, new window.MouseEvent('mouseup', { bubbles: true, button: 0 }));
                dispatchClientDomEvent(element, new window.PointerEvent('pointerup', { bubbles: true, button: 0 }));
                element.click();
            });
        },
        cleanup
    };
}