-
Notifications
You must be signed in to change notification settings - Fork 43
/
app-controller.ts
333 lines (312 loc) · 9.42 KB
/
app-controller.ts
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
/// <reference types="@previewjs/iframe/preview/window" />
import type { Preview, Workspace } from "@previewjs/core";
import fs from "fs-extra";
import path from "path";
import type playwright from "playwright";
export class AppController {
private preview: Preview | null = null;
constructor(
private readonly page: playwright.Page,
private readonly workspace: Workspace,
readonly port: number
) {}
async start() {
this.preview = await this.workspace.preview.start(async () => this.port);
}
async stop() {
await this.preview?.stop();
this.preview = null;
}
async waitForIdle() {
await this.page.waitForLoadState("networkidle");
try {
await (await this.previewIframe()).waitForLoadState("networkidle");
} catch (e) {
// It's OK for the iframe to be replace by another one, in which case wait again.
await (await this.previewIframe()).waitForLoadState("networkidle");
}
}
previewIframe = async () => {
let iframe: playwright.ElementHandle<Element> | null = null;
let frame: playwright.Frame | null = null;
while (!frame) {
iframe = await this.page.waitForSelector("iframe", {
state: "attached",
});
if (iframe) {
frame = await iframe.contentFrame();
}
}
return frame;
};
async onBeforeFileUpdated() {
try {
const iframe = await this.page.$("iframe");
if (!iframe) {
// No iframe yet, so no need to expect anything to change.
return;
}
} catch (e) {
// Ignore, most likely due to whole-page refresh.
return;
}
const frame = await this.previewIframe();
await frame.$eval("body", () => {
return window.__expectFutureRefresh__();
});
}
async waitForExpectedIframeRefresh() {
const frame = await this.previewIframe();
try {
await frame.$eval("body", async () => {
// It's possible that __waitForExpectedRefresh__ isn't ready yet.
let waitStart = Date.now();
while (
!window.__waitForExpectedRefresh__ &&
Date.now() - waitStart < 5000
) {
await new Promise((resolve) => setTimeout(resolve, 100));
}
return window.__waitForExpectedRefresh__();
});
} catch (e: any) {
if (
e.message.includes(
"Execution context was destroyed, most likely because of a navigation"
)
) {
await this.waitForExpectedIframeRefresh();
} else {
throw e;
}
}
}
async show(componentId: string, options: { expectMissing?: boolean } = {}) {
if (!this.preview) {
throw new Error(`Preview server is not started.`);
}
const filePath = componentId.split(":")[0]!;
const detectedComponents =
await this.workspace.frameworkPlugin.detectComponents(
this.workspace.typeAnalyzer,
[path.join(this.workspace.rootDirPath, filePath)]
);
const matchingDetectedComponent = detectedComponents.find(
(c) =>
componentId ===
`${path
.relative(this.workspace.rootDirPath, c.absoluteFilePath)
.replace(/\\/g, "/")}:${c.name}`
);
if (!matchingDetectedComponent && !options.expectMissing) {
throw new Error(
`Component may be previewable but was not detected by framework plugin: ${componentId}`
);
}
const previewBaseUrl = this.preview.url();
const url = `${previewBaseUrl}?p=${encodeURIComponent(componentId)}`;
if (this.page.url().startsWith(previewBaseUrl)) {
// Soft refresh.
await this.page.evaluate((componentId: string) => {
// @ts-ignore
window.__previewjs_navigate(componentId);
}, componentId);
} else {
// Hard refresh.
await this.page.goto(url);
}
}
async takeScreenshot(preview: playwright.Frame, destinationPath: string) {
preview.addStyleTag({
content: `
*,
*::after,
*::before {
transition-delay: 0s !important;
transition-duration: 0s !important;
animation-delay: -0.0001s !important;
animation-duration: 0s !important;
animation-play-state: paused !important;
caret-color: transparent !important;
color-adjust: exact !important;
}
`,
});
// Ensure all images are loaded.
// Source: https://stackoverflow.com/a/49233383
await preview.evaluate(async () => {
const selectors = Array.from(document.querySelectorAll("img"));
await Promise.all(
selectors.map((img) => {
if (img.complete) {
return;
}
return new Promise<unknown>((resolve) => {
const observer = new IntersectionObserver((entries) => {
if (entries[0]?.isIntersecting) {
img.addEventListener("load", resolve);
// If an image fails to load, ignore it.
img.addEventListener("error", resolve);
} else {
resolve(null);
}
observer.unobserve(img);
});
observer.observe(img);
});
})
);
});
const destinationDirPath = path.dirname(destinationPath);
await fs.mkdirp(destinationDirPath);
await this.waitForIdle();
await this.page.screenshot({
path: destinationPath,
});
}
noSelection = this.element("#no-selection");
fullscreenRenderingError = this.element("#fullscreen-rendering-error");
appError = this.element("#app-error");
component = {
label: () => {
return this.element("#component-label");
},
};
variant = {
get: (label: string) => {
return this.element(
`xpath=//*[contains(@class, 'variant')][contains(., '${label}')]`
);
},
selected: () => {
return this.element("#selected-variant");
},
};
bottomPanel = {
tabs: {
get: (label: string) => {
return this.element(
`xpath=//button[contains(@class, 'panel-tab')][contains(., '${label}')]`
);
},
selected: () => {
return this.element(".panel-tab-selected");
},
},
};
actionLog = {
get: (label: string) => {
return this.element(
`xpath=//*[contains(@class, 'action-log')][contains(., '${label}')]`
);
},
};
console = {
container: this.element("#console-container"),
clearButton: this.element("#clear-console-button"),
notificationCount: this.element(".notification-count"),
items: {
at: async (index: number) => {
return this.element(`.console-item:nth-child(${index + 1})`);
},
count: async () => {
return (await this.page.$$(".console-item")).length;
},
withText: (text: string) => {
return this.element(
`xpath=//*[contains(@class, 'console-item')][contains(., '${text}')]`
);
},
},
};
props = {
refreshButton: this.element("#editor-refresh-button"),
editor: (() => {
const getText = async () => {
const editorContent = await this.page.waitForSelector(
"#editor-content",
{
state: "attached",
}
);
if (!editorContent) {
throw new Error(`#editor-content not found`);
}
return editorContent.evaluate(
(element) => element.getAttribute("data-value") as string
);
};
return {
...this.element("#editor-content"),
isReady: async () => {
return this.element("#editor-ready").waitUntilExists();
},
getText,
replaceText: async (text: string) => {
await this.page.waitForSelector(".monaco-editor");
await this.page.click(".monaco-editor");
const currentText = await getText();
for (let i = 0; i < currentText.length; i++) {
await this.page.keyboard.press("ArrowRight");
await this.page.keyboard.press("Backspace");
}
for (let i = 0; i < text.length; i++) {
await this.page.type(".monaco-editor", text.charAt(i));
if ((await getText()).replace(/\r/g, "").length > i + 1) {
// Erase any automatically inserted brackets, etc.
await this.page.keyboard.press("ArrowRight");
await this.page.keyboard.press("Backspace");
}
}
},
};
})(),
};
element(selector: string) {
const getter = () => {
return this.page.$(selector);
};
const methods = {
visible: async () => {
return !!(await this.page.$(selector));
},
waitUntilVisible: async () => {
await this.page.waitForSelector(selector, {
state: "attached",
});
},
waitUntilExists: async () => {
await this.page.waitForSelector(selector, {
state: "attached",
});
},
waitUntilGone: async () => {
await this.page.waitForSelector(selector, {
state: "hidden",
});
},
className: async () => {
const element = await getter();
if (!element) {
throw new Error(`${selector} not found`);
}
return element.evaluate((element) => element.className);
},
text: async () => {
const element = await getter();
if (!element) {
return null;
}
return element.evaluate((element) => element.textContent);
},
click: async () => {
const element = await getter();
if (!element) {
throw new Error(`${selector} not found`);
}
await element.click();
},
};
return methods;
}
}