Repository navigation
Expand file tree
/
Copy pathqa-mobile-canvas-layout.mts
More file actions
281 lines (279 loc) · 10.5 KB
/
Copy pathqa-mobile-canvas-layout.mts
File metadata and controls
281 lines (279 loc) · 10.5 KB
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
import assert from "node:assert/strict";
import { randomBytes } from "node:crypto";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { chromium, webkit } from "playwright-core";
import sharp from "sharp";
import { createUser } from "@core/modules/identity/passwords.js";
import { createContent } from "@core/workflows/resources.js";
import { storageRuntime } from "@server/adapters/storage.js";
import { createApp } from "@server/app/create-app.js";
import { openTestDatabase } from "../tests/database.js";
const output = resolve(process.env.DOCA_CANVAS_QA_OUTPUT ?? "artifacts/verification/mobile-canvas-photo-qr");
await mkdir(output, { recursive: true });
const root = await mkdtemp(join(output, "fixture-"));
const port = Number(process.env.DOCA_CANVAS_QA_PORT ?? 44276);
const origin = process.env.DOCA_CANVAS_QA_ORIGIN ?? `http://127.0.0.1:${port}`;
const pluginDirectory = join(root, "plugins");
const manifest = {
schemaVersion: 1,
id: "qa.canvas-sidebar",
version: "1.0.0",
displayName: "Canvas QA",
sdkRange: "^0.2.0",
};
const pluginPath = join(pluginDirectory, manifest.id);
await mkdir(join(pluginPath, "web"), { recursive: true });
await writeFile(join(pluginPath, "manifest.json"), JSON.stringify(manifest));
await writeFile(
join(pluginPath, "package.json"),
JSON.stringify({
name: "@qa/canvas-sidebar",
version: manifest.version,
type: "module",
doca: {
storage: "host",
dataVersion: "1",
manifest: "./manifest.json",
server: "./server.js",
web: { directory: "./web", entry: "./index.js" },
},
}),
);
await writeFile(
join(pluginPath, "server.js"),
`export default () => ({ manifest: ${JSON.stringify(manifest)}, async uninstall() {} });`,
);
await writeFile(
join(pluginPath, "web", "index.js"),
`
const pluginId = ${JSON.stringify(manifest.id)};
export default ({ React }) => ({
manifest: { pluginId, version: "1.0.0", targets: ["web"] },
views: [{
id: pluginId + ".view", pluginId, title: { en: "Canvas sidebar", zh: "画布验收侧栏" },
supportedContexts: ["document"],
render: () => React.createElement("div", { style: { minHeight: 900 } }, "Sidebar content"),
}],
placements: [{
id: pluginId + ".placement", pluginId, slot: "document.sidebar", viewId: pluginId + ".view",
conditions: { formats: ["canvas"] },
}],
});
`,
);
const storage = join(root, "storage");
process.env.DOCA_FILE_STORE_ID = "local";
process.env.DOCA_FILE_STORES_JSON = JSON.stringify({
version: 1,
stores: { local: { provider: "local", root: storage } },
});
process.env.DOCA_CREDENTIAL_MASTER_KEY = randomBytes(32).toString("hex");
const db = await openTestDatabase({ driver: "sqlite", path: ":memory:" });
const login = "canvasqa";
const password = randomBytes(16).toString("hex");
const owner = await createUser(
db,
{ login, password, displayName: "画布验收账号" },
{ bootstrap: true },
);
await db
.updateTable("account_settings")
.set({ config: JSON.stringify({ qrLoginEnabled: true }) })
.where("id", "=", "identity")
.execute();
const canvas = await createContent(db).create(owner, {
title: "带侧栏的手机画布",
kind: "document",
format: "canvas",
initialContent: {
version: 1,
scene: {
children: [
{
id: "green-card",
tag: "Rect",
x: 85,
y: 65,
width: 190,
height: 100,
fill: "#159d78",
},
],
},
},
});
const wideCanvas = await createContent(db).create(owner, {
title: "大幅手机画布",
kind: "document",
format: "canvas",
initialContent: {
version: 1,
scene: {
children: [
{ id: "left-card", tag: "Rect", x: -800, y: -80, width: 280, height: 230, fill: "#159d78" },
{ id: "right-card", tag: "Rect", x: 660, y: 230, width: 280, height: 230, fill: "#4267ba" },
{ id: "find-target", tag: "Text", x: 690, y: 280, text: "Doca viewport target", fontSize: 24, fill: "#1f2329" },
],
},
},
});
const app = await createApp(db, {
origin,
staticDirectory: resolve(process.env.DOCA_CANVAS_QA_WEB ?? "apps/web/dist"),
pluginDirectory,
storage: { ...storageRuntime(), root: storage },
ai: { memory: { driver: "sqlite", url: ":memory:" } },
});
try {
await app.listen({ port, host: "127.0.0.1" });
const fixture = join(output, `fixture-${port}.json`);
await writeFile(
fixture,
JSON.stringify({ origin, login, password, canvas: canvas.id, wideCanvas: wideCanvas.id }),
{ mode: 0o600 },
);
if (process.argv.includes("--serve")) {
console.log(`Isolated fixture at ${origin} · ${fixture}`);
await new Promise<void>((done) => {
process.once("SIGTERM", () => done());
process.once("SIGINT", () => done());
});
} else {
const response = await fetch(origin + "/api/v1/auth/login", {
method: "POST",
headers: {
"content-type": "application/json",
"x-doca-client": "mobile",
},
body: JSON.stringify({ login, password }),
});
assert.equal(response.status, 200);
const { sessionToken } = (await response.json()) as {
sessionToken: string;
};
for (const [name, engine] of Object.entries({ chromium, webkit })) {
const browser = await engine.launch(
name === "chromium" ? { channel: "chrome" } : {},
);
try {
const page = await browser.newPage({
viewport: { width: 360, height: 640 },
isMobile: true,
hasTouch: true,
});
const ticketResponse = await fetch(
origin + "/api/v1/auth/webview-ticket",
{
method: "POST",
headers: { authorization: "Bearer " + sessionToken },
},
);
assert.equal(ticketResponse.status, 200);
const { ticket } = (await ticketResponse.json()) as { ticket: string };
await page.goto(
origin +
"/#/m/auth?" +
new URLSearchParams({ ticket, to: "/m/r/" + canvas.id }),
);
const sidebar = page.locator(".plugin-slot-document-sidebar");
const drawing = page.locator(".canvas-host");
await sidebar.waitFor({ state: "visible" });
await drawing.locator("canvas").first().waitFor({ state: "attached" });
const narrow = await drawing.boundingBox();
assert.ok(
narrow && narrow.width === 360 && narrow.height >= 365,
JSON.stringify(narrow),
);
const scrollTop = await sidebar.evaluate((panel) => {
panel.scrollTop = 100;
return panel.scrollTop;
});
assert.equal(scrollTop, 100);
const screenshot = await page.screenshot({
path: join(output, `canvas-sidebar-${name}.png`),
});
const { data, info } = await sharp(screenshot)
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
let greenPixels = 0;
for (let offset = 0; offset < data.length; offset += info.channels) {
if (
data[offset] === 21 &&
data[offset + 1] === 157 &&
data[offset + 2] === 120
)
greenPixels++;
}
assert.ok(greenPixels > 5000, `Rendered green pixels: ${greenPixels}`);
await sidebar.evaluate((panel) => ((panel as HTMLElement).style.display = "none"));
assert.equal((await drawing.boundingBox())?.height, 595);
await sidebar.evaluate((panel) => ((panel as HTMLElement).style.display = ""));
await page.goto(origin + "/#/m/r/" + wideCanvas.id);
await sidebar.waitFor({ state: "visible" });
const fit = page.locator(".mobile-canvas-controls button");
await fit.waitFor({ state: "visible" });
const readColors = async (label: string) => {
const shot = await page.screenshot({ path: join(output, `${label}-${name}.png`) });
const { data: pixels, info: shape } = await sharp(shot).removeAlpha().raw().toBuffer({ resolveWithObject: true });
let green = 0;
let blue = 0;
for (let offset = 0; offset < pixels.length; offset += shape.channels) {
if (pixels[offset] === 21 && pixels[offset + 1] === 157 && pixels[offset + 2] === 120) green++;
if (pixels[offset] === 66 && pixels[offset + 1] === 103 && pixels[offset + 2] === 186) blue++;
}
return { green, blue };
};
const zoomSelector = ".zoom-controls .zoom-value";
await page.waitForFunction((selector) => {
const value = Number.parseInt(document.querySelector(selector)?.textContent ?? "", 10);
return value > 0 && value < 25;
}, zoomSelector);
const initialZoom = await page.locator(zoomSelector).innerText();
const initial = await readColors("canvas-wide-initial");
assert.ok(initial.green > 400 && initial.blue > 400, JSON.stringify(initial));
await page.getByRole("button", { name: /^(Zoom in|放大)$/ }).click();
await page.waitForFunction(({ selector, zoom }) => document.querySelector(selector)?.textContent !== zoom, { selector: zoomSelector, zoom: initialZoom });
await fit.click();
await page.waitForFunction(({ selector, zoom }) => document.querySelector(selector)?.textContent === zoom, { selector: zoomSelector, zoom: initialZoom });
const refit = await readColors("canvas-wide-refit");
assert.ok(refit.green > 400 && refit.blue > 400, JSON.stringify(refit));
await page.goto(origin + "/#/m/r/" + wideCanvas.id + "?find=Doca+viewport+target");
await page.reload();
await fit.waitFor({ state: "visible" });
const search = await readColors("canvas-search");
assert.ok(search.blue > 1_000 && search.green === 0, JSON.stringify(search));
await page.setViewportSize({ width: 1280, height: 800 });
await page.goto(origin + "/#/r/" + canvas.id);
await page.reload();
await sidebar.waitFor({ state: "visible" });
await drawing.waitFor({ state: "visible" });
const [desktop, desktopSidebar] = await Promise.all([
drawing.boundingBox(),
sidebar.boundingBox(),
]);
assert.ok(
desktop &&
desktopSidebar &&
desktopSidebar.x >= desktop.x + desktop.width - 1,
);
console.log(
JSON.stringify({
browser: name,
narrow,
greenPixels,
scrollTop,
desktop,
desktopSidebar,
}),
);
} finally {
await browser.close();
}
}
}
} finally {
await app.close();
await db.destroy();
}