Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cb62b0260 | ||
|
|
ba0b2032cc | ||
|
|
ed230961e0 | ||
|
|
b1c14ed7d9 | ||
|
|
09a5fcbcc2 | ||
|
|
d961d2e64f | ||
|
|
5316f95086 | ||
|
|
bdf6d0aca1 | ||
|
|
fb9907ae7f | ||
|
|
dbf410ada3 | ||
|
|
2906da7ed1 | ||
|
|
4f609d7bb9 | ||
|
|
39e0d715fc |
@@ -1,5 +1,84 @@
|
||||
# NestQuest Release Notes
|
||||
|
||||
## Version 0.9.0 — 2026-09-26
|
||||
|
||||
### Scope
|
||||
|
||||
Minor release carrying expanded, customisable task icons — Lucide, Font Awesome
|
||||
Free and emoji — onto `main`.
|
||||
|
||||
- **Namespaced icon keys:** a quest definition's `icon` now accepts
|
||||
`lucide:<kebab-name>`, `fa:<kebab-name>` and `emoji:<grapheme>`. A legacy bare
|
||||
name (e.g. `dog`) is read as `lucide:dog`, so existing rows keep working with
|
||||
no stored-data migration. The strict write validator rejects an unknown
|
||||
namespace, a malformed name, an over-cap or markup-bearing emoji payload, and
|
||||
`javascript:`. (PRs #241, #249.)
|
||||
- **Shared icon registry:** one canonical set — the curated Lucide set plus a
|
||||
curated Font Awesome Free solid subset — generates identical,
|
||||
framework-agnostic registry modules for the admin and panel bundles, guarded by
|
||||
a drift test. There is no CDN and no runtime fetch, and only the curated Font
|
||||
Awesome glyphs are shipped. (PR #242.)
|
||||
- **Admin PWA picker:** the definition edit sheet offers the Lucide set, the
|
||||
Font Awesome subset and an emoji input; a selection stores the namespaced key
|
||||
and an existing namespaced or legacy icon pre-fills correctly. The definition
|
||||
list renders all three forms with a fallback glyph. Editing a definition whose
|
||||
stored icon is a legacy value no longer resubmits the unchanged icon.
|
||||
(PRs #243, #250.)
|
||||
- **Kids' panel:** open quest cards render the definition's icon (Lucide stroked,
|
||||
Font Awesome filled, emoji as text) with the existing star fallback; the sealed
|
||||
card keeps its star/seal glyph. (PR #245.)
|
||||
- **Docs and attribution:** ADMIN-SPEC and PANEL-SPEC describe the namespaced
|
||||
model; `THIRD-PARTY-NOTICES.md` records Font Awesome Free (icons CC BY 4.0,
|
||||
fonts SIL OFL 1.1, code MIT) and Lucide (ISC). (PR #246.)
|
||||
|
||||
### Upgrade note
|
||||
|
||||
The database schema is unchanged at version **9**; no migration or backup step
|
||||
is needed beyond the 0.8.0 note. This release adds no runtime dependency — the
|
||||
icon path data is embedded in the shipped bundles at build time.
|
||||
|
||||
### Requirements
|
||||
|
||||
Home Assistant 2024.6.0 or newer. Install through HACS from the
|
||||
`Maniacs-Mansion/NestQuest` GitHub mirror (kept current by the Gitea push
|
||||
mirror).
|
||||
|
||||
## Version 0.8.0 — 2026-09-25
|
||||
|
||||
### Scope
|
||||
|
||||
Minor release carrying the multi-pattern presence model (schema 9), the
|
||||
Sunday-first calendar week, and the create-materializes fix, plus the
|
||||
definition start-date field, onto `main`.
|
||||
|
||||
- **Multiple presence patterns per child (schema 9):** a child now has zero or
|
||||
more presence patterns instead of at most one. Each pattern has a name, a kind
|
||||
(`home` or `away`), its own cycle length (1–4 weeks), its own anchor date and a
|
||||
per-week weekday set. Evaluation is first-match-wins — overrides, then away,
|
||||
then home, then absent when the child has at least one home pattern, else
|
||||
present. Migration 9 copies each existing schedule into a `home` pattern named
|
||||
"Home schedule" and drops the old `presence_schedules` table. (PRs #231, #232.)
|
||||
- **Sunday-first calendar week:** the admin Schedule month grid and the
|
||||
Definitions weekday picker now render weeks Sunday-first; the stored/API
|
||||
weekday numbering is unchanged (Monday=0..Sunday=6). (PR #230.)
|
||||
- **Fix — newly created tasks materialize immediately:** creating a quest
|
||||
definition now regenerates its future instances over the rolling horizon, so a
|
||||
new task reaches the panel without waiting for an unrelated write. (PRs #235,
|
||||
#236.)
|
||||
- **Definition start date:** the definition edit sheet gains a Start date field
|
||||
so a task can be scheduled to begin on a future date. (PRs #237, #238.)
|
||||
- **Docs:** the multi-pattern decision (D-016), the migration-9 rollback step in
|
||||
the runbook, and the ADMIN-SPEC Schedule section. (PRs #233, #234.)
|
||||
|
||||
### Upgrade note
|
||||
|
||||
This release runs schema version **9**. Version 0.7.1 refuses a version-9
|
||||
database, so take a copy of the SQLite file (or note the Litestream generation)
|
||||
before the first start on 0.8.0 if you need a rollback path.
|
||||
|
||||
### Requirements
|
||||
|
||||
|
||||
## Version 0.7.1 — 2026-09-24
|
||||
|
||||
### Scope
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Third-party notices
|
||||
|
||||
NestQuest bundles glyph data from the icon sets below. The curated names are listed in
|
||||
`tools/icons/curated-icons.json`; `tools/icons/generate.mjs` reads each glyph's SVG path
|
||||
data from the locally installed packages and generates it into both bundles
|
||||
(`admin/src/icons/registry.generated.ts` and `frontend/src/icons/registry.generated.ts`).
|
||||
Nothing is loaded from a CDN or fetched at runtime. The package versions used are recorded
|
||||
in the header of each generated file.
|
||||
|
||||
## Font Awesome Free
|
||||
|
||||
- Project: <https://fontawesome.com> · repository: <https://github.com/FortAwesome/Font-Awesome>
|
||||
- Package: `@fortawesome/free-solid-svg-icons`
|
||||
- Licence: <https://fontawesome.com/license/free>
|
||||
- Icons: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/)
|
||||
- Fonts: [SIL OFL 1.1](https://openfontlicense.org)
|
||||
- Code: [MIT](https://opensource.org/licenses/MIT)
|
||||
- Use in NestQuest: a curated subset of the Free **solid** icon set, embedded as SVG path
|
||||
data. No fonts are bundled.
|
||||
|
||||
Font Awesome Free by @fontawesome — https://fontawesome.com — icons licensed under CC BY 4.0.
|
||||
|
||||
## Lucide
|
||||
|
||||
- Project: <https://lucide.dev> · repository: <https://github.com/lucide-icons/lucide>
|
||||
- Package: `lucide-react`
|
||||
- Licence: [ISC](https://github.com/lucide-icons/lucide/blob/main/LICENSE)
|
||||
- Use in NestQuest: a curated subset of Lucide icons, embedded as SVG path data.
|
||||
|
||||
Lucide icons are Copyright (c) Lucide Contributors, licensed under the ISC License.
|
||||
Portions derived from Feather are Copyright (c) Cole Bemis, licensed under the MIT License.
|
||||
Generated
+26
-1
@@ -8,17 +8,18 @@
|
||||
"name": "nestquest-admin",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"lucide-react": "^1.47.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@fortawesome/free-solid-svg-icons": "7.3.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/react": "^19.2.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"jsdom": "^30.1.1",
|
||||
"lucide-react": "1.47.0",
|
||||
"typescript": "^5.9.2",
|
||||
"vite": "^7.1.5",
|
||||
"vitest": "^3.2.4"
|
||||
@@ -982,6 +983,29 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@fortawesome/fontawesome-common-types": {
|
||||
"version": "7.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-7.3.1.tgz",
|
||||
"integrity": "sha512-k0C0sdHmZtAo6dRDtd1Z/qcpyHbL0CKsjV8seMY/21xGhY5Wsv0XRmiI/xEEH4y2c9b1+jvgNs/3EqhV27yUEA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@fortawesome/free-solid-svg-icons": {
|
||||
"version": "7.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-7.3.1.tgz",
|
||||
"integrity": "sha512-v0BLa0eqg7ubvVWeNSHVBs8fWH/GJicERZoJaxJ3FE/lj67VSqzoMg9pzfZVOfLMX10y0pGwQAuxoRVVH2patg==",
|
||||
"dev": true,
|
||||
"license": "(CC-BY-4.0 AND MIT)",
|
||||
"dependencies": {
|
||||
"@fortawesome/fontawesome-common-types": "7.3.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@jridgewell/gen-mapping": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||
@@ -2262,6 +2286,7 @@
|
||||
"version": "1.47.0",
|
||||
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.47.0.tgz",
|
||||
"integrity": "sha512-o8C23aXpNQypRY73W7fW02EyvWJinEMXgKeGjFoKym0zj3Q73hD97A1IQps1g8C14HTGsOpZL0Am+xjfgFZAbg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"peerDependencies": {
|
||||
"react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
|
||||
+2
-1
@@ -10,17 +10,18 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"lucide-react": "^1.47.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@fortawesome/free-solid-svg-icons": "7.3.1",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/react": "^19.2.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"jsdom": "^30.1.1",
|
||||
"lucide-react": "1.47.0",
|
||||
"typescript": "^5.9.2",
|
||||
"vite": "^7.1.5",
|
||||
"vitest": "^3.2.4"
|
||||
|
||||
@@ -147,10 +147,36 @@ export async function updateDefinition(
|
||||
return readJson<QuestDefinition>(await sendJson(`${DEFINITIONS_PATH}/${id}`, "PATCH", body));
|
||||
}
|
||||
|
||||
/** `DELETE /quest-definitions/{id}`: exactly one of `deleted` / `retired` is true. */
|
||||
export interface DefinitionDeleteResult {
|
||||
definition_id: number;
|
||||
deleted: boolean;
|
||||
retired: boolean;
|
||||
/** The retired (now inactive) definition; null when it was deleted. */
|
||||
definition: QuestDefinition | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a task if it has no completion history; otherwise the API retires
|
||||
* (deactivates) it. Retirement preserves the definition row, schedule rule,
|
||||
* assignees, windows and ALL durable completion history. Like any
|
||||
* deactivation it regenerates, so future UNCOMPLETED instances are cleared
|
||||
* (rolling, regenerable rows) and not recreated while inactive; durable
|
||||
* history lives only in the append-only `completion_events`.
|
||||
*/
|
||||
export async function deleteDefinition(id: number): Promise<DefinitionDeleteResult> {
|
||||
return readJson<DefinitionDeleteResult>(
|
||||
await apiFetch(`${DEFINITIONS_PATH}/${id}`, { method: "DELETE" }),
|
||||
);
|
||||
}
|
||||
|
||||
export const OCCURRENCES_PREVIEW_PATH = `${DEFINITIONS_PATH}/occurrences-preview`;
|
||||
|
||||
export interface OccurrencesPreviewOptions {
|
||||
/** "YYYY-MM-DD"; the API defaults to its host's today. */
|
||||
/**
|
||||
* "YYYY-MM-DD"; the API defaults to the household-local today in the
|
||||
* configured `timezone` (the API host's local time when that is empty).
|
||||
*/
|
||||
startDate?: string;
|
||||
/** 1..50; the API defaults to 10. */
|
||||
count?: number;
|
||||
|
||||
@@ -569,6 +569,26 @@
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.defs-save--danger {
|
||||
background: var(--nq-a-danger);
|
||||
}
|
||||
|
||||
.defs-delete {
|
||||
display: block;
|
||||
width: 100%;
|
||||
margin-top: 10px;
|
||||
padding: 11px 0;
|
||||
border: 1px solid var(--nq-a-danger-bg);
|
||||
border-radius: var(--nq-a-density-radius);
|
||||
background: var(--nq-a-surface);
|
||||
color: var(--nq-a-danger-strong);
|
||||
font-family: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.defs-delete:disabled,
|
||||
.defs-cancel:disabled,
|
||||
.defs-save:disabled {
|
||||
opacity: 0.6;
|
||||
@@ -583,3 +603,14 @@
|
||||
color: var(--nq-a-ink-secondary);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.defs-sublabel {
|
||||
margin-top: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--nq-a-ink-secondary);
|
||||
}
|
||||
|
||||
.defs-emoji {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import DefinitionsTab from "./DefinitionsTab";
|
||||
import { DEFINITION_ICONS, DefinitionIcon } from "./definitionIcons";
|
||||
import {
|
||||
DEFINITION_ICONS,
|
||||
DefinitionIcon,
|
||||
FA_DEFINITION_ICONS,
|
||||
emojiIconKey,
|
||||
faIconName,
|
||||
findDefinitionIcon,
|
||||
normalizeDefinitionIconName,
|
||||
} from "./definitionIcons";
|
||||
import type { AdminChild, DefinitionRule, QuestDefinition } from "../api/definitions";
|
||||
import { storeTokens } from "../auth/oidc";
|
||||
|
||||
@@ -113,6 +121,8 @@ function fakeApi(initial: QuestDefinition[]) {
|
||||
const calls: Call[] = [];
|
||||
let nextWrite: Response | null = null;
|
||||
let preview: PreviewHandler = async () => jsonResponse({ dates: [] });
|
||||
// Definitions with completion history: the API retires these on DELETE.
|
||||
const withHistory = new Set<number>();
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL, init: RequestInit = {}) => {
|
||||
const path = new URL(String(input), "http://localhost").pathname;
|
||||
const method = init.method ?? "GET";
|
||||
@@ -153,6 +163,10 @@ function fakeApi(initial: QuestDefinition[]) {
|
||||
}
|
||||
const match = /^\/api\/v1\/admin\/quest-definitions\/(\d+)$/.exec(path);
|
||||
if (method === "PATCH" && match) {
|
||||
// Like the API's strict validate_icon: a Lucide name never has a colon.
|
||||
if (typeof body.icon === "string" && /^lucide:.*:/.test(body.icon)) {
|
||||
return jsonResponse({ detail: "icon is not a valid icon key" }, 422);
|
||||
}
|
||||
const id = Number(match[1]);
|
||||
definitions = definitions.map((d) =>
|
||||
d.id === id
|
||||
@@ -175,6 +189,16 @@ function fakeApi(initial: QuestDefinition[]) {
|
||||
);
|
||||
return jsonResponse(definitions.find((d) => d.id === id));
|
||||
}
|
||||
if (method === "DELETE" && match) {
|
||||
const id = Number(match[1]);
|
||||
if (withHistory.has(id)) {
|
||||
definitions = definitions.map((d) => (d.id === id ? { ...d, is_active: false } : d));
|
||||
const retired = definitions.find((d) => d.id === id);
|
||||
return jsonResponse({ definition_id: id, deleted: false, retired: true, definition: retired });
|
||||
}
|
||||
definitions = definitions.filter((d) => d.id !== id);
|
||||
return jsonResponse({ definition_id: id, deleted: true, retired: false, definition: null });
|
||||
}
|
||||
return jsonResponse({ detail: "unexpected" }, 500);
|
||||
});
|
||||
return {
|
||||
@@ -191,6 +215,9 @@ function fakeApi(initial: QuestDefinition[]) {
|
||||
failNextWrite: (response: Response) => {
|
||||
nextWrite = response;
|
||||
},
|
||||
markHistory: (id: number) => {
|
||||
withHistory.add(id);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -455,7 +482,6 @@ describe("DefinitionsTab", () => {
|
||||
path: "/api/v1/admin/quest-definitions/11",
|
||||
body: {
|
||||
title: "Take out the bins",
|
||||
icon: null,
|
||||
rule: {
|
||||
rule_type: "monthly_day",
|
||||
interval: 1,
|
||||
@@ -567,14 +593,15 @@ describe("DefinitionsTab", () => {
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
const s = sheet();
|
||||
const title = within(s).getByRole("textbox", { name: "Title" });
|
||||
const save = within(s).getByRole("button", { name: "Save changes" });
|
||||
// The edit sheet's last focusable control is its Delete button.
|
||||
const last = within(s).getByRole("button", { name: "Delete task" });
|
||||
|
||||
save.focus();
|
||||
last.focus();
|
||||
fireEvent.keyDown(s, { key: "Tab" });
|
||||
expect(document.activeElement).toBe(title);
|
||||
|
||||
fireEvent.keyDown(s, { key: "Tab", shiftKey: true });
|
||||
expect(document.activeElement).toBe(save);
|
||||
expect(document.activeElement).toBe(last);
|
||||
});
|
||||
|
||||
it("Escape does not close the sheet while saving", async () => {
|
||||
@@ -683,6 +710,73 @@ describe("DefinitionsTab", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("the Delete control is only offered for an existing task", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByRole("button", { name: "New" }));
|
||||
expect(within(sheet()).queryByRole("button", { name: "Delete task" })).toBeNull();
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Cancel" }));
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
expect(within(sheet()).getByRole("button", { name: "Delete task" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("Delete asks first, explaining delete-vs-retire; Go back writes nothing", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
|
||||
const confirm = screen.getByTestId("delete-confirm");
|
||||
expect(confirm.textContent).toContain("If it has no completion history it is deleted");
|
||||
expect(confirm.textContent).toContain("otherwise it is retired");
|
||||
expect(api.writes()).toHaveLength(0);
|
||||
fireEvent.click(within(confirm).getByRole("button", { name: "Go back" }));
|
||||
expect(screen.queryByTestId("delete-confirm")).toBeNull();
|
||||
expect(api.writes()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("confirming Delete on a task without history removes its row", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
|
||||
fireEvent.click(
|
||||
within(screen.getByTestId("delete-confirm")).getByRole("button", { name: "Delete task" }),
|
||||
);
|
||||
await waitFor(() => expect(screen.queryByTestId("definition-10")).toBeNull());
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
expect(api.writes()).toEqual([
|
||||
{ method: "DELETE", path: "/api/v1/admin/quest-definitions/10", body: null },
|
||||
]);
|
||||
expect(screen.getByTestId("definition-11")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("confirming Delete on a task with history shows it retired (inactive)", async () => {
|
||||
await renderReady();
|
||||
api.markHistory(10);
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
|
||||
fireEvent.click(
|
||||
within(screen.getByTestId("delete-confirm")).getByRole("button", { name: "Delete task" }),
|
||||
);
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
|
||||
const row = screen.getByTestId("definition-10");
|
||||
expect(row.className).toContain("defs-row--inactive");
|
||||
expect(meta(row)).toContain("· inactive");
|
||||
expect(api.writes().map((c) => c.method)).toEqual(["DELETE"]);
|
||||
});
|
||||
|
||||
it("a failed Delete shows the API's detail and keeps the sheet open", async () => {
|
||||
await renderReady();
|
||||
api.failNextWrite(jsonResponse({ detail: "Quest definition not found" }, 404));
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
fireEvent.click(within(sheet()).getByRole("button", { name: "Delete task" }));
|
||||
fireEvent.click(
|
||||
within(screen.getByTestId("delete-confirm")).getByRole("button", { name: "Delete task" }),
|
||||
);
|
||||
expect((await screen.findByTestId("sheet-error")).textContent).toBe(
|
||||
"Quest definition not found",
|
||||
);
|
||||
expect(screen.getByRole("dialog")).toBeTruthy();
|
||||
expect(screen.getByTestId("definition-10")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("scroll column carries the 92px bottom padding", async () => {
|
||||
await renderReady();
|
||||
expect(screen.getByTestId("definitions-scroll").style.paddingBottom).toBe("92px");
|
||||
@@ -1052,7 +1146,7 @@ describe("DefinitionsTab icon picker", () => {
|
||||
|
||||
expect(api.writes()).toHaveLength(1);
|
||||
expect(api.writes()[0].method).toBe("POST");
|
||||
expect((api.writes()[0].body as { icon: string }).icon).toBe("bed");
|
||||
expect((api.writes()[0].body as { icon: string }).icon).toBe("lucide:bed");
|
||||
expect(rowIcon(await screen.findByTestId("definition-99"))).toBe("bed");
|
||||
});
|
||||
|
||||
@@ -1073,13 +1167,13 @@ describe("DefinitionsTab icon picker", () => {
|
||||
const { method, path, body } = api.writes()[0];
|
||||
expect(method).toBe("PATCH");
|
||||
expect(path).toBe("/api/v1/admin/quest-definitions/11");
|
||||
expect((body as { icon: string }).icon).toBe("trash-2");
|
||||
expect((body as { icon: string }).icon).toBe("lucide:trash-2");
|
||||
// Inactive "Old" stays assigned: the unchanged selection is still omitted.
|
||||
expect(body).not.toHaveProperty("assignee_child_ids");
|
||||
await waitFor(() => expect(rowIcon(screen.getByTestId("definition-11"))).toBe("trash-2"));
|
||||
});
|
||||
|
||||
it("an unchanged icon is still sent on edit and shows as selected", async () => {
|
||||
it("an unchanged icon is omitted on edit and shows as selected", async () => {
|
||||
await renderReady();
|
||||
expect(rowIcon(screen.getByTestId("definition-10"))).toBe("smile");
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
@@ -1093,7 +1187,7 @@ describe("DefinitionsTab icon picker", () => {
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Save changes" }));
|
||||
});
|
||||
|
||||
expect((api.writes()[0].body as { icon: string }).icon).toBe("smile");
|
||||
expect(api.writes()[0].body).not.toHaveProperty("icon");
|
||||
});
|
||||
|
||||
it("an unknown legacy icon falls back to the generic glyph and is kept on save", async () => {
|
||||
@@ -1113,8 +1207,519 @@ describe("DefinitionsTab icon picker", () => {
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Save changes" }));
|
||||
});
|
||||
|
||||
expect((api.writes()[0].body as { icon: string }).icon).toBe("rocket-ship-9000");
|
||||
expect(api.writes()[0].body).not.toHaveProperty("icon");
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
|
||||
expect(rowIcon(screen.getByTestId("definition-20"))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("DefinitionsTab namespaced icons", () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
storeTokens({ access_token: "at-123", expires_in: 600 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function rowIcon(row: HTMLElement): string | null {
|
||||
const svg = row.querySelector(".defs-row-glyph svg");
|
||||
expect(svg).not.toBeNull();
|
||||
return svg!.getAttribute("data-icon");
|
||||
}
|
||||
|
||||
function iconRadio(s: HTMLElement, label: string): HTMLElement {
|
||||
return within(within(s).getByRole("radiogroup", { name: "Icon" })).getByRole("radio", {
|
||||
name: label,
|
||||
});
|
||||
}
|
||||
|
||||
it("normalizes lucide-namespaced and legacy bare values to one Lucide name", () => {
|
||||
expect(normalizeDefinitionIconName("lucide:dog")).toBe("dog");
|
||||
expect(normalizeDefinitionIconName("dog")).toBe("dog");
|
||||
expect(normalizeDefinitionIconName("fa:dog")).toBeNull();
|
||||
expect(normalizeDefinitionIconName("emoji:🐶")).toBeNull();
|
||||
expect(normalizeDefinitionIconName("mystery:dog")).toBeNull();
|
||||
expect(normalizeDefinitionIconName(null)).toBeNull();
|
||||
});
|
||||
|
||||
for (const icon of ["lucide:dog", "dog"]) {
|
||||
it(`renders and selects the Dog glyph for ${icon}`, async () => {
|
||||
await renderReady([{ ...BRUSH, id: 30, icon }]);
|
||||
const row = screen.getByTestId("definition-30");
|
||||
expect(rowIcon(row)).toBe("dog");
|
||||
|
||||
fireEvent.click(row);
|
||||
const s = sheet();
|
||||
expect(iconRadio(s, "Dog").getAttribute("aria-checked")).toBe("true");
|
||||
expect(iconRadio(s, "Dog").className).toContain("defs-icon--on");
|
||||
expect(iconRadio(s, "No icon").getAttribute("aria-checked")).toBe("false");
|
||||
});
|
||||
}
|
||||
|
||||
for (const icon of ["mystery:dog", "lucide:not-an-icon", "fa:not-an-icon", "emoji:a b"]) {
|
||||
it(`renders the fallback tile and selects nothing for ${icon}`, async () => {
|
||||
await renderReady([{ ...BRUSH, id: 31, icon }]);
|
||||
const row = screen.getByTestId("definition-31");
|
||||
expect(rowIcon(row)).toBeNull();
|
||||
|
||||
fireEvent.click(row);
|
||||
const s = sheet();
|
||||
for (const name of ["Icon", "Font Awesome"]) {
|
||||
const group = within(s).getByRole("radiogroup", { name });
|
||||
for (const radio of within(group).getAllByRole("radio")) {
|
||||
expect(radio.getAttribute("aria-checked")).toBe("false");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it("tapping a Lucide choice on a namespaced task PATCHes lucide:<name>, and No icon clears it", async () => {
|
||||
await renderReady([{ ...BRUSH, id: 32, icon: "lucide:dog" }]);
|
||||
fireEvent.click(screen.getByTestId("definition-32"));
|
||||
let s = sheet();
|
||||
fireEvent.click(iconRadio(s, "Cat"));
|
||||
expect(iconRadio(s, "Cat").getAttribute("aria-checked")).toBe("true");
|
||||
expect(iconRadio(s, "Dog").getAttribute("aria-checked")).toBe("false");
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Save changes" }));
|
||||
});
|
||||
expect((api.writes()[0].body as { icon: string }).icon).toBe("lucide:cat");
|
||||
await waitFor(() => expect(rowIcon(screen.getByTestId("definition-32"))).toBe("cat"));
|
||||
|
||||
fireEvent.click(screen.getByTestId("definition-32"));
|
||||
s = sheet();
|
||||
expect(iconRadio(s, "Cat").getAttribute("aria-checked")).toBe("true");
|
||||
fireEvent.click(iconRadio(s, "No icon"));
|
||||
expect(iconRadio(s, "No icon").getAttribute("aria-checked")).toBe("true");
|
||||
await act(async () => {
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Save changes" }));
|
||||
});
|
||||
expect((api.writes()[1].body as { icon: string | null }).icon).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("DefinitionsTab Font Awesome and emoji icons", () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
storeTokens({ access_token: "at-123", expires_in: 600 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
/** What a row draws: `svg:<data-icon>`, `emoji:<text>`, or `fallback`. */
|
||||
function rowGlyph(row: HTMLElement): string {
|
||||
const glyph = row.querySelector(".defs-row-glyph");
|
||||
const emoji = glyph!.querySelector("[data-emoji]");
|
||||
if (emoji) return `emoji:${emoji.textContent}`;
|
||||
const svg = glyph!.querySelector("svg");
|
||||
expect(svg).not.toBeNull();
|
||||
const name = svg!.getAttribute("data-icon");
|
||||
if (name === null) return "fallback";
|
||||
return `${svg!.getAttribute("fill") === "none" ? "lucide" : "fa"}:${name}`;
|
||||
}
|
||||
|
||||
function radio(s: HTMLElement, group: "Icon" | "Font Awesome", label: string): HTMLElement {
|
||||
return within(within(s).getByRole("radiogroup", { name: group })).getByRole("radio", {
|
||||
name: label,
|
||||
});
|
||||
}
|
||||
|
||||
function emojiInput(s: HTMLElement): HTMLInputElement {
|
||||
return within(s).getByRole("textbox", { name: "Emoji" }) as HTMLInputElement;
|
||||
}
|
||||
|
||||
async function save(s: HTMLElement) {
|
||||
await act(async () => {
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Save changes" }));
|
||||
});
|
||||
}
|
||||
|
||||
function fillNewTask(s: HTMLElement) {
|
||||
fireEvent.change(within(s).getByRole("textbox", { name: "Title" }), {
|
||||
target: { value: "Walk the dog" },
|
||||
});
|
||||
fireEvent.click(within(s).getByRole("button", { name: /Assigned children/ }));
|
||||
fireEvent.click(within(s).getByRole("checkbox", { name: "Declan" }));
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Morning" }));
|
||||
}
|
||||
|
||||
it("ships the curated Font Awesome subset, each drawn as a filled glyph", () => {
|
||||
expect(FA_DEFINITION_ICONS.length).toBeGreaterThan(0);
|
||||
for (const entry of FA_DEFINITION_ICONS) {
|
||||
expect(entry.kind).toBe("fa");
|
||||
expect(findDefinitionIcon(`fa:${entry.name}`)).toBe(entry);
|
||||
const { container, unmount } = render(<DefinitionIcon name={`fa:${entry.name}`} />);
|
||||
const svg = container.querySelector("svg");
|
||||
expect(svg, entry.name).not.toBeNull();
|
||||
expect(svg!.getAttribute("data-icon")).toBe(entry.name);
|
||||
expect(svg!.getAttribute("fill")).toBe("currentColor");
|
||||
unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("builds and validates emoji keys like the registry", () => {
|
||||
expect(emojiIconKey("🐶")).toBe("emoji:🐶");
|
||||
expect(emojiIconKey("👨👩👧👦")).toBe("emoji:👨👩👧👦");
|
||||
expect(emojiIconKey("⭐".repeat(8))).toBe(`emoji:${"⭐".repeat(8)}`);
|
||||
for (const bad of ["", " ", " 🐶 ", "🐶 ", "\t🐶", "⭐".repeat(9), "a b", "<b>", "a&b", "🐶\u0007"]) {
|
||||
expect(emojiIconKey(bad), JSON.stringify(bad)).toBeNull();
|
||||
}
|
||||
expect(faIconName("fa:dog")).toBe("dog");
|
||||
expect(faIconName("lucide:dog")).toBeNull();
|
||||
expect(faIconName(null)).toBeNull();
|
||||
});
|
||||
|
||||
it("renders lucide, legacy, fa and emoji rows, and the fallback for none or unknown", async () => {
|
||||
await renderReady([
|
||||
{ ...BRUSH, id: 40, icon: "lucide:dog" },
|
||||
{ ...BRUSH, id: 41, title: "Task 41", icon: "dog" },
|
||||
{ ...BRUSH, id: 42, title: "Task 42", icon: "fa:dog" },
|
||||
{ ...BRUSH, id: 43, title: "Task 43", icon: "emoji:🐶" },
|
||||
{ ...BRUSH, id: 44, title: "Task 44", icon: null },
|
||||
{ ...BRUSH, id: 45, title: "Task 45", icon: "" },
|
||||
{ ...BRUSH, id: 46, title: "Task 46", icon: "mystery:dog" },
|
||||
]);
|
||||
expect(rowGlyph(screen.getByTestId("definition-40"))).toBe("lucide:dog");
|
||||
expect(rowGlyph(screen.getByTestId("definition-41"))).toBe("lucide:dog");
|
||||
expect(rowGlyph(screen.getByTestId("definition-42"))).toBe("fa:dog");
|
||||
expect(rowGlyph(screen.getByTestId("definition-43"))).toBe("emoji:🐶");
|
||||
expect(rowGlyph(screen.getByTestId("definition-44"))).toBe("fallback");
|
||||
expect(rowGlyph(screen.getByTestId("definition-45"))).toBe("fallback");
|
||||
expect(rowGlyph(screen.getByTestId("definition-46"))).toBe("fallback");
|
||||
});
|
||||
|
||||
it("a Font Awesome choice is POSTed as fa:<name> and renders on its row", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByRole("button", { name: "New" }));
|
||||
const s = sheet();
|
||||
fillNewTask(s);
|
||||
fireEvent.click(radio(s, "Font Awesome", "Dog"));
|
||||
expect(radio(s, "Font Awesome", "Dog").getAttribute("aria-checked")).toBe("true");
|
||||
expect(radio(s, "Font Awesome", "Dog").className).toContain("defs-icon--on");
|
||||
expect(radio(s, "Icon", "Dog").getAttribute("aria-checked")).toBe("false");
|
||||
expect(radio(s, "Icon", "No icon").getAttribute("aria-checked")).toBe("false");
|
||||
|
||||
await save(s);
|
||||
expect(api.writes()).toHaveLength(1);
|
||||
expect(api.writes()[0].method).toBe("POST");
|
||||
expect((api.writes()[0].body as { icon: string }).icon).toBe("fa:dog");
|
||||
expect(rowGlyph(await screen.findByTestId("definition-99"))).toBe("fa:dog");
|
||||
});
|
||||
|
||||
it("a typed emoji is POSTed as emoji:<grapheme> and renders on its row", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByRole("button", { name: "New" }));
|
||||
const s = sheet();
|
||||
fillNewTask(s);
|
||||
fireEvent.change(emojiInput(s), { target: { value: "🐶" } });
|
||||
expect(radio(s, "Icon", "No icon").getAttribute("aria-checked")).toBe("false");
|
||||
|
||||
await save(s);
|
||||
expect(api.writes()).toHaveLength(1);
|
||||
expect((api.writes()[0].body as { icon: string }).icon).toBe("emoji:🐶");
|
||||
expect(rowGlyph(await screen.findByTestId("definition-99"))).toBe("emoji:🐶");
|
||||
});
|
||||
|
||||
it("a Lucide choice is POSTed as lucide:<name> after an emoji was typed", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByRole("button", { name: "New" }));
|
||||
const s = sheet();
|
||||
fillNewTask(s);
|
||||
fireEvent.change(emojiInput(s), { target: { value: "🐶" } });
|
||||
fireEvent.click(radio(s, "Icon", "Dog"));
|
||||
expect(emojiInput(s).value).toBe("");
|
||||
|
||||
await save(s);
|
||||
expect((api.writes()[0].body as { icon: string }).icon).toBe("lucide:dog");
|
||||
expect(rowGlyph(await screen.findByTestId("definition-99"))).toBe("lucide:dog");
|
||||
});
|
||||
|
||||
for (const bad of [" 🐶 ", "🐶 ", " ", "a b", "<b>", "a&b", "⭐".repeat(9)]) {
|
||||
it(`an invalid emoji entry ${JSON.stringify(bad)} is not saved`, async () => {
|
||||
await renderReady([{ ...BRUSH, id: 50, icon: "lucide:dog" }]);
|
||||
fireEvent.click(screen.getByTestId("definition-50"));
|
||||
const s = sheet();
|
||||
fireEvent.change(emojiInput(s), { target: { value: bad } });
|
||||
|
||||
await save(s);
|
||||
expect(api.writes()).toHaveLength(0);
|
||||
expect(within(s).getByText(/Enter a single emoji/)).toBeTruthy();
|
||||
expect(screen.getByRole("dialog")).toBe(s);
|
||||
});
|
||||
}
|
||||
|
||||
it("prefills a fa:<name> task and PATCHes an emoji replacement", async () => {
|
||||
await renderReady([{ ...BRUSH, id: 51, icon: "fa:dog" }]);
|
||||
fireEvent.click(screen.getByTestId("definition-51"));
|
||||
const s = sheet();
|
||||
expect(radio(s, "Font Awesome", "Dog").getAttribute("aria-checked")).toBe("true");
|
||||
expect(radio(s, "Icon", "Dog").getAttribute("aria-checked")).toBe("false");
|
||||
expect(radio(s, "Icon", "No icon").getAttribute("aria-checked")).toBe("false");
|
||||
expect(emojiInput(s).value).toBe("");
|
||||
|
||||
fireEvent.change(emojiInput(s), { target: { value: "🐱" } });
|
||||
expect(radio(s, "Font Awesome", "Dog").getAttribute("aria-checked")).toBe("false");
|
||||
await save(s);
|
||||
const { method, path, body } = api.writes()[0];
|
||||
expect(method).toBe("PATCH");
|
||||
expect(path).toBe("/api/v1/admin/quest-definitions/51");
|
||||
expect((body as { icon: string }).icon).toBe("emoji:🐱");
|
||||
await waitFor(() => expect(rowGlyph(screen.getByTestId("definition-51"))).toBe("emoji:🐱"));
|
||||
});
|
||||
|
||||
it("prefills an emoji:<grapheme> task and PATCHes a Font Awesome replacement", async () => {
|
||||
await renderReady([{ ...BRUSH, id: 52, icon: "emoji:🐶" }]);
|
||||
fireEvent.click(screen.getByTestId("definition-52"));
|
||||
const s = sheet();
|
||||
expect(emojiInput(s).value).toBe("🐶");
|
||||
expect(radio(s, "Icon", "No icon").getAttribute("aria-checked")).toBe("false");
|
||||
for (const name of ["Icon", "Font Awesome"]) {
|
||||
const group = within(s).getByRole("radiogroup", { name });
|
||||
expect(within(group).queryAllByRole("radio", { checked: true })).toHaveLength(0);
|
||||
}
|
||||
|
||||
fireEvent.click(radio(s, "Font Awesome", "Pets"));
|
||||
expect(emojiInput(s).value).toBe("");
|
||||
await save(s);
|
||||
expect((api.writes()[0].body as { icon: string }).icon).toBe("fa:paw");
|
||||
await waitFor(() => expect(rowGlyph(screen.getByTestId("definition-52"))).toBe("fa:paw"));
|
||||
});
|
||||
|
||||
it("an unchanged emoji is omitted on edit", async () => {
|
||||
await renderReady([{ ...BRUSH, id: 53, icon: "emoji:🐶" }]);
|
||||
fireEvent.click(screen.getByTestId("definition-53"));
|
||||
const s = sheet();
|
||||
fireEvent.change(within(s).getByRole("textbox", { name: "Title" }), {
|
||||
target: { value: "Feed the dog" },
|
||||
});
|
||||
await save(s);
|
||||
expect(api.writes()[0].body).not.toHaveProperty("icon");
|
||||
});
|
||||
|
||||
it("No icon and an emptied emoji field both clear the icon to null", async () => {
|
||||
await renderReady([
|
||||
{ ...BRUSH, id: 54, icon: "emoji:🐶" },
|
||||
{ ...BRUSH, id: 55, title: "Task 55", icon: "fa:dog" },
|
||||
]);
|
||||
fireEvent.click(screen.getByTestId("definition-54"));
|
||||
let s = sheet();
|
||||
fireEvent.change(emojiInput(s), { target: { value: "" } });
|
||||
expect(radio(s, "Icon", "No icon").getAttribute("aria-checked")).toBe("true");
|
||||
await save(s);
|
||||
expect((api.writes()[0].body as { icon: string | null }).icon).toBeNull();
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
|
||||
|
||||
fireEvent.click(screen.getByTestId("definition-55"));
|
||||
s = sheet();
|
||||
fireEvent.click(radio(s, "Icon", "No icon"));
|
||||
expect(radio(s, "Font Awesome", "Dog").getAttribute("aria-checked")).toBe("false");
|
||||
await save(s);
|
||||
expect((api.writes()[1].body as { icon: string | null }).icon).toBeNull();
|
||||
await waitFor(() => expect(rowGlyph(screen.getByTestId("definition-55"))).toBe("fallback"));
|
||||
});
|
||||
});
|
||||
|
||||
/* ── Legacy icons ───────────────────────────────────────────────────── */
|
||||
|
||||
describe("DefinitionsTab legacy icon edits", () => {
|
||||
// The API reads a stored legacy `mdi:tooth` back as `lucide:mdi:tooth`,
|
||||
// which its strict write validation rejects if sent back.
|
||||
const LEGACY: QuestDefinition = { ...BRUSH, id: 60, icon: "lucide:mdi:tooth" };
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
storeTokens({ access_token: "at-123", expires_in: 600 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function radio(s: HTMLElement, group: "Icon" | "Font Awesome", label: string): HTMLElement {
|
||||
return within(within(s).getByRole("radiogroup", { name: group })).getByRole("radio", {
|
||||
name: label,
|
||||
});
|
||||
}
|
||||
|
||||
async function save(s: HTMLElement) {
|
||||
await act(async () => {
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Save changes" }));
|
||||
});
|
||||
}
|
||||
|
||||
it("editing only the title omits the legacy icon and saves", async () => {
|
||||
await renderReady([LEGACY]);
|
||||
fireEvent.click(screen.getByTestId("definition-60"));
|
||||
const s = sheet();
|
||||
fireEvent.change(within(s).getByRole("textbox", { name: "Title" }), {
|
||||
target: { value: "Brush teeth well" },
|
||||
});
|
||||
await save(s);
|
||||
|
||||
expect(api.writes()).toHaveLength(1);
|
||||
expect(api.writes()[0].method).toBe("PATCH");
|
||||
expect(api.writes()[0].body).not.toHaveProperty("icon");
|
||||
expect((api.writes()[0].body as { title: string }).title).toBe("Brush teeth well");
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
|
||||
expect(await screen.findByText("Brush teeth well")).toBeTruthy();
|
||||
});
|
||||
|
||||
for (const [label, choose, sent] of [
|
||||
["a Lucide", (s: HTMLElement) => fireEvent.click(radio(s, "Icon", "Dog")), "lucide:dog"],
|
||||
["a Font Awesome", (s: HTMLElement) => fireEvent.click(radio(s, "Font Awesome", "Dog")), "fa:dog"],
|
||||
[
|
||||
"an emoji",
|
||||
(s: HTMLElement) =>
|
||||
fireEvent.change(within(s).getByRole("textbox", { name: "Emoji" }), {
|
||||
target: { value: "🦷" },
|
||||
}),
|
||||
"emoji:🦷",
|
||||
],
|
||||
["No icon", (s: HTMLElement) => fireEvent.click(radio(s, "Icon", "No icon")), null],
|
||||
] as const) {
|
||||
it(`choosing ${label} replacement for the legacy icon sends ${JSON.stringify(sent)}`, async () => {
|
||||
await renderReady([LEGACY]);
|
||||
fireEvent.click(screen.getByTestId("definition-60"));
|
||||
const s = sheet();
|
||||
choose(s);
|
||||
await save(s);
|
||||
|
||||
expect(api.writes()).toHaveLength(1);
|
||||
expect(api.writes()[0].body).toHaveProperty("icon", sent);
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
|
||||
});
|
||||
}
|
||||
|
||||
it("an invalid emoji replacing the legacy icon is still rejected before the request", async () => {
|
||||
await renderReady([LEGACY]);
|
||||
fireEvent.click(screen.getByTestId("definition-60"));
|
||||
const s = sheet();
|
||||
fireEvent.change(within(s).getByRole("textbox", { name: "Emoji" }), {
|
||||
target: { value: "a b" },
|
||||
});
|
||||
await save(s);
|
||||
|
||||
expect(api.writes()).toHaveLength(0);
|
||||
expect(within(s).getByText(/Enter a single emoji/)).toBeTruthy();
|
||||
});
|
||||
|
||||
it("creating a task still sends icon, even when none is chosen", async () => {
|
||||
await renderReady([LEGACY]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "New" }));
|
||||
const s = sheet();
|
||||
fireEvent.change(within(s).getByRole("textbox", { name: "Title" }), {
|
||||
target: { value: "Floss" },
|
||||
});
|
||||
fireEvent.click(within(s).getByRole("button", { name: /Assigned children/ }));
|
||||
fireEvent.click(within(s).getByRole("checkbox", { name: "Declan" }));
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Morning" }));
|
||||
await save(s);
|
||||
|
||||
expect(api.writes()).toHaveLength(1);
|
||||
expect(api.writes()[0].method).toBe("POST");
|
||||
expect(api.writes()[0].body).toHaveProperty("icon", null);
|
||||
});
|
||||
});
|
||||
|
||||
/* ── Start date ─────────────────────────────────────────────────────── */
|
||||
|
||||
function startDateInput(s: HTMLElement): HTMLInputElement {
|
||||
return within(s).getByLabelText("Start date", { selector: "input" }) as HTMLInputElement;
|
||||
}
|
||||
|
||||
describe("DefinitionsTab start date", () => {
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
storeTokens({ access_token: "at-123", expires_in: 600 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("a new task defaults to today and POSTs the chosen start date", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
vi.setSystemTime(new Date(2026, 8, 23, 9, 0)); // Wed 23 Sep 2026, local
|
||||
await renderReady();
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "New" }));
|
||||
const s = sheet();
|
||||
const input = startDateInput(s);
|
||||
expect(input.type).toBe("date");
|
||||
expect(input.value).toBe("2026-09-23");
|
||||
|
||||
fireEvent.change(within(s).getByRole("textbox", { name: "Title" }), {
|
||||
target: { value: "Feed the cat" },
|
||||
});
|
||||
fireEvent.click(within(s).getByRole("button", { name: /Assigned children/ }));
|
||||
fireEvent.click(within(s).getByRole("checkbox", { name: "Declan" }));
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Evening" }));
|
||||
fireEvent.change(input, { target: { value: "2026-10-15" } });
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Save changes" }));
|
||||
});
|
||||
expect(api.writes()).toHaveLength(1);
|
||||
expect(api.writes()[0].method).toBe("POST");
|
||||
expect((api.writes()[0].body as { rule: DefinitionRule }).rule.start_date).toBe("2026-10-15");
|
||||
});
|
||||
|
||||
it("an edit pre-fills the definition's start date and PATCHes a changed one", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
const s = sheet();
|
||||
const input = startDateInput(s);
|
||||
expect(input.value).toBe("2026-01-01");
|
||||
|
||||
fireEvent.change(input, { target: { value: "2026-11-02" } });
|
||||
await act(async () => {
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Save changes" }));
|
||||
});
|
||||
expect(api.writes()).toEqual([
|
||||
expect.objectContaining({
|
||||
method: "PATCH",
|
||||
path: "/api/v1/admin/quest-definitions/10",
|
||||
body: expect.objectContaining({ rule: rule({ start_date: "2026-11-02" }) }),
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("the occurrence preview requests the chosen start date", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
const s = sheet();
|
||||
await waitFor(() => expect(api.previews()).toHaveLength(1));
|
||||
|
||||
fireEvent.change(startDateInput(s), { target: { value: "2027-03-01" } });
|
||||
await settleDebounce();
|
||||
await waitFor(() => expect(api.previews()).toHaveLength(2));
|
||||
expect((api.previews()[1].body as { rule: DefinitionRule }).rule.start_date).toBe(
|
||||
"2027-03-01",
|
||||
);
|
||||
});
|
||||
|
||||
it("a cleared start date is not submitted", async () => {
|
||||
await renderReady();
|
||||
fireEvent.click(screen.getByTestId("definition-10"));
|
||||
const s = sheet();
|
||||
fireEvent.change(startDateInput(s), { target: { value: "" } });
|
||||
await act(async () => {
|
||||
fireEvent.click(within(s).getByRole("button", { name: "Save changes" }));
|
||||
});
|
||||
expect(api.writes()).toHaveLength(0);
|
||||
expect(within(s).getByText("Pick a start date.")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,12 +13,14 @@ import { ApiForbiddenError } from "../api/client";
|
||||
import {
|
||||
ApiRequestError,
|
||||
createDefinition,
|
||||
deleteDefinition,
|
||||
fetchChildren,
|
||||
fetchDefinitions,
|
||||
previewOccurrences,
|
||||
updateDefinition,
|
||||
type AdminChild,
|
||||
type DefinitionCreateBody,
|
||||
type DefinitionDeleteResult,
|
||||
type DefinitionEditBody,
|
||||
type DefinitionRule,
|
||||
type QuestDefinition,
|
||||
@@ -43,7 +45,18 @@ import {
|
||||
PlusGlyph,
|
||||
TaskGlyph,
|
||||
} from "./glyphs";
|
||||
import { DEFINITION_ICONS, DefinitionIcon } from "./definitionIcons";
|
||||
import {
|
||||
DEFINITION_ICONS,
|
||||
DefinitionIcon,
|
||||
FA_DEFINITION_ICONS,
|
||||
emojiIconKey,
|
||||
emojiIconText,
|
||||
faIconKey,
|
||||
faIconName,
|
||||
lucideIconKey,
|
||||
normalizeDefinitionIconName,
|
||||
} from "./definitionIcons";
|
||||
import { GlyphSvg } from "../icons/GlyphSvg";
|
||||
import "./DefinitionsTab.css";
|
||||
|
||||
/** ADMIN-SPEC §1: every scroll column ends with 92px so content clears the tab bar. */
|
||||
@@ -78,8 +91,13 @@ const WEEKDAY_LONG = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "S
|
||||
|
||||
interface Draft {
|
||||
title: string;
|
||||
/** A Lucide name; a legacy value outside the subset is kept until replaced. */
|
||||
/**
|
||||
* The stored icon key (`lucide:`, `fa:` or `emoji:`); a legacy value
|
||||
* outside the curated sets is kept until replaced.
|
||||
*/
|
||||
icon: string | null;
|
||||
/** The emoji field's text; typing in it sets `icon` to `emoji:<text>`. */
|
||||
emoji: string;
|
||||
assigneeIds: number[];
|
||||
repeats: Repeats;
|
||||
interval: string;
|
||||
@@ -120,6 +138,7 @@ function newDraft(activeChildren: AdminChild[]): Draft {
|
||||
return {
|
||||
title: "",
|
||||
icon: null,
|
||||
emoji: "",
|
||||
assigneeIds: activeChildren.length === 1 ? [activeChildren[0].id] : [],
|
||||
repeats: "daily",
|
||||
interval: "1",
|
||||
@@ -145,6 +164,7 @@ function draftFrom(definition: QuestDefinition, activeChildren: AdminChild[]): D
|
||||
return {
|
||||
title: definition.title,
|
||||
icon: definition.icon,
|
||||
emoji: emojiIconText(definition.icon),
|
||||
// Inactive children cannot be submitted (the API rejects them with 422).
|
||||
assigneeIds: definition.assignees.map((a) => a.id).filter((id) => active.has(id)),
|
||||
repeats: REPEATS_BY_RULE[rule.rule_type],
|
||||
@@ -177,6 +197,7 @@ function parseWhole(value: string, min: number, max: number): number | null {
|
||||
function buildRule(draft: Draft): DefinitionRule | string {
|
||||
const interval = parseWhole(draft.interval, 1, 999);
|
||||
if (interval === null) return "Interval must be a whole number of at least 1.";
|
||||
if (draft.startDate === "") return "Pick a start date.";
|
||||
const rule: DefinitionRule = {
|
||||
rule_type: "daily",
|
||||
interval,
|
||||
@@ -230,6 +251,9 @@ function buildBody(draft: Draft, keepsAssignees = false): DefinitionCreateBody |
|
||||
if (!title) return "Give the task a title.";
|
||||
if (draft.assigneeIds.length === 0 && !keepsAssignees) return "Assign at least one child.";
|
||||
if (draft.windows.length === 0) return "Pick at least one window.";
|
||||
if (draft.emoji && draft.icon === null) {
|
||||
return "Enter a single emoji (no spaces or < > &), or clear the emoji field.";
|
||||
}
|
||||
const rule = buildRule(draft);
|
||||
if (typeof rule === "string") return rule;
|
||||
const windows: WindowEntry[] = WINDOW_ORDER.filter((w) => draft.windows.includes(w)).map(
|
||||
@@ -251,6 +275,12 @@ function saveErrorMessage(error: unknown): string {
|
||||
return "The task could not be saved. Check your connection and try again.";
|
||||
}
|
||||
|
||||
function deleteErrorMessage(error: unknown): string {
|
||||
if (error instanceof ApiForbiddenError) return error.message;
|
||||
if (error instanceof ApiRequestError && error.detail) return error.detail;
|
||||
return "The task could not be deleted. Check your connection and try again.";
|
||||
}
|
||||
|
||||
function toggle<T>(list: T[], value: T): T[] {
|
||||
return list.includes(value) ? list.filter((item) => item !== value) : [...list, value];
|
||||
}
|
||||
@@ -427,11 +457,13 @@ function EditSheet({
|
||||
activeChildren,
|
||||
onCancel,
|
||||
onSaved,
|
||||
onDeleted,
|
||||
}: {
|
||||
target: "new" | QuestDefinition;
|
||||
activeChildren: AdminChild[];
|
||||
onCancel: () => void;
|
||||
onSaved: () => void;
|
||||
onDeleted: (result: DefinitionDeleteResult) => void;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<Draft>(() =>
|
||||
target === "new" ? newDraft(activeChildren) : draftFrom(target, activeChildren),
|
||||
@@ -440,6 +472,10 @@ function EditSheet({
|
||||
// assignee_child_ids, because the API replaces the whole set and inactive
|
||||
// children cannot be sent back.
|
||||
const [originalActiveIds] = useState(() => draft.assigneeIds);
|
||||
// The icon as loaded: while it is unchanged, the PATCH omits `icon` (absent
|
||||
// means unchanged), because a legacy value read back as `lucide:<old>` would
|
||||
// fail the API's strict icon validation if sent back.
|
||||
const [originalIcon] = useState(() => draft.icon);
|
||||
const inactiveAssignees =
|
||||
target === "new"
|
||||
? []
|
||||
@@ -447,6 +483,7 @@ function EditSheet({
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [confirming, setConfirming] = useState(false);
|
||||
const [confirmingDelete, setConfirmingDelete] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
// A ref, not state: two taps in one frame must not both see `saving === false`.
|
||||
const inFlight = useRef(false);
|
||||
@@ -464,8 +501,8 @@ function EditSheet({
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (confirming) confirmRef.current?.focus();
|
||||
}, [confirming]);
|
||||
if (confirming || confirmingDelete) confirmRef.current?.focus();
|
||||
}, [confirming, confirmingDelete]);
|
||||
|
||||
function onKeyDown(event: ReactKeyboardEvent<HTMLDivElement>) {
|
||||
if (event.key === "Escape") {
|
||||
@@ -522,6 +559,7 @@ function EditSheet({
|
||||
} else {
|
||||
const edit: DefinitionEditBody = { ...body };
|
||||
if (keepsAssignees) delete edit.assignee_child_ids;
|
||||
if (draft.icon === originalIcon) delete edit.icon;
|
||||
await updateDefinition(target.id, edit);
|
||||
}
|
||||
onSaved();
|
||||
@@ -532,6 +570,21 @@ function EditSheet({
|
||||
}
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
if (target === "new" || inFlight.current) return;
|
||||
setConfirmingDelete(false);
|
||||
inFlight.current = true;
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
try {
|
||||
onDeleted(await deleteDefinition(target.id));
|
||||
} catch (err) {
|
||||
setError(deleteErrorMessage(err));
|
||||
inFlight.current = false;
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="defs-sheet-layer">
|
||||
<div
|
||||
@@ -568,28 +621,67 @@ function EditSheet({
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={draft.icon === null}
|
||||
aria-checked={draft.icon === null && !draft.emoji}
|
||||
aria-label="No icon"
|
||||
className={draft.icon === null ? "defs-icon defs-icon--on" : "defs-icon"}
|
||||
onClick={() => update({ icon: null })}
|
||||
className={
|
||||
draft.icon === null && !draft.emoji ? "defs-icon defs-icon--on" : "defs-icon"
|
||||
}
|
||||
onClick={() => update({ icon: null, emoji: "" })}
|
||||
>
|
||||
<TaskGlyph size={18} />
|
||||
</button>
|
||||
{DEFINITION_ICONS.map(({ name, label, Icon }) => (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={draft.icon === name}
|
||||
aria-label={label}
|
||||
data-icon-option={name}
|
||||
className={draft.icon === name ? "defs-icon defs-icon--on" : "defs-icon"}
|
||||
onClick={() => update({ icon: name })}
|
||||
>
|
||||
<Icon size={18} aria-hidden="true" focusable="false" />
|
||||
</button>
|
||||
))}
|
||||
{DEFINITION_ICONS.map((icon) => {
|
||||
const { name, label } = icon;
|
||||
const on = normalizeDefinitionIconName(draft.icon) === name;
|
||||
return (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={on}
|
||||
aria-label={label}
|
||||
data-icon-option={name}
|
||||
className={on ? "defs-icon defs-icon--on" : "defs-icon"}
|
||||
onClick={() => update({ icon: lucideIconKey(name), emoji: "" })}
|
||||
>
|
||||
<GlyphSvg icon={icon} size={18} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<span className="defs-sublabel" id="defs-label-icon-fa">
|
||||
Font Awesome
|
||||
</span>
|
||||
<div className="defs-icon-grid" role="radiogroup" aria-labelledby="defs-label-icon-fa">
|
||||
{FA_DEFINITION_ICONS.map((icon) => {
|
||||
const { name, label } = icon;
|
||||
const on = faIconName(draft.icon) === name;
|
||||
return (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={on}
|
||||
aria-label={label}
|
||||
data-icon-option={faIconKey(name)}
|
||||
className={on ? "defs-icon defs-icon--on" : "defs-icon"}
|
||||
onClick={() => update({ icon: faIconKey(name), emoji: "" })}
|
||||
>
|
||||
<GlyphSvg icon={icon} size={18} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<label className="defs-due">
|
||||
<span>Emoji</span>
|
||||
<input
|
||||
className="defs-input"
|
||||
aria-label="Emoji"
|
||||
placeholder="e.g. 🐶"
|
||||
value={draft.emoji}
|
||||
onChange={(e) => update({ emoji: e.target.value, icon: emojiIconKey(e.target.value) })}
|
||||
/>
|
||||
</label>
|
||||
</Field>
|
||||
|
||||
<Field label="Assigned children" id="defs-label-children">
|
||||
@@ -740,6 +832,16 @@ function EditSheet({
|
||||
<OccurrencePreview ruleKey={previewKey} />
|
||||
</Field>
|
||||
|
||||
<Field label="Start date" id="defs-label-start">
|
||||
<input
|
||||
className="defs-input"
|
||||
type="date"
|
||||
aria-labelledby="defs-label-start"
|
||||
value={draft.startDate}
|
||||
onChange={(e) => update({ startDate: e.target.value })}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field label="Due time" id="defs-label-due">
|
||||
{orderedWindows.length === 0 ? (
|
||||
<p className="defs-hint">Pick a window to set its due time.</p>
|
||||
@@ -830,15 +932,56 @@ function EditSheet({
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="defs-sheet-footer">
|
||||
<button type="button" className="defs-cancel" onClick={onCancel} disabled={saving}>
|
||||
Cancel
|
||||
</button>
|
||||
<button type="button" className="defs-save" onClick={() => save()} disabled={saving}>
|
||||
{saving ? "Saving…" : "Save changes"}
|
||||
</button>
|
||||
) : confirmingDelete ? (
|
||||
<div
|
||||
className="defs-confirm"
|
||||
role="group"
|
||||
aria-labelledby="defs-delete-confirm-text"
|
||||
data-testid="delete-confirm"
|
||||
ref={confirmRef}
|
||||
tabIndex={-1}
|
||||
>
|
||||
<p id="defs-delete-confirm-text">
|
||||
Delete this task? If it has no completion history it is deleted; otherwise it is
|
||||
retired (deactivated) and its history is kept.
|
||||
</p>
|
||||
<div className="defs-sheet-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="defs-cancel"
|
||||
onClick={() => setConfirmingDelete(false)}
|
||||
>
|
||||
Go back
|
||||
</button>
|
||||
<button type="button" className="defs-save defs-save--danger" onClick={remove}>
|
||||
Delete task
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="defs-sheet-footer">
|
||||
<button type="button" className="defs-cancel" onClick={onCancel} disabled={saving}>
|
||||
Cancel
|
||||
</button>
|
||||
<button type="button" className="defs-save" onClick={() => save()} disabled={saving}>
|
||||
{saving ? "Saving…" : "Save changes"}
|
||||
</button>
|
||||
</div>
|
||||
{target !== "new" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="defs-delete"
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
setError(null);
|
||||
setConfirmingDelete(true);
|
||||
}}
|
||||
>
|
||||
Delete task
|
||||
</button>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -962,6 +1105,21 @@ export default function DefinitionsTab() {
|
||||
setSheet(null);
|
||||
setAttempt((n) => n + 1);
|
||||
}}
|
||||
onDeleted={(result) => {
|
||||
setSheet(null);
|
||||
setState((current) =>
|
||||
current.kind !== "ready"
|
||||
? current
|
||||
: {
|
||||
...current,
|
||||
definitions: result.definition
|
||||
? current.definitions.map((d) =>
|
||||
d.id === result.definition_id ? result.definition! : d,
|
||||
)
|
||||
: current.definitions.filter((d) => d.id !== result.definition_id),
|
||||
},
|
||||
);
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -1,103 +1,90 @@
|
||||
/**
|
||||
* The shipped Lucide subset a definition's `icon` may name (ADMIN-SPEC §3.3).
|
||||
* Only these named imports are bundled — no CDN, no runtime fetch. The stored
|
||||
* value is the Lucide kebab-case name, so it stays meaningful to any surface.
|
||||
* The icons a definition's `icon` may name (ADMIN-SPEC §3.3): the curated
|
||||
* Lucide set, the curated Font Awesome Free solid subset, or an emoji. The
|
||||
* names, labels and path data come from the shared icon registry
|
||||
* (`src/icons/registry.generated.ts`, generated from
|
||||
* `tools/icons/curated-icons.json`) — no CDN, no runtime fetch. The stored
|
||||
* value is namespaced — `lucide:<name>`, `fa:<name>` or `emoji:<grapheme>` —
|
||||
* and a legacy bare `<kebab-name>` still names the same Lucide entry.
|
||||
*/
|
||||
import {
|
||||
Apple,
|
||||
Backpack,
|
||||
Bath,
|
||||
Bed,
|
||||
Bike,
|
||||
BookOpen,
|
||||
Brush,
|
||||
BrushCleaning,
|
||||
Calendar,
|
||||
Cat,
|
||||
Clock,
|
||||
CookingPot,
|
||||
Dog,
|
||||
Droplets,
|
||||
Fish,
|
||||
Gamepad2,
|
||||
Heart,
|
||||
House,
|
||||
ListChecks,
|
||||
Moon,
|
||||
Music,
|
||||
Pencil,
|
||||
Recycle,
|
||||
Shirt,
|
||||
ShowerHead,
|
||||
Smile,
|
||||
Sofa,
|
||||
SprayCan,
|
||||
Sprout,
|
||||
Star,
|
||||
Sun,
|
||||
Toilet,
|
||||
Trash2,
|
||||
Utensils,
|
||||
Volleyball,
|
||||
WashingMachine,
|
||||
type LucideIcon,
|
||||
} from "lucide-react";
|
||||
import { GlyphSvg } from "../icons/GlyphSvg";
|
||||
import { FA_ICONS, LUCIDE_ICONS, resolveIcon, type GlyphIcon } from "../icons/registry.generated";
|
||||
import { TaskGlyph } from "./glyphs";
|
||||
|
||||
export interface DefinitionIconEntry {
|
||||
name: string;
|
||||
label: string;
|
||||
Icon: LucideIcon;
|
||||
export type DefinitionIconEntry = GlyphIcon;
|
||||
|
||||
export const DEFINITION_ICONS: readonly DefinitionIconEntry[] = LUCIDE_ICONS;
|
||||
|
||||
export const FA_DEFINITION_ICONS: readonly DefinitionIconEntry[] = FA_ICONS;
|
||||
|
||||
const LUCIDE_PREFIX = "lucide:";
|
||||
const FA_PREFIX = "fa:";
|
||||
const EMOJI_PREFIX = "emoji:";
|
||||
|
||||
/** The canonical stored key for a Lucide choice, e.g. `lucide:dog`. */
|
||||
export function lucideIconKey(name: string): string {
|
||||
return `${LUCIDE_PREFIX}${name}`;
|
||||
}
|
||||
|
||||
export const DEFINITION_ICONS: readonly DefinitionIconEntry[] = [
|
||||
{ name: "bed", label: "Bed", Icon: Bed },
|
||||
{ name: "bath", label: "Bath", Icon: Bath },
|
||||
{ name: "shower-head", label: "Shower", Icon: ShowerHead },
|
||||
{ name: "toilet", label: "Toilet", Icon: Toilet },
|
||||
{ name: "brush", label: "Brush", Icon: Brush },
|
||||
{ name: "smile", label: "Smile", Icon: Smile },
|
||||
{ name: "shirt", label: "Clothes", Icon: Shirt },
|
||||
{ name: "washing-machine", label: "Laundry", Icon: WashingMachine },
|
||||
{ name: "utensils", label: "Meal", Icon: Utensils },
|
||||
{ name: "cooking-pot", label: "Cooking", Icon: CookingPot },
|
||||
{ name: "apple", label: "Snack", Icon: Apple },
|
||||
{ name: "brush-cleaning", label: "Sweep", Icon: BrushCleaning },
|
||||
{ name: "spray-can", label: "Clean", Icon: SprayCan },
|
||||
{ name: "trash-2", label: "Bins", Icon: Trash2 },
|
||||
{ name: "recycle", label: "Recycling", Icon: Recycle },
|
||||
{ name: "sofa", label: "Tidy", Icon: Sofa },
|
||||
{ name: "house", label: "Home", Icon: House },
|
||||
{ name: "backpack", label: "School bag", Icon: Backpack },
|
||||
{ name: "book-open", label: "Reading", Icon: BookOpen },
|
||||
{ name: "pencil", label: "Homework", Icon: Pencil },
|
||||
{ name: "music", label: "Music", Icon: Music },
|
||||
{ name: "dog", label: "Dog", Icon: Dog },
|
||||
{ name: "cat", label: "Cat", Icon: Cat },
|
||||
{ name: "fish", label: "Fish", Icon: Fish },
|
||||
{ name: "sprout", label: "Plants", Icon: Sprout },
|
||||
{ name: "droplets", label: "Water", Icon: Droplets },
|
||||
{ name: "bike", label: "Bike", Icon: Bike },
|
||||
{ name: "volleyball", label: "Sport", Icon: Volleyball },
|
||||
{ name: "gamepad-2", label: "Games", Icon: Gamepad2 },
|
||||
{ name: "star", label: "Star", Icon: Star },
|
||||
{ name: "heart", label: "Heart", Icon: Heart },
|
||||
{ name: "sun", label: "Morning", Icon: Sun },
|
||||
{ name: "moon", label: "Bedtime", Icon: Moon },
|
||||
{ name: "clock", label: "Clock", Icon: Clock },
|
||||
{ name: "calendar", label: "Calendar", Icon: Calendar },
|
||||
{ name: "list-checks", label: "Checklist", Icon: ListChecks },
|
||||
];
|
||||
|
||||
const BY_NAME = new Map(DEFINITION_ICONS.map((entry) => [entry.name, entry]));
|
||||
|
||||
export function findDefinitionIcon(name: string | null): DefinitionIconEntry | null {
|
||||
return name === null ? null : (BY_NAME.get(name) ?? null);
|
||||
/** The canonical stored key for a Font Awesome choice, e.g. `fa:dog`. */
|
||||
export function faIconKey(name: string): string {
|
||||
return `${FA_PREFIX}${name}`;
|
||||
}
|
||||
|
||||
/** A definition's glyph; no icon, or one outside the subset, gets the generic task glyph. */
|
||||
/**
|
||||
* The stored key for typed emoji text, e.g. `emoji:🐶`. The raw text — not
|
||||
* trimmed, as the backend rejects any whitespace — must pass the registry's
|
||||
* emoji check (1-8 code points, no whitespace, control characters or `<`,
|
||||
* `>`, `&`), else null. Only an empty field means "no icon".
|
||||
*/
|
||||
export function emojiIconKey(text: string): string | null {
|
||||
const key = `${EMOJI_PREFIX}${text}`;
|
||||
return resolveIcon(key).kind === "emoji" ? key : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Lucide name an icon value refers to: `lucide:dog` and a legacy bare
|
||||
* `dog` both give `dog`. Any other namespace (`fa:`, `emoji:`, unknown) and
|
||||
* null give null — the admin has no Lucide entry for them.
|
||||
*/
|
||||
export function normalizeDefinitionIconName(value: string | null): string | null {
|
||||
if (value === null) return null;
|
||||
if (value.startsWith(LUCIDE_PREFIX)) return value.slice(LUCIDE_PREFIX.length);
|
||||
return value.includes(":") ? null : value;
|
||||
}
|
||||
|
||||
/** The Font Awesome name an `fa:<name>` value refers to; anything else gives null. */
|
||||
export function faIconName(value: string | null): string | null {
|
||||
return value?.startsWith(FA_PREFIX) ? value.slice(FA_PREFIX.length) : null;
|
||||
}
|
||||
|
||||
/** The emoji text an `emoji:<grapheme>` value holds; anything else gives "". */
|
||||
export function emojiIconText(value: string | null): string {
|
||||
return value?.startsWith(EMOJI_PREFIX) ? value.slice(EMOJI_PREFIX.length) : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The curated glyph (Lucide or Font Awesome) an icon value resolves to via
|
||||
* the shared parser; emoji, unknown and null values give null.
|
||||
*/
|
||||
export function findDefinitionIcon(value: string | null): DefinitionIconEntry | null {
|
||||
const icon = resolveIcon(value);
|
||||
return icon.kind === "lucide" || icon.kind === "fa" ? icon : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A definition's icon: a Lucide or Font Awesome glyph, an emoji drawn as
|
||||
* text, or — for no icon or an unknown value — the generic task glyph.
|
||||
*/
|
||||
export function DefinitionIcon({ name, size = 17 }: { name: string | null; size?: number }) {
|
||||
const entry = findDefinitionIcon(name);
|
||||
if (!entry) return <TaskGlyph size={size} />;
|
||||
return <entry.Icon size={size} aria-hidden="true" focusable="false" data-icon={entry.name} />;
|
||||
const icon = resolveIcon(name);
|
||||
if (icon.kind === "fallback") return <TaskGlyph size={size} />;
|
||||
if (icon.kind === "emoji") {
|
||||
return (
|
||||
<span className="defs-emoji" style={{ fontSize: size }} aria-hidden="true" data-emoji={icon.text}>
|
||||
{icon.text}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return <GlyphSvg icon={icon} size={size} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Draws a registry glyph (`registry.generated.ts`) as an inline SVG — the
|
||||
* path data is bundled, so there is no CDN and no runtime fetch. Lucide
|
||||
* glyphs are stroked on their 24px grid; Font Awesome glyphs are filled.
|
||||
*/
|
||||
import type { GlyphIcon } from "./registry.generated";
|
||||
|
||||
export function GlyphSvg({ icon, size }: { icon: GlyphIcon; size: number }) {
|
||||
const stroked = icon.kind === "lucide";
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox={icon.viewBox}
|
||||
fill={stroked ? "none" : "currentColor"}
|
||||
stroke={stroked ? "currentColor" : undefined}
|
||||
strokeWidth={stroked ? 2 : undefined}
|
||||
strokeLinecap={stroked ? "round" : undefined}
|
||||
strokeLinejoin={stroked ? "round" : undefined}
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
data-icon={icon.name}
|
||||
>
|
||||
{icon.paths.map((d, index) => (
|
||||
<path key={index} d={d} />
|
||||
))}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
// GENERATED by tools/icons/generate.mjs from tools/icons/curated-icons.json — do not edit.
|
||||
// Regenerate with `node tools/icons/generate.mjs` (the drift tests fail if this
|
||||
// file differs from a fresh generation).
|
||||
//
|
||||
// Glyph path data is embedded at generation time; nothing is fetched at runtime.
|
||||
// Lucide glyphs: lucide-react 1.47.0 (ISC licence).
|
||||
// Font Awesome glyphs: @fortawesome/free-solid-svg-icons 7.3.1
|
||||
// (Font Awesome Free, icons under CC BY 4.0).
|
||||
|
||||
/** A vector glyph: draw each path in `paths` inside an <svg viewBox>. Lucide
|
||||
* glyphs are stroked (fill none, stroke-width 2, round caps and joins);
|
||||
* Font Awesome glyphs are filled. */
|
||||
export interface GlyphIcon {
|
||||
kind: "lucide" | "fa";
|
||||
key: string;
|
||||
name: string;
|
||||
label: string;
|
||||
viewBox: string;
|
||||
paths: readonly string[];
|
||||
}
|
||||
|
||||
/** An emoji icon; render `text` as text. */
|
||||
export interface EmojiIcon {
|
||||
kind: "emoji";
|
||||
key: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** No usable icon: the caller draws its own default glyph. */
|
||||
export interface FallbackIcon {
|
||||
kind: "fallback";
|
||||
key: null;
|
||||
}
|
||||
|
||||
export type ResolvedIcon = GlyphIcon | EmojiIcon | FallbackIcon;
|
||||
|
||||
export const LUCIDE_ICONS: readonly GlyphIcon[] = [
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:bed",
|
||||
"name": "bed",
|
||||
"label": "Bed",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M2 4v16",
|
||||
"M2 8h18a2 2 0 0 1 2 2v10",
|
||||
"M2 17h20",
|
||||
"M6 8v9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:bath",
|
||||
"name": "bath",
|
||||
"label": "Bath",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M10 4 8 6",
|
||||
"M17 19v2",
|
||||
"M2 12h20",
|
||||
"M7 19v2",
|
||||
"M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:shower-head",
|
||||
"name": "shower-head",
|
||||
"label": "Shower",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"m4 4 2.5 2.5",
|
||||
"M13.5 6.5a4.95 4.95 0 0 0-7 7",
|
||||
"M15 5 5 15",
|
||||
"M14 17v.01",
|
||||
"M10 16v.01",
|
||||
"M13 13v.01",
|
||||
"M16 10v.01",
|
||||
"M11 20v.01",
|
||||
"M17 14v.01",
|
||||
"M20 11v.01"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:toilet",
|
||||
"name": "toilet",
|
||||
"label": "Toilet",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M7 12h13a1 1 0 0 1 1 1 5 5 0 0 1-5 5h-.598a.5.5 0 0 0-.424.765l1.544 2.47a.5.5 0 0 1-.424.765H5.402a.5.5 0 0 1-.424-.765L7 18",
|
||||
"M8 18a5 5 0 0 1-5-5V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:brush",
|
||||
"name": "brush",
|
||||
"label": "Brush",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"m11 10 3 3",
|
||||
"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",
|
||||
"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:smile",
|
||||
"name": "smile",
|
||||
"label": "Smile",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M15 10V9",
|
||||
"M16.472 15a6 6 0 01-8.943 0",
|
||||
"M9 10V9",
|
||||
"M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:shirt",
|
||||
"name": "shirt",
|
||||
"label": "Clothes",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 2 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 2 0 0 0-1.34-2.23z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:washing-machine",
|
||||
"name": "washing-machine",
|
||||
"label": "Laundry",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M3 6h3",
|
||||
"M17 6h.01",
|
||||
"M5 2h14a2 2 0 0 1 2 2v16a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-16a2 2 0 0 1 2 -2z",
|
||||
"M7 13a5 5 0 1 0 10 0a5 5 0 1 0 -10 0",
|
||||
"M12 18a2.5 2.5 0 0 0 0-5 2.5 2.5 0 0 1 0-5"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:utensils",
|
||||
"name": "utensils",
|
||||
"label": "Meal",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2",
|
||||
"M7 2v20",
|
||||
"M21 15V2a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:cooking-pot",
|
||||
"name": "cooking-pot",
|
||||
"label": "Cooking",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M2 12h20",
|
||||
"M20 12v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8",
|
||||
"m4 8 16-4",
|
||||
"m8.86 6.78-.45-1.81a2 2 0 0 1 1.45-2.43l1.94-.48a2 2 0 0 1 2.43 1.46l.45 1.8"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:apple",
|
||||
"name": "apple",
|
||||
"label": "Snack",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M12 6.528V3a1 1 0 0 1 1-1h0",
|
||||
"M18.237 21A15 15 0 0 0 22 11a6 6 0 0 0-10-4.472A6 6 0 0 0 2 11a15.1 15.1 0 0 0 3.763 10 3 3 0 0 0 3.648.648 5.5 5.5 0 0 1 5.178 0A3 3 0 0 0 18.237 21"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:brush-cleaning",
|
||||
"name": "brush-cleaning",
|
||||
"label": "Sweep",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"m16 22-1-4",
|
||||
"M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1",
|
||||
"M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z",
|
||||
"m8 22 1-4"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:spray-can",
|
||||
"name": "spray-can",
|
||||
"label": "Clean",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M3 3h.01",
|
||||
"M7 5h.01",
|
||||
"M11 7h.01",
|
||||
"M3 7h.01",
|
||||
"M7 9h.01",
|
||||
"M3 11h.01",
|
||||
"M15 5h4v4h-4z",
|
||||
"m19 9 2 2v10c0 .6-.4 1-1 1h-6c-.6 0-1-.4-1-1V11l2-2",
|
||||
"m13 14 8-2",
|
||||
"m13 19 8-2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:trash-2",
|
||||
"name": "trash-2",
|
||||
"label": "Bins",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M10 11v6",
|
||||
"M14 11v6",
|
||||
"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",
|
||||
"M3 6h18",
|
||||
"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:recycle",
|
||||
"name": "recycle",
|
||||
"label": "Recycling",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M7 19H4.815a1.83 1.83 0 0 1-1.57-.881 1.785 1.785 0 0 1-.004-1.784L7.196 9.5",
|
||||
"M11 19h8.203a1.83 1.83 0 0 0 1.556-.89 1.784 1.784 0 0 0 0-1.775l-1.226-2.12",
|
||||
"m14 16-3 3 3 3",
|
||||
"M8.293 13.596 7.196 9.5 3.1 10.598",
|
||||
"m9.344 5.811 1.093-1.892A1.83 1.83 0 0 1 11.985 3a1.784 1.784 0 0 1 1.546.888l3.943 6.843",
|
||||
"m13.378 9.633 4.096 1.098 1.097-4.096"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:sofa",
|
||||
"name": "sofa",
|
||||
"label": "Tidy",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M20 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v3",
|
||||
"M2 16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",
|
||||
"M4 18v2",
|
||||
"M20 18v2",
|
||||
"M12 4v9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:house",
|
||||
"name": "house",
|
||||
"label": "Home",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",
|
||||
"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:backpack",
|
||||
"name": "backpack",
|
||||
"label": "School bag",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M4 10a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z",
|
||||
"M8 10h8",
|
||||
"M8 18h8",
|
||||
"M8 22v-6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v6",
|
||||
"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:book-open",
|
||||
"name": "book-open",
|
||||
"label": "Reading",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M12 5v16",
|
||||
"M20.001 19A2 2 0 0022 17V5a2 2 0 00-1.999-2L16 3.002A5 5 0 0012 5a5 5 0 00-4-2H4a2 2 0 00-2 2v12a2 2 0 001.999 2H8a5 5 0 014 2 5 5 0 014-2z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:pencil",
|
||||
"name": "pencil",
|
||||
"label": "Homework",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",
|
||||
"m15 5 4 4"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:music",
|
||||
"name": "music",
|
||||
"label": "Music",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M9 18V5l12-2v13",
|
||||
"M3 18a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",
|
||||
"M15 16a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:dog",
|
||||
"name": "dog",
|
||||
"label": "Dog",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M11.25 16.25h1.5L12 17z",
|
||||
"M16 14v.5",
|
||||
"M4.42 11.247A13.152 13.152 0 0 0 4 14.556C4 18.728 7.582 21 12 21s8-2.272 8-6.444a11.702 11.702 0 0 0-.493-3.309",
|
||||
"M8 14v.5",
|
||||
"M8.5 8.5c-.384 1.05-1.083 2.028-2.344 2.5-1.931.722-3.576-.297-3.656-1-.113-.994 1.177-6.53 4-7 1.923-.321 3.651.845 3.651 2.235A7.497 7.497 0 0 1 14 5.277c0-1.39 1.844-2.598 3.767-2.277 2.823.47 4.113 6.006 4 7-.08.703-1.725 1.722-3.656 1-1.261-.472-1.855-1.45-2.239-2.5"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:cat",
|
||||
"name": "cat",
|
||||
"label": "Cat",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M12 5c.67 0 1.35.09 2 .26 1.78-2 5.03-2.84 6.42-2.26 1.4.58-.42 7-.42 7 .57 1.07 1 2.24 1 3.44C21 17.9 16.97 21 12 21s-9-3-9-7.56c0-1.25.5-2.4 1-3.44 0 0-1.89-6.42-.5-7 1.39-.58 4.72.23 6.5 2.23A9.04 9.04 0 0 1 12 5Z",
|
||||
"M8 14v.5",
|
||||
"M16 14v.5",
|
||||
"M11.25 16.25h1.5L12 17l-.75-.75Z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:fish",
|
||||
"name": "fish",
|
||||
"label": "Fish",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M6.5 12c.94-3.46 4.94-6 8.5-6 3.56 0 6.06 2.54 7 6-.94 3.47-3.44 6-7 6s-7.56-2.53-8.5-6Z",
|
||||
"M18 12v.5",
|
||||
"M16 17.93a9.77 9.77 0 0 1 0-11.86",
|
||||
"M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33",
|
||||
"M10.46 7.26C10.2 5.88 9.17 4.24 8 3h5.8a2 2 0 0 1 1.98 1.67l.23 1.4",
|
||||
"m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:sprout",
|
||||
"name": "sprout",
|
||||
"label": "Plants",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M14 9.536V7a4 4 0 0 1 4-4h1.5a.5.5 0 0 1 .5.5V5a4 4 0 0 1-4 4 4 4 0 0 0-4 4c0 2 1 3 1 5a5 5 0 0 1-1 3",
|
||||
"M4 9a5 5 0 0 1 8 4 5 5 0 0 1-8-4",
|
||||
"M5 21h14"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:droplets",
|
||||
"name": "droplets",
|
||||
"label": "Water",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z",
|
||||
"M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:bike",
|
||||
"name": "bike",
|
||||
"label": "Bike",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M15 17.5a3.5 3.5 0 1 0 7 0a3.5 3.5 0 1 0 -7 0",
|
||||
"M2 17.5a3.5 3.5 0 1 0 7 0a3.5 3.5 0 1 0 -7 0",
|
||||
"M14 5a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",
|
||||
"M12 17.5V14l-3-3 4-3 2 3h2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:volleyball",
|
||||
"name": "volleyball",
|
||||
"label": "Sport",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M11 7a16 16 20 0 1 10.98 4.362",
|
||||
"M12 12a13 13 0 0 1-8.66 5",
|
||||
"M16.83 13.634a16 16 0 0 1-9.267 7.328",
|
||||
"M20.66 17A13 13 0 0 0 12 12a13 13 0 0 1 0-10",
|
||||
"M8.17 15.366a16 16 0 0 1-1.713-11.69",
|
||||
"M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:gamepad-2",
|
||||
"name": "gamepad-2",
|
||||
"label": "Games",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M6 11L10 11",
|
||||
"M8 9L8 13",
|
||||
"M15 12L15.01 12",
|
||||
"M18 10L18.01 10",
|
||||
"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:star",
|
||||
"name": "star",
|
||||
"label": "Star",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:heart",
|
||||
"name": "heart",
|
||||
"label": "Heart",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:sun",
|
||||
"name": "sun",
|
||||
"label": "Morning",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M8 12a4 4 0 1 0 8 0a4 4 0 1 0 -8 0",
|
||||
"M12 2v2",
|
||||
"M12 20v2",
|
||||
"m4.93 4.93 1.41 1.41",
|
||||
"m17.66 17.66 1.41 1.41",
|
||||
"M2 12h2",
|
||||
"M20 12h2",
|
||||
"m6.34 17.66-1.41 1.41",
|
||||
"m19.07 4.93-1.41 1.41"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:moon",
|
||||
"name": "moon",
|
||||
"label": "Bedtime",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:clock",
|
||||
"name": "clock",
|
||||
"label": "Clock",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0",
|
||||
"M12 6v6l4 2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:calendar",
|
||||
"name": "calendar",
|
||||
"label": "Calendar",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M8 2v3",
|
||||
"M16 2v3",
|
||||
"M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2z",
|
||||
"M3 9h18"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:list-checks",
|
||||
"name": "list-checks",
|
||||
"label": "Checklist",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M13 5h8",
|
||||
"M13 12h8",
|
||||
"M13 19h8",
|
||||
"m3 17 2 2 4-4",
|
||||
"m3 7 2 2 4-4"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
export const FA_ICONS: readonly GlyphIcon[] = [
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:broom",
|
||||
"name": "broom",
|
||||
"label": "Sweep",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M566.6 54.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-192 192-34.7-34.7c-4.2-4.2-10-6.6-16-6.6-12.5 0-22.6 10.1-22.6 22.6l0 29.1 108.3 108.3 29.1 0c12.5 0 22.6-10.1 22.6-22.6 0-6-2.4-11.8-6.6-16l-34.7-34.7 192-192zM341.1 353.4L222.6 234.9c-42.7-3.7-85.2 11.7-115.8 42.3l-8 8c-22.3 22.3-34.8 52.5-34.8 84 0 6.8 7.1 11.2 13.2 8.2l51.1-25.5c5-2.5 9.5 4.1 5.4 7.9L7.3 473.4C2.7 477.6 0 483.6 0 489.9 0 502.1 9.9 512 22.1 512l173.3 0c38.8 0 75.9-15.4 103.4-42.8 30.6-30.6 45.9-73.1 42.3-115.8z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:spray-can-sparkles",
|
||||
"name": "spray-can-sparkles",
|
||||
"label": "Clean",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M160 32l0 80 128 0 0-80c0-17.7-14.3-32-32-32L192 0c-17.7 0-32 14.3-32 32zm0 128c-53 0-96 43-96 96l0 208c0 26.5 21.5 48 48 48l224 0c26.5 0 48-21.5 48-48l0-208c0-53-43-96-96-96l-128 0zm64 96a80 80 0 1 1 0 160 80 80 0 1 1 0-160zM448 48c0-1.4-1-3-2.2-3.6L416 32 403.6 2.2C403 1 401.4 0 400 0s-3 1-3.6 2.2L384 32 354.2 44.4c-1.2 .6-2.2 2.2-2.2 3.6 0 1.4 1 3 2.2 3.6L384 64 396.4 93.8C397 95 398.6 96 400 96s3-1 3.6-2.2L416 64 445.8 51.6C447 51 448 49.4 448 48zm76.4 45.8C525 95 526.6 96 528 96s3-1 3.6-2.2L544 64 573.8 51.6c1.2-.6 2.2-2.2 2.2-3.6 0-1.4-1-3-2.2-3.6L544 32 531.6 2.2C531 1 529.4 0 528 0s-3 1-3.6 2.2L512 32 482.2 44.4c-1.2 .6-2.2 2.2-2.2 3.6 0 1.4 1 3 2.2 3.6L512 64 524.4 93.8zm7.2 100.4c-.6-1.2-2.2-2.2-3.6-2.2s-3 1-3.6 2.2L512 224 482.2 236.4c-1.2 .6-2.2 2.2-2.2 3.6 0 1.4 1 3 2.2 3.6L512 256 524.4 285.8c.6 1.2 2.2 2.2 3.6 2.2s3-1 3.6-2.2L544 256 573.8 243.6c1.2-.6 2.2-2.2 2.2-3.6 0-1.4-1-3-2.2-3.6L544 224 531.6 194.2zM512 144c0-1.4-1-3-2.2-3.6L480 128 467.6 98.2C467 97 465.4 96 464 96s-3 1-3.6 2.2L448 128 418.2 140.4c-1.2 .6-2.2 2.2-2.2 3.6 0 1.4 1 3 2.2 3.6L448 160 460.4 189.8c.6 1.2 2.2 2.2 3.6 2.2s3-1 3.6-2.2L480 160 509.8 147.6c1.2-.6 2.2-2.2 2.2-3.6z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:bucket",
|
||||
"name": "bucket",
|
||||
"label": "Mop",
|
||||
"viewBox": "0 0 448 512",
|
||||
"paths": [
|
||||
"M443.7 208c2.7 4.7 4.3 10.2 4.3 16 0 17.7-14.3 32-32 32l-5.1 0-22.4 213c-2.6 24.4-23.2 43-47.8 43l-233.6 0c-24.6 0-45.2-18.5-47.8-43L37.1 256 32 256c-17.7 0-32-14.3-32-32 0-5.8 1.6-11.3 4.3-16l439.4 0zM224-16c79.5 0 144 64.5 144 144l0 32-48 0 0-32c0-53-43-96-96-96s-96 43-96 96l0 32-48 0 0-32C80 48.5 144.5-16 224-16z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:soap",
|
||||
"name": "soap",
|
||||
"label": "Wash hands",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M208-32a48 48 0 1 1 0 96 48 48 0 1 1 0-96zM320 96a64 64 0 1 1 0 128 64 64 0 1 1 0-128zM352 0a32 32 0 1 1 64 0 32 32 0 1 1 -64 0zM96 160l112 0c0 23.8 7.4 45.9 20.1 64L160 224c-53 0-96 43-96 96s43 96 96 96l192 0c53 0 96-43 96-96 0-35.1-18.9-65.9-47-82.6 19-19.8 30.7-46.6 31-76.1 45.4 7.6 80 47.1 80 94.7l0 128c0 53-43 96-96 96L96 480c-53 0-96-43-96-96L0 256c0-53 43-96 96-96zm64 112l192 0c26.5 0 48 21.5 48 48s-21.5 48-48 48l-192 0c-26.5 0-48-21.5-48-48s21.5-48 48-48z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:sink",
|
||||
"name": "sink",
|
||||
"label": "Dishes",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M288 96c0-17.7 14.3-32 32-32s32 14.3 32 32 14.3 32 32 32 32-14.3 32-32c0-53-43-96-96-96s-96 43-96 96l0 192-64 0 0-40c0-30.9-25.1-56-56-56l-48 0c-13.3 0-24 10.7-24 24s10.7 24 24 24l48 0c4.4 0 8 3.6 8 8l0 40-80 0c-17.7 0-32 14.3-32 32s14.3 32 32 32l0 64c0 53 43 96 96 96l256 0c53 0 96-43 96-96l0-64c17.7 0 32-14.3 32-32s-14.3-32-32-32l-80 0 0-40c0-4.4 3.6-8 8-8l56 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-56 0c-30.9 0-56 25.1-56 56l0 40-64 0 0-192z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:jug-detergent",
|
||||
"name": "jug-detergent",
|
||||
"label": "Laundry",
|
||||
"viewBox": "0 0 384 512",
|
||||
"paths": [
|
||||
"M96 24c0-13.3 10.7-24 24-24l80 0c13.3 0 24 10.7 24 24l0 24 8 0c13.3 0 24 10.7 24 24s-10.7 24-24 24L88 96C74.7 96 64 85.3 64 72S74.7 48 88 48l8 0 0-24zM0 256c0-70.7 57.3-128 128-128l128 0c70.7 0 128 57.3 128 128l0 192c0 35.3-28.7 64-64 64L64 512c-35.3 0-64-28.7-64-64L0 256zm256 0l0 96c0 17.7 14.3 32 32 32s32-14.3 32-32l0-96c0-17.7-14.3-32-32-32s-32 14.3-32 32z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:socks",
|
||||
"name": "socks",
|
||||
"label": "Socks",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M252.8 0L176 0c-26.5 0-48 21.5-48 48l0 16 112 0 0-16c0-17.5 4.7-33.9 12.8-48zM128 112l0 128c0 20.1-9.5 39.1-25.6 51.2l-64 48c-24.2 18.1-38.4 46.6-38.4 76.8 0 53 43 96 96 96 15.4 0 30.5-3.7 44-10.7-17.6-23.9-28-53.4-28-85.3 0-45.3 21.3-88 57.6-115.2l64-48c4-3 6.4-7.8 6.4-12.8l0-128-112 0zm160 0l0 128c0 20.1-9.5 39.1-25.6 51.2l-64 48c-24.2 18.1-38.4 46.6-38.4 76.8 0 53 43 96 96 96 20.8 0 41-6.7 57.6-19.2l115.2-86.4C461 382.2 480 344.3 480 304l0-192-192 0zM480 64l0-16c0-26.5-21.5-48-48-48L336 0c-26.5 0-48 21.5-48 48l0 16 192 0z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:shirt",
|
||||
"name": "shirt",
|
||||
"label": "Clothes",
|
||||
"viewBox": "0 0 640 512",
|
||||
"paths": [
|
||||
"M320.2 112c44.2 0 80-35.8 80-80l53.5 0c17 0 33.3 6.7 45.3 18.7L617.6 169.4c12.5 12.5 12.5 32.8 0 45.3l-50.7 50.7c-12.5 12.5-32.8 12.5-45.3 0l-41.4-41.4 0 224c0 35.3-28.7 64-64 64l-192 0c-35.3 0-64-28.7-64-64l0-224-41.4 41.4c-12.5 12.5-32.8 12.5-45.3 0L22.9 214.6c-12.5-12.5-12.5-32.8 0-45.3L141.5 50.7c12-12 28.3-18.7 45.3-18.7l53.5 0c0 44.2 35.8 80 80 80z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:bed",
|
||||
"name": "bed",
|
||||
"label": "Bed",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M32 32c17.7 0 32 14.3 32 32l0 224 224 0 0-128c0-17.7 14.3-32 32-32l160 0c53 0 96 43 96 96l0 224c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-64-448 0 0 64c0 17.7-14.3 32-32 32S0 465.7 0 448L0 64C0 46.3 14.3 32 32 32zm80 160a64 64 0 1 1 128 0 64 64 0 1 1 -128 0z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:couch",
|
||||
"name": "couch",
|
||||
"label": "Tidy",
|
||||
"viewBox": "0 0 640 512",
|
||||
"paths": [
|
||||
"M144 272C144 224.7 109.8 185.4 64.8 177.5 72 113.6 126.2 64 192 64l256 0c65.8 0 120 49.6 127.2 113.5-45 8-79.2 47.2-79.2 94.5l0 32-352 0 0-32zM0 384L0 272c0-26.5 21.5-48 48-48s48 21.5 48 48l0 80 448 0 0-80c0-26.5 21.5-48 48-48s48 21.5 48 48l0 112c0 35.3-28.7 64-64 64L64 448c-35.3 0-64-28.7-64-64z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:bath",
|
||||
"name": "bath",
|
||||
"label": "Bath",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M96 77.3c0-7.3 5.9-13.3 13.3-13.3 3.5 0 6.9 1.4 9.4 3.9l14.9 14.9c-3.6 9.1-5.5 18.9-5.5 29.2 0 19.9 7.2 38 19.2 52-5.3 9.2-4 21.1 3.8 29 9.4 9.4 24.6 9.4 33.9 0L289 89c9.4-9.4 9.4-24.6 0-33.9-7.8-7.9-19.8-9.1-29-3.8-14-12-32.1-19.2-52-19.2-10.3 0-20.2 2-29.2 5.5L163.9 22.6C149.4 8.1 129.7 0 109.3 0 66.6 0 32 34.6 32 77.3L32 256c-17.7 0-32 14.3-32 32s14.3 32 32 32l0 48c0 28.4 12.4 54 32 71.6L64 480c0 17.7 14.3 32 32 32s32-14.3 32-32l0-16 256 0 0 16c0 17.7 14.3 32 32 32s32-14.3 32-32l0-40.4c19.6-17.6 32-43.1 32-71.6l0-48c17.7 0 32-14.3 32-32s-14.3-32-32-32L96 256 96 77.3z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:tooth",
|
||||
"name": "tooth",
|
||||
"label": "Teeth",
|
||||
"viewBox": "0 0 448 512",
|
||||
"paths": [
|
||||
"M145 5.7L224 32 303 5.7C314.3 1.9 326 0 337.9 0 398.7 0 448 49.3 448 110.1l0 68.5c0 29.4-9.5 58.1-27.2 81.6l-1.1 1.5c-12.9 17.2-21.3 37.4-24.3 58.7L373.7 471.9c-3.3 23-23 40.1-46.2 40.1-22.8 0-42.3-16.5-46-39L261.3 351.6c-3-18.2-18.8-31.6-37.3-31.6s-34.2 13.4-37.3 31.6L166.5 473c-3.8 22.5-23.2 39-46 39-23.2 0-42.9-17.1-46.2-40.1L52.6 320.5c-3-21.3-11.4-41.5-24.3-58.7l-1.1-1.5C9.5 236.7 0 208.1 0 178.7l0-68.5C0 49.3 49.3 0 110.1 0 122 0 133.7 1.9 145 5.7z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:utensils",
|
||||
"name": "utensils",
|
||||
"label": "Meal",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M63.9 14.4C63.1 6.2 56.2 0 48 0s-15.1 6.2-16 14.3L17.9 149.7c-1.3 6-1.9 12.1-1.9 18.2 0 45.9 35.1 83.6 80 87.7L96 480c0 17.7 14.3 32 32 32s32-14.3 32-32l0-224.4c44.9-4.1 80-41.8 80-87.7 0-6.1-.6-12.2-1.9-18.2L223.9 14.3C223.1 6.2 216.2 0 208 0s-15.1 6.2-15.9 14.4L178.5 149.9c-.6 5.7-5.4 10.1-11.1 10.1-5.8 0-10.6-4.4-11.2-10.2L143.9 14.6C143.2 6.3 136.3 0 128 0s-15.2 6.3-15.9 14.6L99.8 149.8c-.5 5.8-5.4 10.2-11.2 10.2-5.8 0-10.6-4.4-11.1-10.1L63.9 14.4zM448 0C432 0 320 32 320 176l0 112c0 35.3 28.7 64 64 64l32 0 0 128c0 17.7 14.3 32 32 32s32-14.3 32-32l0-448c0-17.7-14.3-32-32-32z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:bowl-food",
|
||||
"name": "bowl-food",
|
||||
"label": "Set the table",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M0 176c0-35.3 28.7-64 64-64 .5 0 1.1 0 1.6 0 7.4-36.5 39.7-64 78.4-64 15 0 29 4.1 40.9 11.2 13.3-25.7 40.1-43.2 71.1-43.2s57.8 17.6 71.1 43.2c12-7.1 26-11.2 40.9-11.2 38.7 0 71 27.5 78.4 64 .5 0 1.1 0 1.6 0 35.3 0 64 28.7 64 64 0 11.7-3.1 22.6-8.6 32L8.6 208C3.1 198.6 0 187.7 0 176zM0 283.4C0 268.3 12.3 256 27.4 256l457.1 0c15.1 0 27.4 12.3 27.4 27.4 0 70.5-44.4 130.7-106.7 154.1L403.5 452c-2 16-15.6 28-31.8 28l-231.5 0c-16.1 0-29.8-12-31.8-28l-1.8-14.4C44.4 414.1 0 353.9 0 283.4z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:basket-shopping",
|
||||
"name": "basket-shopping",
|
||||
"label": "Groceries",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M288 0c6.6 0 12.9 2.7 17.4 7.5l144 152 .5 .5 78.1 0c17.7 0 32 14.3 32 32 0 14.5-9.6 26.7-22.8 30.7L491.1 429.9c-6.5 29.3-32.5 50.1-62.5 50.1l-281.3 0c-30 0-56-20.8-62.5-50.1l-46-207.2c-13.2-3.9-22.8-16.2-22.8-30.7 0-17.7 14.3-32 32-32l78.1 0 .5-.5 144-152C275.1 2.7 281.4 0 288 0zm0 58.9L192.2 160 383.8 160 288 58.9zM208 264c0-13.3-10.7-24-24-24s-24 10.7-24 24l0 112c0 13.3 10.7 24 24 24s24-10.7 24-24l0-112zm80-24c-13.3 0-24 10.7-24 24l0 112c0 13.3 10.7 24 24 24s24-10.7 24-24l0-112c0-13.3-10.7-24-24-24zm128 24c0-13.3-10.7-24-24-24s-24 10.7-24 24l0 112c0 13.3 10.7 24 24 24s24-10.7 24-24l0-112z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:trash-can",
|
||||
"name": "trash-can",
|
||||
"label": "Bins",
|
||||
"viewBox": "0 0 448 512",
|
||||
"paths": [
|
||||
"M136.7 5.9C141.1-7.2 153.3-16 167.1-16l113.9 0c13.8 0 26 8.8 30.4 21.9L320 32 416 32c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 96C14.3 96 0 81.7 0 64S14.3 32 32 32l96 0 8.7-26.1zM32 144l384 0 0 304c0 35.3-28.7 64-64 64L96 512c-35.3 0-64-28.7-64-64l0-304zm88 64c-13.3 0-24 10.7-24 24l0 192c0 13.3 10.7 24 24 24s24-10.7 24-24l0-192c0-13.3-10.7-24-24-24zm104 0c-13.3 0-24 10.7-24 24l0 192c0 13.3 10.7 24 24 24s24-10.7 24-24l0-192c0-13.3-10.7-24-24-24zm104 0c-13.3 0-24 10.7-24 24l0 192c0 13.3 10.7 24 24 24s24-10.7 24-24l0-192c0-13.3-10.7-24-24-24z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:recycle",
|
||||
"name": "recycle",
|
||||
"label": "Recycling",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M152.3 60C198.5-20 314-20 360.2 60l37.3 64.6 27.7-16c8.4-4.9 18.9-4.2 26.6 1.7s11.1 15.9 8.6 25.3L436.9 223c-3.4 12.8-16.6 20.4-29.4 17l-87.4-23.4c-9.4-2.5-16.3-10.4-17.6-20s3.4-19.1 11.8-23.9l27.7-16-37.3-64.6c-21.6-37.3-75.4-37.3-97 0l-5.3 9.1c-8.8 15.3-28.4 20.5-43.7 11.7S138.2 84.5 147 69.1l5.3-9.1zM449.7 279.1c15.3-8.8 34.9-3.6 43.7 11.7l5.3 9.1c46.2 80-11.5 180-103.9 180l-74.6 0 0 32c0 9.7-5.8 18.5-14.8 22.2s-19.3 1.7-26.2-5.2l-64-64c-9.4-9.4-9.4-24.6 0-33.9l64-64c6.9-6.9 17.2-8.9 26.2-5.2s14.8 12.5 14.8 22.2l0 32 74.6 0c43.1 0 70.1-46.7 48.5-84l-5.3-9.1c-8.8-15.3-3.6-34.9 11.7-43.7zM51 235.4l-27.7-16c-8.4-4.9-13.1-14.3-11.8-23.9s8.2-17.5 17.6-20L116.5 152c12.8-3.4 26 4.2 29.4 17l23.4 87.4c2.5 9.4-.9 19.3-8.6 25.3s-18.2 6.6-26.6 1.7l-27.7-16-37.3 64.6c-21.6 37.3 5.4 84 48.5 84l10.6 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-10.6 0C25.3 480-32.4 380 13.8 300L51 235.4z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:dog",
|
||||
"name": "dog",
|
||||
"label": "Dog",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M32 112c16.6 0 30.2 12.6 31.8 28.7l.3 6.6C65.8 163.4 79.4 176 96 176l179.1 0 140.9 60.4 0 243.6c0 17.7-14.3 32-32 32l-32 0c-17.7 0-32-14.3-32-32l0-131.3C296 361 268.8 368 240 368s-56-7-80-19.3L160 480c0 17.7-14.3 32-32 32l-32 0c-17.7 0-32-14.3-32-32l0-245.6c-37.3-13.2-64-48.6-64-90.4 0-17.7 14.3-32 32-32zM355.8-32c7.7 0 14.9 3.6 19.6 9.8L392 0 444.1 0c12.7 0 24.9 5.1 33.9 14.1L496 32 552 32c13.3 0 24 10.7 24 24l0 24c0 44.2-35.8 80-80 80l-64 0-7 28-124.7-53.4 31.6-147.2C334.3-23.9 344.2-32 355.8-32zM448 44a20 20 0 1 0 0 40 20 20 0 1 0 0-40z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:cat",
|
||||
"name": "cat",
|
||||
"label": "Cat",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M64 96c53 0 96 43 96 96l0 85.8c29.7-44.7 77.8-76.2 133.4-84 25.6 60 85.2 102.1 154.6 102.1 10.9 0 21.6-1.1 32-3.1L480 480c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-140.8-136 108.8 56 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-144 0c-53 0-96-43-96-96l0-224c0-16.6-12.6-30.2-28.7-31.8l-6.6-.3C44.6 158.2 32 144.6 32 128 32 110.3 46.3 96 64 96zM533.8 3.2C544.2-5.5 560 1.9 560 15.5L560 128c0 61.9-50.1 112-112 112S336 189.9 336 128l0-112.5c0-13.6 15.8-21 26.2-12.3L416 48 480 48 533.8 3.2zM400 108a20 20 0 1 0 0 40 20 20 0 1 0 0-40zm96 0a20 20 0 1 0 0 40 20 20 0 1 0 0-40z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:paw",
|
||||
"name": "paw",
|
||||
"label": "Pets",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M234.5 92.9c14.3 42.9-.3 86.2-32.6 96.8s-70.1-15.6-84.4-58.5 .3-86.2 32.6-96.8 70.1 15.6 84.4 58.5zM100.4 198.6c18.9 32.4 14.3 70.1-10.2 84.1s-59.7-.9-78.5-33.3-14.3-70.1 10.2-84.1 59.7 .9 78.5 33.3zM69.2 401.2C121.6 259.9 214.7 224 256 224s134.4 35.9 186.8 177.2c3.6 9.7 5.2 20.1 5.2 30.5l0 1.6c0 25.8-20.9 46.7-46.7 46.7-11.5 0-22.9-1.4-34-4.2l-88-22c-15.3-3.8-31.3-3.8-46.6 0l-88 22c-11.1 2.8-22.5 4.2-34 4.2-25.8 0-46.7-20.9-46.7-46.7l0-1.6c0-10.4 1.6-20.8 5.2-30.5zM421.8 282.7c-24.5-14-29.1-51.7-10.2-84.1s54-47.3 78.5-33.3 29.1 51.7 10.2 84.1-54 47.3-78.5 33.3zM310.1 189.7c-32.3-10.6-46.9-53.9-32.6-96.8s52.1-69.1 84.4-58.5 46.9 53.9 32.6 96.8-52.1 69.1-84.4 58.5z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:seedling",
|
||||
"name": "seedling",
|
||||
"label": "Plants",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M512 32C512 140.1 435.4 230.3 333.6 251.4 325.7 193.3 299.6 141 261.1 100.5 301.2 40 369.9 0 448 0l32 0c17.7 0 32 14.3 32 32zM0 96C0 78.3 14.3 64 32 64l32 0c123.7 0 224 100.3 224 224l0 192c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-160C100.3 320 0 219.7 0 96z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:book",
|
||||
"name": "book",
|
||||
"label": "Reading",
|
||||
"viewBox": "0 0 448 512",
|
||||
"paths": [
|
||||
"M384 512L96 512c-53 0-96-43-96-96L0 96C0 43 43 0 96 0L400 0c26.5 0 48 21.5 48 48l0 288c0 20.9-13.4 38.7-32 45.3l0 66.7c17.7 0 32 14.3 32 32s-14.3 32-32 32l-32 0zM96 384c-17.7 0-32 14.3-32 32s14.3 32 32 32l256 0 0-64-256 0zm32-232c0 13.3 10.7 24 24 24l176 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-176 0c-13.3 0-24 10.7-24 24zm24 72c-13.3 0-24 10.7-24 24s10.7 24 24 24l176 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-176 0z"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
export const FALLBACK_ICON: FallbackIcon = { kind: "fallback", key: null };
|
||||
|
||||
/** Mirrors core/icons.py EMOJI_MAX_CODE_POINTS. */
|
||||
export const EMOJI_MAX_CODE_POINTS = 8;
|
||||
|
||||
const LUCIDE_BY_NAME: ReadonlyMap<string, GlyphIcon> = new Map(LUCIDE_ICONS.map((icon) => [icon.name, icon]));
|
||||
const FA_BY_NAME: ReadonlyMap<string, GlyphIcon> = new Map(FA_ICONS.map((icon) => [icon.name, icon]));
|
||||
|
||||
function isEmojiPayload(text: string): boolean {
|
||||
const codePoints = [...text];
|
||||
if (codePoints.length === 0 || codePoints.length > EMOJI_MAX_CODE_POINTS) return false;
|
||||
return !codePoints.some((char) => /[\s<>&]|\p{Cc}/u.test(char));
|
||||
}
|
||||
|
||||
/**
|
||||
* The renderable icon for a stored definition `icon` value.
|
||||
*
|
||||
* `lucide:<name>` and a legacy bare `<name>` resolve against the curated
|
||||
* Lucide set, `fa:<name>` against the curated Font Awesome set, and
|
||||
* `emoji:<grapheme>` to its text. Like the backend's
|
||||
* normalize_icon_for_read, nothing here throws: null, empty, an unknown
|
||||
* namespace or name, or a malformed emoji all resolve to FALLBACK_ICON.
|
||||
*/
|
||||
export function resolveIcon(value: string | null | undefined): ResolvedIcon {
|
||||
if (!value || !value.trim()) return FALLBACK_ICON;
|
||||
const colon = value.indexOf(":");
|
||||
if (colon === -1) return LUCIDE_BY_NAME.get(value) ?? FALLBACK_ICON;
|
||||
const namespace = value.slice(0, colon);
|
||||
const name = value.slice(colon + 1);
|
||||
if (namespace === "lucide") return LUCIDE_BY_NAME.get(name) ?? FALLBACK_ICON;
|
||||
if (namespace === "fa") return FA_BY_NAME.get(name) ?? FALLBACK_ICON;
|
||||
if (namespace === "emoji" && isEmojiPayload(name)) return { kind: "emoji", key: value, text: name };
|
||||
return FALLBACK_ICON;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import { readFileSync, readdirSync, statSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
// The offline generator is the only writer of both registry artefacts.
|
||||
import { OUTPUT_PATHS, REPO_ROOT, SOURCE_PATH, renderRegistry } from "../../../tools/icons/generate.mjs";
|
||||
import { EMOJI_MAX_CODE_POINTS, FALLBACK_ICON, FA_ICONS, LUCIDE_ICONS, resolveIcon } from "./registry.generated";
|
||||
|
||||
type Curated = { lucide: { name: string; label: string }[]; fa: { name: string; label: string }[] };
|
||||
|
||||
const curated = JSON.parse(readFileSync(SOURCE_PATH, "utf8")) as Curated;
|
||||
|
||||
type EmojiPayloadCase = { payload: string; valid: boolean; why: string };
|
||||
|
||||
const emojiPayloadCases = JSON.parse(
|
||||
readFileSync(join(REPO_ROOT, "tools", "icons", "emoji-payload-cases.json"), "utf8"),
|
||||
) as { cases: EmojiPayloadCase[] };
|
||||
|
||||
describe("shared icon registry — one source of truth", () => {
|
||||
it("both committed artefacts are byte-identical to a fresh generation", async () => {
|
||||
const fresh = await renderRegistry();
|
||||
expect(OUTPUT_PATHS).toHaveLength(2);
|
||||
for (const path of OUTPUT_PATHS) {
|
||||
expect(readFileSync(path, "utf8"), `${path} drifted — run node tools/icons/generate.mjs`).toBe(fresh);
|
||||
}
|
||||
});
|
||||
|
||||
it("the generated sets carry exactly the curated names and labels, in order", () => {
|
||||
expect(LUCIDE_ICONS.map(({ name, label }) => ({ name, label }))).toEqual(curated.lucide);
|
||||
expect(FA_ICONS.map(({ name, label }) => ({ name, label }))).toEqual(curated.fa);
|
||||
expect(curated.lucide).toHaveLength(36);
|
||||
expect(FA_ICONS.length).toBeGreaterThanOrEqual(15);
|
||||
expect(FA_ICONS.length).toBeLessThanOrEqual(25);
|
||||
});
|
||||
|
||||
it("every glyph is plain data: a viewBox and at least one path", () => {
|
||||
for (const icon of LUCIDE_ICONS) {
|
||||
expect(icon.kind).toBe("lucide");
|
||||
expect(icon.key).toBe(`lucide:${icon.name}`);
|
||||
expect(icon.viewBox).toBe("0 0 24 24");
|
||||
expect(icon.paths.length, icon.name).toBeGreaterThan(0);
|
||||
}
|
||||
for (const icon of FA_ICONS) {
|
||||
expect(icon.kind).toBe("fa");
|
||||
expect(icon.key).toBe(`fa:${icon.name}`);
|
||||
expect(icon.viewBox).toMatch(/^0 0 \d+ 512$/);
|
||||
expect(icon.paths.length, icon.name).toBeGreaterThan(0);
|
||||
}
|
||||
for (const icon of [...LUCIDE_ICONS, ...FA_ICONS]) {
|
||||
for (const d of icon.paths) expect(d, icon.key).toMatch(/^[Mm][-0-9.,\sA-Za-z]+$/);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveIcon", () => {
|
||||
it("resolves lucide:, fa: and emoji: keys", () => {
|
||||
const dog = resolveIcon("lucide:dog");
|
||||
expect(dog.kind).toBe("lucide");
|
||||
expect(dog).toBe(LUCIDE_ICONS.find((icon) => icon.name === "dog"));
|
||||
|
||||
const broom = resolveIcon("fa:broom");
|
||||
expect(broom.kind).toBe("fa");
|
||||
expect(broom).toBe(FA_ICONS.find((icon) => icon.name === "broom"));
|
||||
|
||||
expect(resolveIcon("emoji:🐶")).toEqual({ kind: "emoji", key: "emoji:🐶", text: "🐶" });
|
||||
expect(resolveIcon("emoji:👨👩👧")).toEqual({ kind: "emoji", key: "emoji:👨👩👧", text: "👨👩👧" });
|
||||
});
|
||||
|
||||
it("reads a legacy bare name as Lucide", () => {
|
||||
expect(resolveIcon("dog")).toBe(resolveIcon("lucide:dog"));
|
||||
expect(resolveIcon("trash-2")).toBe(LUCIDE_ICONS.find((icon) => icon.name === "trash-2"));
|
||||
});
|
||||
|
||||
it("falls back — never throws — for empty or unknown values", () => {
|
||||
for (const value of [
|
||||
null,
|
||||
undefined,
|
||||
"",
|
||||
" ",
|
||||
"rocket-ship-9000",
|
||||
"lucide:",
|
||||
"lucide:rocket-ship-9000",
|
||||
"fa:",
|
||||
"fa:rocket-ship-9000",
|
||||
"fa:Dog",
|
||||
"mystery:dog",
|
||||
"emoji:",
|
||||
"emoji:<b>",
|
||||
"emoji:a b",
|
||||
"emoji:123456789",
|
||||
]) {
|
||||
expect(resolveIcon(value), String(value)).toBe(FALLBACK_ICON);
|
||||
}
|
||||
expect(FALLBACK_ICON).toEqual({ kind: "fallback", key: null });
|
||||
});
|
||||
|
||||
// tests/test_core_icons.py asserts the same table against the backend's
|
||||
// validate_icon, so the two emoji rules cannot drift apart silently.
|
||||
it.each(emojiPayloadCases.cases)("emoji verdict matches the shared table: $why", ({ payload, valid }) => {
|
||||
const value = `emoji:${payload}`;
|
||||
expect(resolveIcon(value)).toEqual(valid ? { kind: "emoji", key: value, text: payload } : FALLBACK_ICON);
|
||||
});
|
||||
|
||||
it("the shared emoji table covers the contract edges", () => {
|
||||
const verdicts = new Map(emojiPayloadCases.cases.map(({ payload, valid }) => [payload, valid]));
|
||||
expect(verdicts.get("\ufeff")).toBe(false);
|
||||
expect(verdicts.get("👨\u200d👩\u200d👧\u200d👦")).toBe(true);
|
||||
expect(verdicts.get("🐕 ")).toBe(false);
|
||||
expect(verdicts.get("🐕\u0000")).toBe(false);
|
||||
for (const markup of ["<b>", "a>b", "a&b"]) expect(verdicts.get(markup)).toBe(false);
|
||||
expect(verdicts.get("⭐".repeat(EMOJI_MAX_CODE_POINTS))).toBe(true);
|
||||
expect(verdicts.get("⭐".repeat(EMOJI_MAX_CODE_POINTS + 1))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function filesUnder(dir: string): string[] {
|
||||
return readdirSync(dir).flatMap((entry) => {
|
||||
const path = join(dir, entry);
|
||||
return statSync(path).isDirectory() ? filesUnder(path) : [path];
|
||||
});
|
||||
}
|
||||
|
||||
describe("offline bundling", () => {
|
||||
const registryFiles = [SOURCE_PATH, join(REPO_ROOT, "tools", "icons", "generate.mjs"), ...OUTPUT_PATHS];
|
||||
|
||||
it("the registry has no remote URL, CDN reference or data-lucide runtime", () => {
|
||||
for (const path of registryFiles) {
|
||||
const text = readFileSync(path, "utf8");
|
||||
expect(text, path).not.toMatch(/https?:\/\//i);
|
||||
expect(text, path).not.toMatch(/\/\/[a-z0-9.-]+\.[a-z]{2,}\//i);
|
||||
expect(text, path).not.toMatch(/\bcdn\b|jsdelivr|unpkg|cdnjs|kit\.fontawesome/i);
|
||||
expect(text, path).not.toContain("data-lucide");
|
||||
expect(text, path).not.toMatch(/\bfetch\s*\(/);
|
||||
}
|
||||
});
|
||||
|
||||
it("no bundled source imports an icon package — only the curated generated data ships", () => {
|
||||
const sources = [join(REPO_ROOT, "admin", "src"), join(REPO_ROOT, "frontend", "src")]
|
||||
.flatMap(filesUnder)
|
||||
.filter((path) => /\.(ts|tsx)$/.test(path) && !path.endsWith(".test.ts") && !path.endsWith(".test.tsx"));
|
||||
expect(sources.length).toBeGreaterThan(0);
|
||||
for (const path of sources) {
|
||||
const text = readFileSync(path, "utf8");
|
||||
expect(text, path).not.toMatch(/from\s+["'](lucide|lucide-react|lucide-static|@fortawesome\/[^"']+)["']/);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -370,7 +370,7 @@ describe("SettingsScreen — preferences", () => {
|
||||
fireEvent.click(within(form).getByRole("button", { name: "Save preferences" }));
|
||||
}
|
||||
|
||||
it("renders the current value of all ten fields", async () => {
|
||||
it("renders the current value of the ten settings form fields (timezone is API-only)", async () => {
|
||||
const { form } = await renderPreferences();
|
||||
expect(field(form, "Planning horizon (days)").value).toBe("14");
|
||||
expect(field(form, "Day rollover").value).toBe("03:00");
|
||||
|
||||
@@ -152,6 +152,10 @@ core_quest_definitions = importlib.import_module(
|
||||
f"{_CORE_MODULE_NAME}.quest_definitions"
|
||||
)
|
||||
|
||||
#: The icon-key module (``core.icons.normalize_icon_for_read``) the
|
||||
#: admin plane's quest-definition responses normalize ``icon`` through.
|
||||
core_icons = importlib.import_module(f"{_CORE_MODULE_NAME}.icons")
|
||||
|
||||
#: The recurrence model (``core.recurrence.ScheduleRule`` and
|
||||
#: ``RuleValidationError``) the quest-definition routes build request
|
||||
#: rules with — the model validates at construction, the routes never
|
||||
@@ -215,6 +219,7 @@ __all__ = [
|
||||
"core_db",
|
||||
"core_events",
|
||||
"core_history",
|
||||
"core_icons",
|
||||
"core_materialize",
|
||||
"core_migrations",
|
||||
"core_presence",
|
||||
|
||||
+146
-40
@@ -165,10 +165,12 @@ integration's Home-Assistant config-entry options remain a temporary,
|
||||
SEPARATE source until Feature 18 wires the client to the API — the two
|
||||
are deliberately not unified here:
|
||||
|
||||
- ``GET /settings`` returns the current effective settings: all ten
|
||||
- ``GET /settings`` returns the current effective settings: all eleven
|
||||
documented fields (the rolling horizon, the day rollover time, the
|
||||
notify target, the three notification times and the four enable
|
||||
toggles) — the defaults on a fresh database.
|
||||
notify target, the three notification times, the four enable
|
||||
toggles and the ``timezone`` — the IANA household zone the
|
||||
household-local dates derive from, empty meaning host local) — the
|
||||
defaults on a fresh database.
|
||||
- ``PATCH /settings`` updates ONLY the supplied fields: the body is a
|
||||
JSON object of settings field names to new values, passed STRAIGHT
|
||||
to :func:`nestquest_core.settings_store.update_settings` — the
|
||||
@@ -184,18 +186,38 @@ The missed-sweep trigger (task 058c7b69) follows the same pattern over
|
||||
:mod:`nestquest_core.sweep` — the HA-free sweep policy the
|
||||
integration's rollover listener shares:
|
||||
|
||||
- ``POST /missed-sweep`` runs the sweep for the API host's local
|
||||
``today`` (ONE :func:`_local_now` clock read threaded into the core
|
||||
call) and publishes each returned ``(event_type, payload)`` pair
|
||||
DIRECTLY on the app's ONE transition publisher — the sweep-built
|
||||
payload, never re-fetched (the core commits its watermark before
|
||||
returning, so a failed re-fetch after it would lose the missed event
|
||||
forever), the same publish-what-the-core-built shape
|
||||
api/scheduler.py uses. The watermark rule
|
||||
(a same-day rerun announces nothing, a post-downtime run sweeps the
|
||||
accumulated window once), the no-completion-event rule and the
|
||||
read-only-over-the-domain-tables guarantee all live in the core; the
|
||||
response reports how many transitions were published.
|
||||
- ``POST /missed-sweep`` runs the sweep for the household-local
|
||||
``today`` (ONE :func:`_local_now` clock read re-expressed in the
|
||||
configured household ``timezone`` — empty falls back to host local —
|
||||
threaded into the core call) and publishes each returned
|
||||
``(event_type, payload)`` pair DIRECTLY on the app's ONE transition
|
||||
publisher — the sweep-built payload, never re-fetched (the core
|
||||
commits its watermark before returning, so a failed re-fetch after it
|
||||
would lose the missed event forever), the same
|
||||
publish-what-the-core-built shape api/scheduler.py uses. The
|
||||
watermark rule (a same-day rerun announces nothing, a post-downtime
|
||||
run sweeps the accumulated window once), the no-completion-event rule
|
||||
and the read-only-over-the-domain-tables guarantee all live in the
|
||||
core; the response reports how many transitions were published.
|
||||
|
||||
The quest-definition DELETE route (task 3efb07b4) is the hybrid admin
|
||||
delete (owner decision 2026-09-26: "delete if there's no history,
|
||||
retire/deactivate if there is"):
|
||||
|
||||
- ``DELETE /quest-definitions/{definition_id}`` is a thin adapter over
|
||||
:func:`nestquest_core.quest_definitions.delete_quest_definition`. A
|
||||
definition with NO completion event on any instance is hard-deleted
|
||||
(instances, assignees, windows, the row and its unreferenced rule, in
|
||||
one core transaction); one WITH history is retired by deactivation.
|
||||
Retirement preserves the definition row, schedule rule, assignees,
|
||||
windows and ALL durable completion history; like any deactivation it
|
||||
regenerates, so future UNCOMPLETED instances are cleared (rolling,
|
||||
regenerable rows) and none are recreated while the definition is
|
||||
inactive — the retired task stops generating and shows no open work.
|
||||
Durable instance history lives only in the append-only
|
||||
``completion_events``. The response reports which happened
|
||||
(``deleted`` / ``retired``) and carries the retired definition, or
|
||||
``null`` when deleted. An unknown id is 404.
|
||||
|
||||
The occurrence-preview route (task 5f843564) lets the admin PWA's
|
||||
Definitions edit sheet show the next dates a rule fires on WITHOUT
|
||||
@@ -205,9 +227,10 @@ reimplementing the recurrence rules client-side:
|
||||
``rule`` object create/edit take (:class:`AdminRuleRequest`, built
|
||||
through the SAME :func:`_rule_from_request` / core ``from_dict``
|
||||
validation, so a rejected rule is 422 exactly as on create), an
|
||||
optional ``start_date`` (default: the API host's local ``today``,
|
||||
ONE :func:`_local_now` clock read) and an optional ``count`` (1..50,
|
||||
default 10). The dates come from ONE
|
||||
optional ``start_date`` (default: the household-local ``today`` —
|
||||
ONE :func:`_local_now` clock read re-expressed in the configured
|
||||
household ``timezone``, empty falling back to host local) and an
|
||||
optional ``count`` (1..50, default 10). The dates come from ONE
|
||||
:func:`nestquest_core.recurrence.occurrences_between` call — the
|
||||
same engine the materializer walks — so the preview can only agree
|
||||
with what would be generated. The scan is BOUNDED server-side: the
|
||||
@@ -336,6 +359,7 @@ from api.nestquest_core import (
|
||||
core_dao_children,
|
||||
core_dao_rules,
|
||||
core_history,
|
||||
core_icons,
|
||||
core_materialize,
|
||||
core_presence_management,
|
||||
core_quest_definitions,
|
||||
@@ -448,6 +472,19 @@ class AdminQuestDefinitionListResponse(BaseModel):
|
||||
definitions: list[AdminQuestDefinitionResponse]
|
||||
|
||||
|
||||
class AdminQuestDefinitionDeleteResponse(BaseModel):
|
||||
"""The body ``DELETE /api/v1/admin/quest-definitions/{id}`` answers.
|
||||
|
||||
Exactly one of ``deleted`` / ``retired`` is true. ``definition`` is
|
||||
the retired (now inactive) definition, or null when it was deleted.
|
||||
"""
|
||||
|
||||
definition_id: int
|
||||
deleted: bool
|
||||
retired: bool
|
||||
definition: AdminQuestDefinitionResponse | None
|
||||
|
||||
|
||||
class AdminChildCreateRequest(BaseModel):
|
||||
"""The body of ``POST /api/v1/admin/children``.
|
||||
|
||||
@@ -531,9 +568,10 @@ class AdminOccurrencesPreviewRequest(BaseModel):
|
||||
|
||||
``rule`` is the SAME object create/edit take. ``start_date`` is an
|
||||
optional strict ``YYYY-MM-DD`` (validated by the core; default the
|
||||
API host's today). ``count`` is a strict JSON integer in
|
||||
1..``_PREVIEW_MAX_COUNT`` — anything else is 422 before any handler
|
||||
code runs.
|
||||
household-local today in the configured ``timezone``, empty falling
|
||||
back to the API host's local time). ``count`` is a strict JSON
|
||||
integer in 1..``_PREVIEW_MAX_COUNT`` — anything else is 422 before
|
||||
any handler code runs.
|
||||
"""
|
||||
|
||||
rule: AdminRuleRequest
|
||||
@@ -867,7 +905,7 @@ class AdminSettingsResponse(BaseModel):
|
||||
"""The effective settings as the admin plane serializes them.
|
||||
|
||||
Mirrors the core :class:`~nestquest_core.settings.NestQuestSettings`
|
||||
— all TEN documented fields, resolved (every absent stored field
|
||||
— all ELEVEN documented fields, resolved (every absent stored field
|
||||
already fell back to its default in the core). The same shape both
|
||||
the GET and the PATCH route answer with.
|
||||
"""
|
||||
@@ -882,6 +920,9 @@ class AdminSettingsResponse(BaseModel):
|
||||
afternoon_reminder_enabled: bool
|
||||
end_of_day_report_enabled: bool
|
||||
celebration_enabled: bool
|
||||
#: The household IANA time zone the API reads its clock in; ``""``
|
||||
#: means the API host's local time.
|
||||
timezone: str
|
||||
|
||||
|
||||
class AdminMissedSweepResponse(BaseModel):
|
||||
@@ -1178,6 +1219,26 @@ def _local_now() -> datetime.datetime:
|
||||
return datetime.datetime.now().astimezone()
|
||||
|
||||
|
||||
async def _household_clock(
|
||||
database: object,
|
||||
) -> tuple[object, datetime.datetime]:
|
||||
"""Return the stored settings and ONE household-local clock read.
|
||||
|
||||
The API host may run UTC while the household does not, so the one
|
||||
:func:`_local_now` read is re-expressed in the stored settings'
|
||||
``timezone`` (:meth:`NestQuestSettings.household_now`); an unset
|
||||
zone keeps the host's local time.
|
||||
"""
|
||||
settings = await core_settings_store.load_settings(database)
|
||||
return settings, settings.household_now(_local_now())
|
||||
|
||||
|
||||
async def _household_today(database: object) -> datetime.date:
|
||||
"""Return the household-local date of ONE :func:`_household_clock` read."""
|
||||
_settings, now = await _household_clock(database)
|
||||
return now.date()
|
||||
|
||||
|
||||
def _rule_from_request(rule: AdminRuleRequest) -> core_recurrence.ScheduleRule:
|
||||
"""Build the core ScheduleRule from the request's ``rule`` object.
|
||||
|
||||
@@ -1205,7 +1266,7 @@ def _quest_definition_response(
|
||||
id=bundle.definition.id,
|
||||
title=bundle.definition.title,
|
||||
description=bundle.definition.description,
|
||||
icon=bundle.definition.icon,
|
||||
icon=core_icons.normalize_icon_for_read(bundle.definition.icon),
|
||||
is_active=bundle.definition.is_active,
|
||||
skip_on_away=bundle.definition.skip_on_away,
|
||||
rule=_rule_response(bundle.rule),
|
||||
@@ -1496,7 +1557,7 @@ async def admin_create_quest_definition(
|
||||
response_model=AdminOccurrencesPreviewResponse,
|
||||
)
|
||||
async def admin_preview_occurrences(
|
||||
body: AdminOccurrencesPreviewRequest,
|
||||
body: AdminOccurrencesPreviewRequest, request: Request
|
||||
) -> AdminOccurrencesPreviewResponse:
|
||||
"""Return the first ``count`` dates the supplied rule fires on.
|
||||
|
||||
@@ -1509,12 +1570,15 @@ async def admin_preview_occurrences(
|
||||
call over the bounded window ``[start_date, start_date + 366
|
||||
days]`` — ``start_date`` defaulting to ONE :func:`_local_now` clock
|
||||
read — truncated to ``count``. Every core ``ValueError`` is 422
|
||||
(:func:`_raise_preview_error`). No database access.
|
||||
(:func:`_raise_preview_error`). The only database access is the
|
||||
settings read behind the household clock.
|
||||
"""
|
||||
start_date = (
|
||||
body.start_date
|
||||
if body.start_date is not None
|
||||
else _local_now().date().isoformat()
|
||||
else (
|
||||
await _household_today(request.app.state.db.database)
|
||||
).isoformat()
|
||||
)
|
||||
try:
|
||||
rule = _rule_from_request(body.rule)
|
||||
@@ -1579,16 +1643,16 @@ async def admin_set_quest_definition_active(
|
||||
body: AdminQuestDefinitionActiveRequest,
|
||||
request: Request,
|
||||
) -> AdminQuestDefinitionResponse:
|
||||
"""Deactivate (or reactivate) a definition; it is NEVER deleted.
|
||||
"""Deactivate (or reactivate) a definition; it is never deleted here.
|
||||
|
||||
Requires a valid admin JWT (the router's shared
|
||||
:func:`~api.auth.require_admin` dependency — the ONE check; this
|
||||
handler performs NO auth of its own). Thin adapter: ``is_active``
|
||||
goes straight to
|
||||
:func:`nestquest_core.quest_definitions.set_quest_definition_active`
|
||||
— deactivation is the only removal path (the row, rule, assignees
|
||||
and windows all survive, so completion history keeps its
|
||||
references). An unknown definition id is mapped to 404
|
||||
— the row, rule, assignees and windows all survive, so completion
|
||||
history keeps its references (the hybrid DELETE route is the only
|
||||
hard-delete path, and only for a definition without history). An unknown definition id is mapped to 404
|
||||
(:func:`_raise_quest_definition_error`); the body model already
|
||||
makes the core's real-bool check unreachable from this route.
|
||||
"""
|
||||
@@ -1602,6 +1666,44 @@ async def admin_set_quest_definition_active(
|
||||
return _quest_definition_response(bundle)
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/quest-definitions/{definition_id}",
|
||||
summary="Delete a quest definition, or retire it if it has history",
|
||||
response_model=AdminQuestDefinitionDeleteResponse,
|
||||
)
|
||||
async def admin_delete_quest_definition(
|
||||
definition_id: int, request: Request
|
||||
) -> AdminQuestDefinitionDeleteResponse:
|
||||
"""Hard-delete a history-free definition; retire one with history.
|
||||
|
||||
Requires a valid admin JWT (the router's shared
|
||||
:func:`~api.auth.require_admin` dependency — the ONE check; this
|
||||
handler performs NO auth of its own). Thin adapter: the id goes
|
||||
straight to
|
||||
:func:`nestquest_core.quest_definitions.delete_quest_definition`,
|
||||
which decides delete-vs-retire atomically in the core. An unknown
|
||||
definition id is mapped to 404
|
||||
(:func:`_raise_quest_definition_error`).
|
||||
"""
|
||||
state: DatabaseState = request.app.state.db
|
||||
try:
|
||||
result = await core_quest_definitions.delete_quest_definition(
|
||||
state.database, definition_id
|
||||
)
|
||||
except ValueError as error:
|
||||
_raise_quest_definition_error(error)
|
||||
return AdminQuestDefinitionDeleteResponse(
|
||||
definition_id=result.definition_id,
|
||||
deleted=result.deleted,
|
||||
retired=result.retired,
|
||||
definition=(
|
||||
None
|
||||
if result.definition is None
|
||||
else _quest_definition_response(result.definition)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/children/{child_id}/presence-patterns",
|
||||
summary="List a child's repeating presence patterns",
|
||||
@@ -1839,7 +1941,7 @@ async def admin_presence_override_consequence(
|
||||
body.start_date,
|
||||
body.end_date,
|
||||
body.is_present,
|
||||
today=_local_now().date(),
|
||||
today=await _household_today(state.database),
|
||||
)
|
||||
)
|
||||
except ValueError as error:
|
||||
@@ -1926,7 +2028,7 @@ async def admin_uncomplete_instance(
|
||||
"""
|
||||
state: DatabaseState = request.app.state.db
|
||||
database = state.database
|
||||
now = _local_now()
|
||||
_settings, now = await _household_clock(database)
|
||||
sub = claims.get("sub")
|
||||
try:
|
||||
result = await core_completion.uncomplete_instance(
|
||||
@@ -1992,7 +2094,7 @@ async def admin_regenerate(
|
||||
"""
|
||||
state: DatabaseState = request.app.state.db
|
||||
database = state.database
|
||||
today = _local_now().date()
|
||||
today = await _household_today(state.database)
|
||||
|
||||
if body.scope == "household":
|
||||
end_date = today + datetime.timedelta(
|
||||
@@ -2077,7 +2179,7 @@ def _settings_response(
|
||||
"""Serialize one core NestQuestSettings into the documented payload.
|
||||
|
||||
Explicit field-by-field (not ``dataclasses.asdict``) so the payload
|
||||
stays pinned to the ten documented fields even if the core
|
||||
stays pinned to the eleven documented fields even if the core
|
||||
dataclass later grows another one.
|
||||
"""
|
||||
return AdminSettingsResponse(
|
||||
@@ -2091,6 +2193,7 @@ def _settings_response(
|
||||
afternoon_reminder_enabled=settings.afternoon_reminder_enabled,
|
||||
end_of_day_report_enabled=settings.end_of_day_report_enabled,
|
||||
celebration_enabled=settings.celebration_enabled,
|
||||
timezone=settings.timezone,
|
||||
)
|
||||
|
||||
|
||||
@@ -2122,7 +2225,7 @@ async def admin_history_query(
|
||||
``ValueError`` is 422 (:func:`_raise_history_error`).
|
||||
"""
|
||||
state: DatabaseState = request.app.state.db
|
||||
today = _local_now().date()
|
||||
today = await _household_today(state.database)
|
||||
try:
|
||||
rows = await core_history.query_history(
|
||||
state.database, filter, start, end, today=today
|
||||
@@ -2165,7 +2268,7 @@ async def admin_history_csv(
|
||||
JSON route's (:func:`_raise_history_error`).
|
||||
"""
|
||||
state: DatabaseState = request.app.state.db
|
||||
today = _local_now().date()
|
||||
today = await _household_today(state.database)
|
||||
try:
|
||||
csv_text = await core_history.export_history_csv(
|
||||
state.database, filter, start, end, today=today
|
||||
@@ -2188,7 +2291,7 @@ async def admin_history_csv(
|
||||
response_model=AdminSettingsResponse,
|
||||
)
|
||||
async def admin_get_settings(request: Request) -> AdminSettingsResponse:
|
||||
"""Return the current effective settings (all ten documented fields).
|
||||
"""Return the current effective settings (all eleven documented fields).
|
||||
|
||||
Requires a valid admin JWT (the router's shared
|
||||
:func:`~api.auth.require_admin` dependency — the ONE check; this
|
||||
@@ -2253,7 +2356,9 @@ async def admin_run_missed_sweep(
|
||||
handler performs NO auth of its own). Thin adapter over the SAME
|
||||
HA-free sweep policy the integration's rollover listener runs
|
||||
(:mod:`nestquest_core.sweep`): ONE timezone-aware clock read
|
||||
(:func:`_local_now`) pins the API host's local ``today``, and ONE
|
||||
(:func:`_local_now`, re-expressed in the configured household
|
||||
``timezone``; empty falls back to host local) pins the
|
||||
household-local ``today``, and ONE
|
||||
:func:`nestquest_core.sweep.run_missed_sweep` call does everything
|
||||
else — the past-due open-instance query, the documented payload
|
||||
build and the watermark update (a same-day rerun is an empty
|
||||
@@ -2280,7 +2385,7 @@ async def admin_run_missed_sweep(
|
||||
"""
|
||||
state: DatabaseState = request.app.state.db
|
||||
database = state.database
|
||||
today = _local_now().date()
|
||||
today = await _household_today(state.database)
|
||||
try:
|
||||
events = await core_sweep.run_missed_sweep(database, today=today)
|
||||
except ValueError as error:
|
||||
@@ -2309,8 +2414,9 @@ async def admin_snapshot(request: Request) -> AdminSnapshotResponse:
|
||||
:class:`AdminSnapshotResponse`.
|
||||
"""
|
||||
state: DatabaseState = request.app.state.db
|
||||
settings, now = await _household_clock(state.database)
|
||||
snapshot = await core_snapshot.build_snapshot(
|
||||
state.database, core_settings.NestQuestSettings(), _local_now()
|
||||
state.database, settings, now
|
||||
)
|
||||
return AdminSnapshotResponse(
|
||||
today_iso=snapshot.today_iso,
|
||||
|
||||
+21
-6
@@ -8,9 +8,9 @@ this router inherits the check).
|
||||
|
||||
The snapshot route is a thin adapter over the bundled core: it performs
|
||||
NO business logic. It reads the live database off ``app.state.db``,
|
||||
resolves ONE timezone-aware ``now`` (the API host's local time — the
|
||||
API is the household's "local" host now that the domain no longer lives
|
||||
inside Home Assistant), calls the pure
|
||||
resolves ONE timezone-aware ``now`` (the host clock re-expressed in the
|
||||
stored household ``timezone`` setting — the API host may run UTC while
|
||||
the household does not), calls the pure
|
||||
:func:`nestquest_core.snapshot.build_snapshot`, shapes each child's
|
||||
instances through :func:`nestquest_core.snapshot.instance_payload` with
|
||||
``include_missed=False`` (D-009: missed instances are OMITTED from the
|
||||
@@ -63,7 +63,7 @@ from api.dependencies import require_panel_token
|
||||
from api.nestquest_core import (
|
||||
core_completion,
|
||||
core_events,
|
||||
core_settings,
|
||||
core_settings_store,
|
||||
core_snapshot,
|
||||
)
|
||||
from api import transitions as api_transitions
|
||||
@@ -178,6 +178,20 @@ def _local_now() -> datetime.datetime:
|
||||
return datetime.datetime.now().astimezone()
|
||||
|
||||
|
||||
async def _household_clock(
|
||||
database: object,
|
||||
) -> tuple[object, datetime.datetime]:
|
||||
"""Return the stored settings and ONE household-local clock read.
|
||||
|
||||
The API host may run UTC while the household does not, so the one
|
||||
:func:`_local_now` read is re-expressed in the stored settings'
|
||||
``timezone`` (:meth:`NestQuestSettings.household_now`); an unset
|
||||
zone keeps the host's local time.
|
||||
"""
|
||||
settings = await core_settings_store.load_settings(database)
|
||||
return settings, settings.household_now(_local_now())
|
||||
|
||||
|
||||
@router.get(
|
||||
"/snapshot",
|
||||
summary="Today's household snapshot",
|
||||
@@ -196,8 +210,9 @@ async def panel_snapshot(request: Request) -> PanelSnapshotResponse:
|
||||
:class:`PanelSnapshotResponse`.
|
||||
"""
|
||||
state: DatabaseState = request.app.state.db
|
||||
settings, now = await _household_clock(state.database)
|
||||
snapshot = await core_snapshot.build_snapshot(
|
||||
state.database, core_settings.NestQuestSettings(), _local_now()
|
||||
state.database, settings, now
|
||||
)
|
||||
return PanelSnapshotResponse(
|
||||
today_iso=snapshot.today_iso,
|
||||
@@ -282,7 +297,7 @@ async def panel_complete_instance(
|
||||
detail="Quest instance not found for this child",
|
||||
)
|
||||
|
||||
now = _local_now()
|
||||
_settings, now = await _household_clock(database)
|
||||
try:
|
||||
result = await core_completion.complete_instance(
|
||||
database,
|
||||
|
||||
+57
-13
@@ -8,7 +8,8 @@ configured ``day_rollover_time`` — read fresh from the settings store
|
||||
at the top of EVERY cycle, so an admin's settings change applies on
|
||||
the next scheduling decision without a restart — then runs the
|
||||
HA-free core's :func:`nestquest_core.sweep.run_missed_sweep` for the
|
||||
API host's local date and publishes each returned
|
||||
household-local date (the stored ``timezone`` setting; the API host's
|
||||
local date when unset) and publishes each returned
|
||||
``nestquest_quest_missed`` event on the app's ONE transition publisher
|
||||
(the same SSE stream every route publishes through).
|
||||
|
||||
@@ -43,19 +44,56 @@ LOGGER = logging.getLogger(__name__)
|
||||
_RETRY_BACKOFF_SECONDS = 60.0
|
||||
|
||||
|
||||
def _delay_seconds(target: datetime.time, now: datetime.datetime) -> float:
|
||||
"""Seconds from ``now`` until the next occurrence of ``target``.
|
||||
#: Upper bound on the minute-by-minute search past a nonexistent wall
|
||||
#: time; real DST gaps are an hour, the largest ever skipped a day.
|
||||
_MAX_GAP_MINUTES = 2 * 24 * 60
|
||||
|
||||
``target`` is a plain ``HH:MM`` time of day: the next wall-clock
|
||||
occurrence strictly AFTER ``now`` (an equal time schedules for
|
||||
tomorrow, so the just-run sweep is never instantly re-run).
|
||||
|
||||
def _resolve_wall_time(
|
||||
day: datetime.date, target: datetime.time, zone: datetime.tzinfo
|
||||
) -> datetime.datetime:
|
||||
"""The aware instant ``target`` (``HH:MM``) names on ``day`` in ``zone``.
|
||||
|
||||
A nonexistent wall time (inside a spring-forward gap) resolves to
|
||||
the first valid wall minute at/after it — the gap's end, e.g. 02:30
|
||||
on a 02:00→03:00 day becomes 03:00. An ambiguous wall time (the
|
||||
repeated fall-back hour) resolves to its FIRST occurrence
|
||||
(``fold=0``).
|
||||
"""
|
||||
scheduled = now.replace(
|
||||
hour=target.hour, minute=target.minute, second=0, microsecond=0
|
||||
wall = datetime.datetime.combine(
|
||||
day, datetime.time(target.hour, target.minute)
|
||||
)
|
||||
if scheduled <= now:
|
||||
scheduled += datetime.timedelta(days=1)
|
||||
return (scheduled - now).total_seconds()
|
||||
for _ in range(_MAX_GAP_MINUTES):
|
||||
candidate = wall.replace(tzinfo=zone)
|
||||
round_trip = candidate.astimezone(datetime.timezone.utc).astimezone(
|
||||
zone
|
||||
)
|
||||
if round_trip.replace(tzinfo=None) == wall:
|
||||
return candidate
|
||||
wall += datetime.timedelta(minutes=1)
|
||||
raise ValueError(f"no valid wall time at/after {target} on {day}")
|
||||
|
||||
|
||||
def _delay_seconds(target: datetime.time, now: datetime.datetime) -> float:
|
||||
"""Real seconds from ``now`` until the next occurrence of ``target``.
|
||||
|
||||
``target`` is a plain ``HH:MM`` household time of day, resolved in
|
||||
``now``'s zone by :func:`_resolve_wall_time` (nonexistent → first
|
||||
valid instant after the gap; ambiguous → first occurrence). The
|
||||
result is the next such instant strictly AFTER ``now`` (an equal
|
||||
time schedules for tomorrow, so the just-run sweep is never
|
||||
instantly re-run). Both instants are compared and subtracted in
|
||||
UTC: same-``tzinfo`` aware arithmetic is wall-clock arithmetic and
|
||||
would be an hour off across a DST transition.
|
||||
"""
|
||||
now_utc = now.astimezone(datetime.timezone.utc)
|
||||
day = now.date()
|
||||
while True:
|
||||
scheduled = _resolve_wall_time(day, target, now.tzinfo)
|
||||
scheduled_utc = scheduled.astimezone(datetime.timezone.utc)
|
||||
if scheduled_utc > now_utc:
|
||||
return (scheduled_utc - now_utc).total_seconds()
|
||||
day += datetime.timedelta(days=1)
|
||||
|
||||
|
||||
class MissedSweepScheduler:
|
||||
@@ -130,7 +168,11 @@ class MissedSweepScheduler:
|
||||
)
|
||||
await self._sleep(_RETRY_BACKOFF_SECONDS)
|
||||
continue
|
||||
delay = _delay_seconds(rollover, self._clock())
|
||||
# The host may run UTC: the rollover is a household wall-clock
|
||||
# time, so the clock read is re-expressed in the stored zone.
|
||||
delay = _delay_seconds(
|
||||
rollover, settings.household_now(self._clock())
|
||||
)
|
||||
LOGGER.info(
|
||||
"NestQuest missed sweep scheduled for %s (%.0fs from now)",
|
||||
settings.day_rollover_time,
|
||||
@@ -138,7 +180,9 @@ class MissedSweepScheduler:
|
||||
)
|
||||
await self._sleep(delay)
|
||||
try:
|
||||
await self._run_once(self._clock().date())
|
||||
await self._run_once(
|
||||
settings.household_now(self._clock()).date()
|
||||
)
|
||||
except Exception:
|
||||
# Not silent either: the sweep error is logged and the
|
||||
# loop backs off before the next cycle, whose watermark
|
||||
|
||||
@@ -112,6 +112,13 @@ CONF_AFTERNOON_REMINDER_ENABLED = "afternoon_reminder_enabled"
|
||||
CONF_END_OF_DAY_REPORT_ENABLED = "end_of_day_report_enabled"
|
||||
CONF_CELEBRATION_ENABLED = "celebration_enabled"
|
||||
DEFAULT_AUTOMATION_ENABLED = True
|
||||
# The household's IANA time zone (e.g. ``America/New_York``) the API
|
||||
# service reads its clock in. The empty string keeps the historical
|
||||
# behaviour — the API host's own local time — so an existing install is
|
||||
# unchanged until the owner sets it. The integration itself always uses
|
||||
# Home Assistant's configured ``time_zone`` and ignores this field.
|
||||
CONF_TIMEZONE = "timezone"
|
||||
DEFAULT_TIMEZONE = ""
|
||||
|
||||
# Panel-plane API client (Feature 18): the integration reaches the
|
||||
# NestQuest API service (Feature 16) over HTTP instead of the database.
|
||||
|
||||
@@ -13,8 +13,12 @@ Guardrail mapping:
|
||||
- ``schedule_rules`` deletion is delete-if-unreferenced: a rule still
|
||||
referenced by any quest definition is rejected (the done-condition),
|
||||
not cascaded.
|
||||
- ``quest_definitions`` has no delete path at all: definitions are
|
||||
deactivated, never hard-deleted, and history must survive.
|
||||
- ``quest_definitions`` has exactly one delete path,
|
||||
:meth:`QuestDefinitionsDao.delete_if_no_history` (owner decision
|
||||
2026-09-26): a definition with NO completion event on any of its
|
||||
instances is hard-deleted with its instances, assignees, windows and
|
||||
(if unreferenced) rule; a definition WITH history is never deleted —
|
||||
it is retired by deactivation, so history always survives.
|
||||
- Assignment is multi-assignee (D-008): :meth:`add_assignee` and
|
||||
:meth:`remove_assignee` change future instances only — the DAO writes
|
||||
the assignee table and nothing else; assignment edits never rewrite
|
||||
@@ -25,8 +29,8 @@ Guardrail mapping:
|
||||
:meth:`QuestDefinitionsDao.add_assignee` (active child); no
|
||||
permission checks here, that is the Feature 09 gate's job.
|
||||
|
||||
Concurrency: ``delete_rule_if_unreferenced`` and the assignee
|
||||
mutations perform their checks and writes inside one transaction under
|
||||
Concurrency: ``delete_rule_if_unreferenced``,
|
||||
``delete_if_no_history`` and the assignee mutations perform their checks and writes inside one transaction under
|
||||
the connection-scoped lock shared with :mod:`.dao_children`, so a
|
||||
definition referencing the rule (or an assignee appearing) cannot slip
|
||||
in between check and write on this connection.
|
||||
@@ -608,26 +612,42 @@ class ScheduleRulesDao:
|
||||
"""
|
||||
async with _connection_lock(self._database):
|
||||
async with self._database.transaction():
|
||||
row = await self._database.fetch_one(
|
||||
"SELECT 1 FROM quest_definitions "
|
||||
"WHERE schedule_rule_id = ? LIMIT 1",
|
||||
(rule_id,),
|
||||
return await _delete_rule_if_unreferenced_in_transaction(
|
||||
self._database, rule_id
|
||||
)
|
||||
if row is not None:
|
||||
return False
|
||||
result = await self._database.execute(
|
||||
"DELETE FROM schedule_rules WHERE id = ?",
|
||||
(rule_id,),
|
||||
)
|
||||
return result.rowcount > 0
|
||||
|
||||
|
||||
async def _delete_rule_if_unreferenced_in_transaction(
|
||||
database: NestQuestDatabase, rule_id: int
|
||||
) -> bool:
|
||||
"""Delete-if-unreferenced body; the CALLER holds lock + transaction.
|
||||
|
||||
Shared by :meth:`ScheduleRulesDao.delete_if_unreferenced` and
|
||||
:meth:`QuestDefinitionsDao.delete_if_no_history`, so the rule's
|
||||
reference check runs in whichever transaction removed the last
|
||||
definition that could reference it.
|
||||
"""
|
||||
row = await database.fetch_one(
|
||||
"SELECT 1 FROM quest_definitions "
|
||||
"WHERE schedule_rule_id = ? LIMIT 1",
|
||||
(rule_id,),
|
||||
)
|
||||
if row is not None:
|
||||
return False
|
||||
result = await database.execute(
|
||||
"DELETE FROM schedule_rules WHERE id = ?",
|
||||
(rule_id,),
|
||||
)
|
||||
return result.rowcount > 0
|
||||
|
||||
|
||||
class QuestDefinitionsDao:
|
||||
"""Typed async access to ``quest_definitions`` and its assignees.
|
||||
|
||||
No delete method exists: definitions are deactivated via
|
||||
:meth:`set_active`, never hard-deleted, so completion history keeps
|
||||
its references (feature guardrail). Assignment is multi-assignee
|
||||
The only delete method is :meth:`delete_if_no_history`: a
|
||||
definition with completion history is never hard-deleted (it is
|
||||
deactivated via :meth:`set_active` instead), so completion history
|
||||
always keeps its references (feature guardrail, D-005). Assignment is multi-assignee
|
||||
(D-008): the definition row carries no child; assignees live in
|
||||
``quest_definition_assignees`` and are managed explicitly so the
|
||||
operations stay separately loggable and permission-gateable.
|
||||
@@ -1140,6 +1160,54 @@ class QuestDefinitionsDao:
|
||||
)
|
||||
return result.rowcount
|
||||
|
||||
async def delete_if_no_history(self, definition_id: int) -> bool | None:
|
||||
"""Hard-delete a definition that has NO completion history.
|
||||
|
||||
Returns None when the definition does not exist, False when any
|
||||
of its instances has a completion event (nothing is touched —
|
||||
the caller retires it by deactivation instead), and True when it
|
||||
was deleted: its ``quest_instances``, assignee and window rows,
|
||||
the definition row, and its schedule rule if no other definition
|
||||
references it.
|
||||
|
||||
The history check and every DELETE run inside ONE transaction
|
||||
under the connection lock, so a completion recorded concurrently
|
||||
cannot land between the check and the delete (D-005: an instance
|
||||
with a completion event is never deleted).
|
||||
"""
|
||||
async with _connection_lock(self._database):
|
||||
async with self._database.transaction():
|
||||
row = await self._database.fetch_one(
|
||||
"SELECT schedule_rule_id FROM quest_definitions "
|
||||
"WHERE id = ?",
|
||||
(definition_id,),
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
schedule_rule_id = row[0]
|
||||
history = await self._database.fetch_one(
|
||||
"SELECT 1 FROM completion_events "
|
||||
"JOIN quest_instances "
|
||||
"ON quest_instances.id = completion_events.instance_id "
|
||||
"WHERE quest_instances.definition_id = ? LIMIT 1",
|
||||
(definition_id,),
|
||||
)
|
||||
if history is not None:
|
||||
return False
|
||||
for statement in (
|
||||
"DELETE FROM quest_instances WHERE definition_id = ?",
|
||||
"DELETE FROM quest_definition_assignees "
|
||||
"WHERE definition_id = ?",
|
||||
"DELETE FROM quest_definition_windows "
|
||||
"WHERE definition_id = ?",
|
||||
"DELETE FROM quest_definitions WHERE id = ?",
|
||||
):
|
||||
await self._database.execute(statement, (definition_id,))
|
||||
await _delete_rule_if_unreferenced_in_transaction(
|
||||
self._database, schedule_rule_id
|
||||
)
|
||||
return True
|
||||
|
||||
async def add_assignee(
|
||||
self, definition_id: int, child_id: int
|
||||
) -> list[ChildRecord]:
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Namespaced quest-definition icon keys.
|
||||
|
||||
A definition's ``icon`` is stored as ``<namespace>:<name>`` where the
|
||||
namespace is one of :data:`ICON_NAMESPACES`:
|
||||
|
||||
- ``lucide:<name>`` / ``fa:<name>`` — ``<name>`` is a lowercase kebab
|
||||
name (ASCII ``[a-z0-9-]``, not starting or ending with ``-``).
|
||||
- ``emoji:<payload>`` — a short emoji string of at most
|
||||
:data:`EMOJI_MAX_CODE_POINTS` code points, with no whitespace (JS
|
||||
``\\s``, so including U+FEFF), no control characters and none of
|
||||
``<``, ``>``, ``&``.
|
||||
|
||||
Rows written before namespacing hold a bare Lucide name (``dog``).
|
||||
:func:`validate_icon` (writes) normalizes such a legacy value to
|
||||
``lucide:<name>``; :func:`normalize_icon_for_read` (reads) does the same
|
||||
leniently so legacy rows render without a data migration.
|
||||
|
||||
Nothing here imports :mod:`homeassistant`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
ICON_NAMESPACE_LUCIDE = "lucide"
|
||||
ICON_NAMESPACE_FA = "fa"
|
||||
ICON_NAMESPACE_EMOJI = "emoji"
|
||||
ICON_NAMESPACES = frozenset(
|
||||
{ICON_NAMESPACE_LUCIDE, ICON_NAMESPACE_FA, ICON_NAMESPACE_EMOJI}
|
||||
)
|
||||
|
||||
#: Upper bound on an emoji payload's length in code points — enough for
|
||||
#: ZWJ sequences such as a family emoji, too short for arbitrary text.
|
||||
EMOJI_MAX_CODE_POINTS = 8
|
||||
|
||||
_KEBAB_NAME = re.compile(r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
|
||||
# U+FEFF (BOM / zero-width no-break space) is neither str.isspace() nor
|
||||
# ``Cc`` in Python, but JS ``\s`` matches it, so it is listed here to keep
|
||||
# this rule identical to the frontends' isEmojiPayload (/[\s<>&]|\p{Cc}/u).
|
||||
# Other format characters, notably the ZWJ U+200D that emoji sequences
|
||||
# need, stay valid in both runtimes.
|
||||
_EMOJI_FORBIDDEN = frozenset("<>&\ufeff")
|
||||
|
||||
|
||||
def _is_kebab_name(value: str) -> bool:
|
||||
return _KEBAB_NAME.fullmatch(value) is not None
|
||||
|
||||
|
||||
def _is_valid_emoji_payload(value: str) -> bool:
|
||||
if not value or len(value) > EMOJI_MAX_CODE_POINTS:
|
||||
return False
|
||||
return not any(
|
||||
char.isspace()
|
||||
or char in _EMOJI_FORBIDDEN
|
||||
or unicodedata.category(char) == "Cc"
|
||||
for char in value
|
||||
)
|
||||
|
||||
|
||||
def validate_icon(value: object) -> str | None:
|
||||
"""Return the canonical namespaced icon key, or raise naming ``icon``.
|
||||
|
||||
``None`` or an empty/whitespace-only string returns ``None`` (the
|
||||
icon is cleared). Otherwise the raw value is validated untrimmed, so
|
||||
edge whitespace or control characters are rejected rather than
|
||||
silently stripped. A value with no ``:`` is a legacy bare Lucide
|
||||
name and is stored as ``lucide:<value>``. An unknown namespace, an
|
||||
empty or malformed name, or an invalid emoji payload raises
|
||||
ValueError.
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"icon must be a string, got {value!r}")
|
||||
if not value.strip():
|
||||
return None
|
||||
|
||||
namespace, separator, name = value.partition(":")
|
||||
if not separator:
|
||||
if not _is_kebab_name(value):
|
||||
raise ValueError(
|
||||
f"icon must be a lowercase kebab name, got {value!r}"
|
||||
)
|
||||
return f"{ICON_NAMESPACE_LUCIDE}:{value}"
|
||||
|
||||
if namespace not in ICON_NAMESPACES:
|
||||
raise ValueError(
|
||||
f"icon has an unknown namespace {namespace!r}; expected one of "
|
||||
f"{sorted(ICON_NAMESPACES)}"
|
||||
)
|
||||
if namespace == ICON_NAMESPACE_EMOJI:
|
||||
if not _is_valid_emoji_payload(name):
|
||||
raise ValueError(
|
||||
f"icon emoji must be 1-{EMOJI_MAX_CODE_POINTS} code points "
|
||||
f"with no whitespace, control characters or markup, "
|
||||
f"got {value!r}"
|
||||
)
|
||||
elif not _is_kebab_name(name):
|
||||
raise ValueError(
|
||||
f"icon {namespace} name must be a lowercase kebab name, "
|
||||
f"got {value!r}"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def normalize_icon_for_read(value: str | None) -> str | None:
|
||||
"""Return a stored icon in namespaced form for output.
|
||||
|
||||
Lenient: ``None``/empty returns ``None``, a recognised namespace is
|
||||
returned unchanged, and anything else becomes ``lucide:<value>`` so
|
||||
legacy rows render (an unknown name falls through to the frontend's
|
||||
fallback icon rather than erroring).
|
||||
"""
|
||||
if not value or not value.strip():
|
||||
return None
|
||||
namespace, separator, _ = value.partition(":")
|
||||
if separator and namespace in ICON_NAMESPACES:
|
||||
return value
|
||||
return f"{ICON_NAMESPACE_LUCIDE}:{value}"
|
||||
@@ -7,7 +7,9 @@ all-or-nothing create/edit here, and never touch the DAO SQL directly.
|
||||
:func:`edit_quest_definition` the edit path (which may also replace the
|
||||
whole assignee set), :func:`assign_child` and
|
||||
:func:`unassign_child` the single-child assignment paths, and
|
||||
:func:`set_quest_definition_active` the deactivate/reactivate path.
|
||||
:func:`set_quest_definition_active` the deactivate/reactivate path,
|
||||
and :func:`delete_quest_definition` the hybrid admin delete (hard-delete
|
||||
when there is no completion history, retire by deactivation otherwise).
|
||||
There is no permission check here (that is Feature 09).
|
||||
|
||||
Validation policy mirrors :mod:`.children`:
|
||||
@@ -59,6 +61,7 @@ from .dao_rules import (
|
||||
schedule_rule_to_storage,
|
||||
)
|
||||
from .db import NestQuestDatabase
|
||||
from .icons import validate_icon
|
||||
from .materialize import regenerate_for_definition
|
||||
from .recurrence import ScheduleRule, occurs_on
|
||||
|
||||
@@ -79,6 +82,21 @@ class CreatedQuestDefinition:
|
||||
windows: list[QuestDefinitionWindowRecord]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeletedQuestDefinition:
|
||||
"""What :func:`delete_quest_definition` actually did.
|
||||
|
||||
Exactly one of ``deleted`` / ``retired`` is True. ``definition`` is
|
||||
the retired (deactivated) definition's updated view, or None when
|
||||
the definition was hard-deleted and no longer exists.
|
||||
"""
|
||||
|
||||
definition_id: int
|
||||
deleted: bool
|
||||
retired: bool
|
||||
definition: CreatedQuestDefinition | None
|
||||
|
||||
|
||||
def _now_stamp() -> str:
|
||||
"""Return the module's strict UTC second-precision stamp."""
|
||||
return datetime.datetime.now(datetime.timezone.utc).isoformat(
|
||||
@@ -248,7 +266,7 @@ async def create_quest_definition(
|
||||
assignee_ids = _validate_assignee_ids(assignee_child_ids)
|
||||
window_specs = _normalize_windows(windows)
|
||||
description_value = _validate_text(description, "description")
|
||||
icon_value = _validate_text(icon, "icon")
|
||||
icon_value = validate_icon(icon)
|
||||
skip_on_away_value = _validate_skip_on_away(skip_on_away)
|
||||
|
||||
storage = schedule_rule_to_storage(rule)
|
||||
@@ -351,7 +369,7 @@ async def edit_quest_definition(
|
||||
|
||||
icon_value: str | None | object = _UNSET
|
||||
if icon is not _UNSET:
|
||||
icon_value = _validate_text(icon, "icon")
|
||||
icon_value = validate_icon(icon)
|
||||
|
||||
rule_storage: ScheduleRuleStorage | object = _UNSET
|
||||
if rule is not _UNSET:
|
||||
@@ -503,12 +521,19 @@ async def set_quest_definition_active(
|
||||
) -> CreatedQuestDefinition:
|
||||
"""Deactivate or reactivate a definition; returns the updated view.
|
||||
|
||||
Flipping the flag is the only removal path (Feature 06 guardrail):
|
||||
Flipping the flag is the only removal path for a definition with
|
||||
completion history (Feature 06 guardrail; a history-free definition
|
||||
may instead be hard-deleted by :func:`delete_quest_definition`):
|
||||
a deactivated definition stops future instance generation but its
|
||||
row, schedule rule, assignees and windows all survive, and existing
|
||||
instances plus completion history are never touched. Reactivation
|
||||
re-enables future generation; generating or removing instances is
|
||||
Feature 07 and does not happen here.
|
||||
row, schedule rule, assignees and windows all survive, and its
|
||||
durable completion history (the append-only ``completion_events``)
|
||||
is never touched. Like every Feature 06 config change, the flip is
|
||||
followed by :func:`~.materialize.regenerate_for_definition`: the
|
||||
definition's future (today onward) UNCOMPLETED instances are cleared
|
||||
— they are rolling, regenerable rows — and, while the definition is
|
||||
inactive, none are re-materialized. Completed and past instances
|
||||
are kept. Reactivation re-enables generation, and the same
|
||||
regeneration re-materializes the rolling horizon.
|
||||
|
||||
``definition_id`` must be a plain int (bools and floats rejected,
|
||||
since SQLite would bind ``True`` onto definition 1) and
|
||||
@@ -561,6 +586,68 @@ async def set_quest_definition_active(
|
||||
)
|
||||
|
||||
|
||||
async def delete_quest_definition(
|
||||
database: NestQuestDatabase,
|
||||
definition_id: int,
|
||||
*,
|
||||
today: datetime.date | None = None,
|
||||
horizon_days: int | None = None,
|
||||
) -> DeletedQuestDefinition:
|
||||
"""Delete a definition if it has no history; otherwise retire it.
|
||||
|
||||
Owner decision (2026-09-26): "delete if there's no history,
|
||||
retire/deactivate if there is". When NO instance of the definition
|
||||
has a completion event, the definition, its instances, assignees,
|
||||
windows and (if no other definition references it) its schedule
|
||||
rule are hard-deleted in ONE transaction by
|
||||
:meth:`~.dao_rules.QuestDefinitionsDao.delete_if_no_history` — the
|
||||
history check is inside that transaction, so a completion recorded
|
||||
concurrently can never be deleted (D-005). When history exists,
|
||||
the definition is retired through :func:`set_quest_definition_active`
|
||||
(``False``). Retirement preserves the definition row, schedule
|
||||
rule, assignees, windows and ALL durable completion history. Like
|
||||
any deactivation it regenerates, so future UNCOMPLETED instances are
|
||||
cleared (they are rolling, regenerable rows) and none are recreated
|
||||
while the definition is inactive — the retired task stops generating
|
||||
and no longer shows open work. Durable instance history lives only
|
||||
in the append-only ``completion_events``.
|
||||
|
||||
``definition_id`` must be a plain int (bools and floats rejected).
|
||||
Raises ValueError naming the field when the id is malformed or the
|
||||
definition does not exist. ``today`` / ``horizon_days`` are threaded
|
||||
into the retire path's regeneration, as in
|
||||
:func:`set_quest_definition_active`.
|
||||
"""
|
||||
_validate_definition_id(definition_id)
|
||||
deleted = await QuestDefinitionsDao(database).delete_if_no_history(
|
||||
definition_id
|
||||
)
|
||||
if deleted is None:
|
||||
raise ValueError(
|
||||
f"definition_id: quest definition {definition_id} does not exist"
|
||||
)
|
||||
if deleted:
|
||||
return DeletedQuestDefinition(
|
||||
definition_id=definition_id,
|
||||
deleted=True,
|
||||
retired=False,
|
||||
definition=None,
|
||||
)
|
||||
retired = await set_quest_definition_active(
|
||||
database,
|
||||
definition_id,
|
||||
False,
|
||||
today=today,
|
||||
horizon_days=horizon_days,
|
||||
)
|
||||
return DeletedQuestDefinition(
|
||||
definition_id=definition_id,
|
||||
deleted=False,
|
||||
retired=True,
|
||||
definition=retired,
|
||||
)
|
||||
|
||||
|
||||
def _bundle_snapshot(
|
||||
snapshot: QuestDefinitionSnapshot,
|
||||
) -> CreatedQuestDefinition:
|
||||
|
||||
@@ -35,6 +35,7 @@ from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from types import MappingProxyType
|
||||
from typing import Any, Mapping
|
||||
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
||||
|
||||
from .const import (
|
||||
CONF_AFTERNOON_REMINDER_ENABLED,
|
||||
@@ -47,12 +48,14 @@ from .const import (
|
||||
CONF_MORNING_SUMMARY_ENABLED,
|
||||
CONF_MORNING_SUMMARY_TIME,
|
||||
CONF_NOTIFY_TARGET,
|
||||
CONF_TIMEZONE,
|
||||
DEFAULT_AFTERNOON_REMINDER_TIME,
|
||||
DEFAULT_AUTOMATION_ENABLED,
|
||||
DEFAULT_DAY_ROLLOVER_TIME,
|
||||
DEFAULT_END_OF_DAY_REPORT_TIME,
|
||||
DEFAULT_HORIZON_DAYS,
|
||||
DEFAULT_MORNING_SUMMARY_TIME,
|
||||
DEFAULT_TIMEZONE,
|
||||
LOGGER,
|
||||
TIME_PATTERN,
|
||||
)
|
||||
@@ -153,6 +156,29 @@ def _resolve_optional_str(value: Any) -> str:
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _resolve_timezone(value: Any) -> str:
|
||||
"""Validate a household time zone and return it.
|
||||
|
||||
The empty string means "the API host's local time" (the historical
|
||||
behaviour); anything else must be an IANA key :class:`ZoneInfo`
|
||||
resolves (e.g. ``America/New_York``). A non-str (including
|
||||
``None``) is rejected; the ``None``-as-absent mapping lives ONLY in
|
||||
:meth:`NestQuestSettings.from_options` (via :func:`_option_value`).
|
||||
"""
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f"timezone must be a string, got {value!r}")
|
||||
if value == "":
|
||||
return value
|
||||
try:
|
||||
ZoneInfo(value)
|
||||
except (ZoneInfoNotFoundError, ValueError) as error:
|
||||
raise ValueError(
|
||||
f"timezone must be an IANA time zone name such as "
|
||||
f"'America/New_York', got {value!r}"
|
||||
) from error
|
||||
return value
|
||||
|
||||
|
||||
#: The single field table the two builders share. Each row is
|
||||
#: ``(field_name, CONF_* key, default, validator)``. ``from_options``
|
||||
#: applies every validator (raising on the first invalid value) while
|
||||
@@ -214,6 +240,7 @@ _FIELDS: tuple[tuple[str, str, Any, Callable[[Any], Any]], ...] = (
|
||||
DEFAULT_AUTOMATION_ENABLED,
|
||||
_resolve_bool,
|
||||
),
|
||||
("timezone", CONF_TIMEZONE, DEFAULT_TIMEZONE, _resolve_timezone),
|
||||
)
|
||||
|
||||
|
||||
@@ -243,6 +270,7 @@ class NestQuestSettings:
|
||||
afternoon_reminder_enabled: bool = DEFAULT_AUTOMATION_ENABLED
|
||||
end_of_day_report_enabled: bool = DEFAULT_AUTOMATION_ENABLED
|
||||
celebration_enabled: bool = DEFAULT_AUTOMATION_ENABLED
|
||||
timezone: str = DEFAULT_TIMEZONE
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Validate STRICTLY at construction so a hand-built instance
|
||||
@@ -281,6 +309,21 @@ class NestQuestSettings:
|
||||
raise ValueError(
|
||||
f"{name} must be a boolean, got {value!r}"
|
||||
)
|
||||
_resolve_timezone(self.timezone)
|
||||
|
||||
def household_now(self, instant: datetime.datetime) -> datetime.datetime:
|
||||
"""Return the aware ``instant`` expressed in the household's zone.
|
||||
|
||||
The API service has no Home Assistant ``time_zone``, so its one
|
||||
clock read (an aware host-local ``now``) is converted here: with
|
||||
:attr:`timezone` set the SAME instant is re-expressed in that
|
||||
zone, so ``.date()`` and ``.time()`` are the household's wall
|
||||
clock even when the host runs UTC. With :attr:`timezone` empty
|
||||
the instant is returned unchanged (the host's local time).
|
||||
"""
|
||||
if not self.timezone:
|
||||
return instant
|
||||
return instant.astimezone(ZoneInfo(self.timezone))
|
||||
|
||||
@property
|
||||
def day_rollover_hour_minute(self) -> tuple[int, int]:
|
||||
|
||||
@@ -18,7 +18,7 @@ API client; the two are deliberately NOT unified here, and neither
|
||||
side reads the other's values.
|
||||
|
||||
STORED SERIALIZATION — the document at ``SETTINGS_META_KEY`` is a JSON
|
||||
object holding exactly the TEN settings fields, keyed by field name
|
||||
object holding exactly the ELEVEN settings fields, keyed by field name
|
||||
(which equals the ``CONF_*`` option key for every field), complete
|
||||
after the first update:
|
||||
|
||||
@@ -30,7 +30,10 @@ after the first update:
|
||||
core's normalizer),
|
||||
- ``morning_summary_enabled``, ``afternoon_reminder_enabled``,
|
||||
``end_of_day_report_enabled``, ``celebration_enabled`` — real
|
||||
booleans.
|
||||
booleans,
|
||||
- ``timezone`` — ``""`` (the API host's local time) or an IANA time
|
||||
zone name such as ``America/New_York``. A document stored before
|
||||
this field existed simply lacks it and resolves to ``""``.
|
||||
|
||||
Only values whose core validators ACCEPTED are ever written, so a
|
||||
stored document always round-trips through the core's option builders.
|
||||
@@ -172,7 +175,7 @@ async def update_settings(
|
||||
update can never leave a half-applied document behind.
|
||||
|
||||
The validated changes are merged onto the current effective
|
||||
settings and the merged (complete, ten-field) document is persisted
|
||||
settings and the merged (complete, eleven-field) document is persisted
|
||||
in one atomic upsert; the updated settings are returned. The whole
|
||||
read → merge → write span runs inside the per-database settings
|
||||
lock, so concurrent updates queue instead of interleaving.
|
||||
|
||||
@@ -42,6 +42,7 @@ from .dao_instances import CompletionEventsDao, QuestInstancesDao
|
||||
from .dao_presence import PresenceOverridesDao, PresencePatternsDao
|
||||
from .dao_rules import QuestDefinitionsDao
|
||||
from .db import NestQuestDatabase
|
||||
from .icons import normalize_icon_for_read
|
||||
from .presence import (
|
||||
MAX_PREVIEW_SCAN_DAYS,
|
||||
PresenceEngine,
|
||||
@@ -262,7 +263,11 @@ async def build_snapshot(
|
||||
definition_id=instance.definition_id,
|
||||
child_id=instance.child_id,
|
||||
title=definition.title if definition else "Quest",
|
||||
icon=definition.icon if definition else None,
|
||||
icon=(
|
||||
normalize_icon_for_read(definition.icon)
|
||||
if definition
|
||||
else None
|
||||
),
|
||||
window=instance.window,
|
||||
due_date=instance.due_date,
|
||||
due_time=instance.due_time,
|
||||
|
||||
@@ -40,8 +40,8 @@ announces nothing.
|
||||
|
||||
The caller supplies ``today`` as a plain :class:`datetime.date`: the
|
||||
household-local calendar date, read from ``hass.config.time_zone`` by
|
||||
the integration or from the API host's local clock by the API. This
|
||||
module never reads a timezone database or config of its own.
|
||||
the integration or from the configured household timezone by the API.
|
||||
This module never reads a timezone database or config of its own.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -98,7 +98,8 @@ async def run_missed_sweep(
|
||||
|
||||
``today`` is the household-local calendar date the sweep runs for
|
||||
(the caller owns the clock: the integration reads it from
|
||||
``hass.config.time_zone``, the API from its host's local time).
|
||||
``hass.config.time_zone``, the API from the configured household
|
||||
timezone, falling back to its host's local time when unset).
|
||||
Returns the ``(event_type, payload)`` tuples to announce, EMPTY
|
||||
when the watermark already covers ``today`` (a same-night rerun) —
|
||||
the caller decides how to publish them and announces nothing on
|
||||
|
||||
@@ -15,5 +15,5 @@
|
||||
"iot_class": "local_polling",
|
||||
"issue_tracker": "https://github.com/Maniacs-Mansion/NestQuest/issues",
|
||||
"requirements": [],
|
||||
"version": "0.7.1"
|
||||
"version": "0.9.0"
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+45
-3
@@ -64,7 +64,8 @@ Header `Tasks` / `7 definitions · 3 children` + gradient `New` button. Filter c
|
||||
(All / one per child): active `#18181D` fill white text, inactive white with border.
|
||||
Rows: glyph 17px · title 13.5px/700 · meta 11px/600 `<assignees> · <recurrence> · <windows>`
|
||||
· `chevron-right`. An inactive definition renders the whole row at
|
||||
`--nq-a-ink-tertiary` with `· inactive` in the meta — never hard-deleted (glossary).
|
||||
`--nq-a-ink-tertiary` with `· inactive` in the meta. A definition with completion
|
||||
history is never hard-deleted (glossary, D-017): Delete retires it to this inactive state.
|
||||
The row being edited takes `--nq-a-selected` with brand-blue glyph, `Editing` meta and
|
||||
`chevron-down`.
|
||||
|
||||
@@ -83,9 +84,50 @@ Bottom sheet, `--nq-a-radius-sheet`, `--nq-a-sheet-shadow`, 38×4px grabber, pad
|
||||
Footer: `Cancel` (flex 1, bordered) + `Save changes` (flex 2, gradient), both 13px vertical
|
||||
padding. Sheet enters over the dimmed list in `--nq-dur-modal`.
|
||||
|
||||
Delete (editing an existing definition only, never on `New`): a full-width bordered
|
||||
`Delete task` button below the footer, danger-ink text. Tapping it swaps the footer for a
|
||||
danger-tinted confirm — "Delete this task? If it has no completion history it is deleted;
|
||||
otherwise it is retired (deactivated) and its history is kept." — with `Go back` and a
|
||||
danger-filled `Delete task`. Confirming calls `DELETE /api/v1/admin/quest-definitions/{id}`
|
||||
(admin plane only; the kids' panel has no equivalent control). Hybrid outcome (D-017): no
|
||||
completion event on any instance → the definition, its instances, assignees, windows and
|
||||
unreferenced rule are hard-deleted and the row leaves the list; otherwise the definition
|
||||
is retired (deactivated) and the row stays, shown inactive. Retirement preserves the
|
||||
definition row, schedule rule, assignees, windows and all durable completion history. Like
|
||||
any deactivation it regenerates, so future uncompleted instances are cleared (they are
|
||||
rolling, regenerable rows) and none are recreated while the definition is inactive — the
|
||||
retired task stops generating and no longer shows open work. Durable instance history lives
|
||||
only in the append-only `completion_events`. An error keeps the sheet open with the API's
|
||||
detail.
|
||||
|
||||
### 3.3 Icon picker
|
||||
Each definition carries a Lucide glyph, shown on both surfaces. **The allowed subset is not
|
||||
yet defined** — pick 24–40 household-relevant glyphs and ship them as a grid picker.
|
||||
Each definition carries one optional icon, shown on both surfaces. The picker offers three
|
||||
sources:
|
||||
|
||||
- **Lucide** — a grid of the curated Lucide glyphs, drawn stroked.
|
||||
- **Font Awesome** — a grid of a curated subset of the Font Awesome Free *solid* set,
|
||||
drawn filled.
|
||||
- **Emoji** — a text input; the typed emoji is stored as entered (not trimmed) and must be
|
||||
1–8 code points with no whitespace, control characters, `<`, `>` or `&`.
|
||||
|
||||
Both curated lists come from `tools/icons/curated-icons.json`; their glyph path data is
|
||||
generated into the admin and panel bundles by `tools/icons/generate.mjs` (no CDN, no
|
||||
runtime fetch). See `THIRD-PARTY-NOTICES.md` for licences.
|
||||
|
||||
The stored value is a **namespaced key**:
|
||||
|
||||
| Source | Stored key | Example |
|
||||
|---|---|---|
|
||||
| Lucide | `lucide:<name>` | `lucide:dog` |
|
||||
| Font Awesome | `fa:<name>` | `fa:paw` |
|
||||
| Emoji | `emoji:<grapheme>` | `emoji:🐶` |
|
||||
|
||||
`<name>` is a lowercase kebab name (`[a-z0-9-]`, no leading or trailing `-`). A **legacy
|
||||
bare name** written before namespacing (`dog`) reads as `lucide:<name>` — the API returns it
|
||||
namespaced, and any write of a bare name is stored as `lucide:<name>`; no data migration. An
|
||||
empty value clears the icon. An empty, unknown, or unresolvable key renders the **fallback
|
||||
glyph** — in the admin, the generic task glyph (clipboard with a check); on the panel, the
|
||||
star (`PANEL-SPEC.md` §3.2).
|
||||
|
||||
## 4. Schedule (1f)
|
||||
|
||||
|
||||
@@ -78,5 +78,6 @@ The panel speaks tabletop; the admin speaks plainly. Both sit on the same `quest
|
||||
decide before shipping the card.
|
||||
- No gamification is in scope. XP, levels, streaks and rarity were explicitly deferred,
|
||||
but the append-only event log already supports computing them later.
|
||||
- Icon per quest definition is chosen by the parent from a Lucide subset; the subset is
|
||||
not yet defined (`ADMIN-SPEC.md` §3.3).
|
||||
- Icon per quest definition is chosen by the parent from curated Lucide and Font Awesome
|
||||
Free sets or as an emoji, stored as a namespaced key (`lucide:`/`fa:`/`emoji:`) —
|
||||
resolved 2026-09-26, see `ADMIN-SPEC.md` §3.3.
|
||||
|
||||
@@ -35,7 +35,7 @@ implementer's call), shaped:
|
||||
{
|
||||
"instances": [
|
||||
{ "id": 4821, "definition_id": 12, "child_id": 3, "title": "Fill bird feeder",
|
||||
"icon": "bird", "window": "afternoon", "due_time": "17:00",
|
||||
"icon": "lucide:bird", "window": "afternoon", "due_time": "17:00",
|
||||
"state": "open", "overdue": true, "completed_at": null, "on_time": null }
|
||||
]
|
||||
}
|
||||
|
||||
+19
-6
@@ -22,10 +22,14 @@ Screens `1a`, `1b`, `1j`, `1c` of the mockups. Two cards:
|
||||
|
||||
Default view on the wall. Layout top to bottom:
|
||||
|
||||
1. **Wordmark row** at y=64. Rule · d20 hexagon · `NestQuest` (66px/900 display, brand
|
||||
gradient via `background-clip: text`) · d20 · rule. d20 marks are 34px hexagons
|
||||
(`clip-path: polygon(50% 0, 93% 25%, 93% 75%, 50% 100%, 7% 75%, 7% 25%)`) filled with
|
||||
the brand gradient, numeral 15px/700 Cinzel.
|
||||
1. **Wordmark row** at y=64. Rule · monogram · `NestQuest` (66px/900 Cinzel Decorative
|
||||
display, brand gradient via `background-clip: text`) · rule — the horizontal lockup of
|
||||
`design/logos/NestQuest_Logo.png`. The monogram is an 80px inline SVG (no raster, no
|
||||
remote asset): a compass rose — four long cardinal points, four short diagonal points,
|
||||
a ring broken by the points — around a d20 hexagon with facet lines and a knocked-out
|
||||
Cinzel Decorative "N", filled with the brand gradient (`--nq-brand-blue` →
|
||||
`--nq-brand-purple`, 135°). Gaps are SVG masks, so the mark stays transparent over the
|
||||
parchment.
|
||||
2. **Kicker** `The Party · <weekday>, <Month D>` — 21px/600 Cinzel, tracking .30em, uppercase.
|
||||
3. **Adventurer plates**, 3-up grid, 56px gap, page inset 110px, top y=262. One plate per
|
||||
child returned by the party sensor, in configured order.
|
||||
@@ -91,7 +95,14 @@ collapse the column, the three-column rhythm is the layout.
|
||||
`--nq-p-quest-min-height` 116px, radius 12px, `--nq-p-card-open`, 1px
|
||||
`--nq-p-card-border`, `--nq-p-card-shadow`, padding 22px, 22px gap, row layout:
|
||||
|
||||
1. **Icon tile** 64×64, radius 10px, `--nq-p-icon-tile`, Lucide glyph 34px white.
|
||||
1. **Icon tile** 64×64, radius 10px, `--nq-p-icon-tile`, glyph 34px white — the
|
||||
definition's icon, resolved from its namespaced key (`ADMIN-SPEC.md` §3.3):
|
||||
`lucide:<name>` draws the curated Lucide glyph **stroked** (fill none, stroke-width 2,
|
||||
round caps and joins); `fa:<name>` draws the curated Font Awesome glyph **filled**;
|
||||
`emoji:<grapheme>` renders the emoji **as text**. A legacy bare name resolves as
|
||||
`lucide:<name>`. No icon, or any key that does not resolve (unknown namespace or name,
|
||||
malformed emoji), falls back to the **star** glyph. Glyph data is bundled from the
|
||||
shared registry — nothing is fetched at runtime.
|
||||
2. **Text** title 30px/700 Cinzel `--nq-p-ink`; meta 22px/600 Nunito
|
||||
`--nq-p-ink-secondary` reading `Due by <h:mm A>`. If past due:
|
||||
`Overdue · due <h:mm A>` in 22px/700 Cinzel uppercase, tracking .10em,
|
||||
@@ -106,7 +117,9 @@ Both the card body and the button open the confirm dialog (§4). Press feedback:
|
||||
### 3.3 Quest card — sealed
|
||||
|
||||
`--nq-p-card-done`, `opacity: .82`, no shadow, **not tappable**. Icon tile
|
||||
`--nq-p-icon-tile-done` with the glyph in `--nq-p-ink-secondary`. Title 30px/700 Cinzel
|
||||
`--nq-p-icon-tile-done` with the glyph in `--nq-p-ink-secondary`. The sealed tile keeps
|
||||
the static star glyph — it does **not** render the definition icon — alongside the wax
|
||||
seal below. Title 30px/700 Cinzel
|
||||
`--nq-p-ink-muted` with `text-decoration: line-through`. Meta reads
|
||||
`Claimed <h:mm A>` 22px/600 Nunito `--nq-p-ink-secondary`.
|
||||
|
||||
|
||||
@@ -231,8 +231,76 @@ function conditionPhrase(condition: string, label: string): string {
|
||||
}
|
||||
|
||||
const SHIELD_CLIP = "polygon(0 0, 100% 0, 100% 62%, 50% 100%, 0 62%)";
|
||||
const HEXAGON_CLIP =
|
||||
"polygon(50% 0, 93% 25%, 93% 75%, 50% 100%, 7% 75%, 7% 25%)";
|
||||
// The brand monogram (design/logos/NestQuest_Logo.png): a compass rose —
|
||||
// four long cardinal points, four short diagonal points, a ring broken by
|
||||
// the points — around a d20 hexagon carrying a knocked-out "N". Drawn on
|
||||
// a 100-unit grid and filled with the brand gradient; the masks cut the
|
||||
// parchment gaps so the mark stays transparent on any backdrop.
|
||||
const MONOGRAM_POINTS =
|
||||
"M50 3 44.5 24.1 50 26 55.5 24.1Z M100 50 75.9 44.5 74 50 75.9 55.5Z " +
|
||||
"M50 97 55.5 75.9 50 74 44.5 75.9Z M0 50 24.1 55.5 26 50 24.1 44.5Z " +
|
||||
"M29.1 29.1 29.7 36.3 36.3 29.7Z M70.9 29.1 63.7 29.7 70.3 36.3Z " +
|
||||
"M70.9 70.9 70.3 63.7 63.7 70.3Z M29.1 70.9 36.3 70.3 29.7 63.7Z";
|
||||
const MONOGRAM_HEX = "M50 26.5 70.4 38.2 70.4 61.8 50 73.5 29.6 61.8 29.6 38.2Z";
|
||||
const MONOGRAM_FACETS =
|
||||
"M29.6 38.2H70.4M29.6 61.8H70.4M50 26.5 36.5 38.2M50 26.5 63.5 38.2" +
|
||||
"M50 73.5 36.5 61.8M50 73.5 63.5 61.8M36.5 38.2V61.8M63.5 38.2V61.8" +
|
||||
"M29.6 38.2 36.5 61.8M36.5 38.2 29.6 61.8" +
|
||||
"M70.4 38.2 63.5 61.8M63.5 38.2 70.4 61.8";
|
||||
const MONOGRAM = html`<svg
|
||||
class="monogram"
|
||||
viewBox="0 0 100 100"
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
>
|
||||
<defs>
|
||||
<linearGradient
|
||||
id="nq-monogram-fill"
|
||||
gradientUnits="userSpaceOnUse"
|
||||
x1="0"
|
||||
y1="0"
|
||||
x2="100"
|
||||
y2="100"
|
||||
>
|
||||
<stop offset="0" style="stop-color: var(--nq-brand-blue)" />
|
||||
<stop offset="1" style="stop-color: var(--nq-brand-purple)" />
|
||||
</linearGradient>
|
||||
<mask id="nq-monogram-points-gap" maskUnits="userSpaceOnUse">
|
||||
<rect width="100" height="100" fill="#fff" />
|
||||
<path d=${MONOGRAM_POINTS} stroke="#000" stroke-width="3.5" />
|
||||
</mask>
|
||||
<mask id="nq-monogram-facets" maskUnits="userSpaceOnUse">
|
||||
<rect width="100" height="100" fill="#fff" />
|
||||
<path d=${MONOGRAM_FACETS} stroke="#000" stroke-width="1.6" />
|
||||
<text
|
||||
x="50"
|
||||
y="59.4"
|
||||
text-anchor="middle"
|
||||
font-family="'Cinzel Decorative', Cinzel, serif"
|
||||
font-weight="900"
|
||||
font-size="25"
|
||||
fill="#fff"
|
||||
stroke="#000"
|
||||
stroke-width="2"
|
||||
paint-order="stroke"
|
||||
>N</text>
|
||||
</mask>
|
||||
</defs>
|
||||
<g fill="url(#nq-monogram-fill)">
|
||||
<path d=${MONOGRAM_POINTS} />
|
||||
<g mask="url(#nq-monogram-points-gap)">
|
||||
<circle
|
||||
cx="50"
|
||||
cy="50"
|
||||
r="34.25"
|
||||
fill="none"
|
||||
stroke="url(#nq-monogram-fill)"
|
||||
stroke-width="6.5"
|
||||
/>
|
||||
<path mask="url(#nq-monogram-facets)" d=${MONOGRAM_HEX} />
|
||||
</g>
|
||||
</g>
|
||||
</svg>`;
|
||||
|
||||
const boardStyles = css`
|
||||
* {
|
||||
@@ -299,23 +367,11 @@ const boardStyles = css`
|
||||
background: rgba(92, 62, 26, 0.35);
|
||||
}
|
||||
|
||||
.d20 {
|
||||
.monogram {
|
||||
flex: none;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
clip-path: ${unsafeCSS(HEXAGON_CLIP)};
|
||||
background: var(--nq-brand-gradient);
|
||||
}
|
||||
|
||||
.d20-numeral {
|
||||
font-family: var(--nq-p-font-heading);
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
color: #ffffff;
|
||||
display: block;
|
||||
width: 80px;
|
||||
height: 80px;
|
||||
}
|
||||
|
||||
.wordmark {
|
||||
@@ -497,11 +553,12 @@ const boardStyles = css`
|
||||
|
||||
.hint {
|
||||
position: absolute;
|
||||
top: 930px;
|
||||
top: 896px;
|
||||
left: 0;
|
||||
right: 0;
|
||||
margin: 0;
|
||||
font-family: var(--nq-p-font-body);
|
||||
font-size: 24px;
|
||||
font-size: 27px;
|
||||
font-weight: 600;
|
||||
line-height: 1.4;
|
||||
text-align: center;
|
||||
@@ -861,13 +918,8 @@ export class NestQuestPartyBoardCard extends LitElement {
|
||||
<div class="frame frame-inner"></div>
|
||||
<div class="wordmark-row">
|
||||
<span class="rule"></span>
|
||||
<span class="d20" aria-hidden="true">
|
||||
<span class="d20-numeral">20</span>
|
||||
</span>
|
||||
${MONOGRAM}
|
||||
<span class="wordmark">NestQuest</span>
|
||||
<span class="d20" aria-hidden="true">
|
||||
<span class="d20-numeral">20</span>
|
||||
</span>
|
||||
<span class="rule"></span>
|
||||
</div>
|
||||
<p class="kicker">The Party · ${formatDay(this._now, this._timeZone())}</p>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { LitElement, css, html, nothing, unsafeCSS, type TemplateResult } from "
|
||||
import { repeat } from "lit/directives/repeat.js";
|
||||
import panelTokens from "../../../custom_components/nestquest/www/nestquest-panel-tokens.css?inline";
|
||||
|
||||
import { renderQuestIcon } from "../icons/render";
|
||||
import { registerCustomCard, type CardConfig, type HassLike } from "../types";
|
||||
|
||||
type QuestLogCardConfig = CardConfig & {
|
||||
@@ -378,7 +379,7 @@ const logStyles = css`
|
||||
flex: none;
|
||||
width: 96px;
|
||||
height: 110px;
|
||||
padding: 3px;
|
||||
padding: 4px;
|
||||
clip-path: ${unsafeCSS(SHIELD_CLIP)};
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
@@ -614,6 +615,11 @@ const logStyles = css`
|
||||
height: 34px;
|
||||
}
|
||||
|
||||
.tile .emoji {
|
||||
font-size: 30px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.sealed .tile {
|
||||
background: var(--nq-p-icon-tile-done);
|
||||
color: var(--nq-p-ink-secondary);
|
||||
@@ -1938,7 +1944,7 @@ export class NestQuestQuestLogCard extends LitElement {
|
||||
const initial = (name?.charAt(0) || "?").toUpperCase();
|
||||
return html`
|
||||
<header class="header">
|
||||
<span class="crest${away ? " away" : nothing}" aria-hidden="true">
|
||||
<span class="crest${away ? " away" : ""}" aria-hidden="true">
|
||||
<span class="crest-face">
|
||||
<span class="initial">${initial}</span>
|
||||
</span>
|
||||
@@ -2093,10 +2099,10 @@ export class NestQuestQuestLogCard extends LitElement {
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span class="tile" aria-hidden="true">${ICON_STAR}</span>
|
||||
<span class="tile" aria-hidden="true">${renderQuestIcon(instance.icon, ICON_STAR)}</span>
|
||||
<div class="body">
|
||||
<span class="quest-title">${instance.title}</span>
|
||||
<span class="meta ${meta.late ? "late" : nothing}">${meta.text}</span>
|
||||
<span class="${meta.late ? "meta late" : "meta"}">${meta.text}</span>
|
||||
</div>
|
||||
<button
|
||||
class="complete"
|
||||
|
||||
@@ -0,0 +1,765 @@
|
||||
// GENERATED by tools/icons/generate.mjs from tools/icons/curated-icons.json — do not edit.
|
||||
// Regenerate with `node tools/icons/generate.mjs` (the drift tests fail if this
|
||||
// file differs from a fresh generation).
|
||||
//
|
||||
// Glyph path data is embedded at generation time; nothing is fetched at runtime.
|
||||
// Lucide glyphs: lucide-react 1.47.0 (ISC licence).
|
||||
// Font Awesome glyphs: @fortawesome/free-solid-svg-icons 7.3.1
|
||||
// (Font Awesome Free, icons under CC BY 4.0).
|
||||
|
||||
/** A vector glyph: draw each path in `paths` inside an <svg viewBox>. Lucide
|
||||
* glyphs are stroked (fill none, stroke-width 2, round caps and joins);
|
||||
* Font Awesome glyphs are filled. */
|
||||
export interface GlyphIcon {
|
||||
kind: "lucide" | "fa";
|
||||
key: string;
|
||||
name: string;
|
||||
label: string;
|
||||
viewBox: string;
|
||||
paths: readonly string[];
|
||||
}
|
||||
|
||||
/** An emoji icon; render `text` as text. */
|
||||
export interface EmojiIcon {
|
||||
kind: "emoji";
|
||||
key: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** No usable icon: the caller draws its own default glyph. */
|
||||
export interface FallbackIcon {
|
||||
kind: "fallback";
|
||||
key: null;
|
||||
}
|
||||
|
||||
export type ResolvedIcon = GlyphIcon | EmojiIcon | FallbackIcon;
|
||||
|
||||
export const LUCIDE_ICONS: readonly GlyphIcon[] = [
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:bed",
|
||||
"name": "bed",
|
||||
"label": "Bed",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M2 4v16",
|
||||
"M2 8h18a2 2 0 0 1 2 2v10",
|
||||
"M2 17h20",
|
||||
"M6 8v9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:bath",
|
||||
"name": "bath",
|
||||
"label": "Bath",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M10 4 8 6",
|
||||
"M17 19v2",
|
||||
"M2 12h20",
|
||||
"M7 19v2",
|
||||
"M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:shower-head",
|
||||
"name": "shower-head",
|
||||
"label": "Shower",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"m4 4 2.5 2.5",
|
||||
"M13.5 6.5a4.95 4.95 0 0 0-7 7",
|
||||
"M15 5 5 15",
|
||||
"M14 17v.01",
|
||||
"M10 16v.01",
|
||||
"M13 13v.01",
|
||||
"M16 10v.01",
|
||||
"M11 20v.01",
|
||||
"M17 14v.01",
|
||||
"M20 11v.01"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:toilet",
|
||||
"name": "toilet",
|
||||
"label": "Toilet",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M7 12h13a1 1 0 0 1 1 1 5 5 0 0 1-5 5h-.598a.5.5 0 0 0-.424.765l1.544 2.47a.5.5 0 0 1-.424.765H5.402a.5.5 0 0 1-.424-.765L7 18",
|
||||
"M8 18a5 5 0 0 1-5-5V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:brush",
|
||||
"name": "brush",
|
||||
"label": "Brush",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"m11 10 3 3",
|
||||
"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",
|
||||
"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:smile",
|
||||
"name": "smile",
|
||||
"label": "Smile",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M15 10V9",
|
||||
"M16.472 15a6 6 0 01-8.943 0",
|
||||
"M9 10V9",
|
||||
"M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:shirt",
|
||||
"name": "shirt",
|
||||
"label": "Clothes",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 2 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 2 0 0 0-1.34-2.23z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:washing-machine",
|
||||
"name": "washing-machine",
|
||||
"label": "Laundry",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M3 6h3",
|
||||
"M17 6h.01",
|
||||
"M5 2h14a2 2 0 0 1 2 2v16a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-16a2 2 0 0 1 2 -2z",
|
||||
"M7 13a5 5 0 1 0 10 0a5 5 0 1 0 -10 0",
|
||||
"M12 18a2.5 2.5 0 0 0 0-5 2.5 2.5 0 0 1 0-5"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:utensils",
|
||||
"name": "utensils",
|
||||
"label": "Meal",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2",
|
||||
"M7 2v20",
|
||||
"M21 15V2a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:cooking-pot",
|
||||
"name": "cooking-pot",
|
||||
"label": "Cooking",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M2 12h20",
|
||||
"M20 12v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8",
|
||||
"m4 8 16-4",
|
||||
"m8.86 6.78-.45-1.81a2 2 0 0 1 1.45-2.43l1.94-.48a2 2 0 0 1 2.43 1.46l.45 1.8"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:apple",
|
||||
"name": "apple",
|
||||
"label": "Snack",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M12 6.528V3a1 1 0 0 1 1-1h0",
|
||||
"M18.237 21A15 15 0 0 0 22 11a6 6 0 0 0-10-4.472A6 6 0 0 0 2 11a15.1 15.1 0 0 0 3.763 10 3 3 0 0 0 3.648.648 5.5 5.5 0 0 1 5.178 0A3 3 0 0 0 18.237 21"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:brush-cleaning",
|
||||
"name": "brush-cleaning",
|
||||
"label": "Sweep",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"m16 22-1-4",
|
||||
"M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1",
|
||||
"M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z",
|
||||
"m8 22 1-4"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:spray-can",
|
||||
"name": "spray-can",
|
||||
"label": "Clean",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M3 3h.01",
|
||||
"M7 5h.01",
|
||||
"M11 7h.01",
|
||||
"M3 7h.01",
|
||||
"M7 9h.01",
|
||||
"M3 11h.01",
|
||||
"M15 5h4v4h-4z",
|
||||
"m19 9 2 2v10c0 .6-.4 1-1 1h-6c-.6 0-1-.4-1-1V11l2-2",
|
||||
"m13 14 8-2",
|
||||
"m13 19 8-2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:trash-2",
|
||||
"name": "trash-2",
|
||||
"label": "Bins",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M10 11v6",
|
||||
"M14 11v6",
|
||||
"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",
|
||||
"M3 6h18",
|
||||
"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:recycle",
|
||||
"name": "recycle",
|
||||
"label": "Recycling",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M7 19H4.815a1.83 1.83 0 0 1-1.57-.881 1.785 1.785 0 0 1-.004-1.784L7.196 9.5",
|
||||
"M11 19h8.203a1.83 1.83 0 0 0 1.556-.89 1.784 1.784 0 0 0 0-1.775l-1.226-2.12",
|
||||
"m14 16-3 3 3 3",
|
||||
"M8.293 13.596 7.196 9.5 3.1 10.598",
|
||||
"m9.344 5.811 1.093-1.892A1.83 1.83 0 0 1 11.985 3a1.784 1.784 0 0 1 1.546.888l3.943 6.843",
|
||||
"m13.378 9.633 4.096 1.098 1.097-4.096"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:sofa",
|
||||
"name": "sofa",
|
||||
"label": "Tidy",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M20 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v3",
|
||||
"M2 16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",
|
||||
"M4 18v2",
|
||||
"M20 18v2",
|
||||
"M12 4v9"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:house",
|
||||
"name": "house",
|
||||
"label": "Home",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",
|
||||
"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:backpack",
|
||||
"name": "backpack",
|
||||
"label": "School bag",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M4 10a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z",
|
||||
"M8 10h8",
|
||||
"M8 18h8",
|
||||
"M8 22v-6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v6",
|
||||
"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:book-open",
|
||||
"name": "book-open",
|
||||
"label": "Reading",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M12 5v16",
|
||||
"M20.001 19A2 2 0 0022 17V5a2 2 0 00-1.999-2L16 3.002A5 5 0 0012 5a5 5 0 00-4-2H4a2 2 0 00-2 2v12a2 2 0 001.999 2H8a5 5 0 014 2 5 5 0 014-2z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:pencil",
|
||||
"name": "pencil",
|
||||
"label": "Homework",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",
|
||||
"m15 5 4 4"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:music",
|
||||
"name": "music",
|
||||
"label": "Music",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M9 18V5l12-2v13",
|
||||
"M3 18a3 3 0 1 0 6 0a3 3 0 1 0 -6 0",
|
||||
"M15 16a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:dog",
|
||||
"name": "dog",
|
||||
"label": "Dog",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M11.25 16.25h1.5L12 17z",
|
||||
"M16 14v.5",
|
||||
"M4.42 11.247A13.152 13.152 0 0 0 4 14.556C4 18.728 7.582 21 12 21s8-2.272 8-6.444a11.702 11.702 0 0 0-.493-3.309",
|
||||
"M8 14v.5",
|
||||
"M8.5 8.5c-.384 1.05-1.083 2.028-2.344 2.5-1.931.722-3.576-.297-3.656-1-.113-.994 1.177-6.53 4-7 1.923-.321 3.651.845 3.651 2.235A7.497 7.497 0 0 1 14 5.277c0-1.39 1.844-2.598 3.767-2.277 2.823.47 4.113 6.006 4 7-.08.703-1.725 1.722-3.656 1-1.261-.472-1.855-1.45-2.239-2.5"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:cat",
|
||||
"name": "cat",
|
||||
"label": "Cat",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M12 5c.67 0 1.35.09 2 .26 1.78-2 5.03-2.84 6.42-2.26 1.4.58-.42 7-.42 7 .57 1.07 1 2.24 1 3.44C21 17.9 16.97 21 12 21s-9-3-9-7.56c0-1.25.5-2.4 1-3.44 0 0-1.89-6.42-.5-7 1.39-.58 4.72.23 6.5 2.23A9.04 9.04 0 0 1 12 5Z",
|
||||
"M8 14v.5",
|
||||
"M16 14v.5",
|
||||
"M11.25 16.25h1.5L12 17l-.75-.75Z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:fish",
|
||||
"name": "fish",
|
||||
"label": "Fish",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M6.5 12c.94-3.46 4.94-6 8.5-6 3.56 0 6.06 2.54 7 6-.94 3.47-3.44 6-7 6s-7.56-2.53-8.5-6Z",
|
||||
"M18 12v.5",
|
||||
"M16 17.93a9.77 9.77 0 0 1 0-11.86",
|
||||
"M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33",
|
||||
"M10.46 7.26C10.2 5.88 9.17 4.24 8 3h5.8a2 2 0 0 1 1.98 1.67l.23 1.4",
|
||||
"m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:sprout",
|
||||
"name": "sprout",
|
||||
"label": "Plants",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M14 9.536V7a4 4 0 0 1 4-4h1.5a.5.5 0 0 1 .5.5V5a4 4 0 0 1-4 4 4 4 0 0 0-4 4c0 2 1 3 1 5a5 5 0 0 1-1 3",
|
||||
"M4 9a5 5 0 0 1 8 4 5 5 0 0 1-8-4",
|
||||
"M5 21h14"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:droplets",
|
||||
"name": "droplets",
|
||||
"label": "Water",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z",
|
||||
"M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:bike",
|
||||
"name": "bike",
|
||||
"label": "Bike",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M15 17.5a3.5 3.5 0 1 0 7 0a3.5 3.5 0 1 0 -7 0",
|
||||
"M2 17.5a3.5 3.5 0 1 0 7 0a3.5 3.5 0 1 0 -7 0",
|
||||
"M14 5a1 1 0 1 0 2 0a1 1 0 1 0 -2 0",
|
||||
"M12 17.5V14l-3-3 4-3 2 3h2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:volleyball",
|
||||
"name": "volleyball",
|
||||
"label": "Sport",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M11 7a16 16 20 0 1 10.98 4.362",
|
||||
"M12 12a13 13 0 0 1-8.66 5",
|
||||
"M16.83 13.634a16 16 0 0 1-9.267 7.328",
|
||||
"M20.66 17A13 13 0 0 0 12 12a13 13 0 0 1 0-10",
|
||||
"M8.17 15.366a16 16 0 0 1-1.713-11.69",
|
||||
"M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:gamepad-2",
|
||||
"name": "gamepad-2",
|
||||
"label": "Games",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M6 11L10 11",
|
||||
"M8 9L8 13",
|
||||
"M15 12L15.01 12",
|
||||
"M18 10L18.01 10",
|
||||
"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:star",
|
||||
"name": "star",
|
||||
"label": "Star",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:heart",
|
||||
"name": "heart",
|
||||
"label": "Heart",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:sun",
|
||||
"name": "sun",
|
||||
"label": "Morning",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M8 12a4 4 0 1 0 8 0a4 4 0 1 0 -8 0",
|
||||
"M12 2v2",
|
||||
"M12 20v2",
|
||||
"m4.93 4.93 1.41 1.41",
|
||||
"m17.66 17.66 1.41 1.41",
|
||||
"M2 12h2",
|
||||
"M20 12h2",
|
||||
"m6.34 17.66-1.41 1.41",
|
||||
"m19.07 4.93-1.41 1.41"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:moon",
|
||||
"name": "moon",
|
||||
"label": "Bedtime",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:clock",
|
||||
"name": "clock",
|
||||
"label": "Clock",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M2 12a10 10 0 1 0 20 0a10 10 0 1 0 -20 0",
|
||||
"M12 6v6l4 2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:calendar",
|
||||
"name": "calendar",
|
||||
"label": "Calendar",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M8 2v3",
|
||||
"M16 2v3",
|
||||
"M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2z",
|
||||
"M3 9h18"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "lucide",
|
||||
"key": "lucide:list-checks",
|
||||
"name": "list-checks",
|
||||
"label": "Checklist",
|
||||
"viewBox": "0 0 24 24",
|
||||
"paths": [
|
||||
"M13 5h8",
|
||||
"M13 12h8",
|
||||
"M13 19h8",
|
||||
"m3 17 2 2 4-4",
|
||||
"m3 7 2 2 4-4"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
export const FA_ICONS: readonly GlyphIcon[] = [
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:broom",
|
||||
"name": "broom",
|
||||
"label": "Sweep",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M566.6 54.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-192 192-34.7-34.7c-4.2-4.2-10-6.6-16-6.6-12.5 0-22.6 10.1-22.6 22.6l0 29.1 108.3 108.3 29.1 0c12.5 0 22.6-10.1 22.6-22.6 0-6-2.4-11.8-6.6-16l-34.7-34.7 192-192zM341.1 353.4L222.6 234.9c-42.7-3.7-85.2 11.7-115.8 42.3l-8 8c-22.3 22.3-34.8 52.5-34.8 84 0 6.8 7.1 11.2 13.2 8.2l51.1-25.5c5-2.5 9.5 4.1 5.4 7.9L7.3 473.4C2.7 477.6 0 483.6 0 489.9 0 502.1 9.9 512 22.1 512l173.3 0c38.8 0 75.9-15.4 103.4-42.8 30.6-30.6 45.9-73.1 42.3-115.8z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:spray-can-sparkles",
|
||||
"name": "spray-can-sparkles",
|
||||
"label": "Clean",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M160 32l0 80 128 0 0-80c0-17.7-14.3-32-32-32L192 0c-17.7 0-32 14.3-32 32zm0 128c-53 0-96 43-96 96l0 208c0 26.5 21.5 48 48 48l224 0c26.5 0 48-21.5 48-48l0-208c0-53-43-96-96-96l-128 0zm64 96a80 80 0 1 1 0 160 80 80 0 1 1 0-160zM448 48c0-1.4-1-3-2.2-3.6L416 32 403.6 2.2C403 1 401.4 0 400 0s-3 1-3.6 2.2L384 32 354.2 44.4c-1.2 .6-2.2 2.2-2.2 3.6 0 1.4 1 3 2.2 3.6L384 64 396.4 93.8C397 95 398.6 96 400 96s3-1 3.6-2.2L416 64 445.8 51.6C447 51 448 49.4 448 48zm76.4 45.8C525 95 526.6 96 528 96s3-1 3.6-2.2L544 64 573.8 51.6c1.2-.6 2.2-2.2 2.2-3.6 0-1.4-1-3-2.2-3.6L544 32 531.6 2.2C531 1 529.4 0 528 0s-3 1-3.6 2.2L512 32 482.2 44.4c-1.2 .6-2.2 2.2-2.2 3.6 0 1.4 1 3 2.2 3.6L512 64 524.4 93.8zm7.2 100.4c-.6-1.2-2.2-2.2-3.6-2.2s-3 1-3.6 2.2L512 224 482.2 236.4c-1.2 .6-2.2 2.2-2.2 3.6 0 1.4 1 3 2.2 3.6L512 256 524.4 285.8c.6 1.2 2.2 2.2 3.6 2.2s3-1 3.6-2.2L544 256 573.8 243.6c1.2-.6 2.2-2.2 2.2-3.6 0-1.4-1-3-2.2-3.6L544 224 531.6 194.2zM512 144c0-1.4-1-3-2.2-3.6L480 128 467.6 98.2C467 97 465.4 96 464 96s-3 1-3.6 2.2L448 128 418.2 140.4c-1.2 .6-2.2 2.2-2.2 3.6 0 1.4 1 3 2.2 3.6L448 160 460.4 189.8c.6 1.2 2.2 2.2 3.6 2.2s3-1 3.6-2.2L480 160 509.8 147.6c1.2-.6 2.2-2.2 2.2-3.6z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:bucket",
|
||||
"name": "bucket",
|
||||
"label": "Mop",
|
||||
"viewBox": "0 0 448 512",
|
||||
"paths": [
|
||||
"M443.7 208c2.7 4.7 4.3 10.2 4.3 16 0 17.7-14.3 32-32 32l-5.1 0-22.4 213c-2.6 24.4-23.2 43-47.8 43l-233.6 0c-24.6 0-45.2-18.5-47.8-43L37.1 256 32 256c-17.7 0-32-14.3-32-32 0-5.8 1.6-11.3 4.3-16l439.4 0zM224-16c79.5 0 144 64.5 144 144l0 32-48 0 0-32c0-53-43-96-96-96s-96 43-96 96l0 32-48 0 0-32C80 48.5 144.5-16 224-16z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:soap",
|
||||
"name": "soap",
|
||||
"label": "Wash hands",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M208-32a48 48 0 1 1 0 96 48 48 0 1 1 0-96zM320 96a64 64 0 1 1 0 128 64 64 0 1 1 0-128zM352 0a32 32 0 1 1 64 0 32 32 0 1 1 -64 0zM96 160l112 0c0 23.8 7.4 45.9 20.1 64L160 224c-53 0-96 43-96 96s43 96 96 96l192 0c53 0 96-43 96-96 0-35.1-18.9-65.9-47-82.6 19-19.8 30.7-46.6 31-76.1 45.4 7.6 80 47.1 80 94.7l0 128c0 53-43 96-96 96L96 480c-53 0-96-43-96-96L0 256c0-53 43-96 96-96zm64 112l192 0c26.5 0 48 21.5 48 48s-21.5 48-48 48l-192 0c-26.5 0-48-21.5-48-48s21.5-48 48-48z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:sink",
|
||||
"name": "sink",
|
||||
"label": "Dishes",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M288 96c0-17.7 14.3-32 32-32s32 14.3 32 32 14.3 32 32 32 32-14.3 32-32c0-53-43-96-96-96s-96 43-96 96l0 192-64 0 0-40c0-30.9-25.1-56-56-56l-48 0c-13.3 0-24 10.7-24 24s10.7 24 24 24l48 0c4.4 0 8 3.6 8 8l0 40-80 0c-17.7 0-32 14.3-32 32s14.3 32 32 32l0 64c0 53 43 96 96 96l256 0c53 0 96-43 96-96l0-64c17.7 0 32-14.3 32-32s-14.3-32-32-32l-80 0 0-40c0-4.4 3.6-8 8-8l56 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-56 0c-30.9 0-56 25.1-56 56l0 40-64 0 0-192z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:jug-detergent",
|
||||
"name": "jug-detergent",
|
||||
"label": "Laundry",
|
||||
"viewBox": "0 0 384 512",
|
||||
"paths": [
|
||||
"M96 24c0-13.3 10.7-24 24-24l80 0c13.3 0 24 10.7 24 24l0 24 8 0c13.3 0 24 10.7 24 24s-10.7 24-24 24L88 96C74.7 96 64 85.3 64 72S74.7 48 88 48l8 0 0-24zM0 256c0-70.7 57.3-128 128-128l128 0c70.7 0 128 57.3 128 128l0 192c0 35.3-28.7 64-64 64L64 512c-35.3 0-64-28.7-64-64L0 256zm256 0l0 96c0 17.7 14.3 32 32 32s32-14.3 32-32l0-96c0-17.7-14.3-32-32-32s-32 14.3-32 32z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:socks",
|
||||
"name": "socks",
|
||||
"label": "Socks",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M252.8 0L176 0c-26.5 0-48 21.5-48 48l0 16 112 0 0-16c0-17.5 4.7-33.9 12.8-48zM128 112l0 128c0 20.1-9.5 39.1-25.6 51.2l-64 48c-24.2 18.1-38.4 46.6-38.4 76.8 0 53 43 96 96 96 15.4 0 30.5-3.7 44-10.7-17.6-23.9-28-53.4-28-85.3 0-45.3 21.3-88 57.6-115.2l64-48c4-3 6.4-7.8 6.4-12.8l0-128-112 0zm160 0l0 128c0 20.1-9.5 39.1-25.6 51.2l-64 48c-24.2 18.1-38.4 46.6-38.4 76.8 0 53 43 96 96 96 20.8 0 41-6.7 57.6-19.2l115.2-86.4C461 382.2 480 344.3 480 304l0-192-192 0zM480 64l0-16c0-26.5-21.5-48-48-48L336 0c-26.5 0-48 21.5-48 48l0 16 192 0z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:shirt",
|
||||
"name": "shirt",
|
||||
"label": "Clothes",
|
||||
"viewBox": "0 0 640 512",
|
||||
"paths": [
|
||||
"M320.2 112c44.2 0 80-35.8 80-80l53.5 0c17 0 33.3 6.7 45.3 18.7L617.6 169.4c12.5 12.5 12.5 32.8 0 45.3l-50.7 50.7c-12.5 12.5-32.8 12.5-45.3 0l-41.4-41.4 0 224c0 35.3-28.7 64-64 64l-192 0c-35.3 0-64-28.7-64-64l0-224-41.4 41.4c-12.5 12.5-32.8 12.5-45.3 0L22.9 214.6c-12.5-12.5-12.5-32.8 0-45.3L141.5 50.7c12-12 28.3-18.7 45.3-18.7l53.5 0c0 44.2 35.8 80 80 80z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:bed",
|
||||
"name": "bed",
|
||||
"label": "Bed",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M32 32c17.7 0 32 14.3 32 32l0 224 224 0 0-128c0-17.7 14.3-32 32-32l160 0c53 0 96 43 96 96l0 224c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-64-448 0 0 64c0 17.7-14.3 32-32 32S0 465.7 0 448L0 64C0 46.3 14.3 32 32 32zm80 160a64 64 0 1 1 128 0 64 64 0 1 1 -128 0z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:couch",
|
||||
"name": "couch",
|
||||
"label": "Tidy",
|
||||
"viewBox": "0 0 640 512",
|
||||
"paths": [
|
||||
"M144 272C144 224.7 109.8 185.4 64.8 177.5 72 113.6 126.2 64 192 64l256 0c65.8 0 120 49.6 127.2 113.5-45 8-79.2 47.2-79.2 94.5l0 32-352 0 0-32zM0 384L0 272c0-26.5 21.5-48 48-48s48 21.5 48 48l0 80 448 0 0-80c0-26.5 21.5-48 48-48s48 21.5 48 48l0 112c0 35.3-28.7 64-64 64L64 448c-35.3 0-64-28.7-64-64z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:bath",
|
||||
"name": "bath",
|
||||
"label": "Bath",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M96 77.3c0-7.3 5.9-13.3 13.3-13.3 3.5 0 6.9 1.4 9.4 3.9l14.9 14.9c-3.6 9.1-5.5 18.9-5.5 29.2 0 19.9 7.2 38 19.2 52-5.3 9.2-4 21.1 3.8 29 9.4 9.4 24.6 9.4 33.9 0L289 89c9.4-9.4 9.4-24.6 0-33.9-7.8-7.9-19.8-9.1-29-3.8-14-12-32.1-19.2-52-19.2-10.3 0-20.2 2-29.2 5.5L163.9 22.6C149.4 8.1 129.7 0 109.3 0 66.6 0 32 34.6 32 77.3L32 256c-17.7 0-32 14.3-32 32s14.3 32 32 32l0 48c0 28.4 12.4 54 32 71.6L64 480c0 17.7 14.3 32 32 32s32-14.3 32-32l0-16 256 0 0 16c0 17.7 14.3 32 32 32s32-14.3 32-32l0-40.4c19.6-17.6 32-43.1 32-71.6l0-48c17.7 0 32-14.3 32-32s-14.3-32-32-32L96 256 96 77.3z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:tooth",
|
||||
"name": "tooth",
|
||||
"label": "Teeth",
|
||||
"viewBox": "0 0 448 512",
|
||||
"paths": [
|
||||
"M145 5.7L224 32 303 5.7C314.3 1.9 326 0 337.9 0 398.7 0 448 49.3 448 110.1l0 68.5c0 29.4-9.5 58.1-27.2 81.6l-1.1 1.5c-12.9 17.2-21.3 37.4-24.3 58.7L373.7 471.9c-3.3 23-23 40.1-46.2 40.1-22.8 0-42.3-16.5-46-39L261.3 351.6c-3-18.2-18.8-31.6-37.3-31.6s-34.2 13.4-37.3 31.6L166.5 473c-3.8 22.5-23.2 39-46 39-23.2 0-42.9-17.1-46.2-40.1L52.6 320.5c-3-21.3-11.4-41.5-24.3-58.7l-1.1-1.5C9.5 236.7 0 208.1 0 178.7l0-68.5C0 49.3 49.3 0 110.1 0 122 0 133.7 1.9 145 5.7z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:utensils",
|
||||
"name": "utensils",
|
||||
"label": "Meal",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M63.9 14.4C63.1 6.2 56.2 0 48 0s-15.1 6.2-16 14.3L17.9 149.7c-1.3 6-1.9 12.1-1.9 18.2 0 45.9 35.1 83.6 80 87.7L96 480c0 17.7 14.3 32 32 32s32-14.3 32-32l0-224.4c44.9-4.1 80-41.8 80-87.7 0-6.1-.6-12.2-1.9-18.2L223.9 14.3C223.1 6.2 216.2 0 208 0s-15.1 6.2-15.9 14.4L178.5 149.9c-.6 5.7-5.4 10.1-11.1 10.1-5.8 0-10.6-4.4-11.2-10.2L143.9 14.6C143.2 6.3 136.3 0 128 0s-15.2 6.3-15.9 14.6L99.8 149.8c-.5 5.8-5.4 10.2-11.2 10.2-5.8 0-10.6-4.4-11.1-10.1L63.9 14.4zM448 0C432 0 320 32 320 176l0 112c0 35.3 28.7 64 64 64l32 0 0 128c0 17.7 14.3 32 32 32s32-14.3 32-32l0-448c0-17.7-14.3-32-32-32z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:bowl-food",
|
||||
"name": "bowl-food",
|
||||
"label": "Set the table",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M0 176c0-35.3 28.7-64 64-64 .5 0 1.1 0 1.6 0 7.4-36.5 39.7-64 78.4-64 15 0 29 4.1 40.9 11.2 13.3-25.7 40.1-43.2 71.1-43.2s57.8 17.6 71.1 43.2c12-7.1 26-11.2 40.9-11.2 38.7 0 71 27.5 78.4 64 .5 0 1.1 0 1.6 0 35.3 0 64 28.7 64 64 0 11.7-3.1 22.6-8.6 32L8.6 208C3.1 198.6 0 187.7 0 176zM0 283.4C0 268.3 12.3 256 27.4 256l457.1 0c15.1 0 27.4 12.3 27.4 27.4 0 70.5-44.4 130.7-106.7 154.1L403.5 452c-2 16-15.6 28-31.8 28l-231.5 0c-16.1 0-29.8-12-31.8-28l-1.8-14.4C44.4 414.1 0 353.9 0 283.4z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:basket-shopping",
|
||||
"name": "basket-shopping",
|
||||
"label": "Groceries",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M288 0c6.6 0 12.9 2.7 17.4 7.5l144 152 .5 .5 78.1 0c17.7 0 32 14.3 32 32 0 14.5-9.6 26.7-22.8 30.7L491.1 429.9c-6.5 29.3-32.5 50.1-62.5 50.1l-281.3 0c-30 0-56-20.8-62.5-50.1l-46-207.2c-13.2-3.9-22.8-16.2-22.8-30.7 0-17.7 14.3-32 32-32l78.1 0 .5-.5 144-152C275.1 2.7 281.4 0 288 0zm0 58.9L192.2 160 383.8 160 288 58.9zM208 264c0-13.3-10.7-24-24-24s-24 10.7-24 24l0 112c0 13.3 10.7 24 24 24s24-10.7 24-24l0-112zm80-24c-13.3 0-24 10.7-24 24l0 112c0 13.3 10.7 24 24 24s24-10.7 24-24l0-112c0-13.3-10.7-24-24-24zm128 24c0-13.3-10.7-24-24-24s-24 10.7-24 24l0 112c0 13.3 10.7 24 24 24s24-10.7 24-24l0-112z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:trash-can",
|
||||
"name": "trash-can",
|
||||
"label": "Bins",
|
||||
"viewBox": "0 0 448 512",
|
||||
"paths": [
|
||||
"M136.7 5.9C141.1-7.2 153.3-16 167.1-16l113.9 0c13.8 0 26 8.8 30.4 21.9L320 32 416 32c17.7 0 32 14.3 32 32s-14.3 32-32 32L32 96C14.3 96 0 81.7 0 64S14.3 32 32 32l96 0 8.7-26.1zM32 144l384 0 0 304c0 35.3-28.7 64-64 64L96 512c-35.3 0-64-28.7-64-64l0-304zm88 64c-13.3 0-24 10.7-24 24l0 192c0 13.3 10.7 24 24 24s24-10.7 24-24l0-192c0-13.3-10.7-24-24-24zm104 0c-13.3 0-24 10.7-24 24l0 192c0 13.3 10.7 24 24 24s24-10.7 24-24l0-192c0-13.3-10.7-24-24-24zm104 0c-13.3 0-24 10.7-24 24l0 192c0 13.3 10.7 24 24 24s24-10.7 24-24l0-192c0-13.3-10.7-24-24-24z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:recycle",
|
||||
"name": "recycle",
|
||||
"label": "Recycling",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M152.3 60C198.5-20 314-20 360.2 60l37.3 64.6 27.7-16c8.4-4.9 18.9-4.2 26.6 1.7s11.1 15.9 8.6 25.3L436.9 223c-3.4 12.8-16.6 20.4-29.4 17l-87.4-23.4c-9.4-2.5-16.3-10.4-17.6-20s3.4-19.1 11.8-23.9l27.7-16-37.3-64.6c-21.6-37.3-75.4-37.3-97 0l-5.3 9.1c-8.8 15.3-28.4 20.5-43.7 11.7S138.2 84.5 147 69.1l5.3-9.1zM449.7 279.1c15.3-8.8 34.9-3.6 43.7 11.7l5.3 9.1c46.2 80-11.5 180-103.9 180l-74.6 0 0 32c0 9.7-5.8 18.5-14.8 22.2s-19.3 1.7-26.2-5.2l-64-64c-9.4-9.4-9.4-24.6 0-33.9l64-64c6.9-6.9 17.2-8.9 26.2-5.2s14.8 12.5 14.8 22.2l0 32 74.6 0c43.1 0 70.1-46.7 48.5-84l-5.3-9.1c-8.8-15.3-3.6-34.9 11.7-43.7zM51 235.4l-27.7-16c-8.4-4.9-13.1-14.3-11.8-23.9s8.2-17.5 17.6-20L116.5 152c12.8-3.4 26 4.2 29.4 17l23.4 87.4c2.5 9.4-.9 19.3-8.6 25.3s-18.2 6.6-26.6 1.7l-27.7-16-37.3 64.6c-21.6 37.3 5.4 84 48.5 84l10.6 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-10.6 0C25.3 480-32.4 380 13.8 300L51 235.4z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:dog",
|
||||
"name": "dog",
|
||||
"label": "Dog",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M32 112c16.6 0 30.2 12.6 31.8 28.7l.3 6.6C65.8 163.4 79.4 176 96 176l179.1 0 140.9 60.4 0 243.6c0 17.7-14.3 32-32 32l-32 0c-17.7 0-32-14.3-32-32l0-131.3C296 361 268.8 368 240 368s-56-7-80-19.3L160 480c0 17.7-14.3 32-32 32l-32 0c-17.7 0-32-14.3-32-32l0-245.6c-37.3-13.2-64-48.6-64-90.4 0-17.7 14.3-32 32-32zM355.8-32c7.7 0 14.9 3.6 19.6 9.8L392 0 444.1 0c12.7 0 24.9 5.1 33.9 14.1L496 32 552 32c13.3 0 24 10.7 24 24l0 24c0 44.2-35.8 80-80 80l-64 0-7 28-124.7-53.4 31.6-147.2C334.3-23.9 344.2-32 355.8-32zM448 44a20 20 0 1 0 0 40 20 20 0 1 0 0-40z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:cat",
|
||||
"name": "cat",
|
||||
"label": "Cat",
|
||||
"viewBox": "0 0 576 512",
|
||||
"paths": [
|
||||
"M64 96c53 0 96 43 96 96l0 85.8c29.7-44.7 77.8-76.2 133.4-84 25.6 60 85.2 102.1 154.6 102.1 10.9 0 21.6-1.1 32-3.1L480 480c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-140.8-136 108.8 56 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-144 0c-53 0-96-43-96-96l0-224c0-16.6-12.6-30.2-28.7-31.8l-6.6-.3C44.6 158.2 32 144.6 32 128 32 110.3 46.3 96 64 96zM533.8 3.2C544.2-5.5 560 1.9 560 15.5L560 128c0 61.9-50.1 112-112 112S336 189.9 336 128l0-112.5c0-13.6 15.8-21 26.2-12.3L416 48 480 48 533.8 3.2zM400 108a20 20 0 1 0 0 40 20 20 0 1 0 0-40zm96 0a20 20 0 1 0 0 40 20 20 0 1 0 0-40z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:paw",
|
||||
"name": "paw",
|
||||
"label": "Pets",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M234.5 92.9c14.3 42.9-.3 86.2-32.6 96.8s-70.1-15.6-84.4-58.5 .3-86.2 32.6-96.8 70.1 15.6 84.4 58.5zM100.4 198.6c18.9 32.4 14.3 70.1-10.2 84.1s-59.7-.9-78.5-33.3-14.3-70.1 10.2-84.1 59.7 .9 78.5 33.3zM69.2 401.2C121.6 259.9 214.7 224 256 224s134.4 35.9 186.8 177.2c3.6 9.7 5.2 20.1 5.2 30.5l0 1.6c0 25.8-20.9 46.7-46.7 46.7-11.5 0-22.9-1.4-34-4.2l-88-22c-15.3-3.8-31.3-3.8-46.6 0l-88 22c-11.1 2.8-22.5 4.2-34 4.2-25.8 0-46.7-20.9-46.7-46.7l0-1.6c0-10.4 1.6-20.8 5.2-30.5zM421.8 282.7c-24.5-14-29.1-51.7-10.2-84.1s54-47.3 78.5-33.3 29.1 51.7 10.2 84.1-54 47.3-78.5 33.3zM310.1 189.7c-32.3-10.6-46.9-53.9-32.6-96.8s52.1-69.1 84.4-58.5 46.9 53.9 32.6 96.8-52.1 69.1-84.4 58.5z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:seedling",
|
||||
"name": "seedling",
|
||||
"label": "Plants",
|
||||
"viewBox": "0 0 512 512",
|
||||
"paths": [
|
||||
"M512 32C512 140.1 435.4 230.3 333.6 251.4 325.7 193.3 299.6 141 261.1 100.5 301.2 40 369.9 0 448 0l32 0c17.7 0 32 14.3 32 32zM0 96C0 78.3 14.3 64 32 64l32 0c123.7 0 224 100.3 224 224l0 192c0 17.7-14.3 32-32 32s-32-14.3-32-32l0-160C100.3 320 0 219.7 0 96z"
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "fa",
|
||||
"key": "fa:book",
|
||||
"name": "book",
|
||||
"label": "Reading",
|
||||
"viewBox": "0 0 448 512",
|
||||
"paths": [
|
||||
"M384 512L96 512c-53 0-96-43-96-96L0 96C0 43 43 0 96 0L400 0c26.5 0 48 21.5 48 48l0 288c0 20.9-13.4 38.7-32 45.3l0 66.7c17.7 0 32 14.3 32 32s-14.3 32-32 32l-32 0zM96 384c-17.7 0-32 14.3-32 32s14.3 32 32 32l256 0 0-64-256 0zm32-232c0 13.3 10.7 24 24 24l176 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-176 0c-13.3 0-24 10.7-24 24zm24 72c-13.3 0-24 10.7-24 24s10.7 24 24 24l176 0c13.3 0 24-10.7 24-24s-10.7-24-24-24l-176 0z"
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
export const FALLBACK_ICON: FallbackIcon = { kind: "fallback", key: null };
|
||||
|
||||
/** Mirrors core/icons.py EMOJI_MAX_CODE_POINTS. */
|
||||
export const EMOJI_MAX_CODE_POINTS = 8;
|
||||
|
||||
const LUCIDE_BY_NAME: ReadonlyMap<string, GlyphIcon> = new Map(LUCIDE_ICONS.map((icon) => [icon.name, icon]));
|
||||
const FA_BY_NAME: ReadonlyMap<string, GlyphIcon> = new Map(FA_ICONS.map((icon) => [icon.name, icon]));
|
||||
|
||||
function isEmojiPayload(text: string): boolean {
|
||||
const codePoints = [...text];
|
||||
if (codePoints.length === 0 || codePoints.length > EMOJI_MAX_CODE_POINTS) return false;
|
||||
return !codePoints.some((char) => /[\s<>&]|\p{Cc}/u.test(char));
|
||||
}
|
||||
|
||||
/**
|
||||
* The renderable icon for a stored definition `icon` value.
|
||||
*
|
||||
* `lucide:<name>` and a legacy bare `<name>` resolve against the curated
|
||||
* Lucide set, `fa:<name>` against the curated Font Awesome set, and
|
||||
* `emoji:<grapheme>` to its text. Like the backend's
|
||||
* normalize_icon_for_read, nothing here throws: null, empty, an unknown
|
||||
* namespace or name, or a malformed emoji all resolve to FALLBACK_ICON.
|
||||
*/
|
||||
export function resolveIcon(value: string | null | undefined): ResolvedIcon {
|
||||
if (!value || !value.trim()) return FALLBACK_ICON;
|
||||
const colon = value.indexOf(":");
|
||||
if (colon === -1) return LUCIDE_BY_NAME.get(value) ?? FALLBACK_ICON;
|
||||
const namespace = value.slice(0, colon);
|
||||
const name = value.slice(colon + 1);
|
||||
if (namespace === "lucide") return LUCIDE_BY_NAME.get(name) ?? FALLBACK_ICON;
|
||||
if (namespace === "fa") return FA_BY_NAME.get(name) ?? FALLBACK_ICON;
|
||||
if (namespace === "emoji" && isEmojiPayload(name)) return { kind: "emoji", key: value, text: name };
|
||||
return FALLBACK_ICON;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Lit rendering for the shared icon registry (`registry.generated.ts`,
|
||||
* generated from tools/icons/curated-icons.json). The glyph path data is
|
||||
* bundled — no CDN and no runtime fetch.
|
||||
*/
|
||||
import { html, svg, type TemplateResult } from "lit";
|
||||
|
||||
import { resolveIcon } from "./registry.generated";
|
||||
|
||||
/**
|
||||
* A stored definition icon (`lucide:<name>`, `fa:<name>`, `emoji:<grapheme>`
|
||||
* or a legacy bare Lucide name) as a template; anything that resolves to the
|
||||
* registry fallback renders `fallback` instead.
|
||||
*/
|
||||
export function renderQuestIcon(
|
||||
value: string | null,
|
||||
fallback: TemplateResult
|
||||
): TemplateResult {
|
||||
const icon = resolveIcon(value);
|
||||
switch (icon.kind) {
|
||||
case "lucide":
|
||||
return html`<svg
|
||||
viewBox=${icon.viewBox}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
data-icon=${icon.key}
|
||||
>
|
||||
${icon.paths.map((d) => svg`<path d=${d}></path>`)}
|
||||
</svg>`;
|
||||
case "fa":
|
||||
return html`<svg
|
||||
viewBox=${icon.viewBox}
|
||||
fill="currentColor"
|
||||
aria-hidden="true"
|
||||
data-icon=${icon.key}
|
||||
>
|
||||
${icon.paths.map((d) => svg`<path d=${d}></path>`)}
|
||||
</svg>`;
|
||||
case "emoji":
|
||||
return html`<span class="emoji" data-icon=${icon.key}>${icon.text}</span>`;
|
||||
case "fallback":
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,14 @@
|
||||
* the card is mounted at the given URL (it resolves its child from the
|
||||
* pathname's last segment), after the optional probe wait one snapshot of
|
||||
* the render is taken mid-wait, then after the optional idle wait stdout
|
||||
* receives one JSON object {location, headline, countdown, html, probe} —
|
||||
* the final window pathname, the rendered title, the complete-screen
|
||||
* countdown text, the rendered shadow DOM, and the probe snapshot when
|
||||
* probe_ms was given. The Python panel tests drive this harness so the
|
||||
* receives one JSON object {location, headline, countdown, html, tiles,
|
||||
* probe, tap} — the final window pathname, the rendered title, the
|
||||
* complete-screen countdown text, the rendered shadow DOM, each quest
|
||||
* card's icon tile, and the probe snapshot when probe_ms was given. With
|
||||
* tap_complete: <instance id> the harness taps that card's Complete button,
|
||||
* records whether the confirm dialog opened, taps the dialog's Complete, and
|
||||
* reports every hass.callService call as tap: {dialog_opened, service_calls}.
|
||||
* The Python panel tests drive this harness so the
|
||||
* assertions run against the exact bundle HACS ships.
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
@@ -43,12 +47,34 @@ globalThis.Event = dom.window.Event;
|
||||
|
||||
await import(pathToFileURL(spec.bundle).href);
|
||||
|
||||
const serviceCalls = [];
|
||||
const hass = {
|
||||
...spec.hass,
|
||||
callService(domain, service, data) {
|
||||
serviceCalls.push({ domain, service, data });
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
|
||||
const element = document.createElement("nestquest-quest-log-card");
|
||||
element.setConfig(spec.config);
|
||||
element.hass = spec.hass;
|
||||
element.hass = hass;
|
||||
document.body.appendChild(element);
|
||||
await element.updateComplete;
|
||||
|
||||
let tap = null;
|
||||
if (spec.tap_complete !== undefined) {
|
||||
element.shadowRoot
|
||||
.querySelector(`.quest[data-instance-id="${spec.tap_complete}"] button.complete`)
|
||||
.click();
|
||||
await element.updateComplete;
|
||||
const confirm = element.shadowRoot.querySelector("button.do-complete");
|
||||
confirm?.click();
|
||||
await element.updateComplete;
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
tap = { dialog_opened: confirm !== null, service_calls: serviceCalls };
|
||||
}
|
||||
|
||||
const snapshot = () => ({
|
||||
location: window.location.pathname,
|
||||
headline: element.shadowRoot.querySelector(".title")?.textContent?.trim() ?? "",
|
||||
@@ -56,6 +82,22 @@ const snapshot = () => ({
|
||||
element.shadowRoot.querySelector(".complete-countdown")?.textContent?.trim() ??
|
||||
"",
|
||||
html: element.shadowRoot.innerHTML,
|
||||
// Each quest card's icon tile: the registry glyph it rendered (its
|
||||
// data-icon key and svg fill), its text (an emoji), and whether it shows
|
||||
// the static star (the star's polygon).
|
||||
tiles: [...element.shadowRoot.querySelectorAll(".quest")].map((quest) => {
|
||||
const tile = quest.querySelector(".tile");
|
||||
const glyph = tile?.querySelector("[data-icon]");
|
||||
return {
|
||||
id: Number(quest.dataset.instanceId),
|
||||
sealed: quest.classList.contains("sealed"),
|
||||
icon: glyph?.getAttribute("data-icon") ?? null,
|
||||
fill: glyph?.getAttribute("fill") ?? null,
|
||||
paths: tile?.querySelectorAll("path").length ?? 0,
|
||||
text: tile?.textContent?.trim() ?? "",
|
||||
star: Boolean(tile?.querySelector("polygon")),
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
let probe = null;
|
||||
@@ -68,6 +110,6 @@ if (spec.idle_ms !== undefined) {
|
||||
await new Promise((resolve) => setTimeout(resolve, spec.idle_ms));
|
||||
}
|
||||
|
||||
const payload = JSON.stringify({ ...snapshot(), probe });
|
||||
const payload = JSON.stringify({ ...snapshot(), probe, tap });
|
||||
await new Promise((resolve) => process.stdout.write(payload, () => resolve()));
|
||||
process.exit(0);
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": false,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022", "DOM"],
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "nestquest"
|
||||
version = "0.7.1"
|
||||
version = "0.9.0"
|
||||
description = "NestQuest Home Assistant Integration"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.11"
|
||||
|
||||
@@ -35,6 +35,7 @@ for malformed bodies.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime
|
||||
import importlib
|
||||
from types import SimpleNamespace
|
||||
|
||||
@@ -223,7 +224,7 @@ async def test_create_persists_definition_with_assignees_and_windows(
|
||||
}
|
||||
assert payload["title"] == "Tidy the den"
|
||||
assert payload["description"] == "Put everything back where it belongs."
|
||||
assert payload["icon"] == "toy-box"
|
||||
assert payload["icon"] == "lucide:toy-box"
|
||||
assert payload["is_active"] is True
|
||||
assert payload["skip_on_away"] is True
|
||||
assert payload["rule"] == _weekly_rule_dict()
|
||||
@@ -245,7 +246,7 @@ async def test_create_persists_definition_with_assignees_and_windows(
|
||||
assert stored.definition.description == (
|
||||
"Put everything back where it belongs."
|
||||
)
|
||||
assert stored.definition.icon == "toy-box"
|
||||
assert stored.definition.icon == "lucide:toy-box"
|
||||
assert stored.definition.is_active is True
|
||||
assert stored.rule.to_dict() == _weekly_rule_dict()
|
||||
assert sorted(child.id for child in stored.assignees) == [ada, bo]
|
||||
@@ -396,7 +397,7 @@ async def test_edit_persists_supplied_fields_and_leaves_omitted_untouched(
|
||||
assert stored.definition.description == (
|
||||
"Put everything back where it belongs."
|
||||
)
|
||||
assert stored.definition.icon == "toy-box"
|
||||
assert stored.definition.icon == "lucide:toy-box"
|
||||
assert stored.rule.to_dict() == _weekly_rule_dict()
|
||||
# assignee_child_ids was omitted: the assignees are untouched.
|
||||
assert sorted(child.id for child in stored.assignees) == [ada, bo]
|
||||
@@ -468,6 +469,89 @@ async def test_edit_can_clear_description_and_icon_explicitly(
|
||||
assert stored.rule.to_dict() == _weekly_rule_dict()
|
||||
|
||||
|
||||
async def test_legacy_bare_icon_reads_back_namespaced(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
"""A row stored with a pre-namespacing bare icon reads as ``lucide:``.
|
||||
|
||||
The row is rewritten through the DAO (bypassing the write-side
|
||||
validation, as a row from before namespacing would be) and then read
|
||||
back through BOTH consumers: the admin definition response and the
|
||||
kids' panel snapshot's per-instance ``icon``.
|
||||
"""
|
||||
client = admin_questdefs.client
|
||||
ada = (await _create_children(client, ("Ada",)))[0]
|
||||
today = datetime.date.today().isoformat()
|
||||
created = await client.post(
|
||||
"/api/v1/admin/quest-definitions",
|
||||
json={
|
||||
"title": "Walk the dog",
|
||||
"rule": {"rule_type": "daily", "start_date": today},
|
||||
"assignee_child_ids": [ada],
|
||||
"windows": ["evening"],
|
||||
"icon": "fa:dog",
|
||||
},
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert created.status_code == 201
|
||||
definition_id = created.json()["id"]
|
||||
|
||||
await _dao_rules.QuestDefinitionsDao(
|
||||
admin_questdefs.database
|
||||
).edit_definition(definition_id, icon="dog")
|
||||
stored = (await _definitions_by_id(admin_questdefs.database))[
|
||||
definition_id
|
||||
]
|
||||
assert stored.definition.icon == "dog"
|
||||
|
||||
listed = await client.get(
|
||||
"/api/v1/admin/quest-definitions", headers=_admin_headers()
|
||||
)
|
||||
assert listed.status_code == 200
|
||||
[definition] = [
|
||||
d for d in listed.json()["definitions"] if d["id"] == definition_id
|
||||
]
|
||||
assert definition["icon"] == "lucide:dog"
|
||||
|
||||
panel = await client.get(
|
||||
"/api/v1/panel/snapshot",
|
||||
headers={"Authorization": "Bearer admin-test-panel-token"},
|
||||
)
|
||||
assert panel.status_code == 200
|
||||
[child] = panel.json()["children"]
|
||||
icons = {
|
||||
instance["icon"]
|
||||
for instance in child["instances"]
|
||||
if instance["definition_id"] == definition_id
|
||||
}
|
||||
assert icons == {"lucide:dog"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"icon", ["foo:dog", "lucide:", "emoji:<b>", "javascript:alert(1)"]
|
||||
)
|
||||
async def test_create_invalid_icon_is_422_naming_icon(
|
||||
admin_questdefs: SimpleNamespace, icon: str
|
||||
) -> None:
|
||||
"""An invalid icon key is a 422 whose detail names the icon field."""
|
||||
client = admin_questdefs.client
|
||||
ada = (await _create_children(client, ("Ada",)))[0]
|
||||
response = await client.post(
|
||||
"/api/v1/admin/quest-definitions",
|
||||
json={
|
||||
"title": "Walk the dog",
|
||||
"rule": _weekly_rule_body(),
|
||||
"assignee_child_ids": [ada],
|
||||
"windows": ["morning"],
|
||||
"icon": icon,
|
||||
},
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert "icon" in str(response.json()["detail"])
|
||||
assert await _definitions_by_id(admin_questdefs.database) == {}
|
||||
|
||||
|
||||
async def test_edit_unknown_definition_is_404(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
@@ -733,3 +817,141 @@ async def test_set_active_malformed_body_is_422(
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert response.status_code == 422
|
||||
|
||||
|
||||
# --- delete: hybrid (delete if no history, retire if there is) --------------
|
||||
|
||||
_dao_instances = importlib.import_module("nestquest_core.dao_instances")
|
||||
|
||||
|
||||
def test_delete_route_lives_on_the_admin_router() -> None:
|
||||
"""The DELETE route is on the admin router, which carries the ONE
|
||||
require_admin dependency — no second auth check is added."""
|
||||
from api.auth import require_admin
|
||||
from api.routes_admin import router as admin_router
|
||||
|
||||
assert require_admin in [d.dependency for d in admin_router.dependencies]
|
||||
matches = [
|
||||
route
|
||||
for route in admin_router.routes
|
||||
if route.path == "/api/v1/admin/quest-definitions/{definition_id}"
|
||||
and "DELETE" in route.methods
|
||||
]
|
||||
assert len(matches) == 1
|
||||
|
||||
|
||||
async def test_delete_refuses_non_admin_and_absent(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
"""A non-admin JWT is 403 and an absent credential 401: nothing is
|
||||
deleted or retired."""
|
||||
client = admin_questdefs.client
|
||||
ada = (await _create_children(client, ("Ada",)))[0]
|
||||
definition_id = (await _create_definition(client, [ada])).json()["id"]
|
||||
non_admin = make_token(groups=("some-other-group",))
|
||||
|
||||
forbidden = await client.delete(
|
||||
f"/api/v1/admin/quest-definitions/{definition_id}",
|
||||
headers={"Authorization": f"Bearer {non_admin}"},
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
unauthenticated = await client.delete(
|
||||
f"/api/v1/admin/quest-definitions/{definition_id}"
|
||||
)
|
||||
assert unauthenticated.status_code == 401
|
||||
|
||||
record = await _dao_rules.QuestDefinitionsDao(
|
||||
admin_questdefs.database
|
||||
).get(definition_id)
|
||||
assert record is not None
|
||||
assert record.is_active is True
|
||||
|
||||
|
||||
async def test_delete_without_history_hard_deletes(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
"""No completion history: 200 ``deleted`` and the row and its
|
||||
unreferenced rule are gone."""
|
||||
client = admin_questdefs.client
|
||||
ada = (await _create_children(client, ("Ada",)))[0]
|
||||
definition_id = (await _create_definition(client, [ada])).json()["id"]
|
||||
dao = _dao_rules.QuestDefinitionsDao(admin_questdefs.database)
|
||||
rule_id = (await dao.get(definition_id)).schedule_rule_id
|
||||
|
||||
response = await client.delete(
|
||||
f"/api/v1/admin/quest-definitions/{definition_id}",
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json() == {
|
||||
"definition_id": definition_id,
|
||||
"deleted": True,
|
||||
"retired": False,
|
||||
"definition": None,
|
||||
}
|
||||
assert await dao.get(definition_id) is None
|
||||
assert await _dao_rules.ScheduleRulesDao(
|
||||
admin_questdefs.database
|
||||
).get(rule_id) is None
|
||||
|
||||
|
||||
async def test_delete_with_history_retires(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
"""Completion history present: 200 ``retired`` with the now-inactive
|
||||
definition; the row, instance and history all remain."""
|
||||
client = admin_questdefs.client
|
||||
database = admin_questdefs.database
|
||||
ada = (await _create_children(client, ("Ada",)))[0]
|
||||
definition_id = (await _create_definition(client, [ada])).json()["id"]
|
||||
instance = await _dao_instances.QuestInstancesDao(database).upsert(
|
||||
definition_id,
|
||||
ada,
|
||||
datetime.date.today().isoformat(),
|
||||
"2026-09-14T12:00:00+00:00",
|
||||
window="morning",
|
||||
)
|
||||
events = _dao_instances.CompletionEventsDao(database)
|
||||
event = await events.append(
|
||||
instance.id,
|
||||
ada,
|
||||
"completed",
|
||||
"user",
|
||||
"2026-09-14T12:00:00+00:00",
|
||||
True,
|
||||
actor_user_id="admin-1",
|
||||
)
|
||||
|
||||
response = await client.delete(
|
||||
f"/api/v1/admin/quest-definitions/{definition_id}",
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
payload = response.json()
|
||||
assert payload["definition_id"] == definition_id
|
||||
assert payload["deleted"] is False
|
||||
assert payload["retired"] is True
|
||||
assert payload["definition"]["id"] == definition_id
|
||||
assert payload["definition"]["is_active"] is False
|
||||
assert payload["definition"]["title"] == "Tidy the den"
|
||||
record = await _dao_rules.QuestDefinitionsDao(database).get(definition_id)
|
||||
assert record is not None
|
||||
assert record.is_active is False
|
||||
assert await _dao_instances.QuestInstancesDao(database).get_by_id(
|
||||
instance.id
|
||||
) == instance
|
||||
assert await events.list_by_instance(instance.id) == [event]
|
||||
|
||||
|
||||
async def test_delete_unknown_definition_is_404(
|
||||
admin_questdefs: SimpleNamespace,
|
||||
) -> None:
|
||||
"""A DELETE naming a definition that does not exist is 404."""
|
||||
response = await admin_questdefs.client.delete(
|
||||
"/api/v1/admin/quest-definitions/999",
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert response.status_code == 404
|
||||
assert response.json()["detail"] == "Quest definition not found"
|
||||
|
||||
@@ -135,7 +135,7 @@ async def test_admin_lists_active_and_inactive_definitions_with_full_shape(
|
||||
"id": active_id,
|
||||
"title": "Tidy the den",
|
||||
"description": "Put everything back where it belongs.",
|
||||
"icon": "toy-box",
|
||||
"icon": "lucide:toy-box",
|
||||
"is_active": True,
|
||||
"skip_on_away": True,
|
||||
"rule": {
|
||||
|
||||
@@ -13,7 +13,7 @@ proven against the DATABASE the routes wrote, not a parallel copy.
|
||||
Proven per the done-condition, everything read back through the API:
|
||||
|
||||
- ``GET /api/v1/admin/settings`` returns the current effective settings
|
||||
— the ten documented fields at their defaults on a fresh database.
|
||||
— the eleven documented fields at their defaults on a fresh database.
|
||||
- ``PATCH /api/v1/admin/settings`` PERSISTS the supplied fields and the
|
||||
NEXT read reflects them; a later partial update merges onto the
|
||||
current effective settings (omitted fields keep their stored value),
|
||||
@@ -60,7 +60,7 @@ _dao_meta = importlib.import_module("nestquest_core.dao_meta")
|
||||
SETTINGS_META_KEY = "settings"
|
||||
|
||||
#: The all-defaults effective settings a fresh database reports — the
|
||||
#: documented ten fields, asserted literally so the payload contract is
|
||||
#: documented eleven fields, asserted literally so the payload contract is
|
||||
#: pinned here, independent of the core constants.
|
||||
DEFAULT_SETTINGS = {
|
||||
"horizon_days": 14,
|
||||
@@ -73,6 +73,7 @@ DEFAULT_SETTINGS = {
|
||||
"afternoon_reminder_enabled": True,
|
||||
"end_of_day_report_enabled": True,
|
||||
"celebration_enabled": True,
|
||||
"timezone": "",
|
||||
}
|
||||
|
||||
|
||||
@@ -103,7 +104,7 @@ async def settings_client(temp_db_path: str) -> SimpleNamespace:
|
||||
async def test_get_settings_returns_defaults_on_a_fresh_database(
|
||||
settings_client: SimpleNamespace,
|
||||
) -> None:
|
||||
"""GET returns the ten documented fields at their defaults."""
|
||||
"""GET returns the eleven documented fields at their defaults."""
|
||||
response = await settings_client.client.get(
|
||||
"/api/v1/admin/settings", headers=_admin_headers()
|
||||
)
|
||||
@@ -139,7 +140,7 @@ async def test_update_persists_and_the_next_read_reflects_it(
|
||||
assert reread.status_code == 200
|
||||
assert reread.json() == expected
|
||||
|
||||
# ...and the DATABASE holds the merged document: the complete ten
|
||||
# ...and the DATABASE holds the merged document: the complete eleven
|
||||
# fields, keyed by field name, under the well-known meta_state key.
|
||||
raw = await _dao_meta.MetaStateDao(settings_client.database).get(
|
||||
SETTINGS_META_KEY
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
"""Household-local clock tests for the API service (task fa7475ba).
|
||||
|
||||
The deployed API container runs UTC while the household is US Eastern,
|
||||
so reading the HOST clock marked every morning quest overdue from the
|
||||
small hours. The API now re-expresses its ONE host clock read in the
|
||||
stored ``timezone`` setting (``NestQuestSettings.household_now``).
|
||||
|
||||
Every test pins the host clock to a UTC instant (the deployed
|
||||
container's zone) and sets the household zone through the real admin
|
||||
``PATCH /api/v1/admin/settings`` route, then reads BOTH snapshot shapes:
|
||||
|
||||
- one second before the 10:00 due time: NOT overdue (previously
|
||||
flagged, because 13:59:59 UTC > 10:00);
|
||||
- exactly at 10:00:00: NOT overdue (the builder's strict
|
||||
``now.time() > due`` convention);
|
||||
- one second after: overdue;
|
||||
- 23:30 household time, already the next day in UTC: ``today_iso`` is
|
||||
still the household's day.
|
||||
|
||||
An unset zone keeps the historical host-local behaviour, and the
|
||||
missed-sweep scheduler waits for the rollover in household time.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime
|
||||
import importlib
|
||||
from types import SimpleNamespace
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from api import routes_admin, routes_panel
|
||||
from api.database import _executor
|
||||
from api.scheduler import MissedSweepScheduler, _delay_seconds
|
||||
from tests.admin_jwt_harness import (
|
||||
ADMIN_KEY,
|
||||
KID,
|
||||
AdminRunner,
|
||||
jwks_for,
|
||||
make_token,
|
||||
)
|
||||
from tests.test_api_panel import _seed_household
|
||||
|
||||
_settings = importlib.import_module("nestquest_core.settings")
|
||||
_settings_store = importlib.import_module("nestquest_core.settings_store")
|
||||
_core_db = importlib.import_module("nestquest_core.db")
|
||||
_core_migrations = importlib.import_module("nestquest_core.migrations")
|
||||
|
||||
#: The panel service token the admin harness app is configured with.
|
||||
HARNESS_PANEL_TOKEN = "admin-test-panel-token"
|
||||
|
||||
UTC = ZoneInfo("UTC")
|
||||
HOUSEHOLD_ZONE = "America/New_York"
|
||||
|
||||
#: A fixed household day on Eastern Daylight Time (UTC-4).
|
||||
TODAY = datetime.date(2026, 9, 26)
|
||||
|
||||
|
||||
def _utc(hour: int, minute: int, second: int = 0, *, day: int = 26):
|
||||
"""An aware UTC instant on September ``day`` 2026."""
|
||||
return datetime.datetime(2026, 9, day, hour, minute, second, tzinfo=UTC)
|
||||
|
||||
|
||||
def _admin_headers() -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {make_token()}"}
|
||||
|
||||
|
||||
def _panel_headers() -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {HARNESS_PANEL_TOKEN}"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def household(temp_db_path: str, monkeypatch) -> SimpleNamespace:
|
||||
"""The seeded household on the admin-plane app, host clock pinnable.
|
||||
|
||||
Ada's open "Pack bag" quest is due 10:00 on :data:`TODAY`. Both
|
||||
routes' host clock read returns ``clock["now"]`` (a UTC instant).
|
||||
"""
|
||||
seed = await _seed_household(temp_db_path, TODAY, _utc(16, 0))
|
||||
clock = {"now": _utc(12, 0)}
|
||||
monkeypatch.setattr(routes_admin, "_local_now", lambda: clock["now"])
|
||||
monkeypatch.setattr(routes_panel, "_local_now", lambda: clock["now"])
|
||||
runner = AdminRunner(temp_db_path, jwks_for(ADMIN_KEY, KID))
|
||||
async with runner as client:
|
||||
yield SimpleNamespace(client=client, seed=seed, clock=clock)
|
||||
|
||||
|
||||
async def _set_zone(household: SimpleNamespace, zone: str) -> None:
|
||||
response = await household.client.patch(
|
||||
"/api/v1/admin/settings",
|
||||
json={"timezone": zone},
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["timezone"] == zone
|
||||
|
||||
|
||||
async def _pack_bag(household: SimpleNamespace, plane: str) -> tuple[str, dict]:
|
||||
"""Return ``(today_iso, Ada's Pack bag instance)`` from one snapshot."""
|
||||
headers = _admin_headers() if plane == "admin" else _panel_headers()
|
||||
response = await household.client.get(
|
||||
f"/api/v1/{plane}/snapshot", headers=headers
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
ada = next(
|
||||
child
|
||||
for child in body["children"]
|
||||
if child["child_id"] == household.seed.ada.id
|
||||
)
|
||||
(instance,) = ada["instances"]
|
||||
assert instance["title"] == "Pack bag"
|
||||
assert instance["due_time"] == "10:00"
|
||||
return body["today_iso"], instance
|
||||
|
||||
|
||||
@pytest.mark.parametrize("plane", ["panel", "admin"])
|
||||
@pytest.mark.parametrize(
|
||||
("host_now", "overdue"),
|
||||
[
|
||||
# 09:59:59 EDT — the pre-fix code compared 13:59:59 (UTC) > 10:00.
|
||||
(_utc(13, 59, 59), False),
|
||||
# 10:00:00 EDT exactly — strict ``>``: not yet overdue.
|
||||
(_utc(14, 0, 0), False),
|
||||
# 10:00:01 EDT — overdue.
|
||||
(_utc(14, 0, 1), True),
|
||||
],
|
||||
ids=["before-due", "at-due", "after-due"],
|
||||
)
|
||||
async def test_overdue_boundary_uses_household_zone(
|
||||
household: SimpleNamespace,
|
||||
plane: str,
|
||||
host_now: datetime.datetime,
|
||||
overdue: bool,
|
||||
) -> None:
|
||||
await _set_zone(household, HOUSEHOLD_ZONE)
|
||||
household.clock["now"] = host_now
|
||||
today_iso, instance = await _pack_bag(household, plane)
|
||||
assert today_iso == TODAY.isoformat()
|
||||
assert instance["state"] == "open"
|
||||
assert instance["overdue"] is overdue
|
||||
|
||||
|
||||
@pytest.mark.parametrize("plane", ["panel", "admin"])
|
||||
async def test_household_day_survives_utc_midnight(
|
||||
household: SimpleNamespace, plane: str
|
||||
) -> None:
|
||||
"""23:30 EDT is already tomorrow in UTC; the household day is today."""
|
||||
await _set_zone(household, HOUSEHOLD_ZONE)
|
||||
household.clock["now"] = _utc(3, 30, day=27)
|
||||
today_iso, instance = await _pack_bag(household, plane)
|
||||
assert today_iso == TODAY.isoformat()
|
||||
assert instance["overdue"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("plane", ["panel", "admin"])
|
||||
async def test_unset_zone_keeps_host_local_time(
|
||||
household: SimpleNamespace, plane: str
|
||||
) -> None:
|
||||
"""Backward compatible: no stored zone reads the host clock as-is."""
|
||||
household.clock["now"] = _utc(13, 59, 59)
|
||||
today_iso, instance = await _pack_bag(household, plane)
|
||||
assert today_iso == TODAY.isoformat()
|
||||
assert instance["overdue"] is True
|
||||
|
||||
|
||||
async def test_panel_completion_on_time_uses_household_zone(
|
||||
household: SimpleNamespace,
|
||||
) -> None:
|
||||
"""A 09:30 EDT tap on a 10:00 quest is on time (13:30 UTC is not)."""
|
||||
await _set_zone(household, HOUSEHOLD_ZONE)
|
||||
household.clock["now"] = _utc(13, 30)
|
||||
seed = household.seed
|
||||
response = await household.client.post(
|
||||
f"/api/v1/panel/instances/{seed.pack_bag_instance.id}/complete",
|
||||
headers=_panel_headers(),
|
||||
json={"actor_child_id": seed.ada.id},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
_today_iso, instance = await _pack_bag(household, "admin")
|
||||
assert instance["state"] == "completed"
|
||||
assert instance["on_time"] is True
|
||||
|
||||
|
||||
async def test_invalid_zone_is_rejected(household: SimpleNamespace) -> None:
|
||||
response = await household.client.patch(
|
||||
"/api/v1/admin/settings",
|
||||
json={"timezone": "Mars/Olympus_Mons"},
|
||||
headers=_admin_headers(),
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert "timezone" in str(response.json()["detail"])
|
||||
reread = await household.client.get(
|
||||
"/api/v1/admin/settings", headers=_admin_headers()
|
||||
)
|
||||
assert reread.json()["timezone"] == ""
|
||||
|
||||
|
||||
# --- the settings object ---------------------------------------------------
|
||||
|
||||
|
||||
def test_settings_timezone_defaults_to_host_local() -> None:
|
||||
settings = _settings.NestQuestSettings()
|
||||
assert settings.timezone == ""
|
||||
instant = _utc(13, 0)
|
||||
assert settings.household_now(instant) is instant
|
||||
|
||||
|
||||
def test_settings_household_now_converts_the_same_instant() -> None:
|
||||
settings = _settings.NestQuestSettings(timezone=HOUSEHOLD_ZONE)
|
||||
local = settings.household_now(_utc(13, 0))
|
||||
assert local == _utc(13, 0)
|
||||
assert (local.date(), local.time()) == (TODAY, datetime.time(9, 0))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["Mars/Olympus_Mons", "../etc/passwd", 5, None])
|
||||
def test_settings_rejects_invalid_timezone(value: object) -> None:
|
||||
with pytest.raises(ValueError, match="timezone"):
|
||||
_settings.NestQuestSettings(timezone=value)
|
||||
|
||||
|
||||
def test_from_options_reads_and_resiliently_defaults_timezone() -> None:
|
||||
assert (
|
||||
_settings.NestQuestSettings.from_options(
|
||||
{"timezone": HOUSEHOLD_ZONE}
|
||||
).timezone
|
||||
== HOUSEHOLD_ZONE
|
||||
)
|
||||
assert _settings.NestQuestSettings.from_options({}).timezone == ""
|
||||
assert (
|
||||
_settings.NestQuestSettings.from_options_resilient(
|
||||
{"timezone": "Nowhere/Land", "horizon_days": 9}
|
||||
).timezone
|
||||
== ""
|
||||
)
|
||||
|
||||
|
||||
# --- the missed-sweep scheduler ----------------------------------------------
|
||||
|
||||
|
||||
async def test_scheduler_waits_for_rollover_in_household_time(
|
||||
temp_db_path: str,
|
||||
) -> None:
|
||||
"""09:00 EDT (13:00 UTC) to a 10:05 rollover is 65 minutes away."""
|
||||
database = _core_db.NestQuestDatabase(_executor)
|
||||
await database.open(temp_db_path)
|
||||
try:
|
||||
await _core_migrations.apply_migrations(database)
|
||||
await _settings_store.update_settings(
|
||||
database,
|
||||
{"day_rollover_time": "10:05", "timezone": HOUSEHOLD_ZONE},
|
||||
)
|
||||
delays: list[float] = []
|
||||
first_sleep = asyncio.Event()
|
||||
|
||||
async def sleep_stub(seconds: float) -> None:
|
||||
delays.append(seconds)
|
||||
first_sleep.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
scheduler = MissedSweepScheduler(
|
||||
database, clock=lambda: _utc(13, 0), sleep=sleep_stub
|
||||
)
|
||||
scheduler.start()
|
||||
try:
|
||||
await asyncio.wait_for(first_sleep.wait(), timeout=5)
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
assert delays == [pytest.approx(65 * 60)]
|
||||
finally:
|
||||
await database.close()
|
||||
|
||||
|
||||
# --- the rollover delay across DST (America/New_York) ------------------------
|
||||
|
||||
NEW_YORK = ZoneInfo("America/New_York")
|
||||
|
||||
|
||||
def _ny(*args: int, fold: int = 0) -> datetime.datetime:
|
||||
return datetime.datetime(*args, tzinfo=NEW_YORK, fold=fold)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("now", "target", "expected"),
|
||||
[
|
||||
# Ordinary EDT day: 09:00 -> 10:05 is 65 minutes.
|
||||
(_ny(2026, 6, 15, 9, 0), datetime.time(10, 5), 65 * 60),
|
||||
# An equal time schedules for tomorrow (strictly after now).
|
||||
(_ny(2026, 6, 15, 10, 5), datetime.time(10, 5), 86400),
|
||||
# Spring-forward: 01:00 EST -> 03:00 EDT is one real hour.
|
||||
(_ny(2026, 3, 8, 1, 0), datetime.time(3, 0), 3600),
|
||||
# Fall-back: 00:30 EDT -> 02:00 EST is two and a half real hours.
|
||||
(_ny(2026, 11, 1, 0, 30), datetime.time(2, 0), 9000),
|
||||
# Nonexistent 02:30 on spring-forward day: the first valid instant
|
||||
# at/after it is 03:00 EDT, one real hour after 01:00 EST.
|
||||
(_ny(2026, 3, 8, 1, 0), datetime.time(2, 30), 3600),
|
||||
# Ambiguous 01:30 on fall-back day resolves to the FIRST (EDT)
|
||||
# occurrence: from 00:30 EDT that is one real hour.
|
||||
(_ny(2026, 11, 1, 0, 30), datetime.time(1, 30), 3600),
|
||||
# Already past the first 01:30 (now is 01:15 EST, the repeated
|
||||
# hour): not the second occurrence, but tomorrow's 01:30 EST.
|
||||
(_ny(2026, 11, 1, 1, 15, fold=1), datetime.time(1, 30), 87300),
|
||||
],
|
||||
)
|
||||
def test_delay_seconds_is_true_elapsed_time_across_dst(
|
||||
now: datetime.datetime, target: datetime.time, expected: float
|
||||
) -> None:
|
||||
assert _delay_seconds(target, now) == expected
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Test the namespaced icon-key module (task 707994b7).
|
||||
|
||||
:func:`validate_icon` is the strict write-side check (create/edit);
|
||||
:func:`normalize_icon_for_read` the lenient read-side normalizer that
|
||||
lets legacy bare Lucide names render without a data migration.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from custom_components.nestquest.core.icons import (
|
||||
EMOJI_MAX_CODE_POINTS,
|
||||
ICON_NAMESPACES,
|
||||
normalize_icon_for_read,
|
||||
validate_icon,
|
||||
)
|
||||
|
||||
|
||||
def test_namespace_and_cap_constants() -> None:
|
||||
assert ICON_NAMESPACES == {"lucide", "fa", "emoji"}
|
||||
assert EMOJI_MAX_CODE_POINTS == 8
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "expected"),
|
||||
[
|
||||
("lucide:dog", "lucide:dog"),
|
||||
("fa:dog", "fa:dog"),
|
||||
("fa:paw-print", "fa:paw-print"),
|
||||
("lucide:toy-box-2", "lucide:toy-box-2"),
|
||||
("emoji:🐕", "emoji:🐕"),
|
||||
# A ZWJ family sequence (7 code points) is within the cap.
|
||||
("emoji:👨👩👧👦", "emoji:👨👩👧👦"),
|
||||
("emoji:" + "⭐" * EMOJI_MAX_CODE_POINTS, "emoji:" + "⭐" * 8),
|
||||
# Legacy bare Lucide names normalize to the lucide namespace.
|
||||
("dog", "lucide:dog"),
|
||||
],
|
||||
)
|
||||
def test_validate_icon_accepts(value: str, expected: str) -> None:
|
||||
assert validate_icon(value) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [None, "", " ", "\t\n"])
|
||||
def test_validate_icon_clears(value: str | None) -> None:
|
||||
assert validate_icon(value) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value",
|
||||
[
|
||||
"foo:dog", # unknown namespace
|
||||
"javascript:alert(1)", # unknown namespace (and markup-ish)
|
||||
"mdi:dog", # not one of the supported namespaces
|
||||
"lucide:", # empty name
|
||||
"fa:", # empty name
|
||||
"emoji:", # empty payload
|
||||
"lucide:Dog", # uppercase
|
||||
"lucide:has space", # whitespace
|
||||
"lucide:-dog", # leading hyphen
|
||||
"lucide:dog-", # trailing hyphen
|
||||
"lucide:dog_bone", # not kebab
|
||||
"fa:dög", # non-ASCII
|
||||
"lucide:a:b", # colon inside the name
|
||||
"Dog", # bare legacy name must still be kebab
|
||||
"has space",
|
||||
"<script>",
|
||||
"emoji:" + "⭐" * (EMOJI_MAX_CODE_POINTS + 1), # over the cap
|
||||
"emoji:a b", # whitespace
|
||||
"emoji:<b>", # markup
|
||||
"emoji:a&b", # entity start
|
||||
"emoji:🐕\x00", # control character
|
||||
"emoji:🐕\x07🐕", # control character between emoji
|
||||
"emoji:\ufeff", # U+FEFF BOM: JS \s matches it, so reject to agree
|
||||
"emoji:🐕\ufeff", # trailing U+FEFF
|
||||
# Edge whitespace/controls are part of the value, never trimmed away.
|
||||
"emoji:🐕 ", # trailing space
|
||||
"emoji:🐕\n", # trailing newline
|
||||
"emoji:🐕\x1c", # trailing control character (str.strip() eats it)
|
||||
" emoji:🐕", # leading space
|
||||
"lucide:dog ", # trailing space
|
||||
" fa:dog ", # padded namespaced key
|
||||
" toy-box ", # padded legacy bare name
|
||||
],
|
||||
)
|
||||
def test_validate_icon_rejects_naming_the_field(value: str) -> None:
|
||||
with pytest.raises(ValueError, match=r"^icon\b"):
|
||||
validate_icon(value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", [42, True, ["dog"], {"icon": "dog"}])
|
||||
def test_validate_icon_rejects_non_strings(value: object) -> None:
|
||||
with pytest.raises(ValueError, match="icon must be a string"):
|
||||
validate_icon(value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "expected"),
|
||||
[
|
||||
(None, None),
|
||||
("", None),
|
||||
(" ", None),
|
||||
("lucide:dog", "lucide:dog"),
|
||||
("fa:dog", "fa:dog"),
|
||||
("emoji:🐕", "emoji:🐕"),
|
||||
# Legacy bare names (and anything else) fall through to lucide so
|
||||
# the frontend's fallback handles an unknown name, never an error.
|
||||
("dog", "lucide:dog"),
|
||||
("mdi:tooth", "lucide:mdi:tooth"),
|
||||
("Not Kebab", "lucide:Not Kebab"),
|
||||
],
|
||||
)
|
||||
def test_normalize_icon_for_read(value: str | None, expected: str | None) -> None:
|
||||
assert normalize_icon_for_read(value) == expected
|
||||
|
||||
|
||||
# The emoji-payload rule is duplicated in the generated JS resolver
|
||||
# (``isEmojiPayload`` in tools/icons/generate.mjs). Both suites assert
|
||||
# this one table — admin/src/icons/registry.test.ts runs it through
|
||||
# resolveIcon — so a divergence between the runtimes fails a test.
|
||||
_EMOJI_PARITY_CASES = json.loads(
|
||||
(
|
||||
Path(__file__).parent.parent / "tools" / "icons" / "emoji-payload-cases.json"
|
||||
).read_text(encoding="utf-8")
|
||||
)["cases"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case", _EMOJI_PARITY_CASES, ids=[case["why"] for case in _EMOJI_PARITY_CASES]
|
||||
)
|
||||
def test_validate_icon_emoji_verdict_matches_shared_table(case: dict) -> None:
|
||||
value = "emoji:" + case["payload"]
|
||||
if case["valid"]:
|
||||
assert validate_icon(value) == value
|
||||
else:
|
||||
with pytest.raises(ValueError, match=r"^icon\b"):
|
||||
validate_icon(value)
|
||||
|
||||
|
||||
def test_emoji_parity_table_covers_the_contract_edges() -> None:
|
||||
payloads = {case["payload"]: case["valid"] for case in _EMOJI_PARITY_CASES}
|
||||
assert payloads["\ufeff"] is False
|
||||
assert payloads["🐕 "] is False
|
||||
assert payloads["🐕\x00"] is False
|
||||
assert payloads["<b>"] is False and payloads["a>b"] is False
|
||||
assert payloads["a&b"] is False
|
||||
assert payloads["⭐" * EMOJI_MAX_CODE_POINTS] is True
|
||||
assert payloads["⭐" * (EMOJI_MAX_CODE_POINTS + 1)] is False
|
||||
family = "👨\u200d👩\u200d👧\u200d👦"
|
||||
assert payloads[family] is True
|
||||
@@ -996,8 +996,9 @@ def test_definition_set_active_missing_returns_zero(tmp_path) -> None:
|
||||
assert _with_db(tmp_path, "definition-set-active-missing.db")(_body) == 0
|
||||
|
||||
|
||||
def test_definition_no_delete_method_exists(tmp_path) -> None:
|
||||
"""Guardrail: definitions are deactivated, never hard-deleted."""
|
||||
def test_definition_only_delete_method_is_history_guarded(tmp_path) -> None:
|
||||
"""Guardrail: the ONLY definition delete path is the history-guarded
|
||||
one (owner decision 2026-09-26); there is no unconditional delete."""
|
||||
async def _body(database, rules, definitions, children, child):
|
||||
import inspect
|
||||
|
||||
@@ -1008,7 +1009,9 @@ def test_definition_no_delete_method_exists(tmp_path) -> None:
|
||||
)
|
||||
}
|
||||
assert "delete" not in methods
|
||||
assert not any(name.startswith("delete") for name in methods)
|
||||
assert {
|
||||
name for name in methods if name.startswith("delete")
|
||||
} == {"delete_if_no_history"}
|
||||
return methods
|
||||
|
||||
_with_db(tmp_path, "definition-no-delete.db")(_body)
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""The shared quest-icon registry: one curated source, two identical artefacts.
|
||||
|
||||
``tools/icons/curated-icons.json`` is the only hand-edited list; the offline
|
||||
generator ``tools/icons/generate.mjs`` writes the same module into the admin
|
||||
PWA and the panel bundle. The admin Vitest suite regenerates and compares
|
||||
byte-for-byte; these checks need no Node for the core guarantees.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
REPO_ROOT = Path(__file__).parent.parent
|
||||
SOURCE = REPO_ROOT / "tools" / "icons" / "curated-icons.json"
|
||||
GENERATOR = REPO_ROOT / "tools" / "icons" / "generate.mjs"
|
||||
ARTEFACTS = (
|
||||
REPO_ROOT / "admin" / "src" / "icons" / "registry.generated.ts",
|
||||
REPO_ROOT / "frontend" / "src" / "icons" / "registry.generated.ts",
|
||||
)
|
||||
PANEL_BUNDLE = (
|
||||
REPO_ROOT / "custom_components" / "nestquest" / "www" / "nestquest-cards.js"
|
||||
)
|
||||
|
||||
|
||||
def _curated() -> dict[str, list[dict[str, str]]]:
|
||||
return json.loads(SOURCE.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _generated_set(text: str, const: str) -> list[dict]:
|
||||
match = re.search(
|
||||
rf"export const {const}: readonly GlyphIcon\[\] = (\[.*?\n\]);",
|
||||
text,
|
||||
re.DOTALL,
|
||||
)
|
||||
assert match, f"{const} not found in the generated registry"
|
||||
return json.loads(match.group(1))
|
||||
|
||||
|
||||
def test_both_artefacts_are_byte_identical() -> None:
|
||||
admin, frontend = (path.read_bytes() for path in ARTEFACTS)
|
||||
assert admin == frontend
|
||||
|
||||
|
||||
def test_artefacts_carry_exactly_the_curated_names_and_labels() -> None:
|
||||
curated = _curated()
|
||||
text = ARTEFACTS[0].read_text(encoding="utf-8")
|
||||
for namespace, const in (("lucide", "LUCIDE_ICONS"), ("fa", "FA_ICONS")):
|
||||
entries = _generated_set(text, const)
|
||||
assert [
|
||||
{"name": e["name"], "label": e["label"]} for e in entries
|
||||
] == curated[namespace]
|
||||
for entry in entries:
|
||||
assert entry["kind"] == namespace
|
||||
assert entry["key"] == f"{namespace}:{entry['name']}"
|
||||
assert re.fullmatch(r"0 0 \d+ \d+", entry["viewBox"])
|
||||
assert entry["paths"] and all(entry["paths"])
|
||||
assert len(curated["lucide"]) == 36
|
||||
assert 15 <= len(curated["fa"]) <= 25
|
||||
|
||||
|
||||
def test_registry_has_no_remote_url_cdn_or_lucide_runtime() -> None:
|
||||
for path in (SOURCE, GENERATOR, *ARTEFACTS):
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert not re.search(r"https?://", text, re.IGNORECASE), path
|
||||
assert not re.search(
|
||||
r"\bcdn\b|jsdelivr|unpkg|cdnjs|kit\.fontawesome", text, re.IGNORECASE
|
||||
), path
|
||||
assert "data-lucide" not in text, path
|
||||
|
||||
|
||||
def test_panel_bundle_embeds_the_registry() -> None:
|
||||
bundle = PANEL_BUNDLE.read_text(encoding="utf-8")
|
||||
assert "fa:broom" in bundle
|
||||
assert "lucide:dog" in bundle
|
||||
assert "data-lucide" not in bundle
|
||||
|
||||
|
||||
def test_generator_reproduces_the_committed_artefacts() -> None:
|
||||
node = shutil.which("node")
|
||||
if node is None or not (REPO_ROOT / "admin" / "node_modules").is_dir():
|
||||
pytest.skip("needs node and admin/node_modules (npm ci in admin/)")
|
||||
result = subprocess.run(
|
||||
[node, str(GENERATOR), "--check"],
|
||||
cwd=REPO_ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
@@ -411,6 +411,36 @@ def test_panel_hard_rules_hold_in_the_card_sources() -> None:
|
||||
assert "@click" not in sealed_template
|
||||
|
||||
|
||||
def test_party_board_hint_clears_the_dock() -> None:
|
||||
"""PANEL-SPEC §2/§2.3: the hint line reads fully above the dock at
|
||||
1920x1080. The hint's line box (top + font-size x line-height) must
|
||||
end above the dock's top edge (1080 - bottom inset - dock height)
|
||||
with a visible gap, at the 27px/600 design size. The hint is a <p>,
|
||||
so its user-agent 1em top margin must be reset or it shifts the box
|
||||
down by a whole font-size."""
|
||||
style = _style_literal(_read(PARTY_BOARD), STYLE_CONSTANTS[PARTY_BOARD])
|
||||
rules = {selector.strip(): body for selector, body in _css_rules(style)}
|
||||
sizes = _size_tokens(_read(REWARD_TOKENS))
|
||||
|
||||
def px(body: str, prop: str) -> float:
|
||||
declared = re.search(rf"(?<![-\w]){prop}:\s*([^;]+);", body)
|
||||
assert declared is not None, prop
|
||||
value = _font_size_px(declared.group(1), sizes)
|
||||
assert value is not None, f"{prop}: {declared.group(1)}"
|
||||
return value
|
||||
|
||||
board, hint, dock = rules[".board"], rules[".hint"], rules[".dock"]
|
||||
assert "margin: 0;" in hint
|
||||
line_height = float(re.search(r"line-height:\s*([\d.]+);", hint).group(1))
|
||||
hint_bottom = px(hint, "top") + px(hint, "font-size") * line_height
|
||||
dock_top = px(board, "height") - px(dock, "bottom") - px(dock, "height")
|
||||
assert px(dock, "height") == 84
|
||||
assert px(dock, "bottom") == 46
|
||||
assert hint_bottom + 12 <= dock_top, (hint_bottom, dock_top)
|
||||
assert px(hint, "font-size") == 27
|
||||
assert "font-weight: 600;" in hint
|
||||
|
||||
|
||||
def test_panel_text_sizes_respect_the_22px_floor() -> None:
|
||||
"""PANEL-SPEC §1: no body text below 22px. Every font-size in the
|
||||
panel styles resolves against the panel size tokens or an explicit
|
||||
@@ -570,6 +600,40 @@ def _render_party_board(
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def test_party_board_wordmark_row_is_the_monogram_lockup() -> None:
|
||||
"""PANEL-SPEC §2 item 1: the wordmark row is rule · compass-rose
|
||||
monogram · NestQuest · rule. The monogram is an inline SVG filled
|
||||
with the brand gradient — the old d20 hexagon pair and its "20"
|
||||
numerals are gone, and nothing is fetched from a remote URL or
|
||||
embedded as a raster logo."""
|
||||
source = _read(PARTY_BOARD)
|
||||
assert "d20" not in _style_literal(source, STYLE_CONSTANTS[PARTY_BOARD])
|
||||
assert 'class="d20' not in source
|
||||
assert "HEXAGON_CLIP" not in source
|
||||
|
||||
html = _render_party_board(
|
||||
{"type": "custom:nestquest-party-board-card"},
|
||||
_three_child_states(),
|
||||
)["html"]
|
||||
row = re.search(r'<div class="wordmark-row">(.*?)</div>', html, re.DOTALL)
|
||||
assert row is not None
|
||||
row_html = row.group(1)
|
||||
classes = re.findall(r'<(?:span|svg) class="([^"]+)"', row_html)
|
||||
assert classes == ["rule", "monogram", "wordmark", "rule"]
|
||||
assert '<svg class="monogram" viewBox="0 0 100 100" aria-hidden="true"' in row_html
|
||||
assert "var(--nq-brand-blue)" in row_html
|
||||
assert "var(--nq-brand-purple)" in row_html
|
||||
assert ">N</text>" in row_html
|
||||
assert ">NestQuest</span>" in row_html
|
||||
assert "d20" not in row_html
|
||||
assert "<img" not in row_html
|
||||
|
||||
bundle = _read(BUNDLE_PATH)
|
||||
assert "d20-numeral\">20<" not in bundle
|
||||
assert "data:image/png" not in bundle
|
||||
assert not re.search(r"https?://", bundle)
|
||||
|
||||
|
||||
def test_party_board_renders_discovered_children_in_sort_order() -> None:
|
||||
"""No child_order key: three plates render in the roster's sort
|
||||
order (the coordinator snapshot's order), one per child."""
|
||||
@@ -764,6 +828,7 @@ def _render_quest_log(
|
||||
url: str,
|
||||
idle_ms: int | None = None,
|
||||
probe_ms: int | None = None,
|
||||
tap_complete: int | None = None,
|
||||
) -> dict:
|
||||
"""Render the built bundle's quest log and report its location.
|
||||
|
||||
@@ -787,6 +852,8 @@ def _render_quest_log(
|
||||
spec["idle_ms"] = idle_ms
|
||||
if probe_ms is not None:
|
||||
spec["probe_ms"] = probe_ms
|
||||
if tap_complete is not None:
|
||||
spec["tap_complete"] = tap_complete
|
||||
completed = subprocess.run(
|
||||
["node", str(QUEST_LOG_HARNESS)],
|
||||
input=json.dumps(spec),
|
||||
@@ -886,3 +953,302 @@ def test_quest_complete_screen_returns_to_the_board_after_the_countdown() -> Non
|
||||
assert result["probe"]["countdown"] == "Returning to The Party in 1 seconds"
|
||||
# …and at zero the card has returned to the party board.
|
||||
assert result["location"] == "/nestquest"
|
||||
|
||||
|
||||
def test_tapping_complete_confirms_and_calls_the_service() -> None:
|
||||
"""Tapping an open quest's Complete opens the confirm dialog, and the
|
||||
dialog's Complete calls nestquest.complete_quest with the panel actor.
|
||||
With ``useDefineForClassFields`` on (the ES2022 default) the card's
|
||||
reactive fields were emitted as native class fields that shadowed
|
||||
Lit's accessors: ``_confirm`` changed but no re-render was scheduled,
|
||||
so the dialog never opened and the tap did nothing."""
|
||||
generated = _generate_dashboard(
|
||||
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
|
||||
)
|
||||
open_quest = {
|
||||
"id": 42,
|
||||
"definition_id": 7,
|
||||
"child_id": 1,
|
||||
"title": "Brush Teeth",
|
||||
"icon": None,
|
||||
"window": "morning",
|
||||
"due_time": "08:15",
|
||||
"state": "open",
|
||||
"overdue": True,
|
||||
"completed_at": None,
|
||||
"on_time": None,
|
||||
}
|
||||
states = {
|
||||
**_three_child_states(),
|
||||
"sensor.nestquest_ada_quests_due_today": _state(
|
||||
"1",
|
||||
child_name="Ada",
|
||||
child_id=1,
|
||||
present=True,
|
||||
instances=[open_quest],
|
||||
),
|
||||
}
|
||||
result = _render_quest_log(
|
||||
generated["views"][1]["cards"][0],
|
||||
states,
|
||||
url="http://homeassistant.local/nestquest/ada",
|
||||
tap_complete=open_quest["id"],
|
||||
)
|
||||
assert result["tap"]["dialog_opened"] is True
|
||||
assert result["tap"]["service_calls"] == [
|
||||
{
|
||||
"domain": "nestquest",
|
||||
"service": "complete_quest",
|
||||
"data": {
|
||||
"instance_id": open_quest["id"],
|
||||
"actor": "panel",
|
||||
"actor_child_id": open_quest["child_id"],
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_card_build_keeps_lit_reactive_accessors() -> None:
|
||||
"""The frontend build must not emit class fields that shadow Lit's
|
||||
reactive property accessors (Lit's documented TypeScript setting)."""
|
||||
tsconfig = json.loads((FRONTEND_DIR / "tsconfig.json").read_text())
|
||||
assert tsconfig["compilerOptions"]["useDefineForClassFields"] is False
|
||||
|
||||
|
||||
def test_quest_log_crest_keeps_its_shield_classes() -> None:
|
||||
"""PANEL-SPEC §3 header crest: a present child's crest renders as the
|
||||
styled shield, not a bare span. Lit removes an attribute outright when
|
||||
any interpolated part of it is ``nothing``, so a class written as
|
||||
``crest${away ? " away" : nothing}`` lost ``crest`` for every present
|
||||
child and the header showed an unstyled sliver. The rendered markup
|
||||
must carry ``class="crest"`` (present) and ``class="crest away"``
|
||||
(away), each wrapping the face and initial."""
|
||||
generated = _generate_dashboard(
|
||||
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
|
||||
)
|
||||
log_config = generated["views"][1]["cards"][0]
|
||||
for slug, crest_class in (("ada", "crest"), ("bo", "crest away")):
|
||||
result = _render_quest_log(
|
||||
log_config,
|
||||
_three_child_states(),
|
||||
url=f"http://homeassistant.local/nestquest/{slug}",
|
||||
)
|
||||
header = result["html"][result["html"].index('<header class="header">') :]
|
||||
crest = re.match(
|
||||
r'<header class="header">\s*(?:<!--[^>]*-->\s*)*<span ([^>]*)>\s*'
|
||||
r'<span class="crest-face">\s*<span class="initial">',
|
||||
header,
|
||||
)
|
||||
assert crest is not None, header[:600]
|
||||
assert f'class="{crest_class}"' in crest.group(1), crest.group(1)
|
||||
|
||||
|
||||
def test_quest_log_meta_line_keeps_its_meta_class() -> None:
|
||||
"""An open quest's meta line is styled by ``.quest .meta`` (and
|
||||
``.quest .meta.late`` when overdue). Written as
|
||||
``meta ${late ? "late" : nothing}``, Lit dropped the whole class
|
||||
attribute for every quest that was not late, leaving the due line
|
||||
unstyled. The rendered markup must carry ``class="meta"`` on time and
|
||||
``class="meta late"`` overdue."""
|
||||
generated = _generate_dashboard(
|
||||
{}, _three_child_states(), url="http://homeassistant.local/nestquest"
|
||||
)
|
||||
|
||||
def quest(instance_id: int, title: str, overdue: bool) -> dict:
|
||||
return {
|
||||
"id": instance_id,
|
||||
"definition_id": instance_id,
|
||||
"child_id": 1,
|
||||
"title": title,
|
||||
"icon": None,
|
||||
"window": "morning",
|
||||
"due_time": "08:15",
|
||||
"state": "open",
|
||||
"overdue": overdue,
|
||||
"completed_at": None,
|
||||
"on_time": None,
|
||||
}
|
||||
|
||||
states = {
|
||||
**_three_child_states(),
|
||||
"sensor.nestquest_ada_quests_due_today": _state(
|
||||
"2",
|
||||
child_name="Ada",
|
||||
child_id=1,
|
||||
present=True,
|
||||
instances=[
|
||||
quest(41, "Make Bed", overdue=False),
|
||||
quest(42, "Brush Teeth", overdue=True),
|
||||
],
|
||||
),
|
||||
}
|
||||
result = _render_quest_log(
|
||||
generated["views"][1]["cards"][0],
|
||||
states,
|
||||
url="http://homeassistant.local/nestquest/ada",
|
||||
)
|
||||
metas = {}
|
||||
for card in result["html"].split('data-instance-id="')[1:]:
|
||||
meta = re.search(
|
||||
r'<span class="quest-title">.*?</span>'
|
||||
r"\s*(?:<!--[^>]*-->\s*)*<span([^>]*)>",
|
||||
card,
|
||||
re.S,
|
||||
)
|
||||
assert meta is not None, card[:800]
|
||||
metas[card[: card.index('"')]] = meta.group(1)
|
||||
assert set(metas) == {"41", "42"}, metas
|
||||
assert metas["41"].strip() == 'class="meta"', metas["41"]
|
||||
assert metas["42"].strip() == 'class="meta late"', metas["42"]
|
||||
|
||||
|
||||
def test_quest_log_crest_matches_the_spec_geometry() -> None:
|
||||
"""PANEL-SPEC §3 header crest: 96x110 shield, 4px ring of
|
||||
rgba(255,255,255,.22) around the --nq-p-crest face, 44px/700 display
|
||||
initial in full-opacity white; away swaps only the face gradient.
|
||||
jsdom cannot lay out, so this pins the stylesheet the rendered test
|
||||
above shows is applied."""
|
||||
source = QUEST_LOG.read_text(encoding="utf-8")
|
||||
|
||||
def rule(selector: str) -> str:
|
||||
found = re.search(
|
||||
r"\n " + re.escape(selector) + r" \{(.*?)\n \}", source, re.DOTALL
|
||||
)
|
||||
assert found is not None, selector
|
||||
return found.group(1)
|
||||
|
||||
crest = rule(".crest")
|
||||
for decl in (
|
||||
"width: 96px;",
|
||||
"height: 110px;",
|
||||
"padding: 4px;",
|
||||
"clip-path: ${unsafeCSS(SHIELD_CLIP)};",
|
||||
"background: rgba(255, 255, 255, 0.22);",
|
||||
):
|
||||
assert decl in crest, decl
|
||||
face = rule(".crest-face")
|
||||
assert "background: var(--nq-p-crest);" in face
|
||||
assert "clip-path: ${unsafeCSS(SHIELD_CLIP)};" in face
|
||||
initial = rule(".crest .initial")
|
||||
for decl in (
|
||||
"font-family: var(--nq-p-font-display);",
|
||||
"font-size: 44px;",
|
||||
"font-weight: 700;",
|
||||
"color: #ffffff;",
|
||||
):
|
||||
assert decl in initial, decl
|
||||
assert "opacity" not in initial
|
||||
away = rule(".crest.away .crest-face")
|
||||
assert away.strip() == "background: var(--nq-p-crest-away);"
|
||||
|
||||
|
||||
# --- Quest card icons (definition icon on the open tile) ---------------------
|
||||
|
||||
|
||||
def _quest_row(instance_id: int, icon: str | None, state: str = "open") -> dict:
|
||||
"""One ``instances`` attribute row for Ada's quests-due sensor."""
|
||||
row = {
|
||||
"id": instance_id,
|
||||
"child_id": 1,
|
||||
"title": f"Quest {instance_id}",
|
||||
"icon": icon,
|
||||
"window": "morning",
|
||||
"due_time": "08:00",
|
||||
"state": state,
|
||||
"overdue": False,
|
||||
"completed_at": None,
|
||||
"on_time": None,
|
||||
}
|
||||
if state == "completed":
|
||||
row["completed_at"] = "2026-09-26T07:30:00+00:00"
|
||||
row["on_time"] = True
|
||||
return row
|
||||
|
||||
|
||||
def _quest_log_tiles(rows: list[dict]) -> dict[int, dict]:
|
||||
"""Render Ada's quest log with ``rows`` and key its tiles by instance id."""
|
||||
states = _three_child_states()
|
||||
states["sensor.nestquest_ada_quests_due_today"] = _state(
|
||||
str(len(rows)), child_name="Ada", present=True, instances=rows
|
||||
)
|
||||
result = _render_quest_log(
|
||||
{"type": "custom:nestquest-quest-log-card"},
|
||||
states,
|
||||
url="http://homeassistant.local/nestquest/ada",
|
||||
)
|
||||
return {tile["id"]: tile for tile in result["tiles"]}
|
||||
|
||||
|
||||
def test_open_quest_tile_renders_the_definition_icon() -> None:
|
||||
"""The open card's tile shows the definition's namespaced icon, drawn
|
||||
from the bundled registry: Lucide as a stroked svg, Font Awesome as a
|
||||
filled svg, an emoji as its text, and a legacy bare name as Lucide."""
|
||||
tiles = _quest_log_tiles(
|
||||
[
|
||||
_quest_row(1, "lucide:bed"),
|
||||
_quest_row(2, "fa:broom"),
|
||||
_quest_row(3, "emoji:🦊"),
|
||||
_quest_row(4, "bath"),
|
||||
]
|
||||
)
|
||||
assert tiles[1]["icon"] == "lucide:bed"
|
||||
assert tiles[1]["fill"] == "none"
|
||||
assert tiles[1]["paths"] > 0
|
||||
assert tiles[2]["icon"] == "fa:broom"
|
||||
assert tiles[2]["fill"] == "currentColor"
|
||||
assert tiles[2]["paths"] > 0
|
||||
assert tiles[3]["icon"] == "emoji:🦊"
|
||||
assert tiles[3]["text"] == "🦊"
|
||||
assert tiles[4]["icon"] == "lucide:bath"
|
||||
assert tiles[4]["fill"] == "none"
|
||||
for tile in tiles.values():
|
||||
assert not tile["sealed"]
|
||||
assert not tile["star"]
|
||||
|
||||
|
||||
def test_open_quest_tile_falls_back_to_the_star() -> None:
|
||||
"""An unknown name, an unknown namespace, or no icon at all keeps the
|
||||
open card's current star glyph."""
|
||||
tiles = _quest_log_tiles(
|
||||
[
|
||||
_quest_row(1, "lucide:not-a-real-icon"),
|
||||
_quest_row(2, "fa:not-a-real-icon"),
|
||||
_quest_row(3, "mdi:bed"),
|
||||
_quest_row(4, ""),
|
||||
_quest_row(5, None),
|
||||
]
|
||||
)
|
||||
assert set(tiles) == {1, 2, 3, 4, 5}
|
||||
for tile in tiles.values():
|
||||
assert tile["star"]
|
||||
assert tile["icon"] is None
|
||||
|
||||
|
||||
def test_sealed_quest_tile_keeps_the_star() -> None:
|
||||
"""A sealed card keeps its star tile (and its wax seal) whatever the
|
||||
definition's icon; only the open card shows the quest's icon."""
|
||||
tiles = _quest_log_tiles(
|
||||
[
|
||||
_quest_row(1, "lucide:bed", state="completed"),
|
||||
_quest_row(2, "fa:broom", state="completed"),
|
||||
_quest_row(3, "emoji:🦊", state="completed"),
|
||||
]
|
||||
)
|
||||
for tile in tiles.values():
|
||||
assert tile["sealed"]
|
||||
assert tile["star"]
|
||||
assert tile["icon"] is None
|
||||
assert tile["text"] == ""
|
||||
|
||||
|
||||
def test_only_the_open_tile_calls_the_icon_resolver() -> None:
|
||||
source = _read(QUEST_LOG)
|
||||
sealed_start = source.index('<div class="quest sealed"')
|
||||
sealed_block = source[sealed_start : source.index("</div>", sealed_start)]
|
||||
assert '<span class="tile" aria-hidden="true">${ICON_STAR}</span>' in sealed_block
|
||||
assert "renderQuestIcon" not in sealed_block
|
||||
assert (
|
||||
source.count("renderQuestIcon(instance.icon, ICON_STAR)") == 1
|
||||
), "only the open card's tile resolves the definition icon"
|
||||
open_start = source.index('class="quest tappable"')
|
||||
assert "renderQuestIcon(instance.icon, ICON_STAR)" in source[open_start:]
|
||||
|
||||
@@ -22,8 +22,10 @@ from custom_components.nestquest.core.db import NestQuestDatabase
|
||||
from custom_components.nestquest.core.migrations import apply_migrations
|
||||
from custom_components.nestquest.core.quest_definitions import (
|
||||
CreatedQuestDefinition,
|
||||
DeletedQuestDefinition,
|
||||
assign_child,
|
||||
create_quest_definition,
|
||||
delete_quest_definition,
|
||||
edit_quest_definition,
|
||||
list_active_definitions,
|
||||
list_definitions_firing_on,
|
||||
@@ -106,13 +108,13 @@ def test_create_one_child_one_window(tmp_path) -> None:
|
||||
[child.id],
|
||||
["morning"],
|
||||
description=" Twice daily ",
|
||||
icon=" mdi:tooth ",
|
||||
icon="lucide:tooth",
|
||||
)
|
||||
assert isinstance(result, CreatedQuestDefinition)
|
||||
definition = result.definition
|
||||
assert definition.title == "Brush teeth"
|
||||
assert definition.description == "Twice daily"
|
||||
assert definition.icon == "mdi:tooth"
|
||||
assert definition.icon == "lucide:tooth"
|
||||
assert definition.is_active is True
|
||||
# D-008: the definition-level due_time column is never set here.
|
||||
assert definition.due_time is None
|
||||
@@ -232,6 +234,89 @@ def test_create_rejects_non_string_title(tmp_path) -> None:
|
||||
_with_db(tmp_path, "create-bad-title-type.db")(_body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("icon", "stored"),
|
||||
[
|
||||
("lucide:dog", "lucide:dog"),
|
||||
("fa:dog", "fa:dog"),
|
||||
("emoji:🐕", "emoji:🐕"),
|
||||
("dog", "lucide:dog"), # legacy bare name: canonical lucide key
|
||||
],
|
||||
)
|
||||
def test_create_stores_canonical_icon(tmp_path, icon, stored) -> None:
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
result = await create_quest_definition(
|
||||
database, "Walk dog", _daily_rule(), [child.id], ["morning"],
|
||||
icon=icon,
|
||||
)
|
||||
assert result.definition.icon == stored
|
||||
row = await definitions.get(result.definition.id)
|
||||
assert row is not None
|
||||
assert row.icon == stored
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "create-icon.db")(_body)
|
||||
|
||||
|
||||
_BAD_ICONS = [
|
||||
"foo:dog",
|
||||
"lucide:",
|
||||
"lucide:Dog",
|
||||
"lucide:has space",
|
||||
"emoji:" + "🐕" * 9,
|
||||
"emoji:a b",
|
||||
"emoji:<b>",
|
||||
"javascript:alert(1)",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", _BAD_ICONS)
|
||||
def test_create_rejects_invalid_icon_and_persists_nothing(tmp_path, bad) -> None:
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
with pytest.raises(ValueError, match=r"^icon\b"):
|
||||
await create_quest_definition(
|
||||
database, "Walk dog", _daily_rule(), [child.id], ["morning"],
|
||||
icon=bad,
|
||||
)
|
||||
assert await definitions.list_active() == []
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "create-bad-icon.db")(_body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", _BAD_ICONS)
|
||||
def test_edit_rejects_invalid_icon_and_changes_nothing(tmp_path, bad) -> None:
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database, "Walk dog", _daily_rule(), [child.id], ["morning"],
|
||||
icon="lucide:dog",
|
||||
)
|
||||
with pytest.raises(ValueError, match=r"^icon\b"):
|
||||
await edit_quest_definition(
|
||||
database, created.definition.id, icon=bad
|
||||
)
|
||||
row = await definitions.get(created.definition.id)
|
||||
assert row is not None
|
||||
assert row.icon == "lucide:dog"
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "edit-bad-icon.db")(_body)
|
||||
|
||||
|
||||
def test_edit_normalizes_legacy_bare_icon(tmp_path) -> None:
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database, "Walk dog", _daily_rule(), [child.id], ["morning"],
|
||||
)
|
||||
result = await edit_quest_definition(
|
||||
database, created.definition.id, icon="dog"
|
||||
)
|
||||
assert result.definition.icon == "lucide:dog"
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "edit-legacy-icon.db")(_body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [None, "daily", 42, {"rule_type": "daily"}])
|
||||
def test_create_rejects_non_schedule_rule(tmp_path, bad) -> None:
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
@@ -535,18 +620,18 @@ def test_edit_title_description_icon(tmp_path) -> None:
|
||||
[child.id],
|
||||
["morning"],
|
||||
description="Old description",
|
||||
icon="mdi:old",
|
||||
icon="lucide:old",
|
||||
)
|
||||
result = await edit_quest_definition(
|
||||
database,
|
||||
created.definition.id,
|
||||
title=" Floss ",
|
||||
description=" New description ",
|
||||
icon=" mdi:new ",
|
||||
icon="fa:new",
|
||||
)
|
||||
assert result.definition.title == "Floss"
|
||||
assert result.definition.description == "New description"
|
||||
assert result.definition.icon == "mdi:new"
|
||||
assert result.definition.icon == "fa:new"
|
||||
# Untouched fields survive the edit unchanged.
|
||||
assert result.definition.id == created.definition.id
|
||||
assert result.definition.schedule_rule_id == created.definition.schedule_rule_id
|
||||
@@ -561,7 +646,7 @@ def test_edit_title_description_icon(tmp_path) -> None:
|
||||
assert stored is not None
|
||||
assert stored.title == "Floss"
|
||||
assert stored.description == "New description"
|
||||
assert stored.icon == "mdi:new"
|
||||
assert stored.icon == "fa:new"
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "edit-metadata.db")(_body)
|
||||
@@ -597,7 +682,7 @@ def test_edit_clears_optional_metadata(tmp_path) -> None:
|
||||
[child.id],
|
||||
["morning"],
|
||||
description="Old",
|
||||
icon="mdi:old",
|
||||
icon="lucide:old",
|
||||
)
|
||||
result = await edit_quest_definition(
|
||||
database,
|
||||
@@ -2043,3 +2128,188 @@ def test_wrappers_forward_horizon_days(tmp_path, mode) -> None:
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, f"wrapper-horizon-{mode}.db")(_body)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# delete_quest_definition: hybrid delete (owner decision 2026-09-26)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
async def _count(database, sql, definition_id) -> int:
|
||||
row = await database.fetch_one(sql, (definition_id,))
|
||||
return row[0]
|
||||
|
||||
|
||||
def test_delete_without_history_hard_deletes_everything(tmp_path) -> None:
|
||||
"""No completion event on any instance: the definition, its
|
||||
instances, assignees, windows and unreferenced rule are all gone."""
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database,
|
||||
"Brush teeth",
|
||||
_daily_rule(),
|
||||
[child.id],
|
||||
["morning", "evening"],
|
||||
)
|
||||
definition_id = created.definition.id
|
||||
rule_id = created.definition.schedule_rule_id
|
||||
instances_sql = (
|
||||
"SELECT COUNT(*) FROM quest_instances WHERE definition_id = ?"
|
||||
)
|
||||
# Create materialized future instances, so the delete has
|
||||
# instance rows to remove (not just an empty table).
|
||||
assert await _count(database, instances_sql, definition_id) > 0
|
||||
|
||||
result = await delete_quest_definition(database, definition_id)
|
||||
|
||||
assert result == DeletedQuestDefinition(
|
||||
definition_id=definition_id,
|
||||
deleted=True,
|
||||
retired=False,
|
||||
definition=None,
|
||||
)
|
||||
assert await definitions.get(definition_id) is None
|
||||
assert await rules.get(rule_id) is None
|
||||
assert await _count(database, instances_sql, definition_id) == 0
|
||||
for table in (
|
||||
"quest_definition_assignees",
|
||||
"quest_definition_windows",
|
||||
):
|
||||
assert await _count(
|
||||
database,
|
||||
f"SELECT COUNT(*) FROM {table} WHERE definition_id = ?",
|
||||
definition_id,
|
||||
) == 0
|
||||
# The child itself is untouched.
|
||||
assert (await children.get(child.id)) is not None
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-no-history.db")(_body)
|
||||
|
||||
|
||||
def test_delete_without_history_keeps_a_shared_rule(tmp_path) -> None:
|
||||
"""The rule is deleted only when no other definition references it."""
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
rule = await rules.create("daily", "2026-09-14")
|
||||
first = await definitions.create(
|
||||
"First", rule.id, NOW, assignee_child_ids=[child.id]
|
||||
)
|
||||
second = await definitions.create(
|
||||
"Second", rule.id, NOW, assignee_child_ids=[child.id]
|
||||
)
|
||||
|
||||
result = await delete_quest_definition(database, first.id)
|
||||
|
||||
assert result.deleted is True
|
||||
assert await definitions.get(first.id) is None
|
||||
assert await definitions.get(second.id) is not None
|
||||
assert await rules.get(rule.id) is not None
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-shared-rule.db")(_body)
|
||||
|
||||
|
||||
def test_delete_with_history_retires_and_preserves_everything(
|
||||
tmp_path,
|
||||
) -> None:
|
||||
"""A completion event on ANY instance: the definition is retired
|
||||
(deactivated) and its row, rule, assignees, windows and completion
|
||||
history all remain. The completed instance survives; only future
|
||||
UNCOMPLETED instances are cleared by the deactivation's regeneration."""
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database, "Brush teeth", _daily_rule(), [child.id], ["morning"]
|
||||
)
|
||||
definition_id = created.definition.id
|
||||
rule_id = created.definition.schedule_rule_id
|
||||
instances = QuestInstancesDao(database)
|
||||
events = CompletionEventsDao(database)
|
||||
instance = await instances.upsert(
|
||||
definition_id, child.id, _today_iso(), NOW, window="morning"
|
||||
)
|
||||
event = await events.append(
|
||||
instance.id,
|
||||
child.id,
|
||||
"completed",
|
||||
"user",
|
||||
NOW,
|
||||
True,
|
||||
actor_user_id="admin-1",
|
||||
)
|
||||
|
||||
result = await delete_quest_definition(database, definition_id)
|
||||
|
||||
assert result.deleted is False
|
||||
assert result.retired is True
|
||||
assert result.definition_id == definition_id
|
||||
assert isinstance(result.definition, CreatedQuestDefinition)
|
||||
assert result.definition.definition.is_active is False
|
||||
stored = await definitions.get(definition_id)
|
||||
assert stored is not None
|
||||
assert stored.is_active is False
|
||||
assert await rules.get(rule_id) is not None
|
||||
assert [c.id for c in await definitions.list_assignees(
|
||||
definition_id
|
||||
)] == [child.id]
|
||||
assert [w.window for w in await definitions.list_windows(
|
||||
definition_id
|
||||
)] == ["morning"]
|
||||
assert await instances.get_by_id(instance.id) == instance
|
||||
assert await events.list_by_instance(instance.id) == [event]
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-with-history.db")(_body)
|
||||
|
||||
|
||||
def test_delete_with_uncompleted_history_still_retires(tmp_path) -> None:
|
||||
"""ANY completion event counts as history — even when the latest
|
||||
event is an un-completion, the definition is retired, not deleted."""
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database, "Brush teeth", _daily_rule(), [child.id], ["morning"]
|
||||
)
|
||||
definition_id = created.definition.id
|
||||
instances = QuestInstancesDao(database)
|
||||
events = CompletionEventsDao(database)
|
||||
instance = await instances.upsert(
|
||||
definition_id, child.id, _today_iso(), NOW, window="morning"
|
||||
)
|
||||
await events.append(
|
||||
instance.id, child.id, "completed", "user", NOW, True,
|
||||
actor_user_id="admin-1",
|
||||
)
|
||||
await events.append(
|
||||
instance.id, child.id, "uncompleted", "user", NOW, None,
|
||||
actor_user_id="admin-1",
|
||||
)
|
||||
|
||||
result = await delete_quest_definition(database, definition_id)
|
||||
|
||||
assert result.retired is True
|
||||
assert await instances.get_by_id(instance.id) == instance
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-uncompleted-history.db")(_body)
|
||||
|
||||
|
||||
def test_delete_nonexistent_definition_names_field(tmp_path) -> None:
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
with pytest.raises(ValueError, match=r"^definition_id:"):
|
||||
await delete_quest_definition(database, 999)
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-missing.db")(_body)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [True, 1.0, "1", None])
|
||||
def test_delete_rejects_non_int_definition_id(tmp_path, bad) -> None:
|
||||
async def _body(database, children, rules, definitions, child):
|
||||
created = await create_quest_definition(
|
||||
database, "Brush teeth", _daily_rule(), [child.id], ["morning"]
|
||||
)
|
||||
with pytest.raises(ValueError, match="definition_id"):
|
||||
await delete_quest_definition(database, bad)
|
||||
assert await definitions.get(created.definition.id) is not None
|
||||
return None
|
||||
|
||||
_with_db(tmp_path, "delete-bad-id.db")(_body)
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"lucide": [
|
||||
{ "name": "bed", "label": "Bed" },
|
||||
{ "name": "bath", "label": "Bath" },
|
||||
{ "name": "shower-head", "label": "Shower" },
|
||||
{ "name": "toilet", "label": "Toilet" },
|
||||
{ "name": "brush", "label": "Brush" },
|
||||
{ "name": "smile", "label": "Smile" },
|
||||
{ "name": "shirt", "label": "Clothes" },
|
||||
{ "name": "washing-machine", "label": "Laundry" },
|
||||
{ "name": "utensils", "label": "Meal" },
|
||||
{ "name": "cooking-pot", "label": "Cooking" },
|
||||
{ "name": "apple", "label": "Snack" },
|
||||
{ "name": "brush-cleaning", "label": "Sweep" },
|
||||
{ "name": "spray-can", "label": "Clean" },
|
||||
{ "name": "trash-2", "label": "Bins" },
|
||||
{ "name": "recycle", "label": "Recycling" },
|
||||
{ "name": "sofa", "label": "Tidy" },
|
||||
{ "name": "house", "label": "Home" },
|
||||
{ "name": "backpack", "label": "School bag" },
|
||||
{ "name": "book-open", "label": "Reading" },
|
||||
{ "name": "pencil", "label": "Homework" },
|
||||
{ "name": "music", "label": "Music" },
|
||||
{ "name": "dog", "label": "Dog" },
|
||||
{ "name": "cat", "label": "Cat" },
|
||||
{ "name": "fish", "label": "Fish" },
|
||||
{ "name": "sprout", "label": "Plants" },
|
||||
{ "name": "droplets", "label": "Water" },
|
||||
{ "name": "bike", "label": "Bike" },
|
||||
{ "name": "volleyball", "label": "Sport" },
|
||||
{ "name": "gamepad-2", "label": "Games" },
|
||||
{ "name": "star", "label": "Star" },
|
||||
{ "name": "heart", "label": "Heart" },
|
||||
{ "name": "sun", "label": "Morning" },
|
||||
{ "name": "moon", "label": "Bedtime" },
|
||||
{ "name": "clock", "label": "Clock" },
|
||||
{ "name": "calendar", "label": "Calendar" },
|
||||
{ "name": "list-checks", "label": "Checklist" }
|
||||
],
|
||||
"fa": [
|
||||
{ "name": "broom", "label": "Sweep" },
|
||||
{ "name": "spray-can-sparkles", "label": "Clean" },
|
||||
{ "name": "bucket", "label": "Mop" },
|
||||
{ "name": "soap", "label": "Wash hands" },
|
||||
{ "name": "sink", "label": "Dishes" },
|
||||
{ "name": "jug-detergent", "label": "Laundry" },
|
||||
{ "name": "socks", "label": "Socks" },
|
||||
{ "name": "shirt", "label": "Clothes" },
|
||||
{ "name": "bed", "label": "Bed" },
|
||||
{ "name": "couch", "label": "Tidy" },
|
||||
{ "name": "bath", "label": "Bath" },
|
||||
{ "name": "tooth", "label": "Teeth" },
|
||||
{ "name": "utensils", "label": "Meal" },
|
||||
{ "name": "bowl-food", "label": "Set the table" },
|
||||
{ "name": "basket-shopping", "label": "Groceries" },
|
||||
{ "name": "trash-can", "label": "Bins" },
|
||||
{ "name": "recycle", "label": "Recycling" },
|
||||
{ "name": "dog", "label": "Dog" },
|
||||
{ "name": "cat", "label": "Cat" },
|
||||
{ "name": "paw", "label": "Pets" },
|
||||
{ "name": "seedling", "label": "Plants" },
|
||||
{ "name": "book", "label": "Reading" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"_comment": "Shared emoji-payload verdicts. tests/test_core_icons.py (validate_icon) and admin/src/icons/registry.test.ts (resolveIcon) both assert every row, so the Python and JS rules cannot diverge silently.",
|
||||
"cases": [
|
||||
{ "payload": "🐕", "valid": true, "why": "plain emoji" },
|
||||
{ "payload": "👨👩👧👦", "valid": true, "why": "ZWJ family (U+200D allowed)" },
|
||||
{ "payload": "⭐⭐⭐⭐⭐⭐⭐⭐", "valid": true, "why": "exactly 8 code points" },
|
||||
{ "payload": "⭐⭐⭐⭐⭐⭐⭐⭐⭐", "valid": false, "why": "9 code points, over the cap" },
|
||||
{ "payload": "", "valid": false, "why": "empty" },
|
||||
{ "payload": "", "valid": false, "why": "U+FEFF BOM alone" },
|
||||
{ "payload": "🐕", "valid": false, "why": "trailing U+FEFF" },
|
||||
{ "payload": "🐕 ", "valid": false, "why": "trailing space" },
|
||||
{ "payload": "a b", "valid": false, "why": "inner space" },
|
||||
{ "payload": "🐕 ", "valid": false, "why": "no-break space" },
|
||||
{ "payload": "🐕 ", "valid": false, "why": "ideographic space" },
|
||||
{ "payload": "🐕
", "valid": false, "why": "line separator" },
|
||||
{ "payload": "🐕\n", "valid": false, "why": "newline" },
|
||||
{ "payload": "🐕\u0000", "valid": false, "why": "NUL control" },
|
||||
{ "payload": "🐕\u0007🐕", "valid": false, "why": "BEL control" },
|
||||
{ "payload": "🐕\u001c", "valid": false, "why": "file-separator control" },
|
||||
{ "payload": "🐕\u0085", "valid": false, "why": "NEL C1 control" },
|
||||
{ "payload": "🐕\u007f", "valid": false, "why": "DEL control" },
|
||||
{ "payload": "<b>", "valid": false, "why": "markup <" },
|
||||
{ "payload": "a>b", "valid": false, "why": "markup >" },
|
||||
{ "payload": "a&b", "valid": false, "why": "entity start &" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* Offline generator for the shared quest-icon registry.
|
||||
*
|
||||
* Reads the curated names + labels in `curated-icons.json` (the one source of
|
||||
* truth), pulls each glyph's SVG path data from locally installed packages in
|
||||
* `admin/node_modules` (lucide-react and @fortawesome/free-solid-svg-icons —
|
||||
* no network), and writes the same TypeScript module into both bundles:
|
||||
*
|
||||
* admin/src/icons/registry.generated.ts
|
||||
* frontend/src/icons/registry.generated.ts
|
||||
*
|
||||
* node tools/icons/generate.mjs # write both artefacts
|
||||
* node tools/icons/generate.mjs --check # exit 1 if either artefact drifted
|
||||
*
|
||||
* Lucide circles, rects and lines are converted to path `d` strings so every
|
||||
* glyph is plain `{ viewBox, paths }` data any renderer can draw.
|
||||
*/
|
||||
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
|
||||
const HERE = dirname(fileURLToPath(import.meta.url));
|
||||
export const REPO_ROOT = join(HERE, "..", "..");
|
||||
export const SOURCE_PATH = join(HERE, "curated-icons.json");
|
||||
export const OUTPUT_PATHS = [
|
||||
join(REPO_ROOT, "admin", "src", "icons", "registry.generated.ts"),
|
||||
join(REPO_ROOT, "frontend", "src", "icons", "registry.generated.ts"),
|
||||
];
|
||||
|
||||
const ADMIN_MODULES = join(REPO_ROOT, "admin", "node_modules");
|
||||
const LUCIDE_ICON_DIR = join(ADMIN_MODULES, "lucide-react", "dist", "esm", "icons");
|
||||
const requireFromAdmin = createRequire(join(REPO_ROOT, "admin", "package.json"));
|
||||
|
||||
function packageVersion(name) {
|
||||
const pkg = JSON.parse(readFileSync(join(ADMIN_MODULES, name, "package.json"), "utf8"));
|
||||
return pkg.version;
|
||||
}
|
||||
|
||||
function num(value, what) {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) throw new Error(`${what}: not a number: ${value}`);
|
||||
return n;
|
||||
}
|
||||
|
||||
/** One Lucide icon-node element as a path `d` string. */
|
||||
function elementToPath(tag, attrs, icon) {
|
||||
const where = `lucide ${icon} <${tag}>`;
|
||||
const known = { path: ["d"], circle: ["cx", "cy", "r"], rect: ["x", "y", "width", "height", "rx", "ry"], line: ["x1", "y1", "x2", "y2"] };
|
||||
if (!(tag in known)) throw new Error(`${where}: unsupported element`);
|
||||
for (const attr of Object.keys(attrs)) {
|
||||
if (attr !== "key" && !known[tag].includes(attr)) throw new Error(`${where}: unsupported attribute ${attr}`);
|
||||
}
|
||||
if (tag === "path") return attrs.d;
|
||||
if (tag === "line") {
|
||||
return `M${num(attrs.x1, where)} ${num(attrs.y1, where)}L${num(attrs.x2, where)} ${num(attrs.y2, where)}`;
|
||||
}
|
||||
if (tag === "circle") {
|
||||
const [cx, cy, r] = [num(attrs.cx, where), num(attrs.cy, where), num(attrs.r, where)];
|
||||
return `M${cx - r} ${cy}a${r} ${r} 0 1 0 ${2 * r} 0a${r} ${r} 0 1 0 ${-2 * r} 0`;
|
||||
}
|
||||
const [x, y, w, h] = [num(attrs.x ?? 0, where), num(attrs.y ?? 0, where), num(attrs.width, where), num(attrs.height, where)];
|
||||
const rxRaw = attrs.rx ?? attrs.ry;
|
||||
const ryRaw = attrs.ry ?? attrs.rx;
|
||||
const rx = Math.min(rxRaw === undefined ? 0 : num(rxRaw, where), w / 2);
|
||||
const ry = Math.min(ryRaw === undefined ? 0 : num(ryRaw, where), h / 2);
|
||||
if (rx === 0 || ry === 0) return `M${x} ${y}h${w}v${h}h${-w}z`;
|
||||
const iw = w - 2 * rx;
|
||||
const ih = h - 2 * ry;
|
||||
return (
|
||||
`M${x + rx} ${y}h${iw}a${rx} ${ry} 0 0 1 ${rx} ${ry}v${ih}` +
|
||||
`a${rx} ${ry} 0 0 1 ${-rx} ${ry}h${-iw}a${rx} ${ry} 0 0 1 ${-rx} ${-ry}` +
|
||||
`v${-ih}a${rx} ${ry} 0 0 1 ${rx} ${-ry}z`
|
||||
);
|
||||
}
|
||||
|
||||
/** A Lucide icon's node list; follows lucide-react's alias re-exports (smile → face-slightly-smiling). */
|
||||
async function lucideNode(name, seen = []) {
|
||||
if (seen.includes(name)) throw new Error(`lucide ${name}: alias cycle ${seen.join(" -> ")}`);
|
||||
const file = join(LUCIDE_ICON_DIR, `${name}.mjs`);
|
||||
const mod = await import(pathToFileURL(file).href);
|
||||
if (mod.__iconData) return mod.__iconData.node;
|
||||
const alias = /export \{ default \} from '\.\/([a-z0-9-]+)\.mjs';/.exec(readFileSync(file, "utf8"));
|
||||
if (!alias) throw new Error(`lucide ${name}: no icon data in ${file}`);
|
||||
return lucideNode(alias[1], [...seen, name]);
|
||||
}
|
||||
|
||||
function faExportName(name) {
|
||||
return "fa" + name.split("-").map((part) => part[0].toUpperCase() + part.slice(1)).join("");
|
||||
}
|
||||
|
||||
function checkCurated(list, namespace) {
|
||||
const seen = new Set();
|
||||
for (const { name, label } of list) {
|
||||
if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(name)) throw new Error(`${namespace}:${name}: not a kebab name`);
|
||||
if (typeof label !== "string" || !label.trim()) throw new Error(`${namespace}:${name}: missing label`);
|
||||
if (seen.has(name)) throw new Error(`${namespace}:${name}: duplicate`);
|
||||
seen.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
async function buildEntries() {
|
||||
const curated = JSON.parse(readFileSync(SOURCE_PATH, "utf8"));
|
||||
checkCurated(curated.lucide, "lucide");
|
||||
checkCurated(curated.fa, "fa");
|
||||
|
||||
const lucide = [];
|
||||
for (const { name, label } of curated.lucide) {
|
||||
const node = await lucideNode(name);
|
||||
const paths = node.map(([tag, attrs]) => elementToPath(tag, attrs, name));
|
||||
lucide.push({ kind: "lucide", key: `lucide:${name}`, name, label, viewBox: "0 0 24 24", paths });
|
||||
}
|
||||
|
||||
const faPackage = requireFromAdmin("@fortawesome/free-solid-svg-icons");
|
||||
const fa = [];
|
||||
for (const { name, label } of curated.fa) {
|
||||
const definition = faPackage[faExportName(name)];
|
||||
if (!definition || definition.iconName !== name) throw new Error(`fa ${name}: not in @fortawesome/free-solid-svg-icons`);
|
||||
const [width, height, , , pathData] = definition.icon;
|
||||
const paths = Array.isArray(pathData) ? pathData.filter(Boolean) : [pathData];
|
||||
fa.push({ kind: "fa", key: `fa:${name}`, name, label, viewBox: `0 0 ${width} ${height}`, paths });
|
||||
}
|
||||
return { lucide, fa };
|
||||
}
|
||||
|
||||
const RESOLVER = `
|
||||
export const FALLBACK_ICON: FallbackIcon = { kind: "fallback", key: null };
|
||||
|
||||
/** Mirrors core/icons.py EMOJI_MAX_CODE_POINTS. */
|
||||
export const EMOJI_MAX_CODE_POINTS = 8;
|
||||
|
||||
const LUCIDE_BY_NAME: ReadonlyMap<string, GlyphIcon> = new Map(LUCIDE_ICONS.map((icon) => [icon.name, icon]));
|
||||
const FA_BY_NAME: ReadonlyMap<string, GlyphIcon> = new Map(FA_ICONS.map((icon) => [icon.name, icon]));
|
||||
|
||||
function isEmojiPayload(text: string): boolean {
|
||||
const codePoints = [...text];
|
||||
if (codePoints.length === 0 || codePoints.length > EMOJI_MAX_CODE_POINTS) return false;
|
||||
return !codePoints.some((char) => /[\\s<>&]|\\p{Cc}/u.test(char));
|
||||
}
|
||||
|
||||
/**
|
||||
* The renderable icon for a stored definition \`icon\` value.
|
||||
*
|
||||
* \`lucide:<name>\` and a legacy bare \`<name>\` resolve against the curated
|
||||
* Lucide set, \`fa:<name>\` against the curated Font Awesome set, and
|
||||
* \`emoji:<grapheme>\` to its text. Like the backend's
|
||||
* normalize_icon_for_read, nothing here throws: null, empty, an unknown
|
||||
* namespace or name, or a malformed emoji all resolve to FALLBACK_ICON.
|
||||
*/
|
||||
export function resolveIcon(value: string | null | undefined): ResolvedIcon {
|
||||
if (!value || !value.trim()) return FALLBACK_ICON;
|
||||
const colon = value.indexOf(":");
|
||||
if (colon === -1) return LUCIDE_BY_NAME.get(value) ?? FALLBACK_ICON;
|
||||
const namespace = value.slice(0, colon);
|
||||
const name = value.slice(colon + 1);
|
||||
if (namespace === "lucide") return LUCIDE_BY_NAME.get(name) ?? FALLBACK_ICON;
|
||||
if (namespace === "fa") return FA_BY_NAME.get(name) ?? FALLBACK_ICON;
|
||||
if (namespace === "emoji" && isEmojiPayload(name)) return { kind: "emoji", key: value, text: name };
|
||||
return FALLBACK_ICON;
|
||||
}
|
||||
`;
|
||||
|
||||
/** The generated module's full text (identical for both bundles). */
|
||||
export async function renderRegistry() {
|
||||
const { lucide, fa } = await buildEntries();
|
||||
const source = relative(REPO_ROOT, SOURCE_PATH);
|
||||
return `// GENERATED by tools/icons/generate.mjs from ${source} — do not edit.
|
||||
// Regenerate with \`node tools/icons/generate.mjs\` (the drift tests fail if this
|
||||
// file differs from a fresh generation).
|
||||
//
|
||||
// Glyph path data is embedded at generation time; nothing is fetched at runtime.
|
||||
// Lucide glyphs: lucide-react ${packageVersion("lucide-react")} (ISC licence).
|
||||
// Font Awesome glyphs: @fortawesome/free-solid-svg-icons ${packageVersion("@fortawesome/free-solid-svg-icons")}
|
||||
// (Font Awesome Free, icons under CC BY 4.0).
|
||||
|
||||
/** A vector glyph: draw each path in \`paths\` inside an <svg viewBox>. Lucide
|
||||
* glyphs are stroked (fill none, stroke-width 2, round caps and joins);
|
||||
* Font Awesome glyphs are filled. */
|
||||
export interface GlyphIcon {
|
||||
kind: "lucide" | "fa";
|
||||
key: string;
|
||||
name: string;
|
||||
label: string;
|
||||
viewBox: string;
|
||||
paths: readonly string[];
|
||||
}
|
||||
|
||||
/** An emoji icon; render \`text\` as text. */
|
||||
export interface EmojiIcon {
|
||||
kind: "emoji";
|
||||
key: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** No usable icon: the caller draws its own default glyph. */
|
||||
export interface FallbackIcon {
|
||||
kind: "fallback";
|
||||
key: null;
|
||||
}
|
||||
|
||||
export type ResolvedIcon = GlyphIcon | EmojiIcon | FallbackIcon;
|
||||
|
||||
export const LUCIDE_ICONS: readonly GlyphIcon[] = ${JSON.stringify(lucide, null, 2)};
|
||||
|
||||
export const FA_ICONS: readonly GlyphIcon[] = ${JSON.stringify(fa, null, 2)};
|
||||
${RESOLVER}`;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const check = process.argv.includes("--check");
|
||||
const text = await renderRegistry();
|
||||
let drifted = false;
|
||||
for (const path of OUTPUT_PATHS) {
|
||||
const shown = relative(REPO_ROOT, path);
|
||||
if (check) {
|
||||
let current = null;
|
||||
try {
|
||||
current = readFileSync(path, "utf8");
|
||||
} catch {
|
||||
// missing counts as drift
|
||||
}
|
||||
if (current !== text) {
|
||||
drifted = true;
|
||||
console.error(`drift: ${shown} differs from a fresh generation`);
|
||||
}
|
||||
} else {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, text);
|
||||
console.log(`wrote ${shown}`);
|
||||
}
|
||||
}
|
||||
if (drifted) {
|
||||
console.error("run `node tools/icons/generate.mjs` and commit the result");
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
await main();
|
||||
}
|
||||
Reference in New Issue
Block a user