Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions apps/mobile/preview/gallery.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// #268: out/index.html, the page writeIndex writes after a run of the preview harness, checked without a browser and
// without a build. Each test calls it with made-up shots in a fresh temp folder (removed at the end), reads the file
// back and asserts on the HTML. gallery.mjs itself is untouched.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { writeIndex } from "./gallery.mjs";

const sections = (html) => html.match(/<section>[\s\S]*?<\/section>/g) ?? [];
const figures = (html) => html.match(/<figure>[\s\S]*?<\/figure>/g) ?? [];

/** Writes the page in its own throwaway folder and returns the HTML. `mockup` also creates mockups/<name> next to the index. */
const run = (shots, mockup) => {
const dir = mkdtempSync(join(tmpdir(), "hermit-gallery-"));
try {
if (mockup) {
mkdirSync(join(dir, "mockups"));
writeFileSync(join(dir, "mockups", mockup), "<svg></svg>");
}
writeIndex(join(dir, "index.html"), shots);
return readFileSync(join(dir, "index.html"), "utf8");
} finally {
rmSync(dir, { recursive: true, force: true });
}
};

/** A made-up shot with the fields writeIndex reads; nothing real in any of them. */
const shot = (over = {}) => ({
id: "HM-CHAT-01",
name: "Hermit chat",
route: "chat",
variant: "",
theme: "light",
lang: "es-419",
file: "chat-light-es-419.png",
errors: [],
...over,
});

test("shots with the same id, name and variant share one section; a different variant gets its own", () => {
const html = run([
shot({ file: "chat-light-es-419.png" }),
shot({ theme: "dark", file: "chat-dark-es-419.png" }),
shot({ variant: "empty", theme: "dark", file: "chat-empty-dark.png" }),
]);
assert.equal(sections(html).length, 2);
const [base, empty] = sections(html);
// Both shots of the base state sit under one heading, one figure each.
assert.equal(figures(base).length, 2);
assert.ok(base.includes("<h2><span class=\"id\">HM-CHAT-01</span> Hermit chat</h2>"));
assert.ok(base.includes("src=\"screens/chat-light-es-419.png\""));
assert.ok(base.includes("src=\"screens/chat-dark-es-419.png\""));
// The empty state keeps the same id and name but is its own section, with the state named.
assert.equal(figures(empty).length, 1);
assert.ok(empty.includes("<code>empty</code>"));
assert.ok(!base.includes("<code>empty</code>"));
});

test("a name or a note with <, >, & and \" comes out escaped, and no raw <script> from a shot reaches the page", () => {
const html = run([
shot({
name: `A & B <script>alert("gotcha")</script> > "z"`,
note: `A & B <script>alert("gotcha")</script> > "z"`,
}),
]);
const escaped = "A &amp; B &lt;script&gt;alert(&quot;gotcha&quot;)&lt;/script&gt; &gt; &quot;z&quot;";
assert.ok(!html.includes("<script>"), "a raw <script> from a shot reached the page");
assert.ok(html.includes(`<h2><span class="id">HM-CHAT-01</span> ${escaped}</h2>`), "the name is escaped in the heading");
assert.ok(html.includes(`. ${escaped}</p>`), "the note is escaped in the meta line");
assert.ok(html.includes(`alt="HM-CHAT-01 ${escaped}, light, es-419"`), "the name is escaped in the alt text");
});

test('"console errors" appears only for a shot whose errors are not empty', () => {
const html = run([
shot({ file: "chat-clean.png" }),
shot({ theme: "dark", file: "chat-noisy.png", errors: ["boom: the page never answered"] }),
]);
const [clean, noisy] = figures(html);
assert.ok(!clean.includes("console errors"));
assert.ok(noisy.includes('title="boom: the page never answered"'));
assert.ok(noisy.includes(">console errors</span>"));
assert.equal(figures(html).filter((f) => f.includes("console errors")).length, 1);
});

test('a "full length" link appears only when the shot has one', () => {
const html = run([
shot({ file: "chat-short.png" }),
shot({ theme: "dark", file: "chat-long.png", full: "chat-long-full.png" }),
]);
const [short, long] = figures(html);
assert.ok(!short.includes("full length"));
assert.ok(long.includes('<a href="screens/chat-long-full.png">full length</a>'));
assert.equal(figures(html).filter((f) => f.includes("full length")).length, 1);
});

test("a mockup figure appears only when mockups/<name> sits next to the index", () => {
const withFile = run([shot({ mockup: "HM-CHAT-01-light-es-419.png" })], "HM-CHAT-01-light-es-419.png");
const [screen, mock] = figures(withFile);
assert.equal(figures(withFile).length, 2);
assert.ok(mock.includes('src="mockups/HM-CHAT-01-light-es-419.png"'));
assert.ok(mock.includes("<figcaption>mockup</figcaption>"));
assert.ok(!screen.includes("mockups/"), "the screen figure is not the mockup");
// The same shot with no mockup file next to the index: the figure is gone.
const withoutFile = run([shot({ mockup: "HM-CHAT-01-light-es-419.png" })]);
assert.equal(figures(withoutFile).length, 1);
assert.ok(!withoutFile.includes('class="mock"'));
assert.ok(!withoutFile.includes("<figcaption>mockup</figcaption>"));
});
2 changes: 1 addition & 1 deletion apps/mobile/preview/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"type": "module",
"scripts": {
"build": "node build.mjs",
"test": "node --test device-lab.test.mjs browser.test.mjs pick.test.mjs",
"test": "node --test device-lab.test.mjs browser.test.mjs pick.test.mjs gallery.test.mjs",
"shoot": "node shoot.mjs",
"compress": "python3 -c \"import glob; from PIL import Image; [Image.open(f).convert('RGB').quantize(colors=256, dither=Image.Dither.NONE).save(f, optimize=True) for f in glob.glob('out/screens/*.png')]\"",
"clips": "node clips.mjs",
Expand Down
12 changes: 7 additions & 5 deletions apps/mobile/src/app/delete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@
import { reloadAppAsync } from "expo";
import { Stack } from "expo-router";
import { useCallback, useEffect, useReducer, useRef, useState } from "react";
import { BackHandler, View } from "react-native";
import { BackHandler, Platform, View } from "react-native";
import { eraseReducer, initialErase, confirmationMatches, type EraseScreen } from "@hermit/runtime";
import { notificationAccessEnabled, openNotificationAccessSettings } from "../adapters";
import { confirmErase, eraseEverything, phoneHasLock, walletBalance } from "../adapters/erase";
import { Icon } from "../components/Icon";
import { Btn, Card, Empty, Failed, Input, Note as NoteLine, Notice, Page, T } from "../components/kit";
import { eraseLines } from "../delete-view";
import { useHermit } from "../hermit-context";
import { t } from "../i18n";
import { radius, s } from "../theme";
import { usePalette } from "../use-palette";

// Read at use, not at import: the word follows the app language (HM-SET-05).
const word = () => t("HM-SET-03.confirmWord");
const LIST = ["listData", "listMessages", "listKeys", "listCache", "listModel"] as const;

interface Facts {
initial: EraseScreen;
Expand Down Expand Up @@ -103,6 +103,7 @@ function Flow({ initial, hasLock, notifAccess }: Facts) {

function Body(props: { screen: EraseScreen; hasLock: boolean; notifAccess: boolean; onType(text: string): void; onSubmit(): void; onWalletAck(): void; onRetry(): void }) {
const p = usePalette();
const lines = eraseLines(Platform.OS);
const { screen } = props;
switch (screen.kind) {
case "wallet_warning":
Expand All @@ -126,11 +127,12 @@ function Body(props: { screen: EraseScreen; hasLock: boolean; notifAccess: boole
return (
<View style={{ gap: s.lg }}>
<T v="body">{t("HM-SET-03.body")}</T>
{/* What goes, on the page color with coral marks. */}
{/* What goes, on the page color with coral marks. On iOS the captured-messages line is not there:
capture is Android-only, and so is the permissions note under the list. */}
<View style={{ gap: s.sm }}>
{LIST.map((k) => <NoteLine key={k} icon="trash-2" tone="coral" text={t(`HM-SET-03.${k}`)} textColor="text" v="body" />)}
{lines.list.map((k) => <NoteLine key={k} icon="trash-2" tone="coral" text={t(`HM-SET-03.${k}`)} textColor="text" v="body" />)}
</View>
<NoteLine icon="info" text={t("HM-SET-03.permissionsStay")} />
{lines.permissionsStay ? <NoteLine icon="info" text={t("HM-SET-03.permissionsStay")} /> : null}
{props.notifAccess ? <Btn label={t("HM-SET-03.openNotificationAccess")} kind="secondary" icon="settings" small onPress={openNotificationAccessSettings} /> : null}
<Input
label={t("HM-SET-03.typePrompt", { word: word() })}
Expand Down
46 changes: 46 additions & 0 deletions apps/mobile/src/bot-templates.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { normalizeSite, SHELL_COLORS, SHELL_SHAPES } from "@hermit/core/bots";
import { fromTemplate, formProblems } from "./bot-form-view.ts";
import { BLANK_LOOK, BOT_TEMPLATES, TEMPLATE_LOOKS } from "./bot-templates.ts";

const locale = (name: string) => JSON.parse(readFileSync(new URL(`../../../packages/copy/locales/${name}.json`, import.meta.url), "utf8")) as Record<string, string>;
const locales = [
["es-419", locale("es-419")],
["en", locale("en")],
] as const;

test("HM-BOT-03: the template ids are unique and TEMPLATE_LOOKS has exactly those ids", () => {
const ids = BOT_TEMPLATES.map((tpl) => tpl.id);
assert.equal(new Set(ids).size, ids.length);
assert.deepEqual(Object.keys(TEMPLATE_LOOKS).sort(), [...ids].sort());
});

test("HM-BOT-03: every template look and the blank look wear a known shape and color", () => {
for (const [id, look] of Object.entries(TEMPLATE_LOOKS)) {
assert.ok((SHELL_SHAPES as readonly string[]).includes(look.shape), `${id} shape ${look.shape}`);
assert.ok((SHELL_COLORS as readonly string[]).includes(look.color), `${id} color ${look.color}`);
}
assert.ok((SHELL_SHAPES as readonly string[]).includes(BLANK_LOOK.shape), `blank shape ${BLANK_LOOK.shape}`);
assert.ok((SHELL_COLORS as readonly string[]).includes(BLANK_LOOK.color), `blank color ${BLANK_LOOK.color}`);
});

test("HM-BOT-03: no two templates wear the same look, and the blank look is different from all of them", () => {
const pairs = Object.values(TEMPLATE_LOOKS).map((look) => `${look.shape}/${look.color}`);
assert.equal(new Set(pairs).size, pairs.length);
assert.ok(!pairs.includes(`${BLANK_LOOK.shape}/${BLANK_LOOK.color}`));
});

test("HM-BOT-03: every template site is already written the way the form keeps it", () => {
for (const tpl of BOT_TEMPLATES) for (const site of tpl.sites) assert.equal(normalizeSite(site), site, `${tpl.id} ${site}`);
});

test("HM-BOT-03: each template's form passes the form's own checks in both languages", () => {
for (const [name, dict] of locales) {
const t = (key: string) => dict[key] ?? key;
for (const tpl of BOT_TEMPLATES) {
assert.deepEqual(formProblems(fromTemplate(tpl.id, t, TEMPLATE_LOOKS[tpl.id])), [], `${name} ${tpl.id}`);
}
}
});
25 changes: 25 additions & 0 deletions apps/mobile/src/delete-view.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// HM-SET-03 (#212): the erase screen's list and notes on each OS. The WhatsApp capture line and the Android
// permissions note only apply where capture exists, which is Android; iOS has no capture.
import { test } from "node:test";
import assert from "node:assert/strict";
import { eraseLines } from "./delete-view.ts";

test("on Android the list keeps every line and the permissions note shows", () => {
const lines = eraseLines("android");
assert.deepEqual(lines.list, ["listData", "listMessages", "listKeys", "listCache", "listModel"]);
assert.equal(lines.permissionsStay, true);
});

test("on iOS the list leaves out the captured messages line and the permissions note is gone", () => {
const lines = eraseLines("ios");
assert.deepEqual(lines.list, ["listData", "listKeys", "listCache", "listModel"]);
assert.equal(lines.permissionsStay, false);
});

test("only Android gets the Android lines", () => {
for (const os of ["web", "macos", "windows"]) {
const lines = eraseLines(os);
assert.ok(!lines.list.includes("listMessages"), os);
assert.equal(lines.permissionsStay, false, os);
}
});
16 changes: 16 additions & 0 deletions apps/mobile/src/delete-view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// HM-SET-03: which of the erase screen's lines apply on this OS. Pure: tested under Node with node --test
// (delete-view.test.ts). WhatsApp capture reads Android notifications, so its line and the Android permissions
// note only apply on Android; iOS has no capture and no such permissions to mention.

export const ERASE_LIST = ["listData", "listMessages", "listKeys", "listCache", "listModel"] as const;

export type EraseListKey = (typeof ERASE_LIST)[number];

/** The "what goes" list keys and whether the permissions note shows, for React Native's `Platform.OS` (or any OS string). */
export function eraseLines(os: string): { list: readonly EraseListKey[]; permissionsStay: boolean } {
const android = os === "android";
return {
list: android ? ERASE_LIST : ERASE_LIST.filter((k) => k !== "listMessages"),
permissionsStay: android,
};
}
88 changes: 88 additions & 0 deletions apps/site/test/meta.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// #267: the metadata of every page, without a build. pageMetadata and chooserMetadata (lib/meta.ts) give each page its
// title, description, canonical address, hreflang alternates and link preview, on the copy translator (lib/i18n.ts)
// returns, so these tests ask the translator too and a copy change doesn't break them. Tests only: lib/meta.ts, the
// locale files and everything else under apps/site stay as they are.
import { describe, expect, test } from "vitest";
import { BRAND_FILES } from "../lib/brand.mjs";
import { href, isLang, LANGS, LOCALE, translator, type Lang, type Page } from "../lib/i18n";
import { chooserMetadata, OG_IMAGE, pageMetadata } from "../lib/meta";
import { SITE_URL } from "../lib/site-config.mjs";

/** Open Graph's locale names (language_TERRITORY): es_LA is the one link previews know for Latin American Spanish. */
const OG_LOCALE: Readonly<Record<Lang, string>> = { en: "en_US", es: "es_LA" };

/** The three pages of the site: the home, the privacy policy and the download page. */
const PAGES: ReadonlyArray<["HM-SITE-01" | "HM-SITE-02" | "HM-SITE-03", Page]> = [
["HM-SITE-01", ""],
["HM-SITE-02", "privacy/"],
["HM-SITE-03", "download/"],
];

describe("lib/meta.ts", () => {
describe("pageMetadata", () => {
for (const lang of LANGS) {
for (const [screen, page] of PAGES) {
test(`${screen} in ${lang} carries the copy, the addresses and the preview`, () => {
const t = translator(lang);
const m = pageMetadata(lang, screen, page);
// The copy comes from the translator, so a copy change moves both together.
expect(m.title).toBe(t(`${screen}.metaTitle`));
expect(m.description).toBe(t(`${screen}.metaDescription`));
// The canonical address is the page's own in this language, and the alternates point at the same page in
// each language, with the chooser at the root as the default.
expect(m.alternates?.canonical).toBe(href(lang, page));
expect(m.alternates?.languages).toEqual({
"es-419": href("es", page),
en: href("en", page),
"x-default": "/",
});
// The link preview: the same copy and address in Open Graph and in the Twitter card, one image from
// OG_IMAGE with the common alt text, and the locale of the page's language plus the other one.
const image = { url: OG_IMAGE.url, width: OG_IMAGE.width, height: OG_IMAGE.height, alt: t("common.ogAlt") };
expect(m.openGraph?.title).toBe(m.title);
expect(m.openGraph?.description).toBe(m.description);
expect(m.openGraph?.url).toBe(href(lang, page));
expect(m.openGraph?.images).toEqual([image]);
expect(m.twitter?.images).toEqual(m.openGraph?.images);
expect(m.openGraph?.locale).toBe(OG_LOCALE[lang]);
expect(m.openGraph?.alternateLocale).toEqual([OG_LOCALE[LOCALE[lang].other]]);
// Relative paths resolve against the site's address.
expect(String(m.metadataBase)).toBe(new URL(SITE_URL).href);
});
}
}

test("chooserMetadata points at the chooser, with the home page's alternates, in Spanish", () => {
const m = chooserMetadata();
expect(m.alternates?.canonical).toBe("/");
expect(m.alternates?.languages).toEqual({
"es-419": href("es", ""),
en: href("en", ""),
"x-default": "/",
});
expect(m.openGraph?.locale).toBe("es_LA");
});

test("the preview image is a brand file the build copies from docs/brand", () => {
expect(OG_IMAGE.url.startsWith("/brand/")).toBe(true);
expect(BRAND_FILES, `OG_IMAGE.url ${OG_IMAGE.url}`).toContain(OG_IMAGE.url.slice("/brand/".length));
});
});

describe("lib/i18n.ts", () => {
test("a missing key is named with its language", () => {
expect(() => translator("es")("HM-SITE-99.nope")).toThrow(/Missing copy key HM-SITE-99\.nope \(es\)/);
});

test("a placeholder with no value is named in the error", () => {
expect(() => translator("en")("HM-SITE-02.updated")).toThrow(/needs \{date\}/);
});

test("isLang accepts only the two URL segments, es and en", () => {
expect([...LANGS]).toEqual(["es", "en"]);
for (const lang of LANGS) expect(isLang(lang), lang).toBe(true);
expect(isLang("es-419")).toBe(false);
expect(isLang("EN")).toBe(false);
});
});
});
Loading
Loading