diff --git a/AGENTS.md b/AGENTS.md
index 118c7662..dd9f90b3 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -70,7 +70,7 @@ Treat scripts, imported ZIPs, Gallery content, Skills, plugin manifests, network
- Swift: 4-space indentation, Xcode defaults, `UpperCamelCase` types and `lowerCamelCase` members. Prefer small SwiftUI views, modern Observation for new state models where deployment allows, stable `ForEach` identity, and accessibility labels for icon-only controls.
- JavaScript/React: 2-space indentation, `UpperCamelCase` components and `lowerCamelCase` functions. Match surrounding formatting; avoid unrelated whole-file rewrites.
-- Runtime examples: keep `main.jsx` UTF-8, deterministic, within runtime budgets, and compatible with their declared permissions/hosts/plugins.
+- Runtime examples: keep `main.jsx` UTF-8, deterministic, within runtime budgets, and compatible with their declared permissions/hosts/plugins. They are formatted with Prettier (`Editor/editorfe/node_modules/.bin/prettier --no-config --print-width 100`) and commented for a reader who is new to ScriptWidget; a text with two spaces in a row must be written as a string in braces, because the formatter joins them.
- Xcode projects use explicit file references. When adding shared Swift sources, add them to every app/widget/test target that compiles or references them, then lint both `.pbxproj` files with `plutil -lint`.
- Preserve user-authored or unrelated dirty-worktree changes. Generated editor bundles are the exception only when deliberately rebuilt from matching frontend source.
diff --git a/Android/app/src/main/assets/Script.android/android/Automation Counter/main.jsx b/Android/app/src/main/assets/Script.android/android/Automation Counter/main.jsx
index 029ec5a7..3d781cc5 100644
--- a/Android/app/src/main/assets/Script.android/android/Automation Counter/main.jsx
+++ b/Android/app/src/main/assets/Script.android/android/Automation Counter/main.jsx
@@ -1,40 +1,70 @@
// A counter with two declared actions. The buttons run them, and so can
// another app: on Android turn on Settings > Automation, allow this package,
// and send the "increment" or "reset" action from Tasker or a similar app.
-const valueKey = "counter.value", sourceKey = "counter.source";
+// The actions and their functions are declared under "actions" in widget.json, which
+// also lists the "storage" permission that $storage needs.
+// Try: change the step in increment(), or add a third action here and in widget.json.
+// The keys under which $storage, the small store of this package, keeps the two values.
+const valueKey = "counter.value",
+ sourceKey = "counter.source";
+// The count is stored as text. If the text is not a number, start again from 0.
function read() {
const value = Number($storage.getString(valueKey));
return Number.isFinite(value) ? value : 0;
}
+// Save the new count and what caused the change.
function write(value) {
$storage.setString(valueKey, String(value));
// "widget" for a tap, "shortcut" for an app shortcut, "automation" for another app.
$storage.setString(sourceKey, $getenv("action-source"));
$render({"Count " + value});
}
-function increment() { write(read() + 1); }
-function reset() { write(0); }
+// These two names are the "function" values of the actions in widget.json.
+function increment() {
+ write(read() + 1);
+}
+function reset() {
+ write(0);
+}
+// For a widget this is "small", "medium" or "large". "action" and "function" mean the
+// script was started to run an action, not to draw the widget.
const size = $getenv("widget-size");
if (size === "action" || size === "function") {
// The host calls the declared function after this script was evaluated.
} else {
+ // Empty text until the count was changed for the first time.
const source = $storage.getString(sourceKey);
// A small widget has room for the icons only.
const small = size === "small";
+ // One button. actionID names an action declared in widget.json.
const control = (id, symbol, title) => (
-
+
);
+ // Draw the widget. frame="max" makes the stack fill it. Colors named material.
+ // follow the Android wallpaper.
$render(
- Counter
- {String(read())}
- {source ? "Changed by " + source : "Not changed yet"}
+
+ Counter
+
+
+ {String(read())}
+
+
+ {source ? "Changed by " + source : "Not changed yet"}
+
{control("increment", "plus.circle.fill", "Add one")}
{control("reset", "arrow.counterclockwise", "Reset")}
-
+ ,
);
}
diff --git a/Android/app/src/main/assets/Script.android/android/Scrolling Checklist/main.jsx b/Android/app/src/main/assets/Script.android/android/Scrolling Checklist/main.jsx
index 7d27671c..1190cf15 100644
--- a/Android/app/src/main/assets/Script.android/android/Scrolling Checklist/main.jsx
+++ b/Android/app/src/main/assets/Script.android/android/Scrolling Checklist/main.jsx
@@ -1,34 +1,79 @@
// A list that scrolls inside the widget, which only Android can do.
// Every row is a toggle that keeps its own state in package storage.
// iPhone widgets cannot scroll, so the first rows are shown there.
+// $storage needs the "storage" permission, which widget.json lists.
+// Try: change the texts in items, or the number of rows shown without a list.
const items = [
- "Water the plants", "Reply to Sam", "Book the dentist", "Renew the library card", "Back up the photos",
- "Order printer ink", "Call the plumber", "Pay the electricity bill", "Plan the weekend trip", "Clean the keyboard",
- "Update the budget", "Return the parcel", "Charge the camera", "Sort the bookshelf", "Write to grandma",
- "Check the tire pressure", "Buy a birthday card", "Defrost the freezer", "Review the notes", "Stretch for ten minutes",
+ "Water the plants",
+ "Reply to Sam",
+ "Book the dentist",
+ "Renew the library card",
+ "Back up the photos",
+ "Order printer ink",
+ "Call the plumber",
+ "Pay the electricity bill",
+ "Plan the weekend trip",
+ "Clean the keyboard",
+ "Update the budget",
+ "Return the parcel",
+ "Charge the camera",
+ "Sort the bookshelf",
+ "Write to grandma",
+ "Check the tire pressure",
+ "Buy a birthday card",
+ "Defrost the freezer",
+ "Review the notes",
+ "Stretch for ten minutes",
];
+// $system.platform() says where the script runs. Only "android" has .
const android = $system.platform() === "android";
const size = $getenv("widget-size");
+// One stored value per row: the text "true" when the row is checked.
const done = items.map((_, index) => $storage.getString("check." + index) === "true");
const count = done.filter(Boolean).length;
+// One row. stateKey is the $storage key that holds the state of this toggle.
+// A checked row gets the quieter text color.
const row = (title, index) => (
- {title}
+
+ {title}
+
);
-const rows = android
- ? {items.map(row)}
- : {items.slice(0, size === "large" ? 7 : 2).map(row)};
+// Android: every row, in a list that scrolls. Elsewhere is unknown, so show the
+// first 7 rows in a large widget and the first 2 in the other sizes.
+const rows = android ? (
+ {items.map(row)}
+) : (
+
+ {items.slice(0, size === "large" ? 7 : 2).map(row)}
+
+);
+// frame="max,topLeading" fills the widget and puts the content in the top left corner.
$render(
-
+
+ {/* The title on the left and "3 of 20" on the right; pushes them apart. */}
- Checklist
+
+ Checklist
+
- {count + " of " + items.length}
+
+ {count + " of " + items.length}
+
{rows}
-
+ ,
);
diff --git a/Android/app/src/main/assets/Script.android/android/Wallpaper Colors/main.jsx b/Android/app/src/main/assets/Script.android/android/Wallpaper Colors/main.jsx
index 06cf4985..2869fe4a 100644
--- a/Android/app/src/main/assets/Script.android/android/Wallpaper Colors/main.jsx
+++ b/Android/app/src/main/assets/Script.android/android/Wallpaper Colors/main.jsx
@@ -2,23 +2,50 @@
// "material." in any color prop and the widget follows the wallpaper,
// in light and in dark mode. iPhone does not know these names and keeps its
// default colors.
+// Try: replace a role in the list with another one, such as "surfaceVariant" or "outline".
+// Used only for the last line of text, which says where the widget runs.
const android = $system.platform() === "android";
+// A small widget gets shorter texts.
const small = $getenv("widget-size") === "small";
-const roles = ["primary", "secondary", "tertiary", "primaryContainer", "secondaryContainer", "tertiaryContainer"];
+// The roles shown as color swatches.
+const roles = [
+ "primary",
+ "secondary",
+ "tertiary",
+ "primaryContainer",
+ "secondaryContainer",
+ "tertiaryContainer",
+];
+// frame="max,topLeading" fills the widget and puts the content in the top left corner.
$render(
-
- {small ? "Wallpaper" : "Wallpaper colors"}
+
+
+ {small ? "Wallpaper" : "Wallpaper colors"}
+
+ {/* One swatch per role. frame="max,26": as wide as possible and 26 points high. */}
- {roles.map((role) => )}
+ {roles.map((role) => (
+
+ ))}
+ {/* A card in a container color. Its text uses the matching "on" color to stay readable. */}
- {small ? "Follows it" : "Change the wallpaper and this card follows."}
+
+ {small ? "Follows it" : "Change the wallpaper and this card follows."}
+
+ {/* takes the free room, so the last line sits at the bottom. */}
{android ? (small ? "Material colors" : "Material colors of this phone") : "Android only"}
-
+ ,
);
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bb14c639..4ed29757 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,8 @@ Notable user-visible changes are recorded here. ScriptWidget follows semantic ve
- Fix bundled templates whose text was cut off or pushed out of the widget, most visibly with the wider font of Android, Windows and Linux: Month Calendar (long month names, six-week months), the Daily Command Center, Family Command Board, Travel Day and Wellness dashboards, World Clock Faces and Year in Dots at the extra-large size, and fifteen smaller templates.
- Give 21 bundled templates that had one layout a small-widget layout showing their essential content (clocks, battery, focus, reading, sleep, system and the five dashboards), give the Daily Command Center, Family Command Board, Monthly Budget, Travel Day and Wellness dashboards a medium layout, and fix the overlapping rows of the large Monthly Budget Planner and the cut-off header of the medium Personal Dashboard.
- Fix Text Year Days Left, which counted to 31 January of the next year and so showed 31 days too many.
+- Format every bundled example with Prettier and add comments for readers new to ScriptWidget; no example draws anything different.
+- Linux 0.1.4: the management window lists Components and APIs as their own sidebar entries, as on Windows.
- Continue expanded personal-data APIs, authenticated services/music and visual editing on the same release branch; M3–M5 remain in progress.
## Unreleased
diff --git a/Editor/editorfe/scripts/generate-api-docs.mjs b/Editor/editorfe/scripts/generate-api-docs.mjs
index ea61cc4f..6dfe3e64 100644
--- a/Editor/editorfe/scripts/generate-api-docs.mjs
+++ b/Editor/editorfe/scripts/generate-api-docs.mjs
@@ -1,7 +1,13 @@
import { readFile, writeFile } from "node:fs/promises";
import { scriptWidgetAPI as api } from "../src/scriptWidgetAPI.js";
import { dataAPICatalog } from "../src/dataAPICatalog.js";
-import { platformCell, platformColumns, platformRow, platformSentence, platformSupport } from "../src/platformSupport.js";
+import { componentSupport, platformCell, platformColumns, platformRow, platformSentence, platformSupport } from "../src/platformSupport.js";
+
+const componentTable = [
+ `| Component | ${platformColumns.map((column) => column.title).join(" | ")} |`,
+ `| --- | ${platformColumns.map(() => "---").join(" | ")} |`,
+ ...componentSupport.map((row) => `| ${row.label ?? row.components.map((name) => `\`${name}\``).join(", ")} | ${platformColumns.map((column) => platformCell(row[column.id])).join(" | ")} |`),
+];
const outputURL = new URL("../../../docs/scriptwidget-runtime-api.md", import.meta.url);
@@ -10,6 +16,12 @@ const lines = [
"",
`> Generated from Studio's static API metadata (schema v${api.schemaVersion}, runtime ${api.runtimeVersion}). The native runtime switch is authoritative. Do not edit by hand.`,
"",
+ "## Which systems each component runs on",
+ "",
+ "Every component below exists on iPhone, iPad, Mac, Android, Windows and Linux, except the scrolling ``, which only Android has and which is not in this reference (see [ScriptWidget for Android](android/README.md)). What a system draws differently is in this table; [Platform support](platform-support.md) has the same table beside the APIs and the widget features.",
+ "",
+ ...componentTable,
+ "",
"## Components",
"",
];
@@ -80,16 +92,16 @@ function runsOn(apis) {
}
// Replaces what is between the two markers of a hand-written page.
-async function writeBetweenMarkers(file, content) {
+async function writeBetweenMarkers(file, content, start = "", end = "") {
const url = new URL(`../../../docs/${file}`, import.meta.url);
const text = await readFile(url, "utf8");
- const start = "", end = "";
const from = text.indexOf(start), to = text.indexOf(end);
- if (from < 0 || to < from) throw new Error(`docs/${file} has no platforms markers`);
+ if (from < 0 || to < from) throw new Error(`docs/${file} has no ${start} marker`);
await writeFile(url, `${text.slice(0, from + start.length)}\n${content.join("\n")}\n${text.slice(to)}`);
}
await writeBetweenMarkers("platform-support.md", platformTable);
+await writeBetweenMarkers("platform-support.md", componentTable, "", "");
await writeBetweenMarkers("runtime-api.md", platformTable);
for (const [file, apis] of Object.entries({
"calendar-api.md": ["$calendar"],
diff --git a/Editor/editorfe/src/platformSupport.js b/Editor/editorfe/src/platformSupport.js
index af59ecb9..90793a4b 100644
--- a/Editor/editorfe/src/platformSupport.js
+++ b/Editor/editorfe/src/platformSupport.js
@@ -58,3 +58,25 @@ export function platformSentence(row) {
}
return { yes: yes.join(", "), no: no.join(", ") };
}
+
+// The same for the JSX components. Android, Windows and Linux draw with one
+// shared renderer, so a component exists on all three or on none; what differs
+// is listed here. The authorities are docs/public-animations.md for the Apple
+// columns and the "Differences" tables of docs/android, docs/windows and
+// docs/linux for the others.
+const lookAlike = "Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder";
+export const componentSupport = [
+ { components: ["", "", "", "", "", "", ""], label: "Layout: ``, ``, ``, ``, ``, ``, ``", ...everywhere },
+ { components: ["", "',' New text'));
+ // In code with a layer a line, the new layer gets a line at its neighbours' indentation.
+ assert.equal(added,source.replace(' ',' New text\n '));
const next = parseVisualLayout(added), last = next.nodes.at(-1);
assert.equal(apply(next,{type:"remove",id:last.id}),source);
assert.throws(()=>apply(model,{type:"add",id:root,kind:''}),/Unsupported/);
diff --git a/Editor/editorfe/test/visualLayoutFormatted.test.js b/Editor/editorfe/test/visualLayoutFormatted.test.js
new file mode 100644
index 00000000..d945cdb6
--- /dev/null
+++ b/Editor/editorfe/test/visualLayoutFormatted.test.js
@@ -0,0 +1,162 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseVisualLayout, editVisualLayout } from "../src/visualLayout.js";
+
+// Code as a formatter writes it: the element on lines of its own, a comma
+// after it, a comment child, and a text on its own line.
+const formatted = `// A comment above.
+$render(
+ // A comment beside the element.
+
+ {/* A comment child. */}
+
+ Hello
+
+
+ ,
+);
+`;
+
+function apply(source, edit) {
+ let next = source;
+ for (const change of [...edit.changes].reverse()) next = next.slice(0, change.from) + change.insert + next.slice(change.to);
+ return next;
+}
+
+test("formatted code opens in Layout: trailing comma, comments and text on its own line", () => {
+ const model = parseVisualLayout(formatted);
+ assert.equal(model.issue, "");
+ assert.deepEqual(model.nodes.map(node => node.tag), ["vstack", "text", "spacer"]);
+ const [stack, text] = model.nodes;
+ assert.equal(stack.structure, true);
+ assert.equal(text.text, "Hello");
+ assert.equal(text.textEditable, true);
+ // Ranges are those of the real source, not of the copy that was parsed.
+ assert.equal(formatted.slice(text.from, text.to).startsWith(''), true);
+});
+
+test("edits of formatted code keep the comments and stay inside Layout", () => {
+ const model = parseVisualLayout(formatted), [stack, text, spacer] = model.nodes;
+ const renamed = apply(formatted, editVisualLayout(model, formatted, { type: "text", id: text.id, value: "Bye" }));
+ assert.match(renamed, /\{"Bye"\}<\/text>/);
+ assert.match(renamed, /\{\/\* A comment child\. \*\/\}/);
+ assert.equal(parseVisualLayout(renamed).nodes[1].text, "Bye");
+
+ const moved = apply(formatted, editVisualLayout(model, formatted, { type: "move", id: spacer.id, parentID: stack.id, index: 0 }));
+ assert.deepEqual(parseVisualLayout(moved).nodes.map(node => node.tag), ["vstack", "spacer", "text"]);
+ assert.match(moved, /\{\/\* A comment child\. \*\/\}/);
+
+ const property = apply(formatted, editVisualLayout(model, formatted, { type: "property", id: text.id, name: "font", value: "title" }));
+ assert.match(property, //);
+});
+
+test("what is not a comment child is still refused or left alone", () => {
+ // A second argument is not a trailing comma.
+ assert.notEqual(parseVisualLayout("$render(, 1);").issue, "");
+ // A real expression child still makes the container code-only.
+ const dynamic = parseVisualLayout("$render({items});");
+ assert.equal(dynamic.nodes[0].structure, false);
+ // Text over several lines is not one text.
+ const lines = parseVisualLayout("$render(\n one\n two\n);");
+ assert.equal(lines.nodes[0].textEditable, false);
+ // A broken script is still reported.
+ assert.match(parseVisualLayout("$render();").issue, /syntax|Layout needs|match/i);
+ // The text of a comment-like string is read from the real source.
+ const quoted = parseVisualLayout('$render({"{/* x */}"});');
+ assert.equal(quoted.nodes[0].text, "{/* x */}");
+});
+
+test("the bundled examples open in Layout as often as before they were formatted", () => {
+ const bundle = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../Shared/ScriptWidgetRuntime/Resource/Script.bundle");
+ let opened = 0, total = 0;
+ const refused = [];
+ for (const group of ["api", "component", "template"]) {
+ for (const name of fs.readdirSync(path.join(bundle, group))) {
+ const file = path.join(bundle, group, name, "main.jsx");
+ if (!fs.existsSync(file)) continue;
+ total += 1;
+ const model = parseVisualLayout(fs.readFileSync(file, "utf8"));
+ if (model.issue) refused.push(`${group}/${name}`); else opened += 1;
+ }
+ }
+ // 136 of 140 opened before the examples were formatted and commented.
+ assert.ok(total >= 140, `${total} examples`);
+ assert.ok(opened >= total - 4, `only ${opened} of ${total} open; refused: ${refused.join(", ")}`);
+});
+
+const commented = `$render(
+
+ {/* The title. */}
+
+ Hello
+
+
+ {/* Two lines
+ about the row. */}
+
+ {/* unit */}km
+
+
+
+ ,
+);
+`;
+
+// Every layer is selected where the edit says it is.
+function selected(source, edit) {
+ const next = apply(source, edit), model = parseVisualLayout(next);
+ assert.equal(model.issue, "");
+ assert.ok(model.nodes.some(node => node.from === edit.selectedFrom), "the selection is not a layer");
+ return next;
+}
+
+test("a moved or removed layer takes the comment above it and its lines", () => {
+ const model = parseVisualLayout(commented), [stack, title, row, unit, innerSpacer, lastSpacer] = model.nodes;
+ assert.deepEqual([title.outerFrom < title.from, row.outerFrom < row.from, lastSpacer.outerFrom === lastSpacer.from], [true, true, true]);
+
+ const removed = apply(commented, editVisualLayout(model, commented, { type: "remove", id: title.id }));
+ assert.equal(removed.includes("The title."), false);
+ assert.equal(removed, commented.replace(' {/* The title. */}\n \n Hello\n \n', ""));
+
+ // The row and its two-line comment go above the title, one layer a line.
+ const moved = selected(commented, editVisualLayout(model, commented, { type: "move", id: row.id, parentID: stack.id, index: 0 }));
+ assert.ok(moved.indexOf("about the row.") < moved.indexOf("The title."));
+ assert.ok(moved.indexOf("about the row.") < moved.indexOf("\n/);
+ assert.match(moved, / <\/hstack>\n \{\/\* The title\. \*\/\}\n /);
+ assert.equal(/\n[ \t]+\n/.test(moved), false, "a line of only spaces was left");
+
+ // To the end: on its own line before the closing tag.
+ const toEnd = selected(commented, editVisualLayout(model, commented, { type: "move", id: title.id, parentID: stack.id, index: 2 }));
+ assert.match(toEnd, / \n \{\/\* The title\. \*\/\}\n \n Hello\n <\/text>\n <\/vstack>,/);
+
+ // Into a deeper container: the lines are indented for their new place.
+ const deeper = selected(commented, editVisualLayout(model, commented, { type: "move", id: title.id, parentID: row.id, index: 1 }));
+ assert.match(deeper, / \{\/\* The title\. \*\/\}\n \n Hello\n <\/text>\n \n <\/hstack>/);
+
+ // Moving a layer to where it already is changes nothing.
+ assert.deepEqual(editVisualLayout(model, commented, { type: "move", id: row.id, parentID: stack.id, index: 1 }).changes, []);
+});
+
+test("a new layer gets a line of its own, and code on one line stays on one line", () => {
+ const model = parseVisualLayout(commented), [stack, , row] = model.nodes;
+ const added = selected(commented, editVisualLayout(model, commented, { type: "add", id: row.id, kind: "spacer" }));
+ assert.match(added, / \n \n <\/hstack>/);
+ const outer = selected(commented, editVisualLayout(model, commented, { type: "add", id: stack.id, kind: "text" }));
+ assert.match(outer, / \n New text<\/text>\n <\/vstack>,/);
+
+ const oneLine = "$render(Hi);";
+ const flat = parseVisualLayout(oneLine);
+ assert.equal(apply(oneLine, editVisualLayout(flat, oneLine, { type: "add", id: flat.nodes[0].id, kind: "spacer" })), "$render(Hi);");
+});
+
+test("editing a text keeps a comment written inside it", () => {
+ const model = parseVisualLayout(commented), unit = model.nodes.find(node => node.text === "km");
+ assert.equal(unit.textEditable, true);
+ const next = apply(commented, editVisualLayout(model, commented, { type: "text", id: unit.id, value: "mi" }));
+ assert.match(next, /\{\/\* unit \*\/\}\{"mi"\}<\/text>/);
+ assert.equal(parseVisualLayout(next).nodes.find(node => node.text === "mi").textEditable, true);
+});
diff --git a/Gallery/index.json b/Gallery/index.json
index bf152a9c..fc53b4c1 100644
--- a/Gallery/index.json
+++ b/Gallery/index.json
@@ -1,5 +1,5 @@
{
- "generatedAt": "2026-11-18T13:33:48.300Z",
+ "generatedAt": "2026-11-18T17:57:37.972Z",
"items": [
{
"author": "ScriptWidget Community",
@@ -68,15 +68,15 @@
"featured": true,
"files": [
{
- "bytes": 5468,
+ "bytes": 8031,
"path": "lib/countdown.js",
- "sha256": "27c45e3501e11a640003a9a98a36558d372e09384805178b7fa7b1a8ee3298a9",
+ "sha256": "31c7b237f5de7d793a4eb7ccadb0ddda9eb709af551aac16891d21eac01f66f9",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/countdown/lib/countdown.js"
},
{
- "bytes": 3328,
+ "bytes": 5238,
"path": "main.jsx",
- "sha256": "5c64dbd16aaa1573a4b87b9266f2c21aba778cda167df121eda43e5a5f2a639f",
+ "sha256": "e9fab78e0945d1cfd108d9d60fbfd4d1ceedf451d8bd5c12ae83d8937b199b9c",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/countdown/main.jsx"
},
{
@@ -122,15 +122,15 @@
"featured": true,
"files": [
{
- "bytes": 9577,
+ "bytes": 15755,
"path": "lib/repository.js",
- "sha256": "61a6a03539a48c90c8ecdde12b73c4c9c0e065d8732c267430d3bad2ead942ab",
+ "sha256": "e76828ad19edb4b2adb6f6323e850b10e86a843a2e07fa59b332e8a1aff31faf",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/github-repo-stats/lib/repository.js"
},
{
- "bytes": 4567,
+ "bytes": 7290,
"path": "main.jsx",
- "sha256": "c072ea74fba5915bb32e02332218207ed49fd614233d40d87d7bb66b1b32d943",
+ "sha256": "aa748935cdc030e28f0b20f36519bf886b354dc5ea0a01862f35984117607d54",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/github-repo-stats/main.jsx"
},
{
@@ -178,15 +178,15 @@
"featured": true,
"files": [
{
- "bytes": 7140,
+ "bytes": 10404,
"path": "lib/records.js",
- "sha256": "32b406d5d26352eca3eedd45a211c2fef21ad2769c8f556b5929cfba62659776",
+ "sha256": "a718ac7621a84a29c2397668a267ce1a9d42c4103a6b0440f5ab30a4ab07a640",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/habit-heatmap/lib/records.js"
},
{
- "bytes": 8155,
+ "bytes": 11197,
"path": "main.jsx",
- "sha256": "d5c8d8d5224bdcaf059a5719b1e076e9cba790bbc32fd89f0939150112baba4c",
+ "sha256": "210d1611481f9132f070744b4278f87df489b2d19d0e5c92178a3b09c0bf84a6",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/habit-heatmap/main.jsx"
},
{
@@ -226,15 +226,15 @@
"featured": true,
"files": [
{
- "bytes": 7140,
+ "bytes": 10404,
"path": "lib/records.js",
- "sha256": "32b406d5d26352eca3eedd45a211c2fef21ad2769c8f556b5929cfba62659776",
+ "sha256": "a718ac7621a84a29c2397668a267ce1a9d42c4103a6b0440f5ab30a4ab07a640",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/habit-streak/lib/records.js"
},
{
- "bytes": 3833,
+ "bytes": 6197,
"path": "main.jsx",
- "sha256": "a3b03c27036cf078071c75aa10328d1f7efb42aaeaaf8e2570a1d543eeb56ce2",
+ "sha256": "cde1013992fc8140adf962aef49865331837a0769a49d9f870868035c3eb7a8f",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/habit-streak/main.jsx"
},
{
@@ -281,15 +281,15 @@
"featured": true,
"files": [
{
- "bytes": 4975,
+ "bytes": 7170,
"path": "lib/health.js",
- "sha256": "c686cd140c830a90bb88b630f3c142096e2b75b353d04106aed78d2bfdc2c3af",
+ "sha256": "c9820ad46b488e209e8e0c1f23829a860666a6166e8ef291010135c194cf1962",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/health-card/lib/health.js"
},
{
- "bytes": 4016,
+ "bytes": 6532,
"path": "main.jsx",
- "sha256": "39c24b3b1f2b3749a53c8baa751210c3b90c7230e69f34da7be0bf6687434a79",
+ "sha256": "ba86dfaf4a2cd3ccc9d1ea4209fcf3eeb2159b36e75ae858ef386b7776de2962",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/health-card/main.jsx"
},
{
@@ -338,15 +338,15 @@
"featured": true,
"files": [
{
- "bytes": 7140,
+ "bytes": 10404,
"path": "lib/records.js",
- "sha256": "32b406d5d26352eca3eedd45a211c2fef21ad2769c8f556b5929cfba62659776",
+ "sha256": "a718ac7621a84a29c2397668a267ce1a9d42c4103a6b0440f5ab30a4ab07a640",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/hydration-goal/lib/records.js"
},
{
- "bytes": 4454,
+ "bytes": 7100,
"path": "main.jsx",
- "sha256": "7675102ccb166bbb2452e3333458ba5f45af6247cad2ca1d1e00b7d2e4ad1a66",
+ "sha256": "dc0d919f2d65f01b89eb13e1ad6e728e9d129ce40d5cf27a5a09a6c1f38be90f",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/hydration-goal/main.jsx"
},
{
@@ -389,15 +389,15 @@
"featured": true,
"files": [
{
- "bytes": 15633,
+ "bytes": 21959,
"path": "lib/weather.js",
- "sha256": "008d18bb0b090d9de29cc323b2c72998bfbf3712221e6af2758b75f0610b2d4f",
+ "sha256": "c1d1fc15d5dc7f178464fc224f71dcd91da50bcd56a35205c733deadf469d0c4",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/local-weather/lib/weather.js"
},
{
- "bytes": 4517,
+ "bytes": 7178,
"path": "main.jsx",
- "sha256": "d610566038c7fb0b2ea3d79cfcbf14bdf05d4dd8915c6270e8a2b0790f1b661a",
+ "sha256": "fe44ac57b9bed06e1a4dd0561599f56c92484164ae24a5269edc85d1b7949fb3",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/local-weather/main.jsx"
},
{
@@ -445,15 +445,15 @@
"featured": true,
"files": [
{
- "bytes": 7140,
+ "bytes": 10404,
"path": "lib/records.js",
- "sha256": "32b406d5d26352eca3eedd45a211c2fef21ad2769c8f556b5929cfba62659776",
+ "sha256": "a718ac7621a84a29c2397668a267ce1a9d42c4103a6b0440f5ab30a4ab07a640",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/mood-check-in/lib/records.js"
},
{
- "bytes": 3827,
+ "bytes": 6118,
"path": "main.jsx",
- "sha256": "03080a3a6a8ed5c07b1e3b354561504eafc0de6524b6369b1ed8165aead7cf9e",
+ "sha256": "7be497e2439ac95d454ad411ccb4c3e6f003a247af14a990a031d8392d0a4549",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/mood-check-in/main.jsx"
},
{
@@ -495,15 +495,15 @@
"featured": true,
"files": [
{
- "bytes": 7140,
+ "bytes": 10404,
"path": "lib/records.js",
- "sha256": "32b406d5d26352eca3eedd45a211c2fef21ad2769c8f556b5929cfba62659776",
+ "sha256": "a718ac7621a84a29c2397668a267ce1a9d42c4103a6b0440f5ab30a4ab07a640",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/packing-checklist/lib/records.js"
},
{
- "bytes": 4478,
+ "bytes": 6851,
"path": "main.jsx",
- "sha256": "0291b25e88a58c19fbf0e547237ffdf674b7a12ec049e513d71f5af023832e81",
+ "sha256": "40f85d45afcced3d0f5e7206cc02518e694fa24ec58ae8d21fca8253cac3966d",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/packing-checklist/main.jsx"
},
{
@@ -545,15 +545,15 @@
"featured": true,
"files": [
{
- "bytes": 2042,
+ "bytes": 3452,
"path": "lib/configuration.js",
- "sha256": "d5da443e2654ba2a15651b31bcd6ea4622f77cacbb90effad8795427ffdc73ea",
+ "sha256": "2fda3a58c1ff948994e67401fac4912e3e23aaa4d23df74031ce4096f2b4c1d7",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/photo-card/lib/configuration.js"
},
{
- "bytes": 2938,
+ "bytes": 5043,
"path": "main.jsx",
- "sha256": "72060f8ce77b27af0b680f46a7e06b976f4989aacc36510114e1df5b17d977fc",
+ "sha256": "8af25ad342c6c28151020e8eefb3cab612db1329770faefc6eead62f58bede59",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/photo-card/main.jsx"
},
{
@@ -601,15 +601,15 @@
"featured": true,
"files": [
{
- "bytes": 7140,
+ "bytes": 10404,
"path": "lib/records.js",
- "sha256": "32b406d5d26352eca3eedd45a211c2fef21ad2769c8f556b5929cfba62659776",
+ "sha256": "a718ac7621a84a29c2397668a267ce1a9d42c4103a6b0440f5ab30a4ab07a640",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/plant-care/lib/records.js"
},
{
- "bytes": 3955,
+ "bytes": 7477,
"path": "main.jsx",
- "sha256": "18ae5cba70b3aca155a7568d180f8751a0673cb09d0c8d6e85bcbd2efea0d80d",
+ "sha256": "3fb2fcd754ed69159fdefa8e5e66cae256b56374d40d5fb492eee8c2bd3973ca",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/plant-care/main.jsx"
},
{
@@ -657,15 +657,15 @@
"featured": true,
"files": [
{
- "bytes": 7140,
+ "bytes": 10404,
"path": "lib/records.js",
- "sha256": "32b406d5d26352eca3eedd45a211c2fef21ad2769c8f556b5929cfba62659776",
+ "sha256": "a718ac7621a84a29c2397668a267ce1a9d42c4103a6b0440f5ab30a4ab07a640",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/pocket-pet/lib/records.js"
},
{
- "bytes": 4893,
+ "bytes": 8828,
"path": "main.jsx",
- "sha256": "f6e4bc4e646faf6fb9131ad1fcf34be62735664d1a16827fd3873db29d624ead",
+ "sha256": "f5ef84c855d15bf7d45bf9f840230fa9c623cf586846aba33cad30314b981c4c",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/pocket-pet/main.jsx"
},
{
@@ -713,15 +713,15 @@
"featured": true,
"files": [
{
- "bytes": 4227,
+ "bytes": 6873,
"path": "lib/launcher.js",
- "sha256": "642ccca4c9bf96744d30583b6a7d5cc6b47697bf5b3a7d2afb1b99640b59b742",
+ "sha256": "ee1f27c0f2d86cab085bfe48ccc7ef71234e89965232365a7ae48a94aee7f629",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/quick-launcher/lib/launcher.js"
},
{
- "bytes": 2144,
+ "bytes": 3882,
"path": "main.jsx",
- "sha256": "a619bf5026c4cfd4da975450e52cdc30d2dd2011fd0f4305d21273dc63d0439b",
+ "sha256": "277168fac82ab67f9437f4e958457f846456a28cb5da3d06844caf010249d061",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/quick-launcher/main.jsx"
},
{
@@ -769,15 +769,15 @@
"featured": true,
"files": [
{
- "bytes": 2672,
+ "bytes": 3897,
"path": "lib/configuration.js",
- "sha256": "4e9b2e03a5795955789d946a1e46c40d223f415066211be9836d55a0b9ef6845",
+ "sha256": "319d32210ee88e872d21bbfadc6f4de2edab9ced6f8e24fe266d53e8eed591a3",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/wallpaper-match/lib/configuration.js"
},
{
- "bytes": 2797,
+ "bytes": 4945,
"path": "main.jsx",
- "sha256": "d3e4d51dd138053bbadf64d9f040659852c1664c457d90d73e0bfe4dd53d8558",
+ "sha256": "c08803016e54082d9b204121153e9fdb4f7eaabf021a14e535a28d07829581c5",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/wallpaper-match/main.jsx"
},
{
@@ -825,15 +825,15 @@
"featured": true,
"files": [
{
- "bytes": 15633,
+ "bytes": 21959,
"path": "lib/weather.js",
- "sha256": "008d18bb0b090d9de29cc323b2c72998bfbf3712221e6af2758b75f0610b2d4f",
+ "sha256": "c1d1fc15d5dc7f178464fc224f71dcd91da50bcd56a35205c733deadf469d0c4",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/weather-now/lib/weather.js"
},
{
- "bytes": 4517,
+ "bytes": 7065,
"path": "main.jsx",
- "sha256": "d610566038c7fb0b2ea3d79cfcbf14bdf05d4dd8915c6270e8a2b0790f1b661a",
+ "sha256": "3163103561c8584bf39b85aecad44227c56d551d09e3697a4e379a8a8fecffc0",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/weather-now/main.jsx"
},
{
@@ -881,9 +881,9 @@
"featured": true,
"files": [
{
- "bytes": 3166,
+ "bytes": 5157,
"path": "main.jsx",
- "sha256": "f1961ed1c507fa8bc0d019ab6943fe869804d7c1de7ca7428ad976c4c04e8b00",
+ "sha256": "7f9812e0915ad12062c4b8fc572263302ad329a426c6a826d66f779c33383026",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/photo-album-rotator/main.jsx"
},
{
@@ -917,9 +917,9 @@
"featured": true,
"files": [
{
- "bytes": 6248,
+ "bytes": 9809,
"path": "main.jsx",
- "sha256": "35d81bffcac52d79ef1a53a73603d2e15b73ce1aa8b7e69ff1104f979a7b0cb0",
+ "sha256": "b58fb007d9da1bae91f27c64c3654f97f69824edf0d31afae9554f324efea027",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/reminders-agenda/main.jsx"
},
{
@@ -953,9 +953,9 @@
"featured": true,
"files": [
{
- "bytes": 9590,
+ "bytes": 14444,
"path": "main.jsx",
- "sha256": "09056da00937c18a6ed222a87752b2aab321f6242795b586bd6f896a3c858217",
+ "sha256": "b9acaa4dab06b9ecdc2f0e2f304e6e90075e7333c0854aef839db809495f0e7b",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/health-overview/main.jsx"
},
{
@@ -989,9 +989,9 @@
"featured": true,
"files": [
{
- "bytes": 4125,
+ "bytes": 6350,
"path": "main.jsx",
- "sha256": "6bc462231b879cbf2bb539a94f42802937a58daf220823568047f29ebdd45811",
+ "sha256": "5b8aba31fe2eec2953eeefc7ab82a79a93f1617af5b553574a5155533ea4185a",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/github-profile/main.jsx"
},
{
@@ -1025,9 +1025,9 @@
"featured": true,
"files": [
{
- "bytes": 3480,
+ "bytes": 5515,
"path": "main.jsx",
- "sha256": "8cd4403948dc83ed6cd955821657695a69bac3c0f62a672bec3735c676b8a2ab",
+ "sha256": "a92b3ec88648382cdfcd8d130436f00353fd18fc336b105dd4caba6088311631",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/music-playback/main.jsx"
},
{
@@ -1061,9 +1061,9 @@
"featured": true,
"files": [
{
- "bytes": 605,
+ "bytes": 1121,
"path": "main.jsx",
- "sha256": "4c9a60320892baf0870a9d882bdaec1da568961e04fbfaeb8042588a4c6b0519",
+ "sha256": "08973166d669a07bb1eb8a8f2f3d44301e12af5f4a8fc3f7bafa97699b38d4ba",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/layout-starter/main.jsx"
},
{
@@ -1103,9 +1103,9 @@
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/material-study/LICENSE.txt"
},
{
- "bytes": 1207,
+ "bytes": 1902,
"path": "main.jsx",
- "sha256": "c1f17f8090c2bdf9b855bcdd55a96653e826f6e826ed2776a12fcd3de4c547c2",
+ "sha256": "15304290eb9f0fa0191e7a369f6a3806256c15259e543214dbd18b910f9af8cc",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/material-study/main.jsx"
},
{
@@ -1139,15 +1139,15 @@
"featured": false,
"files": [
{
- "bytes": 6158,
+ "bytes": 8310,
"path": "lib/cloud-hydration.js",
- "sha256": "1c1b5205b27a076db9fc2acba6e4788dae995a77b113f29213fff9fdf59bec7b",
+ "sha256": "72dbe296af66df54ba4414bbabb5b408487c12167364b0279518aaea7f4e0393",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/hydration-goal-icloud/lib/cloud-hydration.js"
},
{
- "bytes": 3934,
+ "bytes": 6685,
"path": "main.jsx",
- "sha256": "34f26e89a8b82fc4ebe91dc1382d233fd80d377f938269b51b7483efda588f14",
+ "sha256": "9a112ef8567b1427cf537e07ee4278946f9718d5538cb13d7f28fb10c3d8fac7",
"url": "https://raw.githubusercontent.com/everettjf/scriptwidget/main/Gallery/widgets/hydration-goal-icloud/main.jsx"
},
{
diff --git a/Gallery/widgets/countdown/lib/countdown.js b/Gallery/widgets/countdown/lib/countdown.js
index 73852e27..fdc05cc8 100644
--- a/Gallery/widgets/countdown/lib/countdown.js
+++ b/Gallery/widgets/countdown/lib/countdown.js
@@ -1,81 +1,186 @@
// Calendar days use Gregorian ordinals, never elapsed 24-hour periods.
+// This file is imported by main.jsx. It defines one global, CountdownCalendar,
+// with two functions: configuration() reads the settings and describe() turns them into
+// the texts the widget shows. It draws nothing itself.
var CountdownCalendar = (() => {
- const defaults = {title: "Your next moment", targetDate: "", repeatYearly: false, accent: "blue"};
+ // The settings used when nothing has been saved.
+ const defaults = {
+ title: "Your next moment",
+ targetDate: "",
+ repeatYearly: false,
+ accent: "blue",
+ };
+ // Split "YYYY-MM-DD" into [year, month, day]. Returns null for anything that is not a
+ // real calendar date, such as 2027-02-30.
function parts(text) {
if (typeof text !== "string" || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(text)) return null;
const [year, month, day] = text.split("-").map(Number);
if (year < 1970 || year > 9999) return null;
const date = new Date(Date.UTC(year, month - 1, day));
- return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? [year, month, day] : null;
+ return date.getUTCFullYear() === year &&
+ date.getUTCMonth() === month - 1 &&
+ date.getUTCDate() === day
+ ? [year, month, day]
+ : null;
}
+ // true if `value` holds exactly the four settings, each with a valid value.
function validate(value) {
- return value && typeof value === "object" && !Array.isArray(value) &&
+ return (
+ value &&
+ typeof value === "object" &&
+ !Array.isArray(value) &&
Object.keys(value).sort().join(",") === "accent,repeatYearly,targetDate,title" &&
- typeof value.title === "string" && value.title.trim().length > 0 && value.title.length <= 40 &&
- (value.targetDate === "" || !!parts(value.targetDate)) && typeof value.repeatYearly === "boolean" &&
- ["blue", "rose", "green"].includes(value.accent);
+ typeof value.title === "string" &&
+ value.title.trim().length > 0 &&
+ value.title.length <= 40 &&
+ (value.targetDate === "" || !!parts(value.targetDate)) &&
+ typeof value.repeatYearly === "boolean" &&
+ ["blue", "rose", "green"].includes(value.accent)
+ );
}
+ // Build the settings. `raw` is the saved JSON text from storage ("" if nothing was
+ // saved) and `parameter` is the widget's parameter. Returns { value, time }: the settings
+ // and, if the parameter gave a time of day, [hour, minute, second].
function configuration(raw, parameter) {
- let value = {...defaults};
+ let value = { ...defaults };
+ // The saved text must be { kind: "countdown", version: 1, values: {…} } and at most
+ // 4096 bytes; unescape(encodeURIComponent(raw)).length is its size in UTF-8 bytes.
if (raw !== "") {
let state;
- try { state = JSON.parse(raw); } catch (_) { throw new Error("Saved countdown configuration is invalid. Open Records & Configuration to repair it."); }
- if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096 || !state ||
- Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== "countdown" || !validate(state.values)) {
- throw new Error("Saved countdown configuration is invalid. Open Records & Configuration to repair it.");
+ try {
+ state = JSON.parse(raw);
+ } catch (_) {
+ throw new Error(
+ "Saved countdown configuration is invalid. Open Records & Configuration to repair it.",
+ );
+ }
+ if (
+ typeof raw !== "string" ||
+ unescape(encodeURIComponent(raw)).length > 4096 ||
+ !state ||
+ Object.keys(state).sort().join(",") !== "kind,values,version" ||
+ state.version !== 1 ||
+ state.kind !== "countdown" ||
+ !validate(state.values)
+ ) {
+ throw new Error(
+ "Saved countdown configuration is invalid. Open Records & Configuration to repair it.",
+ );
}
value = state.values;
}
parameter = (parameter || "").trim();
- if (!parameter) return {value, time: null};
+ // No parameter: use the saved settings as they are.
+ if (!parameter) return { value, time: null };
+ // A parameter that starts with "{" is JSON; its keys replace single settings.
if (parameter[0] === "{") {
let custom;
- try { custom = JSON.parse(parameter); } catch (_) { throw new Error("Use valid JSON for countdown settings."); }
- if (!custom || Array.isArray(custom) || Object.keys(custom).some(key => !Object.prototype.hasOwnProperty.call(defaults, key))) throw new Error("Unknown countdown setting.");
- value = {...value, ...custom};
- if (!validate(value)) throw new Error("Use a valid event name, calendar date, repeat setting and accent.");
- return {value, time: null};
+ try {
+ custom = JSON.parse(parameter);
+ } catch (_) {
+ throw new Error("Use valid JSON for countdown settings.");
+ }
+ if (
+ !custom ||
+ Array.isArray(custom) ||
+ Object.keys(custom).some((key) => !Object.prototype.hasOwnProperty.call(defaults, key))
+ )
+ throw new Error("Unknown countdown setting.");
+ value = { ...value, ...custom };
+ if (!validate(value))
+ throw new Error("Use a valid event name, calendar date, repeat setting and accent.");
+ return { value, time: null };
}
+ // Otherwise the parameter is "YYYY-MM-DD Title" or "YYYY-MM-DDTHH:mm:ss Title".
+ // The title is optional.
const match = /^(\d{4}-\d{2}-\d{2})(?:T(\d{2}):(\d{2}):(\d{2}))?(?:\s+(.+))?$/.exec(parameter);
- if (!match || !parts(match[1])) throw new Error("Use YYYY-MM-DD Event or YYYY-MM-DDTHH:mm:ss Event.");
+ if (!match || !parts(match[1]))
+ throw new Error("Use YYYY-MM-DD Event or YYYY-MM-DDTHH:mm:ss Event.");
const time = match[2] === undefined ? null : match.slice(2, 5).map(Number);
- if (time && (time[0] > 23 || time[1] > 59 || time[2] > 59)) throw new Error("Use a valid local time.");
- value = {...value, title: match[5] || value.title, targetDate: match[1], repeatYearly: false};
+ if (time && (time[0] > 23 || time[1] > 59 || time[2] > 59))
+ throw new Error("Use a valid local time.");
+ value = { ...value, title: match[5] || value.title, targetDate: match[1], repeatYearly: false };
if (!validate(value)) throw new Error("Keep the event name to 40 characters.");
- return {value, time};
+ return { value, time };
}
+ // The number of days from 1970-01-01 to a date. The difference of two of these is a count
+ // of calendar days that daylight-saving changes cannot disturb.
const ordinal = ([year, month, day]) => Date.UTC(year, month - 1, day) / 86400000;
+ // Turn the settings into the texts to show at the time `now`.
function describe(settings, now) {
const value = settings.value;
if (!Number.isFinite(now.getTime())) throw new Error("The preview date is invalid.");
- if (!value.targetDate) return {configured: false, title: value.title, number: "—", unit: "Choose a date", summary: "Set up your countdown", date: "Records & Configuration", accent: value.accent};
+ // No date chosen yet: show a hint instead of a number.
+ if (!value.targetDate)
+ return {
+ configured: false,
+ title: value.title,
+ number: "—",
+ unit: "Choose a date",
+ summary: "Set up your countdown",
+ date: "Records & Configuration",
+ accent: value.accent,
+ };
let target = parts(value.targetDate);
const today = [now.getFullYear(), now.getMonth() + 1, now.getDate()];
if (value.repeatYearly) {
+ // A yearly event: find its next occurrence, today included. Looking up to 8 years ahead
+ // covers February 29, which most years lack.
let next = null;
for (let year = today[0]; year <= Math.min(9999, today[0] + 8); year++) {
- const text = `${year}-${String(target[1]).padStart(2,"0")}-${String(target[2]).padStart(2,"0")}`;
+ const text = `${year}-${String(target[1]).padStart(2, "0")}-${String(target[2]).padStart(2, "0")}`;
const candidate = parts(text);
- if (candidate && ordinal(candidate) >= ordinal(today)) { next = candidate; break; }
+ if (candidate && ordinal(candidate) >= ordinal(today)) {
+ next = candidate;
+ break;
+ }
}
if (!next) throw new Error("No upcoming occurrence in the supported date range.");
target = next;
}
+ // Days until the target: positive in the future, negative in the past, 0 today.
const days = ordinal(target) - ordinal(today);
const dayWord = Math.abs(days) === 1 ? "day" : "days";
- let number = String(Math.abs(days)), unit = days === 0 ? "Today" : `${dayWord} ${days > 0 ? "to go" : "since"}`;
+ let number = String(Math.abs(days)),
+ unit = days === 0 ? "Today" : `${dayWord} ${days > 0 ? "to go" : "since"}`;
let summary = days === 0 ? "Today" : `${Math.abs(days)} ${unit}`;
+ // With a time of day, count minutes instead of days.
if (settings.time) {
const [hour, minute, second] = settings.time;
const date = new Date(target[0], target[1] - 1, target[2], hour, minute, second);
- if (date.getFullYear() !== target[0] || date.getMonth() !== target[1] - 1 || date.getDate() !== target[2] || date.getHours() !== hour || date.getMinutes() !== minute || date.getSeconds() !== second) throw new Error("That local time does not exist in this time zone.");
+ // A local time skipped by a daylight-saving change comes back changed; reject it.
+ if (
+ date.getFullYear() !== target[0] ||
+ date.getMonth() !== target[1] - 1 ||
+ date.getDate() !== target[2] ||
+ date.getHours() !== hour ||
+ date.getMinutes() !== minute ||
+ date.getSeconds() !== second
+ )
+ throw new Error("That local time does not exist in this time zone.");
const remaining = date.getTime() - now.getTime();
+ // Round up to whole minutes, then show days, or hours and minutes, or minutes.
const minutes = Math.ceil(Math.abs(remaining) / 60000);
- number = minutes >= 1440 ? String(Math.floor(minutes / 1440)) : minutes >= 60 ? `${Math.floor(minutes / 60)}h ${minutes % 60}m` : `${minutes}m`;
+ number =
+ minutes >= 1440
+ ? String(Math.floor(minutes / 1440))
+ : minutes >= 60
+ ? `${Math.floor(minutes / 60)}h ${minutes % 60}m`
+ : `${minutes}m`;
unit = remaining === 0 ? "Now" : remaining > 0 ? "until the moment" : "since the moment";
summary = `${number} ${unit}`;
}
- return {configured: true, title: value.title, number, unit, summary, date: target.map((p,i) => i ? String(p).padStart(2,"0") : String(p)).join("-"), accent: value.accent, repeatYearly: value.repeatYearly};
+ return {
+ configured: true,
+ title: value.title,
+ number,
+ unit,
+ summary,
+ // The target date as YYYY-MM-DD.
+ date: target.map((p, i) => (i ? String(p).padStart(2, "0") : String(p))).join("-"),
+ accent: value.accent,
+ repeatYearly: value.repeatYearly,
+ };
}
- return {configuration, describe};
+ return { configuration, describe };
})();
diff --git a/Gallery/widgets/countdown/main.jsx b/Gallery/widgets/countdown/main.jsx
index 8e5ec987..bc371fca 100644
--- a/Gallery/widgets/countdown/main.jsx
+++ b/Gallery/widgets/countdown/main.jsx
@@ -2,48 +2,148 @@
// them: 2027-01-01 New Year, 2027-01-01T12:30:00 Flight, or JSON settings.
// Calendar dates follow the device's local Gregorian date. WidgetKit schedules
// updates; this is not a continuously ticking timer.
-if (!$import("lib/countdown.js")) throw new Error("Install the complete Countdown template, including lib/countdown.js.");
-const settings = CountdownCalendar.configuration($storage.getString("recordTemplate.config.v1"), $getenv("widget-param"));
-const moment = CountdownCalendar.describe(settings, new Date($getenv("timeline-date") || Date.now()));
+// widget.json declares the "storage" permission, and a timeline with dailyTimes
+// ["00:00"] so the day count changes at midnight.
+// Try changing the colors in `palette` or the layouts below.
+//
+// $import runs another file of this package; the check fails if it could not be loaded.
+// lib/countdown.js defines the global CountdownCalendar used below.
+if (!$import("lib/countdown.js"))
+ throw new Error("Install the complete Countdown template, including lib/countdown.js.");
+// Read the settings: the saved defaults from $storage, then the widget's parameter.
+const settings = CountdownCalendar.configuration(
+ $storage.getString("recordTemplate.config.v1"),
+ $getenv("widget-param"),
+);
+// Work out the texts to show. "timeline-date" is the date this entry is drawn for;
+// the current time is used when it is not set.
+const moment = CountdownCalendar.describe(
+ settings,
+ new Date($getenv("timeline-date") || Date.now()),
+);
+// Three color sets. The `accent` setting chooses one.
const palette = {
- blue: {background: "#eff6ff", ink: "#1e3a8a", soft: "#3b82f6"},
- rose: {background: "#fff1f2", ink: "#881337", soft: "#e11d48"},
- green: {background: "#ecfdf5", ink: "#064e3b", soft: "#059669"},
+ blue: { background: "#eff6ff", ink: "#1e3a8a", soft: "#3b82f6" },
+ rose: { background: "#fff1f2", ink: "#881337", soft: "#e11d48" },
+ green: { background: "#ecfdf5", ink: "#064e3b", soft: "#059669" },
}[moment.accent];
+// Choose a layout for the widget size. The "accessory" sizes are Lock Screen widgets.
const size = $getenv("widget-size");
if (size === "accessoryInline") {
+ // Lock Screen line: the title and the summary as text.
$render({moment.title + ": " + moment.summary});
} else if (size === "accessoryCircular") {
- $render({moment.number});
+ // Lock Screen circle: an icon and the number.
+ $render(
+
+
+
+ {moment.number}
+
+ ,
+ );
} else if (size === "accessoryRectangular") {
- $render({moment.title}{moment.summary});
+ // Lock Screen rectangle: the title above the summary.
+ $render(
+
+ {moment.title}
+ {moment.summary}
+ ,
+ );
} else if (size === "medium") {
- $render(
-
- COUNTDOWN
- {moment.title}
- {moment.date}
-
-
- {moment.number}{moment.unit}
- );
+ // Medium: the title and date on the left, the number on the right.
+ // frame="max" fills the widget; padding and spacing are in points.
+ $render(
+
+
+
+ COUNTDOWN
+
+
+ {moment.title}
+
+
+ {moment.date}
+
+
+
+
+
+ {moment.number}
+
+
+ {moment.unit}
+
+
+ ,
+ );
} else if (size === "small") {
- const shortTitle = Array.from(moment.title).slice(0, 14).join("") + (Array.from(moment.title).length > 14 ? "…" : "");
- $render(
- COUNTDOWN
- {moment.number}
- {moment.unit}
- {shortTitle}
- {moment.date}
- );
+ // Small: cut the title to 14 characters. Array.from counts whole characters, so an emoji
+ // is not cut in half.
+ const shortTitle =
+ Array.from(moment.title).slice(0, 14).join("") +
+ (Array.from(moment.title).length > 14 ? "…" : "");
+ $render(
+
+
+ COUNTDOWN
+
+
+ {moment.number}
+
+
+ {moment.unit}
+
+
+ {shortTitle}
+
+
+ {moment.date}
+
+ ,
+ );
} else {
- $render(
- COUNTDOWN
-
- {moment.number}
- {moment.unit}
-
- {moment.title}
- {moment.date}
- );
+ // Large and extra-large: the number in the middle, the title and date at the bottom.
+ $render(
+
+
+
+ COUNTDOWN
+
+
+ {/* A repeat icon for a yearly event, a calendar icon otherwise. */}
+
+
+
+
+ {moment.number}
+
+
+ {moment.unit}
+
+
+
+ {moment.title}
+
+
+ {moment.date}
+
+ ,
+ );
}
diff --git a/Gallery/widgets/github-profile/main.jsx b/Gallery/widgets/github-profile/main.jsx
index a8f7d2b2..bdcb09e4 100644
--- a/Gallery/widgets/github-profile/main.jsx
+++ b/Gallery/widgets/github-profile/main.jsx
@@ -1,46 +1,155 @@
// Real authenticated profile. Connect GitHub in Settings > Service Accounts,
// then allow this installed widget. Web Studio supplies editable samples only.
-const family = $getenv("widget-size"), accessory = family.startsWith("accessory");
-const dark = $device.isdarkmode(), compact = family === "small";
+// Shows your GitHub name and repository counts. Try changing the colors, or which
+// numbers the layouts show.
+// $services runs on iPhone, iPad and Mac, and on Android with a fine-grained token (no
+// OAuth sign-in); not on Windows or Linux. widget.json must declare the permissions
+// "services" and "network", and the host api.github.com.
+
+// $getenv("widget-size") is the size being drawn: "small", "medium", "large",
+// "extraLarge", or a Lock Screen size whose name starts with "accessory".
+const family = $getenv("widget-size"),
+ accessory = family.startsWith("accessory");
+// $device.isdarkmode() is true when the system uses the dark appearance.
+const dark = $device.isdarkmode(),
+ compact = family === "small";
+// Lock Screen sizes get a clear background and the system's own text colors.
const background = accessory ? "clear" : dark ? "#192822" : "#f1f8f3";
const primary = accessory ? "primary" : dark ? "#e7f5eb" : "#224432";
const secondary = accessory ? "secondary" : dark ? "#a4bead" : "#60776a";
-let profile = null, state = "notConnected";
+// Read the data. When there is no profile, `state` says why.
+let profile = null,
+ state = "notConnected";
try {
+ // status() only looks at the connection saved on this device; profile() asks GitHub.
state = await $services.status("github");
if (state === "connected") profile = await $services.profile("github");
} catch (error) {
+ // A failed call throws an error whose text contains a code such as service_rate_limit.
const message = String(error);
- state = message.includes("service_rate_limit") ? "rateLimited" : message.includes("service_expired") || message.includes("service_credential") ? "expired"
- : message.includes("service_permission") ? "notGranted" : message.includes("service_not_connected") ? "notConnected" : "offline";
+ state = message.includes("service_rate_limit")
+ ? "rateLimited"
+ : message.includes("service_expired") || message.includes("service_credential")
+ ? "expired"
+ : message.includes("service_permission")
+ ? "notGranted"
+ : message.includes("service_not_connected")
+ ? "notConnected"
+ : "offline";
}
+// What to show for each state: [title, explanation].
const messages = {
notConnected: ["Connect GitHub", "Open Service Accounts in ScriptWidget Settings."],
notGranted: ["Allow this widget", "Choose this widget in Service Accounts."],
unavailable: ["Account unavailable", "Review Service Accounts in ScriptWidget."],
expired: ["Reconnect GitHub", "Update your token in Service Accounts."],
rateLimited: ["Try again later", "GitHub is rate limiting requests."],
- offline: ["Unable to refresh", "Try again when your connection is available."]
+ offline: ["Unable to refresh", "Try again when your connection is available."],
};
const notice = messages[state] || messages.offline;
-const number = value => value === null ? "—" : String(value);
-const Metric = ({label,value}) => {number(value)}{label};
+// A count that GitHub did not share is null; show a dash for it.
+const number = (value) => (value === null ? "—" : String(value));
+// A reusable piece of layout, used below as : a number with a label under it.
+const Metric = ({ label, value }) => (
+
+
+ {number(value)}
+
+
+ {label}
+
+
+);
+// No profile: show the notice in a form that fits the size.
if (!profile) {
if (family === "accessoryInline") $render({notice[0]});
- else if (family === "accessoryCircular") $render({state === "notConnected" ? "Setup" : state === "notGranted" ? "Allow" : state === "expired" ? "Login" : state === "rateLimited" ? "Later" : "Retry"});
- else $render({notice[0]}{notice[1]});
+ else if (family === "accessoryCircular")
+ $render(
+
+
+
+ {state === "notConnected"
+ ? "Setup"
+ : state === "notGranted"
+ ? "Allow"
+ : state === "expired"
+ ? "Login"
+ : state === "rateLimited"
+ ? "Later"
+ : "Retry"}
+
+ ,
+ );
+ else
+ $render(
+
+
+ {notice[0]}
+
+
+ {notice[1]}
+
+ ,
+ );
} else if (family === "accessoryInline") {
+ // Lock Screen, inline: one line of text.
$render({`@${profile.username} · ${profile.publicRepositories} repos`});
} else if (family === "accessoryCircular") {
- $render({number(profile.publicRepositories)}repos);
+ // Lock Screen, circular: only the number of public repositories.
+ $render(
+
+ {number(profile.publicRepositories)}
+ repos
+ ,
+ );
} else if (family === "accessoryRectangular") {
- $render({`@${profile.username}`}{`${profile.publicRepositories} repos · ${number(profile.followers)} followers`});
+ // Lock Screen, rectangular: two short lines.
+ $render(
+
+ {`@${profile.username}`}
+ {`${profile.publicRepositories} repos · ${number(profile.followers)} followers`}
+ ,
+ );
} else {
- $render(
- {profile.displayName || profile.username}{`@${profile.username}`}
-
- {!compact && }
- {!compact && {profile.privateRepositories === null ? "Private repository count not shared" : `${profile.privateRepositories} private repositories`}}
- {family !== "medium" && !compact && }
- );
+ // Home Screen sizes. The small widget (`compact`) leaves out the third number and the
+ // last line. frame="max" fills the widget; padding is the space in points around the content.
+ $render(
+
+
+
+
+
+ {profile.displayName || profile.username}
+
+ {`@${profile.username}`}
+
+
+
+
+
+
+ {!compact && }
+
+ {!compact && (
+
+ {profile.privateRepositories === null
+ ? "Private repository count not shared"
+ : `${profile.privateRepositories} private repositories`}
+
+ )}
+ {family !== "medium" && !compact && }
+ ,
+ );
}
diff --git a/Gallery/widgets/github-repo-stats/lib/repository.js b/Gallery/widgets/github-repo-stats/lib/repository.js
index d3ff3fcf..bfbb8f3e 100644
--- a/Gallery/widgets/github-repo-stats/lib/repository.js
+++ b/Gallery/widgets/github-repo-stats/lib/repository.js
@@ -1,104 +1,372 @@
+// Loads the public counts of one GitHub repository and keeps a copy in $storage, so the
+// widget still has numbers when it is offline or when GitHub limits requests.
+// main.jsx imports this file ("lib/repository.js") and uses `repositoryStats`.
var repositoryStats = (() => {
- const key="github.stats.v1",hour=3600000,day=24*hour;
- const defaults={repository:"everettjf/ScriptWidget",accent:"blue"};
- const closed=(value,keys)=>value && typeof value==="object" && !Array.isArray(value) && Object.keys(value).sort().join(",")===keys.split(",").sort().join(",");
- const count=value=>Number.isSafeInteger(value)&&value>=0&&value<=1000000000;
+ // The storage key of the saved copy, and two time spans in milliseconds.
+ const key = "github.stats.v1",
+ hour = 3600000,
+ day = 24 * hour;
+ const defaults = { repository: "everettjf/ScriptWidget", accent: "blue" };
+ // True when `value` is a plain object with exactly the keys listed in `keys` ("a,b,c").
+ const closed = (value, keys) =>
+ value &&
+ typeof value === "object" &&
+ !Array.isArray(value) &&
+ Object.keys(value).sort().join(",") === keys.split(",").sort().join(",");
+ // A whole number from 0 to one billion.
+ const count = (value) => Number.isSafeInteger(value) && value >= 0 && value <= 1000000000;
+ // True for "owner/name" written the way GitHub allows.
function validRepository(value) {
- if(typeof value!=="string"||value.length>140)return false;
- const parts=value.split("/");return parts.length===2&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(parts[0])&&/^[A-Za-z0-9_.-]{1,100}$/.test(parts[1])&&![".",".."].includes(parts[1]);
+ if (typeof value !== "string" || value.length > 140) return false;
+ const parts = value.split("/");
+ return (
+ parts.length === 2 &&
+ /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(parts[0]) &&
+ /^[A-Za-z0-9_.-]{1,100}$/.test(parts[1]) &&
+ ![".", ".."].includes(parts[1])
+ );
}
- function validate(value){if(!closed(value,"repository,accent")||!validRepository(value.repository)||!["blue","green","rose"].includes(value.accent))throw new Error("Choose a public owner/repository and an accent in Records & Configuration.");return value;}
- function options(raw,parameter){
- let result={...defaults};
- if(raw!==null&&raw!==undefined&&raw!==""){
- if(typeof raw!=="string"||raw.length>4096)throw new Error("Invalid repository configuration.");
- const saved=JSON.parse(raw);if(!closed(saved,"version,kind,values")||saved.version!==1||saved.kind!=="repoStats")throw new Error("Invalid repository configuration.");result={...validate(saved.values)};
+ // Check the settings { repository, accent }, or throw a message the app can show.
+ function validate(value) {
+ if (
+ !closed(value, "repository,accent") ||
+ !validRepository(value.repository) ||
+ !["blue", "green", "rose"].includes(value.accent)
+ )
+ throw new Error("Choose a public owner/repository and an accent in Records & Configuration.");
+ return value;
+ }
+ // Work out the settings: the defaults, then the configuration saved by Records &
+ // Configuration (`raw`), then the widget parameter. The parameter is owner/name, or JSON
+ // such as {"repository":"owner/name","accent":"green"}.
+ function options(raw, parameter) {
+ let result = { ...defaults };
+ if (raw !== null && raw !== undefined && raw !== "") {
+ if (typeof raw !== "string" || raw.length > 4096)
+ throw new Error("Invalid repository configuration.");
+ const saved = JSON.parse(raw);
+ if (
+ !closed(saved, "version,kind,values") ||
+ saved.version !== 1 ||
+ saved.kind !== "repoStats"
+ )
+ throw new Error("Invalid repository configuration.");
+ result = { ...validate(saved.values) };
}
- if(parameter){
- if(typeof parameter!=="string"||parameter.length>4096)throw new Error("Invalid repository parameter.");
- if(parameter.trim().startsWith("{")){
- const override=JSON.parse(parameter);if(!override||typeof override!=="object"||Array.isArray(override)||Object.keys(override).some(key=>!Object.hasOwn(defaults,key)))throw new Error("Unknown repository setting.");result={...result,...override};
- }else result.repository=parameter.trim();
+ if (parameter) {
+ if (typeof parameter !== "string" || parameter.length > 4096)
+ throw new Error("Invalid repository parameter.");
+ if (parameter.trim().startsWith("{")) {
+ const override = JSON.parse(parameter);
+ if (
+ !override ||
+ typeof override !== "object" ||
+ Array.isArray(override) ||
+ Object.keys(override).some((key) => !Object.hasOwn(defaults, key))
+ )
+ throw new Error("Unknown repository setting.");
+ result = { ...result, ...override };
+ } else result.repository = parameter.trim();
}
return validate(result);
}
- const validDate=value=>typeof value==="string"&&value.length<=128&&/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value)&&Number.isFinite(Date.parse(value));
- const validValues=value=>closed(value,"stars,forks,issues")&&count(value.stars)&&count(value.forks)&&count(value.issues);
- function packets(raw,now){
- try{
- if(typeof raw!=="string"||raw.length>32768)return [];
- const data=JSON.parse(raw);if(!closed(data,"version,entries")||data.version!==1||!Array.isArray(data.entries)||data.entries.length>4)return [];
- const seen=new Set();
- for(const entry of data.entries){
- if(!closed(entry,"repository,checkedAt,nextRequestAt,observedAt,lastModified,reason,values,history")||!validRepository(entry.repository)||entry.repository!==entry.repository.toLowerCase()||seen.has(entry.repository)||
- !Number.isSafeInteger(entry.checkedAt)||entry.checkedAt<0||entry.checkedAt>now+60000||!Number.isSafeInteger(entry.nextRequestAt)||entry.nextRequestAtentry.checkedAt+7*day||
- !Number.isSafeInteger(entry.observedAt)||entry.observedAt<0||entry.observedAt>entry.checkedAt||!["","offline","rate","missing","invalid"].includes(entry.reason)||
- (entry.lastModified!==""&&!validDate(entry.lastModified))||(entry.values!==null&&!validValues(entry.values))||
- (entry.values===null?entry.observedAt!==0:entry.observedAt===0)||!Array.isArray(entry.history)||entry.history.length>14||
- entry.history.some((point,index)=>!closed(point,"time,stars")||!count(point.stars)||!Number.isSafeInteger(point.time)||point.time<0||point.time>entry.observedAt||(index>0&&Math.floor(point.time/day)<=Math.floor(entry.history[index-1].time/day)))||
- (entry.values===null&&entry.history.length>0))return [];
+ // An HTTP date such as "Sun, 08 Mar 2026 12:00:00 GMT", as in the Last-Modified header.
+ const validDate = (value) =>
+ typeof value === "string" &&
+ value.length <= 128 &&
+ /^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value) &&
+ Number.isFinite(Date.parse(value));
+ // The three counts and nothing else.
+ const validValues = (value) =>
+ closed(value, "stars,forks,issues") &&
+ count(value.stars) &&
+ count(value.forks) &&
+ count(value.issues);
+ // Read the saved copy: up to 4 repositories, each with its counts, when it was checked
+ // (`checkedAt`), when to ask again (`nextRequestAt`) and up to 14 daily star counts.
+ // Times are milliseconds since 1970. Anything unexpected gives an empty list, so a
+ // damaged copy is simply loaded again.
+ function packets(raw, now) {
+ try {
+ if (typeof raw !== "string" || raw.length > 32768) return [];
+ const data = JSON.parse(raw);
+ if (
+ !closed(data, "version,entries") ||
+ data.version !== 1 ||
+ !Array.isArray(data.entries) ||
+ data.entries.length > 4
+ )
+ return [];
+ const seen = new Set();
+ for (const entry of data.entries) {
+ if (
+ !closed(
+ entry,
+ "repository,checkedAt,nextRequestAt,observedAt,lastModified,reason,values,history",
+ ) ||
+ !validRepository(entry.repository) ||
+ entry.repository !== entry.repository.toLowerCase() ||
+ seen.has(entry.repository) ||
+ !Number.isSafeInteger(entry.checkedAt) ||
+ entry.checkedAt < 0 ||
+ entry.checkedAt > now + 60000 ||
+ !Number.isSafeInteger(entry.nextRequestAt) ||
+ entry.nextRequestAt < entry.checkedAt ||
+ entry.nextRequestAt > entry.checkedAt + 7 * day ||
+ !Number.isSafeInteger(entry.observedAt) ||
+ entry.observedAt < 0 ||
+ entry.observedAt > entry.checkedAt ||
+ !["", "offline", "rate", "missing", "invalid"].includes(entry.reason) ||
+ (entry.lastModified !== "" && !validDate(entry.lastModified)) ||
+ (entry.values !== null && !validValues(entry.values)) ||
+ (entry.values === null ? entry.observedAt !== 0 : entry.observedAt === 0) ||
+ !Array.isArray(entry.history) ||
+ entry.history.length > 14 ||
+ entry.history.some(
+ (point, index) =>
+ !closed(point, "time,stars") ||
+ !count(point.stars) ||
+ !Number.isSafeInteger(point.time) ||
+ point.time < 0 ||
+ point.time > entry.observedAt ||
+ (index > 0 &&
+ Math.floor(point.time / day) <= Math.floor(entry.history[index - 1].time / day)),
+ ) ||
+ (entry.values === null && entry.history.length > 0)
+ )
+ return [];
seen.add(entry.repository);
}
return data.entries;
- }catch{return [];}
+ } catch {
+ return [];
+ }
}
- function publish(packet,now){
- for(let attempt=0;attempt<4;attempt++){
- const raw=$storage.getString(key),entries=packets(raw,now),previous=entries.find(entry=>entry.repository===packet.repository);
- if(previous&&(previous.checkedAt>packet.checkedAt))return true;
+ // Save one repository's entry next to the others. compareAndSetString writes only if the
+ // stored text is still `raw`; if something else saved in between, read again and retry.
+ function publish(packet, now) {
+ for (let attempt = 0; attempt < 4; attempt++) {
+ const raw = $storage.getString(key),
+ entries = packets(raw, now),
+ previous = entries.find((entry) => entry.repository === packet.repository);
+ if (previous && previous.checkedAt > packet.checkedAt) return true;
// Keep newer successful data if an older failed request completes at the same timestamp.
- const candidate=previous?.values && previous.observedAt>packet.observedAt && packet.reason!=="missing" ? {...packet,values:previous.values,observedAt:previous.observedAt,lastModified:previous.lastModified,history:previous.history,nextRequestAt:Math.max(packet.nextRequestAt,previous.nextRequestAt)} : packet;
- const history=[...(previous?.history||[]),...candidate.history].sort((a,b)=>a.time-b.time),daily=[];
- for(const point of history){if(daily.length&&Math.floor(daily[daily.length-1].time/day)===Math.floor(point.time/day))daily[daily.length-1]=point;else daily.push(point);}
- const merged={...candidate,history:candidate.values===null?[]:daily.slice(-14)};
- const next=[merged,...entries.filter(entry=>entry.repository!==packet.repository)].sort((a,b)=>b.checkedAt-a.checkedAt).slice(0,4);
- if($storage.compareAndSetString(key,raw,JSON.stringify({version:1,entries:next})))return true;
+ const candidate =
+ previous?.values && previous.observedAt > packet.observedAt && packet.reason !== "missing"
+ ? {
+ ...packet,
+ values: previous.values,
+ observedAt: previous.observedAt,
+ lastModified: previous.lastModified,
+ history: previous.history,
+ nextRequestAt: Math.max(packet.nextRequestAt, previous.nextRequestAt),
+ }
+ : packet;
+ const history = [...(previous?.history || []), ...candidate.history].sort(
+ (a, b) => a.time - b.time,
+ ),
+ daily = [];
+ // Keep one history point per day (UTC); a later point replaces an earlier one of that day.
+ for (const point of history) {
+ if (
+ daily.length &&
+ Math.floor(daily[daily.length - 1].time / day) === Math.floor(point.time / day)
+ )
+ daily[daily.length - 1] = point;
+ else daily.push(point);
+ }
+ const merged = { ...candidate, history: candidate.values === null ? [] : daily.slice(-14) };
+ // Newest first, and never more than 4 repositories.
+ const next = [merged, ...entries.filter((entry) => entry.repository !== packet.repository)]
+ .sort((a, b) => b.checkedAt - a.checkedAt)
+ .slice(0, 4);
+ if ($storage.compareAndSetString(key, raw, JSON.stringify({ version: 1, entries: next })))
+ return true;
}
return false;
}
- function nextRequest(headers,now){
- const expiry=Date.parse(headers.expires||""),maxAge=/(?:^|,)\s*max-age=(\d+)/i.exec(headers["cache-control"]||"");
- const until=maxAge?now+Number(maxAge[1])*1000:expiry;
- return Math.round(Math.max(now+hour,Number.isFinite(until)&&until<=now+7*day?until:now+hour));
+ // When to ask GitHub again after an answer: when the response says it expires
+ // (Cache-Control max-age, else Expires), but not sooner than one hour. A missing time,
+ // or one more than 7 days away, also gives one hour.
+ function nextRequest(headers, now) {
+ const expiry = Date.parse(headers.expires || ""),
+ maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(headers["cache-control"] || "");
+ const until = maxAge ? now + Number(maxAge[1]) * 1000 : expiry;
+ return Math.round(
+ Math.max(now + hour, Number.isFinite(until) && until <= now + 7 * day ? until : now + hour),
+ );
}
- function retry(headers,now){
- const raw=headers["retry-after"]||"",seconds=/^\d+$/.test(raw)?Number(raw):NaN;
- const until=Number.isFinite(seconds)?now+seconds*1000:Date.parse(raw);
- return Math.round(Number.isFinite(until)&&until>now&&until<=now+7*day?Math.max(now+hour,until):now+hour);
+ // When to ask again after a failure: at the Retry-After time (seconds or a date) if it
+ // is within 7 days, but not sooner than one hour; otherwise in one hour.
+ function retry(headers, now) {
+ const raw = headers["retry-after"] || "",
+ seconds = /^\d+$/.test(raw) ? Number(raw) : NaN;
+ const until = Number.isFinite(seconds) ? now + seconds * 1000 : Date.parse(raw);
+ return Math.round(
+ Number.isFinite(until) && until > now && until <= now + 7 * day
+ ? Math.max(now + hour, until)
+ : now + hour,
+ );
}
- function values(body,repository){
- if(typeof body!=="string"||body.length>2097152)throw new Error("Invalid repository response");
- const data=JSON.parse(body);
- if(!data||typeof data.full_name!=="string"||data.full_name.toLowerCase()!==repository||data.private!==false||!count(data.stargazers_count)||!count(data.forks_count)||!count(data.open_issues_count))throw new Error("Invalid public repository response");
- return {stars:data.stargazers_count,forks:data.forks_count,issues:data.open_issues_count};
+ // Take the three counts out of GitHub's answer, after checking that it describes the
+ // public repository that was asked for.
+ function values(body, repository) {
+ if (typeof body !== "string" || body.length > 2097152)
+ throw new Error("Invalid repository response");
+ const data = JSON.parse(body);
+ if (
+ !data ||
+ typeof data.full_name !== "string" ||
+ data.full_name.toLowerCase() !== repository ||
+ data.private !== false ||
+ !count(data.stargazers_count) ||
+ !count(data.forks_count) ||
+ !count(data.open_issues_count)
+ )
+ throw new Error("Invalid public repository response");
+ return {
+ stars: data.stargazers_count,
+ forks: data.forks_count,
+ issues: data.open_issues_count,
+ };
}
- async function load(config,now,projection){
- validate(config);const repository=config.repository.toLowerCase();
- let packet=packets($storage.getString(key),now).find(entry=>entry.repository===repository),saved=true,fromCache=!!packet;
- if(!projection&&(!packet||now>=packet.nextRequestAt)){
- const previous=packet;
- const headers={"Accept":"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)"};
- if(packet?.lastModified)headers["If-Modified-Since"]=packet.lastModified;
- let responseHeaders={},reason="offline",missing=false;
- try{
- const response=await $http.getResponse(`https://api.github.com/repos/${repository.split("/").map(encodeURIComponent).join("/")}`,{headers});
- if(!response||!Number.isInteger(response.status))throw new Error("Invalid response");
- responseHeaders=response.headers||{};
- if(response.status===304&&packet?.values){packet={...packet,checkedAt:now,observedAt:now,nextRequestAt:nextRequest(responseHeaders,now),reason:""};}
- else if(response.status===200){
- reason="invalid";const result=values(response.body,repository),history=[...(packet?.history||[])].filter(point=>Math.floor(point.time/day)!==Math.floor(now/day));history.push({time:now,stars:result.stars});
- packet={repository,checkedAt:now,observedAt:now,nextRequestAt:nextRequest(responseHeaders,now),lastModified:validDate(responseHeaders["last-modified"])&&Date.parse(responseHeaders["last-modified"])<=now+60000?responseHeaders["last-modified"]:"",reason:"",values:result,history:history.slice(-14)};
- }else{reason=response.status===403||response.status===429?"rate":response.status===404?"missing":"offline";missing=response.status===404;throw new Error("Service unavailable");}
- fromCache=response.status===304;
- }catch{
- packet={repository,checkedAt:now,nextRequestAt:retry(responseHeaders,now),observedAt:missing?0:previous?.observedAt||0,lastModified:missing?"":previous?.lastModified||"",reason,values:missing?null:previous?.values||null,history:missing?[]:previous?.history||[]};
+ // load(config, now, projection) returns what the widget shows. `now` is in milliseconds.
+ // `projection` is true for a future timeline entry, which must not use the network.
+ async function load(config, now, projection) {
+ validate(config);
+ const repository = config.repository.toLowerCase();
+ let packet = packets($storage.getString(key), now).find(
+ (entry) => entry.repository === repository,
+ ),
+ saved = true,
+ fromCache = !!packet;
+ // Ask GitHub only when there is no saved copy or it is due for a refresh.
+ if (!projection && (!packet || now >= packet.nextRequestAt)) {
+ const previous = packet;
+ const headers = {
+ Accept: "application/vnd.github+json",
+ "X-GitHub-Api-Version": "2022-11-28",
+ "User-Agent": "ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)",
+ };
+ // With If-Modified-Since, GitHub can answer 304 "not changed" instead of the counts.
+ if (packet?.lastModified) headers["If-Modified-Since"] = packet.lastModified;
+ let responseHeaders = {},
+ reason = "offline",
+ missing = false;
+ try {
+ // $http.getResponse resolves to { status, body, headers }, also for statuses such as
+ // 404; it throws only when the request itself fails.
+ const response = await $http.getResponse(
+ `https://api.github.com/repos/${repository.split("/").map(encodeURIComponent).join("/")}`,
+ { headers },
+ );
+ if (!response || !Number.isInteger(response.status)) throw new Error("Invalid response");
+ responseHeaders = response.headers || {};
+ // 304: nothing changed, the saved counts are still right.
+ if (response.status === 304 && packet?.values) {
+ packet = {
+ ...packet,
+ checkedAt: now,
+ observedAt: now,
+ nextRequestAt: nextRequest(responseHeaders, now),
+ reason: "",
+ };
+ } else if (response.status === 200) {
+ // 200: new counts. Add today's stars to the history, one point per day.
+ reason = "invalid";
+ const result = values(response.body, repository),
+ history = [...(packet?.history || [])].filter(
+ (point) => Math.floor(point.time / day) !== Math.floor(now / day),
+ );
+ history.push({ time: now, stars: result.stars });
+ packet = {
+ repository,
+ checkedAt: now,
+ observedAt: now,
+ nextRequestAt: nextRequest(responseHeaders, now),
+ lastModified:
+ validDate(responseHeaders["last-modified"]) &&
+ Date.parse(responseHeaders["last-modified"]) <= now + 60000
+ ? responseHeaders["last-modified"]
+ : "",
+ reason: "",
+ values: result,
+ history: history.slice(-14),
+ };
+ } else {
+ // 403 and 429 mean a rate limit, 404 an unknown or private repository.
+ reason =
+ response.status === 403 || response.status === 429
+ ? "rate"
+ : response.status === 404
+ ? "missing"
+ : "offline";
+ missing = response.status === 404;
+ throw new Error("Service unavailable");
+ }
+ fromCache = response.status === 304;
+ } catch {
+ // No usable answer: keep the earlier counts (unless the repository is gone) and note why.
+ packet = {
+ repository,
+ checkedAt: now,
+ nextRequestAt: retry(responseHeaders, now),
+ observedAt: missing ? 0 : previous?.observedAt || 0,
+ lastModified: missing ? "" : previous?.lastModified || "",
+ reason,
+ values: missing ? null : previous?.values || null,
+ history: missing ? [] : previous?.history || [],
+ };
}
- saved=publish(packet,now);
+ saved = publish(packet, now);
}
- const message=packet?.reason==="rate"?"GitHub rate limit":packet?.reason==="missing"?"Repository unavailable":packet?.reason==="invalid"?"Invalid service response":"Refresh unavailable";
- if(!packet?.values||now-packet.observedAt>7*day)return {available:false,repository:config.repository,heading:projection?"Refresh in current entry":message,detail:packet?.reason==="missing"?"Check the public owner/repository. Private or deleted repositories cannot be read.":"Check your connection and try again later.",saved};
- const minutes=Math.max(0,Math.floor((now-packet.observedAt)/60000)),age=minutes<1?"Checked just now":minutes<60?`Checked ${minutes}m ago`:minutes<1440?`Checked ${Math.floor(minutes/60)}h ago`:`Checked ${Math.floor(minutes/1440)}d ago`;
- return {available:true,repository:config.repository,...packet.values,history:packet.history,age,saved,status:!saved?"Cache unavailable":packet.reason?`Saved counts · ${message.toLowerCase()}`:projection||fromCache?"Saved counts":"GitHub · Public repository"};
+ // A short text for the reason of the last failure.
+ const message =
+ packet?.reason === "rate"
+ ? "GitHub rate limit"
+ : packet?.reason === "missing"
+ ? "Repository unavailable"
+ : packet?.reason === "invalid"
+ ? "Invalid service response"
+ : "Refresh unavailable";
+ // No counts, or counts older than 7 days: return a message to show instead.
+ if (!packet?.values || now - packet.observedAt > 7 * day)
+ return {
+ available: false,
+ repository: config.repository,
+ heading: projection ? "Refresh in current entry" : message,
+ detail:
+ packet?.reason === "missing"
+ ? "Check the public owner/repository. Private or deleted repositories cannot be read."
+ : "Check your connection and try again later.",
+ saved,
+ };
+ // How long ago the counts were read, as text.
+ const minutes = Math.max(0, Math.floor((now - packet.observedAt) / 60000)),
+ age =
+ minutes < 1
+ ? "Checked just now"
+ : minutes < 60
+ ? `Checked ${minutes}m ago`
+ : minutes < 1440
+ ? `Checked ${Math.floor(minutes / 60)}h ago`
+ : `Checked ${Math.floor(minutes / 1440)}d ago`;
+ // The counts, plus the texts for the last two lines of the widget.
+ return {
+ available: true,
+ repository: config.repository,
+ ...packet.values,
+ history: packet.history,
+ age,
+ saved,
+ status: !saved
+ ? "Cache unavailable"
+ : packet.reason
+ ? `Saved counts · ${message.toLowerCase()}`
+ : projection || fromCache
+ ? "Saved counts"
+ : "GitHub · Public repository",
+ };
}
- return {options,load};
+ return { options, load };
})();
diff --git a/Gallery/widgets/github-repo-stats/main.jsx b/Gallery/widgets/github-repo-stats/main.jsx
index 7006e494..ffc33438 100644
--- a/Gallery/widgets/github-repo-stats/main.jsx
+++ b/Gallery/widgets/github-repo-stats/main.jsx
@@ -1,25 +1,196 @@
// Public counts only. Configure owner/repository and accent in Records & Configuration.
-if (!$import("lib/repository.js")) throw new Error("Install the complete GitHub Repo Stats template.");
-const config=repositoryStats.options($storage.getString("recordTemplate.config.v1"),$getenv("widget-param"));
-const stats=await repositoryStats.load(config,Date.now(),$getenv("timeline-is-projection")==="true");
-const size=$getenv("widget-size"),small=size==="small",dark=$device.isdarkmode();
-const nameLimit=small?24:40;
-const displayRepository=stats.repository.length<=nameLimit?stats.repository:stats.repository.slice(0,Math.floor(nameLimit/2)-1)+"…"+stats.repository.slice(-Math.floor(nameLimit/2));
-const background=dark?"#111827":"#eff6ff",text=dark?"#f8fafc":"#1e3a8a",secondary=dark?"#cbd5e1":"#475569",accent={blue:"#2563eb",green:"#15803d",rose:"#be185d"}[config.accent];
-const NumberCard=({title,value,icon})=>{String(value)}{title};
-const Trend=()=>stats.history.length>=2?Stars · saved daily checks({label:new Date(point.time).toISOString().slice(0,10),value:point.stars})))}/>{`${stats.history.length} recorded days · ${new Date(stats.history[0].time).toISOString().slice(0,10)} onward`}:Daily star history appears after two recorded days.;
-if(size==="accessoryInline"){
- $render({stats.available?`${displayRepository} · ${stats.stars} stars`:stats.heading});
-}else if(size==="accessoryCircular"){
- $render({stats.available?String(stats.stars):"—"}{stats.available?"stars":"Open app"});
-}else if(size==="accessoryRectangular"){
- $render({displayRepository}{stats.available?`${stats.stars} stars · ${stats.forks} forks`:stats.heading}{stats.available?stats.age:"Check public repository"});
-}else if(!stats.available){
- $render({stats.heading}{stats.detail});
-}else if(small){
- $render({displayRepository}{String(stats.stars)}{stats.age}{stats.status});
-}else if(size==="medium"){
- $render({displayRepository}{stats.age}{stats.status});
-}else{
- $render({displayRepository}{stats.age}{stats.status});
+// Shows the stars, forks and open issues of a public GitHub repository, and a star trend
+// in the large size. Try another repository: write owner/name in the widget parameter.
+// widget.json must declare the permission "network" with the host api.github.com, and
+// "storage" for the saved copy of the counts.
+
+// $import runs another file of this package; lib/repository.js defines `repositoryStats`.
+// It returns false when the file is missing.
+if (!$import("lib/repository.js"))
+ throw new Error("Install the complete GitHub Repo Stats template.");
+// The settings: defaults, then what the app saved in $storage, then the widget parameter
+// ($getenv("widget-param"), a text you set on each widget you place).
+const config = repositoryStats.options(
+ $storage.getString("recordTemplate.config.v1"),
+ $getenv("widget-param"),
+);
+// Read the counts: from GitHub when the saved copy is due for a refresh, else from $storage.
+// "timeline-is-projection" is "true" when the script runs for a future timeline entry;
+// no request is made then.
+const stats = await repositoryStats.load(
+ config,
+ Date.now(),
+ $getenv("timeline-is-projection") === "true",
+);
+// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline".
+const size = $getenv("widget-size"),
+ small = size === "small",
+ dark = $device.isdarkmode();
+// A long owner/name gets its middle replaced by "…".
+const nameLimit = small ? 24 : 40;
+const displayRepository =
+ stats.repository.length <= nameLimit
+ ? stats.repository
+ : stats.repository.slice(0, Math.floor(nameLimit / 2) - 1) +
+ "…" +
+ stats.repository.slice(-Math.floor(nameLimit / 2));
+const background = dark ? "#111827" : "#eff6ff",
+ text = dark ? "#f8fafc" : "#1e3a8a",
+ secondary = dark ? "#cbd5e1" : "#475569",
+ accent = { blue: "#2563eb", green: "#15803d", rose: "#be185d" }[config.accent];
+// A reusable piece of layout: an icon, a number and a title under it.
+const NumberCard = ({ title, value, icon }) => (
+
+
+
+ {String(value)}
+
+
+ {title}
+
+
+);
+// A line chart of the saved daily star counts; it needs two days of history.
+// takes its points as JSON text: [{ label, value }, …].
+const Trend = () =>
+ stats.history.length >= 2 ? (
+
+
+ Stars · saved daily checks
+
+ ({
+ label: new Date(point.time).toISOString().slice(0, 10),
+ value: point.stars,
+ })),
+ )}
+ />
+ {`${stats.history.length} recorded days · ${new Date(stats.history[0].time).toISOString().slice(0, 10)} onward`}
+
+ ) : (
+
+ Daily star history appears after two recorded days.
+
+ );
+// Choose a layout for the widget size.
+if (size === "accessoryInline") {
+ // Lock Screen, inline: one line of text.
+ $render(
+ {stats.available ? `${displayRepository} · ${stats.stars} stars` : stats.heading},
+ );
+} else if (size === "accessoryCircular") {
+ // Lock Screen, circular: the star count.
+ $render(
+
+
+
+ {stats.available ? String(stats.stars) : "—"}
+
+ {stats.available ? "stars" : "Open app"}
+ ,
+ );
+} else if (size === "accessoryRectangular") {
+ // Lock Screen, rectangular: three short lines.
+ $render(
+
+
+ {displayRepository}
+
+
+ {stats.available ? `${stats.stars} stars · ${stats.forks} forks` : stats.heading}
+
+ {stats.available ? stats.age : "Check public repository"}
+ ,
+ );
+} else if (!stats.available) {
+ // No counts to show: say why (offline, rate limit, unknown repository).
+ $render(
+
+
+
+ {stats.heading}
+
+
+ {stats.detail}
+
+ ,
+ );
+} else if (small) {
+ // Small widget: only the star count.
+ $render(
+
+
+ {displayRepository}
+
+
+
+
+
+ {String(stats.stars)}
+
+
+
+ {stats.age}
+
+
+ {stats.status}
+
+ ,
+ );
+} else if (size === "medium") {
+ // Medium widget: the three numbers in a row.
+ $render(
+
+
+ {displayRepository}
+
+
+
+
+
+
+
+
+ {stats.age}
+
+
+
+ {stats.status}
+
+
+ ,
+ );
+} else {
+ // Large and extra large widgets: the three numbers and the trend chart.
+ $render(
+
+
+ {displayRepository}
+
+
+
+
+
+
+
+
+
+
+
+ {stats.age}
+
+
+ {stats.status}
+
+ ,
+ );
}
diff --git a/Gallery/widgets/habit-heatmap/lib/records.js b/Gallery/widgets/habit-heatmap/lib/records.js
index e9eaef0f..3e1682ad 100644
--- a/Gallery/widgets/habit-heatmap/lib/records.js
+++ b/Gallery/widgets/habit-heatmap/lib/records.js
@@ -1,111 +1,216 @@
// Identical package-local helper in the built-in record templates.
// Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync.
+// main.jsx imports this file ("lib/records.js") and then uses `localRecords`.
+// It keeps one value per calendar day in $storage (permission "storage" in widget.json)
+// and reads the settings saved by Records & Configuration in the app.
var localRecords = (() => {
- const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
- const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12);
+ // Day key in local time, for example "2026-03-08".
+ const keyFor = (date) =>
+ `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+ // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it.
+ const offset = (date, days) =>
+ new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12);
+ // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected).
const validDate = (key) => {
if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false;
const parts = key.split("-").map(Number);
return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key;
};
+ // A deep copy, so a caller cannot change the saved state by accident.
const clone = (value) => JSON.parse(JSON.stringify(value));
+ // create(key, validValue, empty) returns the record log stored under `key`.
+ // validValue(value) says whether a day's value is acceptable; `empty` is the value of a
+ // day without a record; `at` is the current time.
function create(key, validValue, empty, at = new Date()) {
- const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365));
- const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); };
+ const now = offset(at, 0),
+ today = keyFor(now),
+ oldest = keyFor(offset(now, -365));
+ const invalid = () => {
+ throw new Error("Saved history is invalid. Restore your records before making changes.");
+ };
+ // Turn the saved text into { version, revision, entries: [{ date, value }], undo },
+ // or throw if anything about it is unexpected.
function parse(raw) {
- if (raw === "") return {version: 1, revision: 0, entries: [], undo: null};
+ // Nothing saved yet: start with an empty history.
+ if (raw === "") return { version: 1, revision: 0, entries: [], undo: null };
if (typeof raw !== "string" || raw.length > 64000) return invalid();
let state;
- try { state = JSON.parse(raw); } catch (_) { return invalid(); }
- if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 ||
- Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid();
+ try {
+ state = JSON.parse(raw);
+ } catch (_) {
+ return invalid();
+ }
+ // Exactly the four expected keys, and at most 366 days.
+ if (
+ !state ||
+ state.version !== 1 ||
+ !Number.isSafeInteger(state.revision) ||
+ state.revision < 0 ||
+ Object.keys(state).sort().join(",") !== "entries,revision,undo,version" ||
+ !Array.isArray(state.entries) ||
+ state.entries.length > 366
+ )
+ return invalid();
const dates = new Set();
+ // Every entry is { date, value } with a real, unique date and an acceptable value.
for (const entry of state.entries) {
- if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid();
+ if (
+ !entry ||
+ Object.keys(entry).sort().join(",") !== "date,value" ||
+ !validDate(entry.date) ||
+ dates.has(entry.date) ||
+ !validValue(entry.value)
+ )
+ return invalid();
dates.add(entry.date);
}
- if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) ||
- (state.undo.value !== null && !validValue(state.undo.value)))) return invalid();
+ // `undo` is null, or the { date, value } that the last change replaced (null = no record).
+ if (
+ state.undo !== null &&
+ (!state.undo ||
+ Object.keys(state.undo).sort().join(",") !== "date,value" ||
+ !validDate(state.undo.date) ||
+ (state.undo.value !== null && !validValue(state.undo.value)))
+ )
+ return invalid();
return state;
}
+ // $storage.getString returns "" when nothing was saved under the key.
const read = () => parse($storage.getString(key));
+ // The value recorded on `date` (today by default), or a copy of `empty`.
const value = (state, date = today) => {
const entry = state.entries.find((item) => item.date === date);
return entry ? clone(entry.value) : clone(empty);
};
+ // Save a change. transform(state) returns the new state, or null for "nothing to save".
+ // compareAndSetString writes only if the stored text is still `raw`; if the app or
+ // another widget saved in between, read again and retry, up to 4 times.
function commit(transform) {
for (let attempt = 0; attempt < 4; attempt++) {
- const raw = $storage.getString(key), state = parse(raw);
+ const raw = $storage.getString(key),
+ state = parse(raw);
const next = transform(clone(state));
if (next === null) return false;
if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid();
next.revision = state.revision + 1;
- next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date));
- if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date.");
+ // Drop days older than 365 days and keep the entries sorted by date.
+ next.entries = next.entries
+ .filter((entry) => entry.date >= oldest)
+ .sort((a, b) => a.date.localeCompare(b.date));
+ if (next.entries.length > 366)
+ throw new Error("History is full. Export records before adding another date.");
const encoded = JSON.stringify(next);
- if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data.");
+ if (encoded.length > 64000)
+ throw new Error("History is full. Export records before adding more data.");
if ($storage.compareAndSetString(key, raw, encoded)) return true;
}
throw new Error("Could not save. Storage is busy or unavailable; please try again.");
}
- const edit = (update) => commit((state) => {
- const old = state.entries.find((entry) => entry.date === today);
- const next = update(value(state));
- if (next !== null && !validValue(next)) throw new Error("Invalid record value.");
- if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null;
- state.undo = {date: today, value: old ? old.value : null};
- state.entries = state.entries.filter((entry) => entry.date !== today);
- if (next !== null) state.entries.push({date: today, value: next});
- return state;
- });
- const undo = () => commit((state) => {
- if (!state.undo) return null;
- if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window.");
- const previous = state.undo;
- state.entries = state.entries.filter((entry) => entry.date !== previous.date);
- if (previous.value !== null) state.entries.push(previous);
- state.undo = null;
- return state;
- });
- const recent = (state, count = 7) => Array.from({length: count}, (_, index) => {
- const date = keyFor(offset(now, index - count + 1));
- return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)};
- });
- return {today, read, value, edit, undo, reset: () => edit(() => null), recent};
+ // Replace today's value with update(currentValue). Returning null removes today's record.
+ const edit = (update) =>
+ commit((state) => {
+ const old = state.entries.find((entry) => entry.date === today);
+ const next = update(value(state));
+ if (next !== null && !validValue(next)) throw new Error("Invalid record value.");
+ // Nothing changed: do not save, and keep the undo step as it is.
+ if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null))
+ return null;
+ // Remember what today looked like, so undo() can put it back.
+ state.undo = { date: today, value: old ? old.value : null };
+ state.entries = state.entries.filter((entry) => entry.date !== today);
+ if (next !== null) state.entries.push({ date: today, value: next });
+ return state;
+ });
+ // Put back what the last edit replaced. Only one step can be undone.
+ const undo = () =>
+ commit((state) => {
+ if (!state.undo) return null;
+ if (state.undo.date < oldest)
+ throw new Error("The last change is outside the retained history window.");
+ const previous = state.undo;
+ state.entries = state.entries.filter((entry) => entry.date !== previous.date);
+ if (previous.value !== null) state.entries.push(previous);
+ state.undo = null;
+ return state;
+ });
+ // The last `count` days, oldest first: { date, value, recorded } for each.
+ const recent = (state, count = 7) =>
+ Array.from({ length: count }, (_, index) => {
+ const date = keyFor(offset(now, index - count + 1));
+ return {
+ date,
+ value: value(state, date),
+ recorded: state.entries.some((entry) => entry.date === date),
+ };
+ });
+ // What main.jsx can use. `today` is today's day key.
+ return { today, read, value, edit, undo, reset: () => edit(() => null), recent };
}
+ // configuration(kind) returns the settings of one template. Records & Configuration saves
+ // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply.
function configuration(kind) {
const defaults = {
- plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"},
- hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"},
- checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"},
- habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"},
+ plantCare: { title: "My plant", intervalDays: 3 },
+ pocketPet: { title: "Pebble" },
+ hydration: { goal: 8, glassML: 250 },
+ mood: { intention: "Pause, breathe, and notice" },
+ checklist: { items: ["Passport", "Charger", "Headphones"] },
+ habitStreak: { title: "Daily habit" },
+ habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" },
+ };
+ const invalid = () => {
+ throw new Error(
+ "Saved template configuration is invalid. Open Records & Configuration to repair it.",
+ );
};
- const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); };
if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid();
const raw = $storage.getString("recordTemplate.config.v1");
if (raw === "") return clone(defaults[kind]);
if (typeof raw !== "string" || raw.length > 4096) return invalid();
let state;
try {
+ // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes.
if (unescape(encodeURIComponent(raw)).length > 4096) return invalid();
state = JSON.parse(raw);
- } catch (_) { return invalid(); }
- if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind ||
- !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid();
+ } catch (_) {
+ return invalid();
+ }
+ // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults.
+ if (
+ !state ||
+ Object.keys(state).sort().join(",") !== "kind,values,version" ||
+ state.version !== 1 ||
+ state.kind !== kind ||
+ !state.values ||
+ Array.isArray(state.values) ||
+ Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")
+ )
+ return invalid();
const value = state.values;
- const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== "");
- const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum;
+ // Two small checks: a text of at most `length` characters, a whole number in a range.
+ const text = (input, length, empty = false) =>
+ typeof input === "string" && input.length <= length && (empty || input.trim() !== "");
+ const integer = (input, minimum, maximum) =>
+ Number.isInteger(input) && input >= minimum && input <= maximum;
let valid = false;
+ // Each template has its own limits.
if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30);
if (kind === "pocketPet") valid = text(value.title, 40);
- if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000);
+ if (kind === "hydration")
+ valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000);
if (kind === "mood") valid = text(value.intention, 80, true);
if (kind === "habitStreak") valid = text(value.title, 40);
- if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40));
- if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 &&
- new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC"));
+ if (kind === "habitHeatmap")
+ valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40));
+ if (kind === "checklist")
+ valid =
+ Array.isArray(value.items) &&
+ value.items.length >= 1 &&
+ value.items.length <= 8 &&
+ new Set(value.items).size === value.items.length &&
+ value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC"));
if (!valid) return invalid();
return clone(value);
}
- return {create, configuration};
+ return { create, configuration };
})();
diff --git a/Gallery/widgets/habit-heatmap/main.jsx b/Gallery/widgets/habit-heatmap/main.jsx
index 59076497..4ab69c1e 100644
--- a/Gallery/widgets/habit-heatmap/main.jsx
+++ b/Gallery/widgets/habit-heatmap/main.jsx
@@ -7,44 +7,91 @@
// renaming a habit's display name preserves its stable id and history.
// Keep up to ten years of local calendar dates per habit. No network required.
// Duplicate copies have separate history; this is not iCloud sync.
+// Shows a grid of the days on which each of three habits was done, like a GitHub
+// contribution graph. Try changing the colors in `habits`, or the weeks and cell size
+// passed to .
+// $storage needs the permission "storage" in widget.json; the buttons need its "actions".
-if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js.");
+// $import runs another file of this package; lib/records.js defines `localRecords`.
+// It returns false when the file is missing.
+if (!$import("lib/records.js"))
+ throw new Error("Install the complete template, including lib/records.js.");
+// The habit names set in Records & Configuration, or the defaults Read, Run, Meditate.
const savedNames = localRecords.configuration("habitHeatmap");
+// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline".
const size = $getenv("widget-size");
+// `action` names the function that a tap calls. `color` holds five shades from empty
+// to full; a day is either done or not, so only the first and the last are used.
const habits = [
- { id: "read", name: savedNames.readName, action: "checkInRead", color: ["#1B2A1E", "#0E4429", "#006D32", "#26A641", "#39D353"] },
- { id: "run", name: savedNames.runName, action: "checkInRun", color: ["#1E1B2A", "#2E2266", "#4434A5", "#6B5BE0", "#9D8CFF"] },
- { id: "meditate", name: savedNames.meditateName, action: "checkInMeditate", color: ["#2A1E1B", "#5C2A10", "#9A4A12", "#D9741C", "#FFA94D"] },
+ {
+ id: "read",
+ name: savedNames.readName,
+ action: "checkInRead",
+ color: ["#1B2A1E", "#0E4429", "#006D32", "#26A641", "#39D353"],
+ },
+ {
+ id: "run",
+ name: savedNames.runName,
+ action: "checkInRun",
+ color: ["#1E1B2A", "#2E2266", "#4434A5", "#6B5BE0", "#9D8CFF"],
+ },
+ {
+ id: "meditate",
+ name: savedNames.meditateName,
+ action: "checkInMeditate",
+ color: ["#2A1E1B", "#5C2A10", "#9A4A12", "#D9741C", "#FFA94D"],
+ },
];
-const dateKey = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+// Day key in local time, for example "2026-03-08".
+const dateKey = (date) =>
+ `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
// Calendar arithmetic at noon handles DST without assuming 24-hour days.
-const dayOffset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12);
+const dayOffset = (date, days) =>
+ new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12);
const today = dayOffset(new Date(), 0);
const todayKey = dateKey(today);
+// Days older than about ten years (3660 days) are dropped when saving.
const oldestKey = dateKey(dayOffset(today, -3659));
+// Each habit's days are saved under its own key, as a JSON list of day keys.
const storageKey = (habit) => `habitHeatmap.v1.${habit.id}`;
+// Turn the saved text into a sorted list of day keys, or throw if it is not such a list.
const parseDays = (raw) => {
if (!raw) return [];
let days;
- try { days = JSON.parse(raw); } catch (error) { throw new Error("Habit history is unreadable. Restore it before checking in."); }
- if (!Array.isArray(days) || days.length > 3660 || days.some((day) => {
- if (typeof day !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(day)) return true;
- const parts = day.split("-").map(Number);
- return dateKey(new Date(parts[0], parts[1] - 1, parts[2], 12)) !== day;
- })) throw new Error("Invalid habit history. Restore it before checking in.");
+ try {
+ days = JSON.parse(raw);
+ } catch (error) {
+ throw new Error("Habit history is unreadable. Restore it before checking in.");
+ }
+ if (
+ !Array.isArray(days) ||
+ days.length > 3660 ||
+ days.some((day) => {
+ if (typeof day !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(day)) return true;
+ const parts = day.split("-").map(Number);
+ return dateKey(new Date(parts[0], parts[1] - 1, parts[2], 12)) !== day;
+ })
+ )
+ throw new Error("Invalid habit history. Restore it before checking in.");
return Array.from(new Set(days)).sort();
};
+// $storage.getString returns "" when nothing was saved under the key.
const readDays = (habit) => parseDays($storage.getString(storageKey(habit)));
+// Mark today as done for one habit. This runs when a Check in button is tapped.
function checkIn(habit) {
// A conflict rereads and revalidates history rather than replacing another
// process's new day. Rendering and rejected attempts never create records.
for (let attempt = 0; attempt < 4; attempt++) {
const raw = $storage.getString(storageKey(habit));
const days = parseDays(raw);
- if (days.includes(todayKey)) { $render(Already checked in); return; }
+ if (days.includes(todayKey)) {
+ $render(Already checked in);
+ return;
+ }
const updated = days.filter((day) => day >= oldestKey);
updated.push(todayKey);
updated.sort();
+ // compareAndSetString writes only if the stored text is still `raw`.
if (updated.length > 3660 || typeof $storage.compareAndSetString !== "function") break;
if ($storage.compareAndSetString(storageKey(habit), raw, JSON.stringify(updated))) {
$render(Checked in);
@@ -53,19 +100,33 @@ function checkIn(habit) {
}
throw new Error("Could not save check-in. Storage may be busy; please try again.");
}
-function checkInRead() { return checkIn(habits[0]); }
-function checkInRun() { return checkIn(habits[1]); }
-function checkInMeditate() { return checkIn(habits[2]); }
+// The functions named by the "actions" in widget.json, one per habit.
+function checkInRead() {
+ return checkIn(habits[0]);
+}
+function checkInRun() {
+ return checkIn(habits[1]);
+}
+function checkInMeditate() {
+ return checkIn(habits[2]);
+}
+// Read the data: one list of days per habit.
const records = habits.map(readDays);
+// Days in a row that are done, ending today, or yesterday if today is not done yet.
const streak = (days) => {
const completed = new Set(days);
let offset = completed.has(todayKey) ? 0 : -1;
let count = 0;
- while (count < 3660 && completed.has(dateKey(dayOffset(today, offset)))) { count++; offset--; }
+ while (count < 3660 && completed.has(dateKey(dayOffset(today, offset)))) {
+ count++;
+ offset--;
+ }
return count;
};
// Monday-first columns; future days in the current week stay blank.
-const weekEnd = dayOffset(today, 6 - (today.getDay() + 6) % 7);
+// getDay() is 0 on Sunday; (getDay() + 6) % 7 is 0 on Monday. weekEnd is this week's Sunday.
+const weekEnd = dayOffset(today, 6 - ((today.getDay() + 6) % 7));
+// Per habit, 26 weeks of cells: 4 = done, 0 = not done, -1 = a day still to come.
const logs = records.map((days) => {
const completed = new Set(days);
return Array.from({ length: 26 * 7 }, (_, index) => {
@@ -74,6 +135,7 @@ const logs = records.map((days) => {
});
});
+// Draws the last `weeks` weeks of a log: squares of `cell` points, `gap` points apart.
const Grid = ({ log, colors, weeks, cell, gap }) => {
const days = log.slice(-weeks * 7);
// Columns are weeks, rows are weekdays, as in a contribution graph.
@@ -81,90 +143,155 @@ const Grid = ({ log, colors, weeks, cell, gap }) => {
{Array.from({ length: weeks }, (_, week) => (
- {days.slice(week * 7, week * 7 + 7).map((level) => )}
+ {days.slice(week * 7, week * 7 + 7).map((level) => (
+
+ ))}
))}
);
};
+// The saved days of a habit.
const daysFor = (habit) => records[habits.findIndex((item) => item.id === habit.id)];
const streakLabel = (habit) => {
const count = streak(daysFor(habit));
return `${count} ${count === 1 ? "day" : "days"}`;
};
+// The habit name on the left; the streak with a flame on the right.
const Header = ({ habit, font }) => (
- {habit.name}
+
+ {habit.name}
+
- {streakLabel(habit)}
+
+ {streakLabel(habit)}
+
);
+// A label to tap. actionID names an action in widget.json, which names the function
+// to call. Needs iOS 17 or macOS 14.
const CheckIn = ({ habit }) => (
);
// The flame counts consecutive days and returns to 0 after a missed day; this
// count is every recorded check-in and never goes down.
-const Total = ({ habit }) => {`${daysFor(habit).length} total`};
+const Total = ({ habit }) => (
+ {`${daysFor(habit).length} total`}
+);
+// Choose a layout for the widget size. A tap runs this script with the size "action".
// App Intent calls the named function after evaluating this source.
if (size === "action") {
// Do not render a widget while handling a tap.
} else if (size === "accessoryCircular") {
- $render({streak(records[0])});
+ // Lock Screen, circular: the streak of the first habit.
+ $render(
+
+
+
+ {streak(records[0])}
+
+ ,
+ );
} else if (size === "accessoryRectangular") {
+ // Lock Screen, rectangular: the first habit as a gray grid of 20 weeks.
$render(
- {habits[0].name} · {streak(records[0])}-day streak
- (level < 0 ? -1 : level > 0 ? 4 : 1))} colors={["#444444", "#666666", "#888888", "#AAAAAA", "#FFFFFF"]} weeks={20} cell={5} gap={1.5} />
-
+
+ {habits[0].name} · {streak(records[0])}-day streak
+
+ (level < 0 ? -1 : level > 0 ? 4 : 1))}
+ colors={["#444444", "#666666", "#888888", "#AAAAAA", "#FFFFFF"]}
+ weeks={20}
+ cell={5}
+ gap={1.5}
+ />
+ ,
);
} else if (size === "accessoryInline") {
- $render({habits[0].name} · {streak(records[0])}-day streak);
+ // Lock Screen, inline: one line of text.
+ $render(
+
+ {habits[0].name} · {streak(records[0])}-day streak
+ ,
+ );
} else if (size === "small") {
+ // Small widget: the first habit, 8 weeks.
$render(
-
-
+
+
+
+
+
+ ,
);
} else if (size === "medium") {
+ // Medium widget: the first habit, 22 weeks.
$render(
-
-
+
+
+
+
+
+ ,
);
} else if (size === "extraLarge") {
+ // Extra large widget: the three habits side by side.
$render(
{habits.map((habit, index) => (
-
+
+
+
+
+
))}
-
+ ,
);
} else {
+ // Large widget: the three habits one below the other, 26 weeks each.
$render(
{habits.map((habit, index) => (
-
+
+
+
+
+
))}
-
+ ,
);
}
diff --git a/Gallery/widgets/habit-streak/lib/records.js b/Gallery/widgets/habit-streak/lib/records.js
index e9eaef0f..3e1682ad 100644
--- a/Gallery/widgets/habit-streak/lib/records.js
+++ b/Gallery/widgets/habit-streak/lib/records.js
@@ -1,111 +1,216 @@
// Identical package-local helper in the built-in record templates.
// Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync.
+// main.jsx imports this file ("lib/records.js") and then uses `localRecords`.
+// It keeps one value per calendar day in $storage (permission "storage" in widget.json)
+// and reads the settings saved by Records & Configuration in the app.
var localRecords = (() => {
- const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
- const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12);
+ // Day key in local time, for example "2026-03-08".
+ const keyFor = (date) =>
+ `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+ // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it.
+ const offset = (date, days) =>
+ new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12);
+ // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected).
const validDate = (key) => {
if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false;
const parts = key.split("-").map(Number);
return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key;
};
+ // A deep copy, so a caller cannot change the saved state by accident.
const clone = (value) => JSON.parse(JSON.stringify(value));
+ // create(key, validValue, empty) returns the record log stored under `key`.
+ // validValue(value) says whether a day's value is acceptable; `empty` is the value of a
+ // day without a record; `at` is the current time.
function create(key, validValue, empty, at = new Date()) {
- const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365));
- const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); };
+ const now = offset(at, 0),
+ today = keyFor(now),
+ oldest = keyFor(offset(now, -365));
+ const invalid = () => {
+ throw new Error("Saved history is invalid. Restore your records before making changes.");
+ };
+ // Turn the saved text into { version, revision, entries: [{ date, value }], undo },
+ // or throw if anything about it is unexpected.
function parse(raw) {
- if (raw === "") return {version: 1, revision: 0, entries: [], undo: null};
+ // Nothing saved yet: start with an empty history.
+ if (raw === "") return { version: 1, revision: 0, entries: [], undo: null };
if (typeof raw !== "string" || raw.length > 64000) return invalid();
let state;
- try { state = JSON.parse(raw); } catch (_) { return invalid(); }
- if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 ||
- Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid();
+ try {
+ state = JSON.parse(raw);
+ } catch (_) {
+ return invalid();
+ }
+ // Exactly the four expected keys, and at most 366 days.
+ if (
+ !state ||
+ state.version !== 1 ||
+ !Number.isSafeInteger(state.revision) ||
+ state.revision < 0 ||
+ Object.keys(state).sort().join(",") !== "entries,revision,undo,version" ||
+ !Array.isArray(state.entries) ||
+ state.entries.length > 366
+ )
+ return invalid();
const dates = new Set();
+ // Every entry is { date, value } with a real, unique date and an acceptable value.
for (const entry of state.entries) {
- if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid();
+ if (
+ !entry ||
+ Object.keys(entry).sort().join(",") !== "date,value" ||
+ !validDate(entry.date) ||
+ dates.has(entry.date) ||
+ !validValue(entry.value)
+ )
+ return invalid();
dates.add(entry.date);
}
- if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) ||
- (state.undo.value !== null && !validValue(state.undo.value)))) return invalid();
+ // `undo` is null, or the { date, value } that the last change replaced (null = no record).
+ if (
+ state.undo !== null &&
+ (!state.undo ||
+ Object.keys(state.undo).sort().join(",") !== "date,value" ||
+ !validDate(state.undo.date) ||
+ (state.undo.value !== null && !validValue(state.undo.value)))
+ )
+ return invalid();
return state;
}
+ // $storage.getString returns "" when nothing was saved under the key.
const read = () => parse($storage.getString(key));
+ // The value recorded on `date` (today by default), or a copy of `empty`.
const value = (state, date = today) => {
const entry = state.entries.find((item) => item.date === date);
return entry ? clone(entry.value) : clone(empty);
};
+ // Save a change. transform(state) returns the new state, or null for "nothing to save".
+ // compareAndSetString writes only if the stored text is still `raw`; if the app or
+ // another widget saved in between, read again and retry, up to 4 times.
function commit(transform) {
for (let attempt = 0; attempt < 4; attempt++) {
- const raw = $storage.getString(key), state = parse(raw);
+ const raw = $storage.getString(key),
+ state = parse(raw);
const next = transform(clone(state));
if (next === null) return false;
if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid();
next.revision = state.revision + 1;
- next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date));
- if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date.");
+ // Drop days older than 365 days and keep the entries sorted by date.
+ next.entries = next.entries
+ .filter((entry) => entry.date >= oldest)
+ .sort((a, b) => a.date.localeCompare(b.date));
+ if (next.entries.length > 366)
+ throw new Error("History is full. Export records before adding another date.");
const encoded = JSON.stringify(next);
- if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data.");
+ if (encoded.length > 64000)
+ throw new Error("History is full. Export records before adding more data.");
if ($storage.compareAndSetString(key, raw, encoded)) return true;
}
throw new Error("Could not save. Storage is busy or unavailable; please try again.");
}
- const edit = (update) => commit((state) => {
- const old = state.entries.find((entry) => entry.date === today);
- const next = update(value(state));
- if (next !== null && !validValue(next)) throw new Error("Invalid record value.");
- if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null;
- state.undo = {date: today, value: old ? old.value : null};
- state.entries = state.entries.filter((entry) => entry.date !== today);
- if (next !== null) state.entries.push({date: today, value: next});
- return state;
- });
- const undo = () => commit((state) => {
- if (!state.undo) return null;
- if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window.");
- const previous = state.undo;
- state.entries = state.entries.filter((entry) => entry.date !== previous.date);
- if (previous.value !== null) state.entries.push(previous);
- state.undo = null;
- return state;
- });
- const recent = (state, count = 7) => Array.from({length: count}, (_, index) => {
- const date = keyFor(offset(now, index - count + 1));
- return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)};
- });
- return {today, read, value, edit, undo, reset: () => edit(() => null), recent};
+ // Replace today's value with update(currentValue). Returning null removes today's record.
+ const edit = (update) =>
+ commit((state) => {
+ const old = state.entries.find((entry) => entry.date === today);
+ const next = update(value(state));
+ if (next !== null && !validValue(next)) throw new Error("Invalid record value.");
+ // Nothing changed: do not save, and keep the undo step as it is.
+ if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null))
+ return null;
+ // Remember what today looked like, so undo() can put it back.
+ state.undo = { date: today, value: old ? old.value : null };
+ state.entries = state.entries.filter((entry) => entry.date !== today);
+ if (next !== null) state.entries.push({ date: today, value: next });
+ return state;
+ });
+ // Put back what the last edit replaced. Only one step can be undone.
+ const undo = () =>
+ commit((state) => {
+ if (!state.undo) return null;
+ if (state.undo.date < oldest)
+ throw new Error("The last change is outside the retained history window.");
+ const previous = state.undo;
+ state.entries = state.entries.filter((entry) => entry.date !== previous.date);
+ if (previous.value !== null) state.entries.push(previous);
+ state.undo = null;
+ return state;
+ });
+ // The last `count` days, oldest first: { date, value, recorded } for each.
+ const recent = (state, count = 7) =>
+ Array.from({ length: count }, (_, index) => {
+ const date = keyFor(offset(now, index - count + 1));
+ return {
+ date,
+ value: value(state, date),
+ recorded: state.entries.some((entry) => entry.date === date),
+ };
+ });
+ // What main.jsx can use. `today` is today's day key.
+ return { today, read, value, edit, undo, reset: () => edit(() => null), recent };
}
+ // configuration(kind) returns the settings of one template. Records & Configuration saves
+ // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply.
function configuration(kind) {
const defaults = {
- plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"},
- hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"},
- checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"},
- habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"},
+ plantCare: { title: "My plant", intervalDays: 3 },
+ pocketPet: { title: "Pebble" },
+ hydration: { goal: 8, glassML: 250 },
+ mood: { intention: "Pause, breathe, and notice" },
+ checklist: { items: ["Passport", "Charger", "Headphones"] },
+ habitStreak: { title: "Daily habit" },
+ habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" },
+ };
+ const invalid = () => {
+ throw new Error(
+ "Saved template configuration is invalid. Open Records & Configuration to repair it.",
+ );
};
- const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); };
if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid();
const raw = $storage.getString("recordTemplate.config.v1");
if (raw === "") return clone(defaults[kind]);
if (typeof raw !== "string" || raw.length > 4096) return invalid();
let state;
try {
+ // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes.
if (unescape(encodeURIComponent(raw)).length > 4096) return invalid();
state = JSON.parse(raw);
- } catch (_) { return invalid(); }
- if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind ||
- !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid();
+ } catch (_) {
+ return invalid();
+ }
+ // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults.
+ if (
+ !state ||
+ Object.keys(state).sort().join(",") !== "kind,values,version" ||
+ state.version !== 1 ||
+ state.kind !== kind ||
+ !state.values ||
+ Array.isArray(state.values) ||
+ Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")
+ )
+ return invalid();
const value = state.values;
- const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== "");
- const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum;
+ // Two small checks: a text of at most `length` characters, a whole number in a range.
+ const text = (input, length, empty = false) =>
+ typeof input === "string" && input.length <= length && (empty || input.trim() !== "");
+ const integer = (input, minimum, maximum) =>
+ Number.isInteger(input) && input >= minimum && input <= maximum;
let valid = false;
+ // Each template has its own limits.
if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30);
if (kind === "pocketPet") valid = text(value.title, 40);
- if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000);
+ if (kind === "hydration")
+ valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000);
if (kind === "mood") valid = text(value.intention, 80, true);
if (kind === "habitStreak") valid = text(value.title, 40);
- if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40));
- if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 &&
- new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC"));
+ if (kind === "habitHeatmap")
+ valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40));
+ if (kind === "checklist")
+ valid =
+ Array.isArray(value.items) &&
+ value.items.length >= 1 &&
+ value.items.length <= 8 &&
+ new Set(value.items).size === value.items.length &&
+ value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC"));
if (!valid) return invalid();
return clone(value);
}
- return {create, configuration};
+ return { create, configuration };
})();
diff --git a/Gallery/widgets/habit-streak/main.jsx b/Gallery/widgets/habit-streak/main.jsx
index 06171965..ff75485a 100644
--- a/Gallery/widgets/habit-streak/main.jsx
+++ b/Gallery/widgets/habit-streak/main.jsx
@@ -1,40 +1,143 @@
// Explicit check-ins only. Optional widget-param: your habit name (up to 40 characters).
// The earlier template recorded automatically on refresh. Its original keys stay
// untouched; they are not reliable evidence of completed days and are never imported.
-if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js.");
-const size = $getenv("widget-size"), title = ($getenv("widget-param") || localRecords.configuration("habitStreak").title).trim();
+// Shows how many days in a row you checked in, with Check in, Undo and Reset buttons.
+// Try changing the colors below, or the habit name in Records & Configuration.
+// $storage needs the permission "storage" in widget.json; the buttons need its "actions".
+
+// $import runs another file of this package; lib/records.js defines `localRecords`.
+// It returns false when the file is missing.
+if (!$import("lib/records.js"))
+ throw new Error("Install the complete template, including lib/records.js.");
+// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline".
+// $getenv("widget-param") is the optional widget parameter, a text you set on each widget.
+const size = $getenv("widget-size"),
+ title = ($getenv("widget-param") || localRecords.configuration("habitStreak").title).trim();
if (!title || title.length > 40) throw new Error("Use a habit name of 1–40 characters.");
+// One record per day under the key "habitStreak.v2": 1 means done; no record reads as 0.
const log = localRecords.create("habitStreak.v2", (value) => value === 1, 0);
-function checkIn() { const changed = log.edit(() => 1); $render({changed ? "Checked in" : "Already checked in"}); }
-function undoRecord() { const changed = log.undo(); $render({changed ? "Change undone" : "Nothing to undo"}); }
-function resetToday() { log.reset(); $render(Today cleared; Undo can restore it); }
-const state = log.read(), done = log.value(state) === 1;
+// The three functions below are named by the "actions" in widget.json. A tap on a
+//