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
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ The rules live in [AGENTS.md](AGENTS.md). Read its non-negotiables before your f
- Report a bug, with steps to reproduce and no personal data.
- Propose a feature. Read [VISION.md](VISION.md) first.
- Run Hermit on your phone and send device data: [docs/devices.md](docs/devices.md) explains how.
- Improve the docs, or the Spanish and English copy.
- Improve the docs, or the Spanish and English copy. [How copy works](packages/copy/README.md) explains how to add a
string.
- Review open pull requests. Reading and running someone's change helps too.

## Set up
Expand Down
73 changes: 73 additions & 0 deletions apps/mobile/src/tokens.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/// <reference types="node" />
// Hermit's design tokens (docs/design/polish/decisions.md): every color is a docs/brand/tokens.json value, or a mix of
// two of them (mix): the surfaces between the canvas and white, the tonal fills between a surface and an accent, and
// the scrims. Light is Quiet craft; dark is Deep sea. The motion tokens live beside them (docs/design/polish/decisions.md,
// "Motion"): plain numbers, no animation library.
import { test } from "node:test";
import assert from "node:assert/strict";
import { mix } from "./theme.ts";
import { duration, easing, stagger, staggerDelay } from "./motion.ts";

test("mix(a, b, t) holds at a when t is 0 and at b when t is 1", () => {
assert.equal(mix("#F5EDE1", "#B4483A", 0), "#F5EDE1");
assert.equal(mix("#F5EDE1", "#B4483A", 1), "#B4483A");
});

test("mix rounds to a whole hex channel at the midpoint", () => {
// Half of #000000 → #808080: the blend rounds, it does not truncate.
assert.equal(mix("#000000", "#FFFFFF", 0.5), "#808080");
});

test("mix answers in uppercase #RRGGBB even when the inputs are lowercase", () => {
assert.match(mix("#ffffff", "#2b221b", 0.5), /^#[0-9A-F]{6}$/);
});

test("mix keeps every channel between the two inputs while t is between 0 and 1", () => {
const pairs: Array<[string, string]> = [
["#000000", "#FFFFFF"],
["#06121D", "#5EF0CF"],
["#2B221B", "#8A5912"],
];
for (const [a, b] of pairs) {
for (const t of [0.25, 0.5, 0.75]) {
const c = mix(a, b, t);
const blend = [0, 1, 2].map((i) => parseInt(c.slice(1 + i * 2, 3 + i * 2), 16));
const from = [0, 1, 2].map((i) => parseInt(a.slice(1 + i * 2, 3 + i * 2), 16));
const to = [0, 1, 2].map((i) => parseInt(b.slice(1 + i * 2, 3 + i * 2), 16));
for (let i = 0; i < 3; i++) {
assert.ok(
blend[i] >= Math.min(from[i], to[i]) && blend[i] <= Math.max(from[i], to[i]),
`channel ${i} of ${c} should stay between ${a} and ${b} at t=${t}`,
);
}
}
}
});

test("staggerDelay spaces items out by one step and stops at stagger.max", () => {
assert.equal(staggerDelay(0), 0);
assert.equal(staggerDelay(1), stagger.step);
assert.equal(staggerDelay(2), stagger.step * 2);
assert.equal(staggerDelay(stagger.max - 1), (stagger.max - 1) * stagger.step);
assert.equal(staggerDelay(stagger.max), stagger.max * stagger.step);
assert.equal(staggerDelay(stagger.max + 4), stagger.max * stagger.step);
});

test("duration tokens are positive whole milliseconds, a press is instant and sheet is the longest", () => {
const values = Object.values(duration);
for (const v of values) {
assert.ok(Number.isInteger(v), `duration ${v} should be a whole number of milliseconds`);
assert.ok(v > 0, `duration ${v} should be positive`);
}
assert.ok(duration.press < 100, `a press should read as instant, got ${duration.press}`);
assert.equal(duration.sheet, Math.max(...values), `sheet should be the longest duration, got ${duration.sheet}`);
});

test("easing curves are four numbers whose control-x values sit between 0 and 1", () => {
for (const curve of Object.values(easing)) {
assert.equal(curve.length, 4, `a cubic-bezier needs four numbers, got ${curve.length}`);
for (const x of [curve[0], curve[2]]) {
assert.ok(x >= 0 && x <= 1, `a cubic-bezier x value should sit between 0 and 1, got ${x}`);
}
}
});
33 changes: 33 additions & 0 deletions apps/site/test/locales.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import { translator } from "../lib/i18n";
const KEY_PATTERN = /^(HM-SITE-\d{2}|common)\.[a-z][a-zA-Z0-9]*$/;
const placeholders = (s: string) => [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort();
const all = [...Object.entries(en), ...Object.entries(es)];
const count = (v: string, ch: string) => v.split(ch).length - 1;
const hasDoubleSpace = (v: string) => v.includes(" ");
const hasEdgeSpace = (v: string) => /^[ \t\r\n]|[ \t\r\n]$/.test(v);
const hasThreeDots = (v: string) => v.includes("...");
const unbalancedMarks = (v: string) => count(v, "¿") !== count(v, "?") || count(v, "¡") !== count(v, "!");

describe("site copy", () => {
test("both languages define exactly the same keys", () => {
Expand Down Expand Up @@ -75,4 +80,32 @@ describe("site copy", () => {
expect(() => translator("en")("HM-SITE-09.nope")).toThrow(/Missing copy key/);
expect(() => translator("en")("HM-SITE-02.updated")).toThrow(/needs \{date\}/);
});

test("the copy hygiene checks flag made up slips", () => {
expect(hasDoubleSpace("hola mundo")).toBe(true);
expect(hasDoubleSpace("{count} {unit}")).toBe(false);
expect(hasEdgeSpace(" hola")).toBe(true);
expect(hasEdgeSpace("hola\n")).toBe(true);
expect(hasEdgeSpace("hola\nmundo")).toBe(false);
expect(hasThreeDots("espera...")).toBe(true);
expect(hasThreeDots("espera…")).toBe(false);
expect(unbalancedMarks("¿Cómo estás?")).toBe(false);
expect(unbalancedMarks("Cómo estás?")).toBe(true);
expect(unbalancedMarks("Hola!")).toBe(true);
});

test("no value in either language of the site has two spaces in a row, edge space or three dots", () => {
for (const [k, v] of all) {
expect(hasDoubleSpace(v), k).toBe(false);
expect(hasEdgeSpace(v), k).toBe(false);
expect(hasThreeDots(v), k).toBe(false);
}
});

test("in the site Spanish the opening marks match the closing ones in every value", () => {
for (const [k, v] of Object.entries(es)) {
expect(count(v, "¿"), k).toBe(count(v, "?"));
expect(count(v, "¡"), k).toBe(count(v, "!"));
}
});
});
129 changes: 129 additions & 0 deletions apps/site/test/release.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// HM-SITE-03: the download page's release fields, checked before anyone copies a hash by hand. People check the APK
// against the SHA-256 on this page, so a short hash or a link to another tag must not ship. Tests only.
import { describe, expect, test } from "vitest";
import { readFileSync } from "node:fs";
import { RELEASE, type Release } from "../lib/release.ts";
import { REPO_URL } from "../lib/site-config.mjs";

const slug = (heading: string) => heading.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, "").replace(/\s/g, "-");

/** The anchors docs/devices.md actually has: its headings outside code fences, slugged as GitHub slugs them. */
function headingAnchors(markdown: string): Set<string> {
const anchors = new Set<string>();
const seen = new Map<string, number>();
let fence: string | null = null;
for (const rawLine of markdown.split("\n")) {
const line = rawLine.replace(/\r$/, "");
const fenceMatch = line.match(/^\s{0,3}(`{3,}|~{3,})/);
if (fenceMatch) {
const marker = fenceMatch[1]!;
if (!fence) fence = marker;
else if (marker[0] === fence[0] && marker.length >= fence.length) fence = null;
continue;
}
if (fence) continue;
const heading = line.match(/^#{1,6}\s+(.*?)\s*#*\s*$/);
if (!heading) continue;
const plain = heading[1]!.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/<[^>]+>/g, "").replace(/[`*~]/g, "");
const base = slug(plain);
const count = seen.get(base) ?? 0;
seen.set(base, count + 1);
anchors.add(count === 0 ? base : `${base}-${count}`);
}
return anchors;
}

const devicesAnchors = headingAnchors(readFileSync(new URL("../../../docs/devices.md", import.meta.url), "utf8"));

const HEX64 = /^[0-9a-f]{64}$/;

/** What is wrong with a published release, field by field. An unpublished one is placeholders, and is fine as it stands. */
function releaseProblems(r: Release, anchors: ReadonlySet<string>): string[] {
if (!r.published) return [];
const problems: string[] = [];
if (!HEX64.test(r.sha256 ?? "")) problems.push(`sha256 should be 64 lowercase hex characters, got ${JSON.stringify(r.sha256)}`);
if (!HEX64.test(r.certSha256 ?? "")) problems.push(`certSha256 should be 64 lowercase hex characters, got ${JSON.stringify(r.certSha256)}`);
const version = /^hermit-(.+)\.apk$/.exec(r.file)?.[1];
if (!version) problems.push(`file should look like hermit-<version>.apk, got ${JSON.stringify(r.file)}`);
const tag = version ? `v${version}` : undefined;

const downloadPrefix = `${REPO_URL}/releases/download/`;
if (!r.url) {
problems.push("url is missing: a published release needs the link to its APK");
} else {
if (!r.url.startsWith(downloadPrefix)) problems.push(`url should start with ${downloadPrefix}, got ${JSON.stringify(r.url)}`);
else if (tag && r.url.slice(downloadPrefix.length).split("/")[0] !== tag) problems.push(`url is for tag ${JSON.stringify(r.url.slice(downloadPrefix.length).split("/")[0])} but file ${JSON.stringify(r.file)} is version ${JSON.stringify(version)}`);
if (!r.url.endsWith(`/${r.file}`)) problems.push(`url should end with /${r.file}, got ${JSON.stringify(r.url)}`);
}

const recipePrefix = tag ? `${REPO_URL}/blob/${tag}/docs/devices.md#` : undefined;
if (!r.recipeUrl) {
problems.push("recipeUrl is missing: a published release needs the link to its rebuild recipe");
} else if (recipePrefix && !r.recipeUrl.startsWith(recipePrefix)) {
problems.push(`recipeUrl should point at docs/devices.md at tag ${tag}, got ${JSON.stringify(r.recipeUrl)}`);
} else if (recipePrefix && !anchors.has(r.recipeUrl.slice(recipePrefix.length))) {
problems.push(`recipeUrl anchor ${JSON.stringify(r.recipeUrl.slice(recipePrefix.length))} matches no heading in docs/devices.md`);
}
return problems;
}

const good: Release = {
published: true,
file: "hermit-1.2.3.apk",
url: `${REPO_URL}/releases/download/v1.2.3/hermit-1.2.3.apk`,
sha256: "a".repeat(64),
certSha256: "b".repeat(64),
recipeUrl: `${REPO_URL}/blob/v1.2.3/docs/devices.md#or-build-it-yourself`,
};

describe("the download page's release (#229)", () => {
test("today's release has no problems, published or not", () => {
expect(releaseProblems(RELEASE, devicesAnchors)).toEqual([]);
});

test("an unpublished release is placeholders, and checks out as it stands", () => {
const placeholder: Release = { published: false, file: "", url: null, sha256: null, certSha256: null, recipeUrl: null };
expect(releaseProblems(placeholder, new Set())).toEqual([]);
});

test("a good made-up release gives no problems", () => {
expect(releaseProblems(good, devicesAnchors)).toEqual([]);
});

test("a short hash gives one problem naming sha256", () => {
const problems = releaseProblems({ ...good, sha256: "a".repeat(63) }, devicesAnchors);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain("sha256");
});

test("an upper case hash gives one problem naming the field", () => {
const upper = releaseProblems({ ...good, sha256: "A".repeat(64) }, devicesAnchors);
expect(upper).toHaveLength(1);
expect(upper[0]).toContain("sha256");
const upperCert = releaseProblems({ ...good, certSha256: "B".repeat(64) }, devicesAnchors);
expect(upperCert).toHaveLength(1);
expect(upperCert[0]).toContain("certSha256");
});

test("a link to another tag gives one problem naming url and the tag", () => {
const problems = releaseProblems({ ...good, url: `${REPO_URL}/releases/download/v9.9.9/hermit-1.2.3.apk` }, devicesAnchors);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain("url");
expect(problems[0]).toContain("v9.9.9");
});

test("a file name that does not match gives one problem naming file", () => {
const problems = releaseProblems({ ...good, file: "other-1.2.3.apk", url: `${REPO_URL}/releases/download/v1.2.3/other-1.2.3.apk` }, devicesAnchors);
expect(problems).toHaveLength(1);
expect(problems[0]).toContain("file");
});

test("a recipe link to another tag, or at a missing heading, gives one problem", () => {
const otherTag = releaseProblems({ ...good, recipeUrl: `${REPO_URL}/blob/v9.9.9/docs/devices.md#or-build-it-yourself` }, devicesAnchors);
expect(otherTag).toHaveLength(1);
expect(otherTag[0]).toContain("recipeUrl");
const missingAnchor = releaseProblems({ ...good, recipeUrl: `${REPO_URL}/blob/v1.2.3/docs/devices.md#no-such-heading` }, devicesAnchors);
expect(missingAnchor).toHaveLength(1);
expect(missingAnchor[0]).toContain("recipeUrl");
});
});
68 changes: 68 additions & 0 deletions packages/copy/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Copy in Hermit

Every string a person sees in the app is a key in this package: [`locales/en.json`](locales/en.json) and
[`locales/es-419.json`](locales/es-419.json), read through the translator in [`src/index.ts`](src/index.ts). Spanish
and English are first class: a string exists in both or it does not exist.

## Naming a key

A key is `HM-XXX-NN.element` for one screen, or `common.*` for a string every screen shares, as `KEY_PATTERN` in
[`src/index.ts`](src/index.ts) requires. For example `HM-APPR-01.approve` is one screen's string and `common.retry`
is shared:

```json
"HM-APPR-01.approve": "Approve with {biometric}",
"common.retry": "Try again"
```

## Add a string

1. Name it as above.
2. Add the same key to both locale files, with the same `{placeholders}` in both. A test holds the two files to
exactly the same keys and placeholders.
3. Use it with `t` from [`apps/mobile/src/i18n.ts`](../../apps/mobile/src/i18n.ts), passing a value for every
placeholder: `t("common.retry")`, or `t("HM-APPR-01.approve")` where the phone's biometric name fills
`{biometric}` by default.

## When a key or a value is missing

The translator throws a `CopyError` instead of returning an empty string: `Missing copy key ...` for a key that is
not there, and `Copy key ... needs {name}.` for a placeholder the call did not fill. A forgotten string fails the
tests instead of shipping blank.

## Counts

`tCount()` in `apps/mobile/src/i18n.ts` says a count right: with a count of 1 it uses the `key.one` form when the
copy has one, and `key` otherwise. The count fills `{count}` either way. One pair that exists today:

```json
"HM-SET-02.count": "{count} times",
"HM-SET-02.count.one": "{count} time"
```

In Spanish the same pair is `"{count} veces"` and `"{count} vez"`.

## House style

The tests in [`test/copy.test.ts`](test/copy.test.ts) hold the copy to it:

- no em or en dashes in either locale;
- Latin American Spanish (es-419), and tú, never vos: "Tienes un recordatorio:" (`HM-CHAT-01.reminders.one`), not a
voseo form. The tú test names the key it flags.
- any Spanish the phone reports resolves to es-419, and everything else to English (`resolveLocale`).

## Tests

```sh
pnpm --filter @hermit/copy test
pnpm --filter @hermit/mobile test
```

The first runs this package's tests (key shape, key and placeholder parity, house style, the translator). The
second includes the test in `apps/mobile/src/copy-keys.test.ts` that every literal key named in the app and package
source exists in both locales.

## The website

The website has its own locale files in [`apps/site/locales`](../../apps/site/locales), with the same rules: the
same keys in both, the same placeholders, no em or en dashes, and tú in Spanish. It does not read this package.
63 changes: 63 additions & 0 deletions packages/copy/test/copy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,66 @@ describe("the biometric's name by platform (issue 128)", () => {
}
});
});

describe("copy hygiene", () => {
const count = (v: string, ch: string) => v.split(ch).length - 1;
const hasDoubleSpace = (v: string) => v.includes(" ");
const hasEdgeSpace = (v: string) => /^[ \t\r\n]|[ \t\r\n]$/.test(v);
const hasThreeDots = (v: string) => v.includes("...");
const unbalancedMarks = (v: string) => count(v, "¿") !== count(v, "?") || count(v, "¡") !== count(v, "!");
const all = [...Object.entries(en), ...Object.entries(es)];

test("the double space check flags made up slips and leaves single spaces alone", () => {
expect(hasDoubleSpace("hola mundo")).toBe(true);
expect(hasDoubleSpace("hola mundo")).toBe(false);
// The placeholders are not text: single spaces around them are fine.
expect(hasDoubleSpace("{count} {unit}")).toBe(false);
expect(hasDoubleSpace("hola\nmundo")).toBe(false);
});

test("the edge space check flags a space, tab or line break at either end only", () => {
expect(hasEdgeSpace(" hola")).toBe(true);
expect(hasEdgeSpace("hola ")).toBe(true);
expect(hasEdgeSpace("\thola")).toBe(true);
expect(hasEdgeSpace("hola\n")).toBe(true);
// A line break inside a value is fine; only the start and the end are checked.
expect(hasEdgeSpace("hola\nmundo")).toBe(false);
expect(hasEdgeSpace("hola mundo")).toBe(false);
});

test("the three dots check flags three dots and leaves the ellipsis character alone", () => {
expect(hasThreeDots("espera...")).toBe(true);
expect(hasThreeDots("espera…")).toBe(false);
expect(hasThreeDots("uno. dos.")).toBe(false);
});

test("the Spanish marks check flags a question or exclamation with no opening mark", () => {
expect(unbalancedMarks("¿Cómo estás?")).toBe(false);
expect(unbalancedMarks("¡Hola!")).toBe(false);
expect(unbalancedMarks("¿Uno? ¡Dos!")).toBe(false);
expect(unbalancedMarks("sin signos")).toBe(false);
expect(unbalancedMarks("Cómo estás?")).toBe(true);
expect(unbalancedMarks("¿Cómo estás")).toBe(true);
expect(unbalancedMarks("Hola!")).toBe(true);
expect(unbalancedMarks("¡Hola")).toBe(true);
});

test("no value in either locale has two spaces in a row", () => {
for (const [k, v] of all) expect(hasDoubleSpace(v), k).toBe(false);
});

test("no value in either locale starts or ends with a space, tab or line break", () => {
for (const [k, v] of all) expect(hasEdgeSpace(v), k).toBe(false);
});

test("no value in either locale has three dots", () => {
for (const [k, v] of all) expect(hasThreeDots(v), k).toBe(false);
});

test("in es-419 the opening marks match the closing ones in every value", () => {
for (const [k, v] of Object.entries(es)) {
expect(count(v, "¿"), k).toBe(count(v, "?"));
expect(count(v, "¡"), k).toBe(count(v, "!"));
}
});
});
Loading
Loading