first commit
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m4s
All checks were successful
Verify and publish Calio container / build-and-push (push) Successful in 1m4s
This commit is contained in:
commit
6fc0a01c56
51 changed files with 11319 additions and 0 deletions
7
.dockerignore
Normal file
7
.dockerignore
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
.git
|
||||
node_modules
|
||||
dist
|
||||
data
|
||||
.env
|
||||
.local
|
||||
test-results
|
||||
7
.env.example
Normal file
7
.env.example
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
# Copy to .env. Never commit .env.
|
||||
APP_ORIGIN=https://calio.example.com
|
||||
CALIO_USERNAME=calio
|
||||
CALIO_PASSWORD=replace-with-a-long-unique-password
|
||||
CALIO_PORT=3000
|
||||
# Only for local testing with APP_ORIGIN=http://localhost:3000:
|
||||
# COOKIE_SECURE=false
|
||||
48
.forgejo/workflows/build.yml
Normal file
48
.forgejo/workflows/build.yml
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
name: Verify and publish Calio container
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
if: github.event.deleted != true
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
JOB_IMAGE: calio-ci:${{ github.run_id }}
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
- name: Set up Node 24
|
||||
uses: https://github.com/actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
- name: Install locked dependencies
|
||||
run: npm ci --no-audit --no-fund
|
||||
- name: Run tests
|
||||
run: npm test
|
||||
- name: Build application
|
||||
run: npm run build
|
||||
- name: Build production container
|
||||
env:
|
||||
COMMIT_SHA: ${{ github.sha }}
|
||||
run: docker build --label "org.opencontainers.image.revision=$COMMIT_SHA" -t "$JOB_IMAGE" .
|
||||
- name: Smoke test container and persistent data
|
||||
run: |
|
||||
node scripts/container-smoke.js "$JOB_IMAGE"
|
||||
node scripts/container-smoke.js "$JOB_IMAGE" --unraid
|
||||
- name: Publish image to Forgejo registry
|
||||
if: github.event_name == 'push' || github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
FORGEJO_PAT: ${{ secrets.FORGEJO_PAT }}
|
||||
SOURCE_IMAGE: ${{ env.JOB_IMAGE }}
|
||||
REGISTRY_USERNAME: ${{ vars.REGISTRY_USERNAME || github.repository_owner }}
|
||||
REPOSITORY: ${{ github.repository }}
|
||||
CI_EVENT: ${{ github.event_name }}
|
||||
COMMIT_SHA: ${{ github.sha }}
|
||||
TARGET_REF: ${{ github.ref }}
|
||||
MAIN_BRANCH: ${{ github.event.repository.default_branch || 'main' }}
|
||||
run: node scripts/publish-image.js
|
||||
- name: Remove temporary build tag
|
||||
if: always()
|
||||
run: docker image rm "$JOB_IMAGE" || true
|
||||
9
.gitignore
vendored
Normal file
9
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
node_modules/
|
||||
dist/
|
||||
data/
|
||||
.env
|
||||
*.tsbuildinfo
|
||||
coverage/
|
||||
test-results/
|
||||
playwright-report/
|
||||
.local/
|
||||
27
Dockerfile
Normal file
27
Dockerfile
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
FROM node:24-alpine AS build
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --no-audit --no-fund
|
||||
COPY tsconfig.json vite.config.ts index.html ./
|
||||
COPY src ./src
|
||||
COPY shared ./shared
|
||||
COPY public ./public
|
||||
COPY scripts/build-sw.js ./scripts/build-sw.js
|
||||
RUN npm run build
|
||||
|
||||
FROM node:24-alpine AS runtime
|
||||
LABEL org.opencontainers.image.title="Calio" \
|
||||
org.opencontainers.image.description="Personal offline-first nutrition and weight journal" \
|
||||
org.opencontainers.image.source="https://git.elijahkuntz.com/Elijah/Calio"
|
||||
ENV NODE_ENV=production PORT=3000 DATA_DIR=/data
|
||||
WORKDIR /app
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --omit=dev --no-audit --no-fund && npm cache clean --force && mkdir /data && chown node:node /data
|
||||
COPY --from=build /app/dist ./dist
|
||||
COPY server ./server
|
||||
COPY shared ./shared
|
||||
USER node
|
||||
VOLUME /data
|
||||
EXPOSE 3000
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s CMD node -e "fetch('http://127.0.0.1:3000/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
|
||||
CMD ["node", "server/index.js"]
|
||||
104
README.md
Normal file
104
README.md
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
# Calio
|
||||
|
||||
A single-user, self-hosted nutrition journal. PWA first, with a responsive desktop layout, light/dark/system themes, configurable accent colors, and no third-party analytics, fonts, or nutrition services. Dark mode uses neutral near-black and charcoal surfaces; choose a preset or custom accent under Settings → Look & feel, then save preferences. Accent preferences sync between devices and remain available offline.
|
||||
|
||||
## Included
|
||||
|
||||
- Daily calorie vessel with colliding physics bubbles, week navigation, meal journal, editable entries, fractional servings. New bubbles drop from the top as calories increase.
|
||||
- Saved foods and reusable plates. Logging a plate creates an atomic batch of independent food entries. Logs retain a nutrition snapshot when library foods change.
|
||||
- Independently enabled calorie, protein, carbohydrate, fat, fiber, sugar and sodium goals.
|
||||
- Weight journal in lb or kg; internally stored in kg. Multiple weigh-ins are retained, with the latest measurement per day used in charts.
|
||||
- 7 / 30 / 90 / 365 day nutrition and weight trends. Unlogged days are excluded from intake averages.
|
||||
- Markdown, CSV and JSON export with date range, nutrient and weight selections. Markdown is designed for LLM analysis. Data is downloaded locally, never submitted to an LLM. Save preferences to remember the export format, range preset and selections.
|
||||
- Password authentication, IndexedDB offline journal/outbox, a precached app shell, automatic foreground/reconnect sync, and explicit PWA update prompts.
|
||||
|
||||
Barcode lookup and nutrition-label OCR are deferred. This release uses manual nutrition entry and saved foods. It does not include Apple Watch integration, HealthKit, fasting, reminders or water tracking; those screenshot features were not part of the requested core.
|
||||
|
||||
## Deploy on Unraid
|
||||
|
||||
Forgejo builds and publishes the image; Unraid runs it through **Docker → Add Container**. Compose is optional and is not required for deployment. Follow [the Unraid setup guide](docs/UNRAID.md), or import [the Docker template](unraid/calio.xml).
|
||||
|
||||
Use repository `git.elijahkuntz.com/elijah/calio:latest`, container port `3000` (suggested host port `3080`), and a persistent mapping from `/mnt/user/appdata/calio` to `/data`. Set `APP_ORIGIN` to the exact **HTTPS origin, without a trailing slash**, `CALIO_USERNAME` to your username, and `CALIO_PASSWORD` to a unique password of at least 12 characters. There is no registration screen or default password. The template runs as Unraid's `99:100`; the mapped directory must be writable by that user. The image's standalone default is UID 1000.
|
||||
|
||||
Forward your HTTPS reverse proxy to `http://<Unraid-IP>:3080`, or to `calio:3000` on a shared Docker network. All paths, including `/api`, must reach Calio. Open the public HTTPS address and sign in once while online. On iPhone, use Safari → Share → **Add to Home Screen**. On Android, use Chrome's **Install app** / **Add to home screen**. Desktop browsers work too.
|
||||
|
||||
The registry image becomes available after the source is pushed and the first publishing workflow succeeds. See the Forgejo setup below for the required registry secret.
|
||||
|
||||
HTTPS is required for installed-device service workers and secure authentication cookies. `COOKIE_SECURE=false` is accepted only when `APP_ORIGIN` uses `localhost` or `127.0.0.1`; use it solely for local tests. Production defaults to Secure, HttpOnly, SameSite=Strict cookies.
|
||||
|
||||
For an optional local source trial, copy `.env.example` to `.env`, set a password, `APP_ORIGIN=http://localhost:3000` and `COOKIE_SECURE=false`, then run `docker compose up -d --build` and visit `http://localhost:3000`. These local settings cannot be used to install from a phone over a LAN IP.
|
||||
|
||||
### Credentials and secrets
|
||||
|
||||
The server supports `CALIO_PASSWORD`, `CALIO_PASSWORD_FILE`, `CALIO_PASSWORD_HASH`, or `CALIO_PASSWORD_HASH_FILE`. File variants accept Docker secrets. A hash avoids retaining a plaintext password in container configuration. Generate a salted scrypt hash by piping a password into `npm run --silent password` (stdin only). Do not put real passwords in shell history.
|
||||
|
||||
When using a hash, replace the `CALIO_PASSWORD` container variable with `CALIO_PASSWORD_HASH`. For a file, mount it read-only and set the appropriate `_FILE` variable to its container path. `.env` and runtime data are ignored by Git.
|
||||
|
||||
Sessions expire after 30 days and persist in SQLite. Changing credentials does not revoke existing sessions automatically. To invalidate all sessions, stop the app and delete the rows from the `sessions` table using a SQLite tool, then restart. The public login is rate limited to 10 requests per 15 minutes per connection IP; behind a proxy this conservatively shares the limit across clients. The app does not trust arbitrary forwarded-IP headers.
|
||||
|
||||
## Persistent data, updates and backups
|
||||
|
||||
SQLite lives at `/data/calio.sqlite`, mapped to `/mnt/user/appdata/calio` on Unraid. Keep this directory and mapping when replacing the image. The optional Compose setup uses a named `calio-data` volume instead. Schema migrations are versioned and transactional; an older app refuses to open a newer schema.
|
||||
|
||||
Before updating, make a consistent backup while Calio is running:
|
||||
|
||||
```sh
|
||||
docker exec calio node server/backup.js /data/backups/before-update.sqlite
|
||||
docker cp calio:/data/backups/before-update.sqlite ./calio-backup.sqlite
|
||||
```
|
||||
|
||||
Choose a new filename for each backup. `VACUUM INTO` captures a consistent SQLite snapshot, including committed writes in WAL; copying only the live main database file is not a safe backup. Keep a copy off the server. Nutrition exports are useful for analysis but are **not** full database backups (they omit library data, tombstones and sessions).
|
||||
|
||||
Use Unraid's **Check for Updates → Update** to pull the new `latest` image and recreate the container with its saved settings. Forgejo publishes images; it does not automatically update or restart Unraid. You can pin the repository field to a full commit SHA or a published `v*` version tag for repeatable deployment. The PWA will offer **Update** after loading online; accepting it changes app code without clearing IndexedDB. Pending local changes must sync before applying an update.
|
||||
|
||||
To restore a database backup: stop Calio, preserve the current data directory, replace `calio.sqlite` with the backup, and remove the old `calio.sqlite-wal` and `calio.sqlite-shm` sidecars **while stopped**. Preserve ownership for the configured container user (`99:100` with the Unraid template; `1000:1000` by default), then restart. A server-only restore does not remove newer records already cached on devices: those may sync back. For a deliberate rollback, export pending device changes first, clear this site's device storage on each device, then sign in and fetch the restored journal. Do not clear device storage before saving unsynced entries.
|
||||
|
||||
### Offline and conflict behavior
|
||||
|
||||
- After the first authenticated sync, the complete journal, settings, food library and plates are held in IndexedDB. The complete current day can be reopened, edited, logged and exported offline.
|
||||
- An IndexedDB transaction saves each local mutation and its outbox entry together. A plate's entries are saved as one transaction. Requests acknowledge only the exact versions sent, so a local edit made during a sync remains queued.
|
||||
- Sync runs on app start, reconnect, return to the foreground, and once a minute while visible. It does not depend on iOS background sync support. If a server is unavailable, entries remain on-device and a retry status is shown.
|
||||
- Independent record additions merge. Edits to the same record use the latest device edit timestamp; exact ties use an ordinal payload comparison for the same result on all devices. Settings are one record, so the latest complete settings edit wins. Deletions are retained as tombstones so stale devices cannot resurrect records. Requests are retried idempotently.
|
||||
- Keep device clocks accurate. Edits over five minutes ahead of the server are rejected with a visible sync error; they remain on-device and can be exported. Once the server clock catches up they can sync. This avoids a bad device clock permanently outranking normal edits.
|
||||
- An expired session preserves the local journal and asks for sign-in to resume server sync. Explicit sign-out requires pending changes to sync, then removes this device's journal. The offline cache is accessible to someone with access to this unlocked browser/device; it is not an encrypted vault.
|
||||
- Browser storage can be cleared or evicted by the OS. Calio requests persistent storage, but the browser decides whether to grant it. Sync and backups remain the durable record. Check the sync status before clearing browser data or leaving a device.
|
||||
- Each sync currently exchanges the complete record set. This keeps the single-user implementation auditable and caches all history; very large multi-year journals may eventually benefit from incremental pagination.
|
||||
|
||||
### Bubble motion
|
||||
|
||||
Tap **Enable tilt** beneath the calorie circle to allow device orientation. On iPhone, Safari asks for motion/orientation permission from that tap; the public site must use HTTPS. The app remembers the choice for the current page session and does not transmit sensor readings. Portrait, landscape and upside-down positions are mapped to the screen's gravity direction. Devices without sensors, or with permission denied, retain downward gravity and the **Give a nudge** control.
|
||||
|
||||
The circle uses a bounded Matter.js simulation: bubbles collide with each other and the circular wall, new calorie bubbles drop from the top, and removing calories removes the corresponding particles. Bubbles draw smaller than their collision boundaries, creating a small visible gap between them. A full hexagonal packing defines the 100% capacity; near a full vessel, the numeric readout moves below the circle so it does not hide dots. The particle count caps at the daily goal; over-goal calories still show the exact excess and a red ring. With the calorie goal disabled, the display uses a fixed 2,500 kcal visual scale. The animation sleeps when settled, pauses in hidden tabs, and honors the device's reduced-motion preference with a still arrangement. The graphic is an approximate visual; the numeric calorie total is authoritative.
|
||||
|
||||
## Forgejo CI and container registry
|
||||
|
||||
`.forgejo/workflows/build.yml` runs on every branch/tag push, pull request and manual dispatch. It installs locked dependencies, runs tests and a production build, builds the Docker image, and runs `scripts/container-smoke.js` with both the image default user and Unraid's `99:100`. The smoke test uses temporary containers/volumes, verifies auth and static assets, and recreates the container to verify journal/session persistence. Probes run inside the container, so socket-mounted runners do not depend on host port forwarding.
|
||||
|
||||
The workflow matches the existing Docker-capable `unraid-runner` label, `ubuntu-latest`, and uses the same secret name as the Study pipeline:
|
||||
|
||||
- In Forgejo account **Settings → Applications**, create a token with `write:package` permission. In Calio **Settings → Actions → Secrets**, save it as `FORGEJO_PAT`. A secret configured only on Study is not automatically available to Calio. Keep the token out of source files and chat.
|
||||
- Optionally set repository variable `REGISTRY_USERNAME` if the token owner differs from the repository owner.
|
||||
- Ensure the registry is enabled at `git.elijahkuntz.com` and the runner can reach Docker Hub/GitHub actions and npm.
|
||||
- Every successful push publishes `git.elijahkuntz.com/elijah/calio:<full-commit-SHA>`.
|
||||
- Successful default-branch (`main`) builds also update `:latest`. Before promotion, the workflow checks the remote branch head to avoid promoting an already superseded build.
|
||||
- Valid `v*` tags also publish a version alias, such as `:v0.1.0`. Other branches and release tags do not overwrite `:latest`.
|
||||
- Pull requests verify without publishing or requiring registry credentials. Deleted refs are skipped. Manual dispatch uses the same publication rules as a push.
|
||||
- Each workflow run uses a unique local image tag, keeping concurrent builds separate. The workflow does not deploy to or restart your server.
|
||||
|
||||
The repository configuration is ready, but a successful live publish still requires `FORGEJO_PAT` and the initial source push. No token, registry publication or server deployment has been performed locally.
|
||||
|
||||
## Develop and verify
|
||||
|
||||
Node 24+ is required for built-in SQLite. `npm ci` installs the lockfile. `npm test` covers authentication, validation, deterministic merges, tombstones, persistence, and client outbox handling.
|
||||
|
||||
For a production preview, run `npm run build`, configure the same environment variables above, then `npm start`. For live UI editing, run `npm run dev:server` on port 3000 and `npm run dev` on port 5173, with `APP_ORIGIN=http://localhost:5173` and `COOKIE_SECURE=false`. Vite proxies `/api`; the service worker is registered only in production builds.
|
||||
|
||||
```sh
|
||||
npm test
|
||||
npm run build
|
||||
docker build -t calio:local .
|
||||
node scripts/container-smoke.js calio:local
|
||||
node scripts/container-smoke.js calio:local --unraid
|
||||
```
|
||||
|
||||
App code is in `src/`, shared schemas/merge rules in `shared/`, and the Express/SQLite server in `server/`. The handwritten service worker is generated from production asset hashes by `scripts/build-sw.js`. Icons are committed PNGs; `scripts/generate-icons.ps1` regenerates them on Windows without external assets.
|
||||
24
compose.yaml
Normal file
24
compose.yaml
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
services:
|
||||
calio:
|
||||
build: .
|
||||
image: calio:local
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:${CALIO_PORT:-3000}:3000"
|
||||
environment:
|
||||
APP_ORIGIN: ${APP_ORIGIN:?Set APP_ORIGIN to your public HTTPS origin}
|
||||
CALIO_USERNAME: ${CALIO_USERNAME:-calio}
|
||||
CALIO_PASSWORD: ${CALIO_PASSWORD:?Set a password of at least 12 characters}
|
||||
COOKIE_SECURE: ${COOKIE_SECURE:-true}
|
||||
volumes:
|
||||
- calio-data:/data
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
stop_grace_period: 20s
|
||||
volumes:
|
||||
calio-data:
|
||||
70
docs/UNRAID.md
Normal file
70
docs/UNRAID.md
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
# Calio on Unraid
|
||||
|
||||
Forgejo builds the image. Install and update it with Unraid's standard Docker interface; Docker Compose is not required.
|
||||
|
||||
## Publish the first image
|
||||
|
||||
The existing `unraid-runner` uses the required `ubuntu-latest` label. Its job environment needs Docker CLI/daemon access, as in the Study build pipeline. Calio installs Node 24 during the job.
|
||||
|
||||
1. In your Forgejo account's **Settings → Applications**, generate a token with `write:package` permission.
|
||||
2. In the **Calio** repository, open **Settings → Actions → Secrets** and add `FORGEJO_PAT`. This matches Study's secret name. A Study-only secret must also be added to Calio, or supplied at an organization scope that includes Calio.
|
||||
3. Push the Calio source. Check the repository's Actions page for the completed workflow. Tests, the application build, and both container smoke tests must pass before publishing.
|
||||
4. The first successful main build publishes `git.elijahkuntz.com/elijah/calio:latest`. Ensure the resulting package is public if Unraid should pull without registry credentials. If using a private package, authenticate Unraid's Docker daemon to the registry with a separate package-read token.
|
||||
|
||||
The token's account defaults to the repository owner, `Elijah`. Set repository variable `REGISTRY_USERNAME` only if using another account that has permission to publish to this owner. Tokens are used at runtime and never baked into the image.
|
||||
|
||||
All branch and tag pushes are built. Successful pushes publish a full commit SHA tag, main also promotes `latest`, and valid `v*` tags add a version alias. PRs only verify. Publishing does not restart the running app.
|
||||
|
||||
## Add the container
|
||||
|
||||
Use **Docker → Add Container** and fill in the following values. Alternatively, copy [calio.xml](../unraid/calio.xml) to `/boot/config/plugins/dockerMan/templates-user/my-calio.xml` on Unraid and select the Calio user template.
|
||||
|
||||
| Field | Value |
|
||||
| -------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| Name | `calio` |
|
||||
| Repository | `git.elijahkuntz.com/elijah/calio:latest` |
|
||||
| Network | `bridge`, or your reverse proxy's shared Docker network |
|
||||
| Container port | `3000/TCP` |
|
||||
| Host port | `3080` (choose another unused port if necessary) |
|
||||
| Container path | `/data` (read/write) |
|
||||
| Host path | `/mnt/user/appdata/calio` |
|
||||
| Variable `APP_ORIGIN` | Your exact public HTTPS origin, e.g. `https://calio.example.com`, without a trailing slash |
|
||||
| Variable `CALIO_USERNAME` | Your single sign-in username |
|
||||
| Variable `CALIO_PASSWORD` | A unique password of at least 12 characters |
|
||||
| Variable `COOKIE_SECURE` | `true` |
|
||||
| Variable `TZ` | `America/Phoenix`, or your timezone |
|
||||
| Extra Parameters (Advanced View) | `--user=99:100 --cap-drop=ALL --security-opt=no-new-privileges` |
|
||||
| WebUI (Advanced View) | The same public HTTPS origin as `APP_ORIGIN` |
|
||||
|
||||
Keep **Privileged** off. The template uses Unraid's `nobody:users` identity (`99:100`). Create the dedicated appdata directory and give that identity ownership before starting. For a new installation using exactly the default path, run in the Unraid terminal:
|
||||
|
||||
```sh
|
||||
mkdir -p /mnt/user/appdata/calio
|
||||
chown 99:100 /mnt/user/appdata/calio
|
||||
chmod 770 /mnt/user/appdata/calio
|
||||
```
|
||||
|
||||
These commands affect only Calio's directory. If you choose another path, use that path instead. Calio does not implement `PUID`/`PGID` environment variables: Docker's `--user` selects the identity. If migrating existing data, ensure its database and sidecar files are also writable by the chosen identity while Calio is stopped. The standalone image otherwise defaults to UID 1000.
|
||||
|
||||
Configure your HTTPS reverse proxy to forward **all paths** to `http://<Unraid-IP>:3080`, or `http://calio:3000` on a shared Docker network. Leave `/api` intact. Open the public HTTPS address for sign-in and PWA installation. The upstream HTTP port alone does not provide the secure cookies or service worker origin needed by a phone PWA.
|
||||
|
||||
On iPhone, use Safari → Share → **Add to Home Screen**. On Android, use Chrome → **Install app** / **Add to home screen**. Sign in online once and allow the initial sync to finish before testing offline use.
|
||||
|
||||
## Update without losing data
|
||||
|
||||
Keep `/mnt/user/appdata/calio` mapped to `/data` on every recreation. It holds the SQLite database, persistent sessions and backups; the image holds only application code.
|
||||
|
||||
Before updating, create a consistent backup from the Unraid terminal:
|
||||
|
||||
```sh
|
||||
docker exec calio node server/backup.js /data/backups/before-update.sqlite
|
||||
docker cp calio:/data/backups/before-update.sqlite ./calio-backup.sqlite
|
||||
```
|
||||
|
||||
Use a new backup filename each time and copy it off the server. Do not copy only the live `calio.sqlite` file while Calio is writing: committed data can still be in its WAL sidecar. See the [README](../README.md#persistent-data-updates-and-backups) for restoration and device-cache considerations.
|
||||
|
||||
After a successful main build, select **Check for Updates → Update** on Unraid's Docker page. Unraid pulls `latest` and recreates the container with the saved port, path and variable settings. The PWA offers its own **Update** prompt after reconnecting; queued offline edits must sync before accepting it.
|
||||
|
||||
For a specific build, replace `:latest` in the repository field with its full commit SHA or published version tag. Database schema checks prevent an older app from opening a newer unsupported schema; a rollback across schema changes may need the matching database backup.
|
||||
|
||||
References: [Unraid container management](https://docs.unraid.net/unraid-os/using-unraid-to/run-docker-containers/managing-and-customizing-containers/), [Forgejo container registry](https://forgejo.org/docs/v11.0/user/packages/container/), and [Study's reference pipeline](https://git.elijahkuntz.com/Elijah/Study/src/branch/main/.forgejo/workflows).
|
||||
25
index.html
Normal file
25
index.html
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta
|
||||
name="viewport"
|
||||
content="width=device-width, initial-scale=1, viewport-fit=cover"
|
||||
/>
|
||||
<meta name="theme-color" content="#f5f5f8" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Calio — a little clarity for your everyday nutrition."
|
||||
/>
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png" />
|
||||
<title>Calio · Everyday, in balance</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
2780
package-lock.json
generated
Normal file
2780
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
38
package.json
Normal file
38
package.json
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
{
|
||||
"name": "calio",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=24.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"dev:server": "node --watch server/index.js",
|
||||
"build": "tsc -b && vite build && node scripts/build-sw.js",
|
||||
"start": "node server/index.js",
|
||||
"test": "node --test tests/*.test.js",
|
||||
"password": "node scripts/password.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"express": "^5.1.0",
|
||||
"express-rate-limit": "^8.1.0",
|
||||
"helmet": "^8.1.0",
|
||||
"idb": "^8.0.3",
|
||||
"lucide-react": "^0.468.0",
|
||||
"matter-js": "^0.20.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"zod": "^4.1.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/matter-js": "^0.20.2",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/react": "^19.2.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@vitejs/plugin-react": "^5.0.0",
|
||||
"fake-indexeddb": "^6.2.6",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^7.1.12"
|
||||
}
|
||||
}
|
||||
1
public/icon.svg
Normal file
1
public/icon.svg
Normal file
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 192"><rect width="192" height="192" rx="48" fill="#8391ed"/><circle cx="96" cy="102" r="54" fill="none" stroke="#f5f5ef" stroke-width="9"/><g fill="#f5f5ef"><circle cx="68" cy="115" r="10"/><circle cx="93" cy="125" r="10"/><circle cx="119" cy="115" r="10"/><circle cx="96" cy="99" r="10"/></g><path d="M96 48Q93 23 120 25Q118 46 96 48" fill="#cad1ff"/></svg>
|
||||
|
After Width: | Height: | Size: 416 B |
BIN
public/icons/apple-touch-icon.png
Normal file
BIN
public/icons/apple-touch-icon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.2 KiB |
BIN
public/icons/icon-192.png
Normal file
BIN
public/icons/icon-192.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.3 KiB |
BIN
public/icons/icon-512.png
Normal file
BIN
public/icons/icon-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
BIN
public/icons/maskable-512.png
Normal file
BIN
public/icons/maskable-512.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 10 KiB |
31
public/manifest.webmanifest
Normal file
31
public/manifest.webmanifest
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
{
|
||||
"id": "/",
|
||||
"name": "Calio",
|
||||
"short_name": "Calio",
|
||||
"description": "Everyday, in balance. Your personal nutrition journal.",
|
||||
"start_url": "/",
|
||||
"scope": "/",
|
||||
"display": "standalone",
|
||||
"background_color": "#f5f5f8",
|
||||
"theme_color": "#8391ed",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/icons/icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/icons/icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "any"
|
||||
},
|
||||
{
|
||||
"src": "/icons/maskable-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png",
|
||||
"purpose": "maskable"
|
||||
}
|
||||
]
|
||||
}
|
||||
29
scripts/build-sw.js
Normal file
29
scripts/build-sw.js
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
const assets = readdirSync("dist/assets").map((name) => "/assets/" + name);
|
||||
const shell = [
|
||||
"/",
|
||||
"/index.html",
|
||||
"/icon.svg",
|
||||
"/manifest.webmanifest",
|
||||
"/icons/apple-touch-icon.png",
|
||||
"/icons/icon-192.png",
|
||||
"/icons/icon-512.png",
|
||||
"/icons/maskable-512.png",
|
||||
...assets,
|
||||
];
|
||||
const digest = createHash("sha256");
|
||||
for (const path of shell)
|
||||
digest.update(readFileSync(path === "/" ? "dist/index.html" : "dist" + path));
|
||||
const hash = digest.digest("hex").slice(0, 12);
|
||||
writeFileSync(
|
||||
"dist/sw.js",
|
||||
`const CACHE='calio-${hash}';const SHELL=${JSON.stringify(shell)};
|
||||
self.addEventListener('install',event=>event.waitUntil(caches.open(CACHE).then(cache=>cache.addAll(SHELL))));
|
||||
self.addEventListener('message',event=>{if(event.data==='ACTIVATE')self.skipWaiting()});
|
||||
self.addEventListener('activate',event=>event.waitUntil(caches.keys().then(keys=>Promise.all(keys.filter(key=>key.startsWith('calio-')&&key!==CACHE).map(key=>caches.delete(key)))).then(()=>self.clients.claim())));
|
||||
self.addEventListener('fetch',event=>{const url=new URL(event.request.url);if(event.request.method!=='GET'||url.origin!==self.location.origin||url.pathname.startsWith('/api/'))return;
|
||||
if(event.request.mode==='navigate'){event.respondWith(caches.open(CACHE).then(cache=>cache.match('/index.html')).then(cached=>cached||fetch(event.request)));return;}
|
||||
if(SHELL.includes(url.pathname))event.respondWith(caches.open(CACHE).then(cache=>cache.match(event.request)).then(cached=>cached||fetch(event.request)));
|
||||
});`,
|
||||
);
|
||||
157
scripts/container-smoke.js
Normal file
157
scripts/container-smoke.js
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import assert from "node:assert/strict";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { emptyNutrients } from "../shared/domain.js";
|
||||
const image = process.argv[2] || "calio:local";
|
||||
const unraid = process.argv.includes("--unraid");
|
||||
const suffix = randomBytes(4).toString("hex");
|
||||
const name = "calio-smoke-" + suffix;
|
||||
const volume = name + "-data";
|
||||
const password = randomBytes(24).toString("hex");
|
||||
const docker = (args, input) =>
|
||||
execFileSync("docker", args, {
|
||||
encoding: "utf8",
|
||||
input,
|
||||
stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
|
||||
}).trim();
|
||||
async function start() {
|
||||
docker([
|
||||
"run",
|
||||
"-d",
|
||||
"--name",
|
||||
name,
|
||||
...(unraid ? ["--user", "99:100"] : []),
|
||||
...(unraid
|
||||
? ["--mount", `type=volume,source=${volume},target=/data,volume-nocopy`]
|
||||
: ["-v", volume + ":/data"]),
|
||||
"--read-only",
|
||||
"--tmpfs",
|
||||
"/tmp",
|
||||
"--cap-drop",
|
||||
"ALL",
|
||||
"--security-opt",
|
||||
"no-new-privileges:true",
|
||||
"-e",
|
||||
"APP_ORIGIN=http://localhost:3000",
|
||||
"-e",
|
||||
"COOKIE_SECURE=false",
|
||||
"-e",
|
||||
"CALIO_USERNAME=smoke",
|
||||
"-e",
|
||||
"CALIO_PASSWORD=" + password,
|
||||
image,
|
||||
]);
|
||||
let lastError;
|
||||
for (let i = 0; i < 50; i++) {
|
||||
try {
|
||||
if ((await request("/api/health")).status === 200) return;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (
|
||||
docker(["inspect", "--format", "{{.State.Running}}", name]) === "false"
|
||||
)
|
||||
break;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
}
|
||||
const logs = spawnSync("docker", ["logs", name], { encoding: "utf8" });
|
||||
throw new Error(
|
||||
"Container failed to start: " +
|
||||
logs.stdout +
|
||||
logs.stderr +
|
||||
"\n" +
|
||||
(lastError?.message || "") +
|
||||
"\n" +
|
||||
docker(["inspect", "--format", "{{json .State}}", name]),
|
||||
);
|
||||
}
|
||||
// In-container probes work on socket-mounted Forgejo runners without published ports.
|
||||
const request = async (path, body, cookie) => {
|
||||
const probe = `let input=''; for await (const chunk of process.stdin) input+=chunk;
|
||||
const {path,body,cookie}=JSON.parse(input);
|
||||
const response=await fetch('http://127.0.0.1:3000'+path,{
|
||||
method:body===undefined?'GET':'POST',
|
||||
headers:{'Content-Type':'application/json',Origin:'http://localhost:3000','X-Calio-Request':'1',Cookie:cookie||''},
|
||||
body:body===undefined?undefined:JSON.stringify(body)
|
||||
});
|
||||
console.log(JSON.stringify({status:response.status,cookie:response.headers.get('set-cookie'),body:await response.text()}));`;
|
||||
const result = JSON.parse(
|
||||
docker(
|
||||
["exec", "-i", name, "node", "--input-type=module", "-e", probe],
|
||||
JSON.stringify({ path, body, cookie }),
|
||||
),
|
||||
);
|
||||
return {
|
||||
status: result.status,
|
||||
headers: new Headers(result.cookie ? { "set-cookie": result.cookie } : {}),
|
||||
text: async () => result.body,
|
||||
json: async () => JSON.parse(result.body),
|
||||
};
|
||||
};
|
||||
try {
|
||||
if (unraid) {
|
||||
docker(["volume", "create", volume]);
|
||||
// Only initialize the unique, disposable test volume, as on Unraid appdata.
|
||||
docker([
|
||||
"run",
|
||||
"--rm",
|
||||
"--user",
|
||||
"0:0",
|
||||
"-v",
|
||||
volume + ":/data",
|
||||
"--entrypoint",
|
||||
"sh",
|
||||
image,
|
||||
"-c",
|
||||
"chown 99:100 /data",
|
||||
]);
|
||||
}
|
||||
await start();
|
||||
assert.equal((await request("/api/records")).status, 401);
|
||||
const login = await request("/api/login", { username: "smoke", password });
|
||||
assert.equal(login.status, 200);
|
||||
const cookie = login.headers.get("set-cookie").split(";")[0];
|
||||
const record = {
|
||||
id: "persistence-test",
|
||||
type: "food",
|
||||
updatedAt: new Date().toISOString(),
|
||||
deleted: false,
|
||||
data: {
|
||||
name: "Test food",
|
||||
serving: "1 serving",
|
||||
nutrients: emptyNutrients(),
|
||||
},
|
||||
};
|
||||
assert.equal(
|
||||
(await request("/api/sync", { records: [record] }, cookie)).status,
|
||||
200,
|
||||
);
|
||||
for (const path of [
|
||||
"/",
|
||||
"/sw.js",
|
||||
"/manifest.webmanifest",
|
||||
"/icons/apple-touch-icon.png",
|
||||
])
|
||||
assert.equal((await request(path)).status, 200, path);
|
||||
const html = await (await request("/")).text();
|
||||
const asset = html.match(/src="(\/assets\/[^\"]+)"/)[1];
|
||||
assert.equal((await request(asset)).status, 200);
|
||||
assert.equal(docker(["exec", name, "id", "-u"]), unraid ? "99" : "1000");
|
||||
if (unraid) assert.equal(docker(["exec", name, "id", "-g"]), "100");
|
||||
docker(["rm", "-f", name]);
|
||||
await start();
|
||||
// Session and journal both survive a full container replacement, as during an update.
|
||||
const response = await request("/api/records", undefined, cookie);
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual((await response.json()).records, [record]);
|
||||
console.log(
|
||||
`PASS (${unraid ? "Unraid 99:100" : "default 1000"}): non-root container, production assets, authentication, read-only root, persistent volume and sessions after container recreation.`,
|
||||
);
|
||||
} finally {
|
||||
try {
|
||||
docker(["rm", "-f", name]);
|
||||
} catch {}
|
||||
try {
|
||||
docker(["volume", "rm", volume]);
|
||||
} catch {}
|
||||
}
|
||||
22
scripts/generate-icons.ps1
Normal file
22
scripts/generate-icons.ps1
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
Add-Type -AssemblyName System.Drawing
|
||||
$iconRoot = Join-Path $PSScriptRoot '../public/icons'
|
||||
New-Item -ItemType Directory -Force -Path $iconRoot | Out-Null
|
||||
foreach ($iconSpec in @(@('icon-192.png',192), @('icon-512.png',512), @('maskable-512.png',512), @('apple-touch-icon.png',180))) {
|
||||
$iconSize = [int]$iconSpec[1]
|
||||
$bitmap = New-Object System.Drawing.Bitmap($iconSize,$iconSize)
|
||||
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
|
||||
$graphics.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$graphics.ScaleTransform($iconSize / 192.0, $iconSize / 192.0)
|
||||
$graphics.Clear([System.Drawing.ColorTranslator]::FromHtml('#8391ed'))
|
||||
$cream = New-Object System.Drawing.SolidBrush([System.Drawing.ColorTranslator]::FromHtml('#f5f5ef'))
|
||||
$ringPen = New-Object System.Drawing.Pen($cream,8)
|
||||
$graphics.DrawEllipse($ringPen,48,54,96,96)
|
||||
foreach ($point in @(@(72,112),@(95,122),@(118,112),@(96,99))) { $graphics.FillEllipse($cream,($point[0]-8),($point[1]-8),16,16) }
|
||||
$leaf = New-Object System.Drawing.Drawing2D.GraphicsPath
|
||||
$leaf.AddBezier(96,50,94,27,119,26,120,27)
|
||||
$leaf.AddBezier(120,27,120,44,105,51,96,50)
|
||||
$green = New-Object System.Drawing.SolidBrush([System.Drawing.ColorTranslator]::FromHtml('#cad1ff'))
|
||||
$graphics.FillPath($green,$leaf)
|
||||
$bitmap.Save((Join-Path $iconRoot $iconSpec[0]),[System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$graphics.Dispose(); $bitmap.Dispose(); $cream.Dispose(); $ringPen.Dispose(); $leaf.Dispose(); $green.Dispose()
|
||||
}
|
||||
10
scripts/password.js
Normal file
10
scripts/password.js
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
import { hashPassword } from "../server/auth.js";
|
||||
// Read from stdin so passwords never need to appear in shell arguments.
|
||||
let input = "";
|
||||
for await (const chunk of process.stdin) input += chunk;
|
||||
const password = input.trimEnd();
|
||||
if (password.length < 12)
|
||||
throw new Error(
|
||||
"Use at least 12 characters. Pipe the password through stdin.",
|
||||
);
|
||||
console.log(hashPassword(password));
|
||||
108
scripts/publish-image.js
Normal file
108
scripts/publish-image.js
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import { spawnSync, execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
export function publicationPlan(env) {
|
||||
if (!["push", "workflow_dispatch"].includes(env.CI_EVENT)) return null;
|
||||
const repository = (env.REPOSITORY || "").toLowerCase();
|
||||
if (!/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/.test(repository))
|
||||
throw new Error("Invalid REPOSITORY");
|
||||
const sha = env.COMMIT_SHA || "";
|
||||
if (!/^[a-f0-9]{40}$/.test(sha))
|
||||
throw new Error("COMMIT_SHA must be a full Git commit ID");
|
||||
const image = "git.elijahkuntz.com/" + repository;
|
||||
const tags = [sha];
|
||||
const ref = env.TARGET_REF || "";
|
||||
const latest = ref === "refs/heads/" + (env.MAIN_BRANCH || "main");
|
||||
const version = ref.startsWith("refs/tags/")
|
||||
? ref.slice("refs/tags/".length)
|
||||
: "";
|
||||
if (/^v[\w][\w.-]{0,126}$/.test(version)) tags.push(version.toLowerCase());
|
||||
return { registry: "git.elijahkuntz.com", image, tags, latest, sha };
|
||||
}
|
||||
|
||||
export function publishImage(env = process.env, dryRun = false) {
|
||||
const plan = publicationPlan(env);
|
||||
if (!plan) {
|
||||
console.log("This event verifies the image without publishing.");
|
||||
return;
|
||||
}
|
||||
if (dryRun) {
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{ ...plan, latestRequiresCurrentBranchHead: plan.latest },
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!env.FORGEJO_PAT)
|
||||
throw new Error(
|
||||
"Add FORGEJO_PAT with write:package permission under Calio Settings → Actions → Secrets, then rerun this workflow.",
|
||||
);
|
||||
if (!env.REGISTRY_USERNAME)
|
||||
throw new Error("REGISTRY_USERNAME must identify the token owner");
|
||||
const configDir = mkdtempSync(join(tmpdir(), "calio-registry-"));
|
||||
const childEnv = { ...process.env, ...env, DOCKER_CONFIG: configDir };
|
||||
const sourceImage = env.SOURCE_IMAGE || "calio:ci";
|
||||
const docker = (args, input) => {
|
||||
const result = spawnSync("docker", args, {
|
||||
env: childEnv,
|
||||
input,
|
||||
stdio: [input === undefined ? "ignore" : "pipe", "inherit", "inherit"],
|
||||
});
|
||||
if (result.error) throw result.error;
|
||||
if (result.status !== 0) throw new Error(`docker ${args[0]} failed`);
|
||||
};
|
||||
try {
|
||||
docker(
|
||||
[
|
||||
"login",
|
||||
plan.registry,
|
||||
"--username",
|
||||
env.REGISTRY_USERNAME,
|
||||
"--password-stdin",
|
||||
],
|
||||
env.FORGEJO_PAT,
|
||||
);
|
||||
for (const tag of plan.tags) {
|
||||
const target = `${plan.image}:${tag}`;
|
||||
docker(["tag", sourceImage, target]);
|
||||
docker(["push", target]);
|
||||
}
|
||||
if (plan.latest) {
|
||||
const head = execFileSync(
|
||||
"git",
|
||||
["ls-remote", "origin", `refs/heads/${env.MAIN_BRANCH || "main"}`],
|
||||
{ encoding: "utf8" },
|
||||
)
|
||||
.trim()
|
||||
.split(/\s+/)[0];
|
||||
if (head !== plan.sha) {
|
||||
console.log(
|
||||
"Main has a newer commit; published the commit tag and left latest unchanged.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
docker(["tag", sourceImage, `${plan.image}:latest`]);
|
||||
docker(["push", `${plan.image}:latest`]);
|
||||
}
|
||||
} finally {
|
||||
rmSync(configDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
process.argv[1] &&
|
||||
import.meta.url === pathToFileURL(process.argv[1]).href
|
||||
) {
|
||||
try {
|
||||
publishImage(process.env, process.argv.includes("--dry-run"));
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
175
server/app.js
Normal file
175
server/app.js
Normal file
|
|
@ -0,0 +1,175 @@
|
|||
import express from "express";
|
||||
import helmet from "helmet";
|
||||
import { rateLimit } from "express-rate-limit";
|
||||
import { randomBytes, timingSafeEqual, createHash } from "node:crypto";
|
||||
import { resolve, join } from "node:path";
|
||||
import { existsSync } from "node:fs";
|
||||
import { z } from "zod";
|
||||
import { recordSchema } from "../shared/domain.js";
|
||||
import { checkPassword, tokenHash } from "./auth.js";
|
||||
|
||||
export function createApp({
|
||||
store,
|
||||
username,
|
||||
passwordHash,
|
||||
origin,
|
||||
secureCookies = true,
|
||||
dist = resolve("dist"),
|
||||
}) {
|
||||
const app = express();
|
||||
app.disable("x-powered-by");
|
||||
app.use(
|
||||
helmet({
|
||||
contentSecurityPolicy: {
|
||||
directives: {
|
||||
"script-src": ["'self'"],
|
||||
"style-src": ["'self'", "'unsafe-inline'"],
|
||||
"img-src": ["'self'", "data:"],
|
||||
"connect-src": ["'self'"],
|
||||
"object-src": ["'none'"],
|
||||
"upgrade-insecure-requests": secureCookies ? [] : null,
|
||||
},
|
||||
},
|
||||
strictTransportSecurity: secureCookies ? undefined : false,
|
||||
}),
|
||||
);
|
||||
app.use("/api", (_, res, next) => {
|
||||
res.set("Cache-Control", "no-store");
|
||||
next();
|
||||
});
|
||||
app.use("/api", (req, res, next) => {
|
||||
if (
|
||||
["POST", "PUT", "PATCH", "DELETE"].includes(req.method) &&
|
||||
(req.get("X-Calio-Request") !== "1" || req.get("Origin") !== origin)
|
||||
)
|
||||
return res.status(403).json({ error: "Request origin rejected" });
|
||||
next();
|
||||
});
|
||||
app.use(express.json({ limit: "2mb" }));
|
||||
app.get("/api/health", (_, res) => res.json({ ok: true, version: "0.1.0" }));
|
||||
const cookieName = secureCookies ? "__Host-calio" : "calio";
|
||||
const getToken = (req) =>
|
||||
req.headers.cookie
|
||||
?.split(";")
|
||||
.map((v) => v.trim())
|
||||
.find((v) => v.startsWith(cookieName + "="))
|
||||
?.slice(cookieName.length + 1) || "";
|
||||
const cookie = {
|
||||
httpOnly: true,
|
||||
secure: secureCookies,
|
||||
sameSite: "strict",
|
||||
path: "/",
|
||||
maxAge: 30 * 86400000,
|
||||
};
|
||||
const requireAuth = (req, res, next) => {
|
||||
const session = store.db
|
||||
.prepare("SELECT expires FROM sessions WHERE token_hash=?")
|
||||
.get(tokenHash(getToken(req)));
|
||||
if (!session || session.expires < Date.now())
|
||||
return res.status(401).json({ error: "Sign in to sync your journal" });
|
||||
next();
|
||||
};
|
||||
const loginLimiter = rateLimit({
|
||||
windowMs: 15 * 60000,
|
||||
limit: 10,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
message: { error: "Too many sign-in attempts. Try again in 15 minutes." },
|
||||
});
|
||||
app.post("/api/login", loginLimiter, (req, res) => {
|
||||
if (
|
||||
typeof req.body?.username !== "string" ||
|
||||
typeof req.body?.password !== "string" ||
|
||||
req.body.password.length > 1024
|
||||
)
|
||||
return res.status(400).json({ error: "Enter a username and password" });
|
||||
const digest = (value) => createHash("sha256").update(value).digest();
|
||||
const correctPassword = checkPassword(req.body.password, passwordHash);
|
||||
if (
|
||||
!timingSafeEqual(digest(req.body.username), digest(username)) ||
|
||||
!correctPassword
|
||||
)
|
||||
return res.status(401).json({ error: "Incorrect username or password" });
|
||||
const token = randomBytes(32).toString("hex");
|
||||
store.db.prepare("DELETE FROM sessions WHERE expires < ?").run(Date.now());
|
||||
store.db
|
||||
.prepare("INSERT INTO sessions VALUES (?,?)")
|
||||
.run(tokenHash(token), Date.now() + cookie.maxAge);
|
||||
res.cookie(cookieName, token, cookie).json({ ok: true });
|
||||
});
|
||||
app.get("/api/session", requireAuth, (_, res) =>
|
||||
res.json({ authenticated: true }),
|
||||
);
|
||||
app.post("/api/logout", (req, res) => {
|
||||
store.db
|
||||
.prepare("DELETE FROM sessions WHERE token_hash=?")
|
||||
.run(tokenHash(getToken(req)));
|
||||
res
|
||||
.clearCookie(cookieName, { ...cookie, maxAge: undefined })
|
||||
.json({ ok: true });
|
||||
});
|
||||
app.get("/api/records", requireAuth, (_, res) =>
|
||||
res.json({ records: store.all(), serverTime: new Date().toISOString() }),
|
||||
);
|
||||
app.post("/api/sync", requireAuth, (req, res) => {
|
||||
const parsed = z
|
||||
.object({ records: z.array(recordSchema).max(1000) })
|
||||
.strict()
|
||||
.safeParse(req.body);
|
||||
if (!parsed.success)
|
||||
return res
|
||||
.status(400)
|
||||
.json({
|
||||
error: "Invalid journal data",
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
if (
|
||||
parsed.data.records.some(
|
||||
(record) => Date.parse(record.updatedAt) > Date.now() + 300000,
|
||||
)
|
||||
)
|
||||
return res
|
||||
.status(400)
|
||||
.json({
|
||||
error: "Your device clock is ahead. Correct it before syncing.",
|
||||
});
|
||||
try {
|
||||
res.json({
|
||||
records: store.merge(parsed.data.records),
|
||||
serverTime: new Date().toISOString(),
|
||||
});
|
||||
} catch {
|
||||
res
|
||||
.status(409)
|
||||
.json({
|
||||
error: "A record ID is already used for another kind of item",
|
||||
});
|
||||
}
|
||||
});
|
||||
app.use("/api", (_, res) => res.status(404).json({ error: "Not found" }));
|
||||
if (existsSync(dist)) {
|
||||
app.use(
|
||||
express.static(dist, {
|
||||
maxAge: 0,
|
||||
setHeaders: (res, path) => {
|
||||
if (path.includes(`${join("assets", "")}`))
|
||||
res.set("Cache-Control", "public, max-age=31536000, immutable");
|
||||
if (path.endsWith("sw.js") || path.endsWith("index.html"))
|
||||
res.set("Cache-Control", "no-cache");
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.get("/{*path}", (_, res) => res.sendFile(join(dist, "index.html")));
|
||||
}
|
||||
app.use((error, _req, res, _next) =>
|
||||
res
|
||||
.status(error.status || 500)
|
||||
.json({
|
||||
error:
|
||||
error.status === 413
|
||||
? "Request is too large"
|
||||
: "Request could not be processed",
|
||||
}),
|
||||
);
|
||||
return app;
|
||||
}
|
||||
25
server/auth.js
Normal file
25
server/auth.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import {
|
||||
scryptSync,
|
||||
randomBytes,
|
||||
timingSafeEqual,
|
||||
createHash,
|
||||
} from "node:crypto";
|
||||
export function hashPassword(password) {
|
||||
const salt = randomBytes(16).toString("hex");
|
||||
return `scrypt:${salt}:${scryptSync(password, salt, 64).toString("hex")}`;
|
||||
}
|
||||
export function checkPassword(password, hash) {
|
||||
const [method, salt, hex] = hash.split(":");
|
||||
if (
|
||||
method !== "scrypt" ||
|
||||
!/^[a-f0-9]{32}$/.test(salt) ||
|
||||
!/^[a-f0-9]{128}$/.test(hex)
|
||||
)
|
||||
return false;
|
||||
return timingSafeEqual(
|
||||
scryptSync(password, salt, 64),
|
||||
Buffer.from(hex, "hex"),
|
||||
);
|
||||
}
|
||||
export const tokenHash = (token) =>
|
||||
createHash("sha256").update(token).digest("hex");
|
||||
24
server/backup.js
Normal file
24
server/backup.js
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import { DatabaseSync } from "node:sqlite";
|
||||
import { mkdirSync, existsSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
const source = resolve(process.env.DATA_DIR || "data", "calio.sqlite");
|
||||
if (!existsSync(source)) throw new Error("No Calio database found.");
|
||||
const output = resolve(
|
||||
process.argv[2] ||
|
||||
(process.env.DATA_DIR || "data") +
|
||||
"/backups/calio-" +
|
||||
new Date().toISOString().replaceAll(":", "-") +
|
||||
".sqlite",
|
||||
);
|
||||
if (output === source || existsSync(output))
|
||||
throw new Error(
|
||||
"Choose a new backup path. Existing files are never overwritten.",
|
||||
);
|
||||
mkdirSync(dirname(output), { recursive: true });
|
||||
const db = new DatabaseSync(source);
|
||||
try {
|
||||
db.prepare("VACUUM INTO ?").run(output);
|
||||
console.log(output);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
50
server/db.js
Normal file
50
server/db.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { DatabaseSync } from "node:sqlite";
|
||||
import { compareRecords } from "../shared/domain.js";
|
||||
|
||||
export function openDatabase(filename) {
|
||||
const db = new DatabaseSync(filename);
|
||||
db.exec(
|
||||
"PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON;",
|
||||
);
|
||||
const version = db.prepare("PRAGMA user_version").get().user_version;
|
||||
if (version > 1) {
|
||||
db.close();
|
||||
throw new Error(
|
||||
"Database was created by a newer Calio version. Refusing to downgrade.",
|
||||
);
|
||||
}
|
||||
if (version < 1) {
|
||||
db.exec(`BEGIN IMMEDIATE;
|
||||
CREATE TABLE records (id TEXT PRIMARY KEY, type TEXT NOT NULL, payload TEXT NOT NULL);
|
||||
CREATE TABLE sessions (token_hash TEXT PRIMARY KEY, expires INTEGER NOT NULL);
|
||||
PRAGMA user_version=1;
|
||||
COMMIT;`);
|
||||
}
|
||||
const all = () =>
|
||||
db
|
||||
.prepare("SELECT payload FROM records ORDER BY id")
|
||||
.all()
|
||||
.map((row) => JSON.parse(row.payload));
|
||||
const merge = (incoming) => {
|
||||
db.exec("BEGIN IMMEDIATE");
|
||||
try {
|
||||
for (const record of incoming) {
|
||||
const row = db
|
||||
.prepare("SELECT payload FROM records WHERE id=?")
|
||||
.get(record.id);
|
||||
if (row && JSON.parse(row.payload).type !== record.type)
|
||||
throw new Error("Record type cannot change");
|
||||
if (!row || compareRecords(record, JSON.parse(row.payload)) > 0)
|
||||
db.prepare(
|
||||
"INSERT INTO records(id,type,payload) VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload",
|
||||
).run(record.id, record.type, JSON.stringify(record));
|
||||
}
|
||||
db.exec("COMMIT");
|
||||
} catch (error) {
|
||||
db.exec("ROLLBACK");
|
||||
throw error;
|
||||
}
|
||||
return all();
|
||||
};
|
||||
return { db, all, merge, close: () => db.close() };
|
||||
}
|
||||
49
server/index.js
Normal file
49
server/index.js
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { openDatabase } from "./db.js";
|
||||
import { createApp } from "./app.js";
|
||||
import { hashPassword } from "./auth.js";
|
||||
const secret = (name) =>
|
||||
process.env[name + "_FILE"]
|
||||
? readFileSync(process.env[name + "_FILE"], "utf8").trimEnd()
|
||||
: process.env[name];
|
||||
const password = secret("CALIO_PASSWORD");
|
||||
const passwordHash =
|
||||
secret("CALIO_PASSWORD_HASH") || (password && hashPassword(password));
|
||||
if (!passwordHash || !/^scrypt:[a-f0-9]{32}:[a-f0-9]{128}$/.test(passwordHash))
|
||||
throw new Error(
|
||||
"Configure CALIO_PASSWORD_HASH[_FILE] or CALIO_PASSWORD[_FILE]. There are no default credentials.",
|
||||
);
|
||||
if (password && password.length < 12)
|
||||
throw new Error("CALIO_PASSWORD must be at least 12 characters.");
|
||||
const origin = process.env.APP_ORIGIN || "http://localhost:3000";
|
||||
if (new URL(origin).origin !== origin)
|
||||
throw new Error("APP_ORIGIN must be an origin without a trailing slash");
|
||||
const secureCookies = process.env.COOKIE_SECURE !== "false";
|
||||
if (
|
||||
!secureCookies &&
|
||||
!["localhost", "127.0.0.1"].includes(new URL(origin).hostname)
|
||||
)
|
||||
throw new Error(
|
||||
"Insecure cookies are allowed only on localhost. Use HTTPS for deployment.",
|
||||
);
|
||||
const dataDir = resolve(process.env.DATA_DIR || "data");
|
||||
mkdirSync(dataDir, { recursive: true });
|
||||
const store = openDatabase(resolve(dataDir, "calio.sqlite"));
|
||||
const app = createApp({
|
||||
store,
|
||||
username: process.env.CALIO_USERNAME || "calio",
|
||||
passwordHash,
|
||||
origin,
|
||||
secureCookies,
|
||||
});
|
||||
const server = app.listen(Number(process.env.PORT || 3000), "0.0.0.0", () =>
|
||||
console.log(`Calio listening at ${origin}`),
|
||||
);
|
||||
for (const signal of ["SIGTERM", "SIGINT"])
|
||||
process.on(signal, () =>
|
||||
server.close(() => {
|
||||
store.close();
|
||||
process.exit(0);
|
||||
}),
|
||||
);
|
||||
157
shared/bubble-physics.js
Normal file
157
shared/bubble-physics.js
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
import Matter from "matter-js";
|
||||
|
||||
const { Bodies, Body, Composite, Engine, Sleeping } = Matter;
|
||||
export const BUBBLE_RADIUS = 9.5;
|
||||
export const DRAW_BUBBLE_RADIUS = 8.4;
|
||||
export const VESSEL_RADIUS = 142;
|
||||
const packedPositions = [];
|
||||
for (let row = -9; row <= 9; row++)
|
||||
for (let col = -9; col <= 9; col++) {
|
||||
const x = 160 + (col + (row % 2) * 0.5) * 19.1;
|
||||
const y = 160 + (row * 19.1 * Math.sqrt(3)) / 2;
|
||||
if (Math.hypot(x - 160, y - 160) <= VESSEL_RADIUS - BUBBLE_RADIUS)
|
||||
packedPositions.push({ x, y });
|
||||
}
|
||||
packedPositions.sort(
|
||||
(a, b) => b.y - a.y || Math.abs(a.x - 160) - Math.abs(b.x - 160),
|
||||
);
|
||||
export const MAX_BUBBLES = packedPositions.length;
|
||||
export function bubbleCount(value, goal, enabled) {
|
||||
const ratio = Math.max(0, Math.min(value / (enabled ? goal : 2500), 1));
|
||||
return ratio > 0 ? Math.max(1, Math.round(ratio * MAX_BUBBLES)) : 0;
|
||||
}
|
||||
|
||||
// Project Earth's gravity onto the screen, then account for portrait/landscape.
|
||||
// Alpha is a compass heading and does not affect gravity.
|
||||
export function screenGravity(beta, gamma, screenAngle = 0) {
|
||||
const b = (beta * Math.PI) / 180;
|
||||
const g = (gamma * Math.PI) / 180;
|
||||
const angle = (screenAngle * Math.PI) / 180;
|
||||
const x = Math.sin(g) * Math.cos(b);
|
||||
const y = Math.sin(b);
|
||||
if (Math.hypot(x, y) < 0.12) return { x: 0, y: 0.18 };
|
||||
return {
|
||||
x: x * Math.cos(angle) + y * Math.sin(angle),
|
||||
y: -x * Math.sin(angle) + y * Math.cos(angle),
|
||||
};
|
||||
}
|
||||
|
||||
export function createBubbleWorld(initialCount = 0, random = Math.random) {
|
||||
const engine = Engine.create({
|
||||
enableSleeping: true,
|
||||
positionIterations: 24,
|
||||
velocityIterations: 8,
|
||||
});
|
||||
engine.gravity.scale = 0.00035;
|
||||
const balls = [];
|
||||
let target = initialCount;
|
||||
let spawnTime = 0;
|
||||
const walls = Array.from({ length: 72 }, (_, i) => {
|
||||
const angle = (i / 72) * Math.PI * 2;
|
||||
const radius = VESSEL_RADIUS + 9;
|
||||
return Bodies.rectangle(
|
||||
160 + Math.cos(angle) * radius,
|
||||
160 + Math.sin(angle) * radius,
|
||||
(2 * Math.PI * radius) / 72 + 2,
|
||||
18,
|
||||
{
|
||||
isStatic: true,
|
||||
angle: angle + Math.PI / 2,
|
||||
friction: 0.05,
|
||||
restitution: 0.2,
|
||||
},
|
||||
);
|
||||
});
|
||||
Composite.add(engine.world, walls);
|
||||
function add(x, y) {
|
||||
const ball = Bodies.polygon(x, y, 24, BUBBLE_RADIUS, {
|
||||
restitution: 0.34,
|
||||
friction: 0.035,
|
||||
frictionStatic: 0.15,
|
||||
frictionAir: 0.018,
|
||||
sleepThreshold: 45,
|
||||
});
|
||||
ball.circleRadius = BUBBLE_RADIUS;
|
||||
balls.push(ball);
|
||||
Composite.add(engine.world, ball);
|
||||
return ball;
|
||||
}
|
||||
function wake() {
|
||||
for (const ball of balls) Sleeping.set(ball, false);
|
||||
}
|
||||
function seed(count) {
|
||||
for (const ball of balls) Composite.remove(engine.world, ball);
|
||||
balls.length = 0;
|
||||
target = Math.min(MAX_BUBBLES, Math.max(0, count));
|
||||
for (let i = 0; i < target; i++)
|
||||
add(packedPositions[i].x, packedPositions[i].y);
|
||||
}
|
||||
seed(initialCount);
|
||||
function setTarget(count) {
|
||||
target = Math.min(MAX_BUBBLES, Math.max(0, count));
|
||||
while (balls.length > target) Composite.remove(engine.world, balls.pop());
|
||||
wake();
|
||||
}
|
||||
function gravity(x, y) {
|
||||
if (Math.hypot(engine.gravity.x - x, engine.gravity.y - y) < 0.025)
|
||||
return false;
|
||||
engine.gravity.x = x;
|
||||
engine.gravity.y = y;
|
||||
wake();
|
||||
return true;
|
||||
}
|
||||
function step(delta = 1000 / 60) {
|
||||
spawnTime += delta;
|
||||
if (balls.length < target && spawnTime >= 45) {
|
||||
spawnTime = 0;
|
||||
// Each new bubble enters at the upper inside edge, then falls naturally.
|
||||
const x = 160 + (random() - 0.5) * 55;
|
||||
const y =
|
||||
160 -
|
||||
Math.sqrt((VESSEL_RADIUS - BUBBLE_RADIUS - 2) ** 2 - (x - 160) ** 2);
|
||||
const ball = add(x, y);
|
||||
Body.setVelocity(ball, { x: (random() - 0.5) * 1.5, y: 0.6 });
|
||||
wake();
|
||||
}
|
||||
Engine.update(engine, Math.min(delta, 1000 / 60));
|
||||
// Prevent rare tunnelling during fast rotation or a suspended-tab resume.
|
||||
for (const ball of balls) {
|
||||
const dx = ball.position.x - 160;
|
||||
const dy = ball.position.y - 160;
|
||||
const distance = Math.hypot(dx, dy);
|
||||
const limit = VESSEL_RADIUS - DRAW_BUBBLE_RADIUS;
|
||||
if (distance > VESSEL_RADIUS + BUBBLE_RADIUS) {
|
||||
const nx = dx / distance;
|
||||
const ny = dy / distance;
|
||||
Body.setPosition(ball, { x: 160 + nx * limit, y: 160 + ny * limit });
|
||||
const outward = ball.velocity.x * nx + ball.velocity.y * ny;
|
||||
if (outward > 0)
|
||||
Body.setVelocity(ball, {
|
||||
x: ball.velocity.x - outward * 1.3 * nx,
|
||||
y: ball.velocity.y - outward * 1.3 * ny,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
function nudge() {
|
||||
for (const ball of balls) {
|
||||
Sleeping.set(ball, false);
|
||||
Body.setVelocity(ball, { x: (random() - 0.5) * 7, y: -2 - random() * 4 });
|
||||
}
|
||||
}
|
||||
return {
|
||||
engine,
|
||||
balls,
|
||||
step,
|
||||
seed,
|
||||
setTarget,
|
||||
gravity,
|
||||
nudge,
|
||||
awake: () =>
|
||||
balls.length < target || balls.some((ball) => !ball.isSleeping),
|
||||
dispose: () => {
|
||||
Composite.clear(engine.world, false);
|
||||
Engine.clear(engine);
|
||||
},
|
||||
};
|
||||
}
|
||||
143
shared/domain.js
Normal file
143
shared/domain.js
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const metricKeys = [
|
||||
"calories",
|
||||
"protein",
|
||||
"carbs",
|
||||
"fat",
|
||||
"fiber",
|
||||
"sugar",
|
||||
"sodium",
|
||||
];
|
||||
const amount = z.number().finite().min(0).max(100000);
|
||||
export const nutrientsSchema = z
|
||||
.object(Object.fromEntries(metricKeys.map((key) => [key, amount])))
|
||||
.strict();
|
||||
const date = z
|
||||
.string()
|
||||
.regex(/^\d{4}-\d{2}-\d{2}$/)
|
||||
.refine((value) => {
|
||||
const parsed = new Date(value + "T12:00:00Z");
|
||||
return (
|
||||
!Number.isNaN(+parsed) && parsed.toISOString().slice(0, 10) === value
|
||||
);
|
||||
}, "Invalid date");
|
||||
const name = z.string().trim().min(1).max(160);
|
||||
const food = z.object({
|
||||
name,
|
||||
serving: z.string().trim().min(1).max(100),
|
||||
nutrients: nutrientsSchema,
|
||||
});
|
||||
const entry = food
|
||||
.extend({
|
||||
date,
|
||||
meal: z.enum(["Breakfast", "Lunch", "Dinner", "Snacks"]),
|
||||
quantity: z.number().finite().positive().max(1000),
|
||||
})
|
||||
.strict();
|
||||
const goal = z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
target: z.number().finite().positive().max(100000),
|
||||
})
|
||||
.strict();
|
||||
const settings = z
|
||||
.object({
|
||||
theme: z.enum(["system", "light", "dark"]),
|
||||
accentColor: z
|
||||
.string()
|
||||
.regex(/^#[a-fA-F0-9]{6}$/)
|
||||
.optional(),
|
||||
unit: z.enum(["kg", "lb"]),
|
||||
goals: z
|
||||
.object(Object.fromEntries(metricKeys.map((key) => [key, goal])))
|
||||
.strict(),
|
||||
exportFormat: z.enum(["markdown", "csv", "json"]),
|
||||
exportDays: z.enum(["7", "30", "90", "all"]),
|
||||
exportMetrics: z.array(z.enum(metricKeys)).max(7).optional(),
|
||||
exportWeight: z.boolean().optional(),
|
||||
})
|
||||
.strict();
|
||||
export const recordSchema = z
|
||||
.object({
|
||||
id: z.string().regex(/^[\w-]{1,80}$/),
|
||||
type: z.enum(["entry", "food", "plate", "weight", "settings"]),
|
||||
updatedAt: z.string().datetime({ offset: false }),
|
||||
deleted: z.boolean(),
|
||||
data: z.unknown(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((record, ctx) => {
|
||||
if (record.type === "settings" && record.id !== "settings")
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: "Settings must use the settings ID",
|
||||
});
|
||||
if (record.type !== "settings" && record.id === "settings")
|
||||
ctx.addIssue({ code: "custom", message: "Reserved settings ID" });
|
||||
const schema = {
|
||||
entry,
|
||||
food: food.strict(),
|
||||
plate: z
|
||||
.object({
|
||||
name,
|
||||
items: z
|
||||
.array(
|
||||
food
|
||||
.extend({ quantity: z.number().finite().positive().max(1000) })
|
||||
.strict(),
|
||||
)
|
||||
.min(1)
|
||||
.max(100),
|
||||
})
|
||||
.strict(),
|
||||
weight: z
|
||||
.object({
|
||||
date,
|
||||
valueKg: z.number().finite().positive().max(1000),
|
||||
notes: z.string().max(500),
|
||||
})
|
||||
.strict(),
|
||||
settings,
|
||||
}[record.type];
|
||||
const result = schema.safeParse(record.data);
|
||||
if (!result.success)
|
||||
for (const issue of result.error.issues)
|
||||
ctx.addIssue({
|
||||
code: "custom",
|
||||
message: issue.message,
|
||||
path: ["data", ...issue.path],
|
||||
});
|
||||
});
|
||||
|
||||
// The full payload breaks same-millisecond ties identically on every device.
|
||||
export function compareRecords(a, b) {
|
||||
const timestamp = Date.parse(a.updatedAt) - Date.parse(b.updatedAt);
|
||||
if (timestamp) return timestamp;
|
||||
const left = JSON.stringify([a.deleted, a.data]);
|
||||
const right = JSON.stringify([b.deleted, b.data]);
|
||||
return left === right ? 0 : left > right ? 1 : -1;
|
||||
}
|
||||
export function emptyNutrients() {
|
||||
return Object.fromEntries(metricKeys.map((k) => [k, 0]));
|
||||
}
|
||||
export function totalNutrients(entries) {
|
||||
const total = emptyNutrients();
|
||||
for (const item of entries)
|
||||
for (const key of metricKeys)
|
||||
total[key] += (item.nutrients[key] || 0) * (item.quantity ?? 1);
|
||||
return total;
|
||||
}
|
||||
export const defaultSettings = {
|
||||
theme: "system",
|
||||
accentColor: "#8391ed",
|
||||
unit: "lb",
|
||||
exportFormat: "markdown",
|
||||
exportDays: "30",
|
||||
goals: Object.fromEntries(
|
||||
metricKeys.map((key, i) => [
|
||||
key,
|
||||
{ enabled: i < 4, target: [2000, 120, 250, 65, 30, 50, 2300][i] },
|
||||
]),
|
||||
),
|
||||
};
|
||||
55
shared/theme.js
Normal file
55
shared/theme.js
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
export const DEFAULT_ACCENT = "#8391ed";
|
||||
export const accentPresets = [
|
||||
{ name: "Periwinkle", color: "#8391ed" },
|
||||
{ name: "Sky", color: "#6daed9" },
|
||||
{ name: "Lavender", color: "#b28adc" },
|
||||
{ name: "Rose", color: "#d780a2" },
|
||||
{ name: "Amber", color: "#d9a65d" },
|
||||
{ name: "Sage", color: "#8ca37a" },
|
||||
];
|
||||
function rgb(hex) {
|
||||
return [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
|
||||
}
|
||||
export function mixColor(color, other, fraction) {
|
||||
const first = rgb(color);
|
||||
const second = rgb(other);
|
||||
return (
|
||||
"#" +
|
||||
first
|
||||
.map((value, i) =>
|
||||
Math.round(value * (1 - fraction) + second[i] * fraction)
|
||||
.toString(16)
|
||||
.padStart(2, "0"),
|
||||
)
|
||||
.join("")
|
||||
);
|
||||
}
|
||||
export function contrastText(color) {
|
||||
const [r, g, b] = rgb(color).map((v) => {
|
||||
const s = v / 255;
|
||||
return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
||||
});
|
||||
return r * 0.2126 + g * 0.7152 + b * 0.0722 > 0.179 ? "#000000" : "#ffffff";
|
||||
}
|
||||
export function accentPalette(value, dark) {
|
||||
const accent = /^#[a-fA-F0-9]{6}$/.test(value || "") ? value : DEFAULT_ACCENT;
|
||||
const hover = mixColor(accent, dark ? "#ffffff" : "#000000", 0.12);
|
||||
return {
|
||||
"--accent": accent,
|
||||
"--accent-dark": hover,
|
||||
"--accent-soft": mixColor(
|
||||
accent,
|
||||
dark ? "#191a20" : "#ffffff",
|
||||
dark ? 0.84 : 0.9,
|
||||
),
|
||||
"--accent-text": mixColor(
|
||||
accent,
|
||||
dark ? "#ffffff" : "#000000",
|
||||
dark ? 0.28 : 0.26,
|
||||
),
|
||||
"--on-accent": contrastText(accent),
|
||||
"--on-accent-hover": contrastText(hover),
|
||||
"--orb-light": mixColor(accent, "#ffffff", dark ? 0.22 : 0.38),
|
||||
"--orb-dark": mixColor(accent, "#000000", 0.04),
|
||||
};
|
||||
}
|
||||
1144
src/App.tsx
Normal file
1144
src/App.tsx
Normal file
File diff suppressed because it is too large
Load diff
467
src/Settings.tsx
Normal file
467
src/Settings.tsx
Normal file
|
|
@ -0,0 +1,467 @@
|
|||
import { useState } from "react";
|
||||
import {
|
||||
Download,
|
||||
Check,
|
||||
LogOut,
|
||||
ShieldCheck,
|
||||
Smartphone,
|
||||
Cloud,
|
||||
RefreshCw,
|
||||
Sun,
|
||||
Moon,
|
||||
Monitor,
|
||||
ArrowUpRight,
|
||||
} from "lucide-react";
|
||||
import type { JournalRecord, Metric, Settings as SettingsData } from "./types";
|
||||
import { metrics } from "./types";
|
||||
import { downloadExport, offsetDay, today } from "./utils";
|
||||
import { logout, saveRecord, sync, useSyncStatus } from "./store";
|
||||
import { accentPresets, DEFAULT_ACCENT } from "../shared/theme.js";
|
||||
|
||||
export function Settings({
|
||||
settings,
|
||||
records,
|
||||
pending,
|
||||
lastSync,
|
||||
notify,
|
||||
install,
|
||||
update,
|
||||
}: {
|
||||
settings: SettingsData;
|
||||
records: JournalRecord[];
|
||||
pending: number;
|
||||
lastSync: string | null;
|
||||
notify: (text: string) => void;
|
||||
install: (() => void) | null;
|
||||
update: (() => void) | null;
|
||||
}) {
|
||||
const [draft, setDraft] = useState(settings);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [format, setFormat] = useState(settings.exportFormat);
|
||||
const [range, setRange] = useState(settings.exportDays);
|
||||
const [start, setStart] = useState(
|
||||
offsetDay(
|
||||
today(),
|
||||
1 - Number(settings.exportDays === "all" ? 30 : settings.exportDays),
|
||||
),
|
||||
);
|
||||
const [end, setEnd] = useState(today());
|
||||
const [selected, setSelected] = useState<Metric[]>(
|
||||
settings.exportMetrics ||
|
||||
metrics.filter((m) => settings.goals[m.key].enabled).map((m) => m.key),
|
||||
);
|
||||
const [includeWeight, setIncludeWeight] = useState(
|
||||
settings.exportWeight ?? true,
|
||||
);
|
||||
const [error, setError] = useState("");
|
||||
const status = useSyncStatus();
|
||||
const effectiveStart =
|
||||
range === "all"
|
||||
? records.reduce((value, r) => {
|
||||
const date = (r.data as { date?: string }).date;
|
||||
return date && date < value ? date : value;
|
||||
}, today())
|
||||
: start;
|
||||
const effectiveEnd =
|
||||
range === "all"
|
||||
? records.reduce((value, r) => {
|
||||
const date = !r.deleted && (r.data as { date?: string }).date;
|
||||
return date && date > value ? date : value;
|
||||
}, today())
|
||||
: end;
|
||||
async function save(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await saveRecord(
|
||||
"settings",
|
||||
{
|
||||
...draft,
|
||||
exportFormat: format,
|
||||
exportDays: range,
|
||||
exportMetrics: selected,
|
||||
exportWeight: includeWeight,
|
||||
},
|
||||
"settings",
|
||||
);
|
||||
notify("Your preferences are saved");
|
||||
} catch {
|
||||
setError("Could not save. Check that each goal is a positive number.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<div className="page-heading">
|
||||
<div>
|
||||
<span className="eyebrow">MAKE ROOM FOR YOU</span>
|
||||
<h1>
|
||||
Your way<span>.</span>
|
||||
</h1>
|
||||
<p>A journal that fits your everyday.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="settings-grid">
|
||||
<form className="card settings-card" onSubmit={save}>
|
||||
<div className="card-title">
|
||||
<div>
|
||||
<span className="eyebrow">FOCUS ON WHAT MATTERS</span>
|
||||
<h2>Daily goals</h2>
|
||||
</div>
|
||||
<span className="tiny-badge">PERSONAL</span>
|
||||
</div>
|
||||
<p className="muted">
|
||||
Choose what you track. Turning a goal off keeps your past nutrition
|
||||
data.
|
||||
</p>
|
||||
<div className="goal-head">
|
||||
<span>Track</span>
|
||||
<span>Daily target</span>
|
||||
</div>
|
||||
{metrics.map((m) => (
|
||||
<div className="goal-row" key={m.key}>
|
||||
<label className="toggle-label">
|
||||
<input
|
||||
className="switch"
|
||||
type="checkbox"
|
||||
checked={draft.goals[m.key].enabled}
|
||||
onChange={(e) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
goals: {
|
||||
...draft.goals,
|
||||
[m.key]: {
|
||||
...draft.goals[m.key],
|
||||
enabled: e.target.checked,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span>{m.label}</span>
|
||||
</label>
|
||||
<label className="unit-input goal-input">
|
||||
<input
|
||||
aria-label={`${m.label} daily goal`}
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
step="any"
|
||||
min="0.1"
|
||||
max="100000"
|
||||
required
|
||||
value={draft.goals[m.key].target}
|
||||
onChange={(e) =>
|
||||
setDraft({
|
||||
...draft,
|
||||
goals: {
|
||||
...draft.goals,
|
||||
[m.key]: {
|
||||
...draft.goals[m.key],
|
||||
target:
|
||||
e.target.value === ""
|
||||
? ("" as unknown as number)
|
||||
: +e.target.value,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span>{m.unit}</span>
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
<div className="settings-section">
|
||||
<h3>Look & feel</h3>
|
||||
<div className="segmented theme-control">
|
||||
{(
|
||||
[
|
||||
{ key: "light", icon: Sun },
|
||||
{ key: "dark", icon: Moon },
|
||||
{ key: "system", icon: Monitor },
|
||||
] as const
|
||||
).map(({ key, icon: Icon }) => (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
className={draft.theme === key ? "active" : ""}
|
||||
onClick={() => setDraft({ ...draft, theme: key })}
|
||||
>
|
||||
<Icon size={16} />
|
||||
{key[0].toUpperCase() + key.slice(1)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="accent-preference">
|
||||
<span className="field-caption">ACCENT COLOR</span>
|
||||
<div className="accent-swatches">
|
||||
{accentPresets.map((preset) => (
|
||||
<button
|
||||
type="button"
|
||||
key={preset.color}
|
||||
aria-label={`${preset.name} accent`}
|
||||
aria-pressed={
|
||||
(draft.accentColor || DEFAULT_ACCENT).toLowerCase() ===
|
||||
preset.color
|
||||
}
|
||||
onClick={() =>
|
||||
setDraft({ ...draft, accentColor: preset.color })
|
||||
}
|
||||
>
|
||||
<span style={{ background: preset.color }} />
|
||||
{(draft.accentColor || DEFAULT_ACCENT).toLowerCase() ===
|
||||
preset.color && <Check size={15} />}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label className="custom-accent">
|
||||
<span>Custom color</span>
|
||||
<code>
|
||||
{(draft.accentColor || DEFAULT_ACCENT).toUpperCase()}
|
||||
</code>
|
||||
<input
|
||||
aria-label="Custom accent color"
|
||||
type="color"
|
||||
value={draft.accentColor || DEFAULT_ACCENT}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, accentColor: e.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="preference-row">
|
||||
<label htmlFor="weight-unit">Weight unit</label>
|
||||
<select
|
||||
id="weight-unit"
|
||||
value={draft.unit}
|
||||
onChange={(e) =>
|
||||
setDraft({ ...draft, unit: e.target.value as "kg" | "lb" })
|
||||
}
|
||||
>
|
||||
<option value="lb">Pounds (lb)</option>
|
||||
<option value="kg">Kilograms (kg)</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
{error && (
|
||||
<p role="alert" className="error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button className="primary wide" disabled={busy}>
|
||||
<Check size={18} />
|
||||
Save preferences
|
||||
</button>
|
||||
</form>
|
||||
<div className="settings-stack">
|
||||
<section className="card settings-card">
|
||||
<div className="card-title">
|
||||
<div>
|
||||
<span className="eyebrow">YOUR DATA, TO GO</span>
|
||||
<h2>Export your journal</h2>
|
||||
</div>
|
||||
<Download size={23} className="muted" />
|
||||
</div>
|
||||
<p className="muted">
|
||||
A clear, portable record for your own analysis or a conversation
|
||||
with an LLM.
|
||||
</p>
|
||||
<div className="form-row">
|
||||
<label>
|
||||
Format
|
||||
<select
|
||||
value={format}
|
||||
onChange={(e) => setFormat(e.target.value as typeof format)}
|
||||
>
|
||||
<option value="markdown">Markdown · LLM friendly</option>
|
||||
<option value="csv">CSV · spreadsheet</option>
|
||||
<option value="json">JSON · structured</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
Date range
|
||||
<select
|
||||
value={range}
|
||||
onChange={(e) => {
|
||||
const value = e.target.value as typeof range;
|
||||
setRange(value);
|
||||
if (value !== "all") {
|
||||
setStart(offsetDay(today(), 1 - +value));
|
||||
setEnd(today());
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="7">Last 7 days</option>
|
||||
<option value="30">Last 30 days</option>
|
||||
<option value="90">Last 90 days</option>
|
||||
<option value="all">All time</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
{range !== "all" && (
|
||||
<div className="form-row">
|
||||
<label>
|
||||
From
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={start}
|
||||
max={end}
|
||||
onChange={(e) => setStart(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Through
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={end}
|
||||
min={start}
|
||||
onChange={(e) => setEnd(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<span className="field-caption">INCLUDE IN EXPORT</span>
|
||||
<div className="export-options">
|
||||
{metrics.map((m) => (
|
||||
<label className="check-row" key={m.key}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selected.includes(m.key)}
|
||||
onChange={(e) =>
|
||||
setSelected(
|
||||
e.target.checked
|
||||
? [...selected, m.key]
|
||||
: selected.filter((v) => v !== m.key),
|
||||
)
|
||||
}
|
||||
/>
|
||||
{m.label}
|
||||
</label>
|
||||
))}
|
||||
<label className="check-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeWeight}
|
||||
onChange={(e) => setIncludeWeight(e.target.checked)}
|
||||
/>
|
||||
Weight
|
||||
</label>
|
||||
</div>
|
||||
<button
|
||||
className="secondary wide"
|
||||
disabled={
|
||||
!effectiveStart ||
|
||||
!effectiveEnd ||
|
||||
effectiveStart > effectiveEnd ||
|
||||
(!selected.length && !includeWeight)
|
||||
}
|
||||
onClick={() => {
|
||||
downloadExport(
|
||||
records,
|
||||
settings,
|
||||
effectiveStart,
|
||||
effectiveEnd,
|
||||
selected,
|
||||
includeWeight,
|
||||
format,
|
||||
pending,
|
||||
);
|
||||
notify("Export downloaded");
|
||||
}}
|
||||
>
|
||||
<Download size={17} />
|
||||
Download export
|
||||
</button>
|
||||
<p className="small muted">
|
||||
Includes locally saved changes. No data is sent to an LLM.
|
||||
</p>
|
||||
</section>
|
||||
<section className="card settings-card">
|
||||
<div className="card-title">
|
||||
<div>
|
||||
<span className="eyebrow">READY WHEN YOU ARE</span>
|
||||
<h2>On your devices</h2>
|
||||
</div>
|
||||
<Smartphone size={22} className="muted" />
|
||||
</div>
|
||||
<div className="status-detail">
|
||||
<Cloud size={22} />
|
||||
<div>
|
||||
<strong>
|
||||
{pending
|
||||
? `${pending} change${pending === 1 ? "" : "s"} waiting to sync`
|
||||
: "Your journal is saved"}
|
||||
<span className="status-dot" />
|
||||
</strong>
|
||||
<small>
|
||||
{lastSync
|
||||
? `Last synced ${new Date(lastSync).toLocaleString()}`
|
||||
: "Your first sync will prepare your offline journal."}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
className="secondary wide"
|
||||
disabled={status.busy || !status.online}
|
||||
onClick={() => void sync()}
|
||||
>
|
||||
<RefreshCw size={16} className={status.busy ? "spin" : ""} />
|
||||
{status.busy ? "Syncing…" : "Sync now"}
|
||||
</button>
|
||||
<p className="small muted">
|
||||
Your synced journal and new entries stay on this device for
|
||||
offline use. Open Calio while online before heading out; sync
|
||||
resumes when you return to the app.
|
||||
</p>
|
||||
{install ? (
|
||||
<button className="text-button" onClick={install}>
|
||||
Install Calio
|
||||
<ArrowUpRight size={16} />
|
||||
</button>
|
||||
) : (
|
||||
<p className="install-tip">
|
||||
<Smartphone size={18} />
|
||||
<span>
|
||||
On iPhone: open in Safari, tap Share, then{" "}
|
||||
<strong>Add to Home Screen</strong>. On Android: use your
|
||||
browser’s Install app menu.
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
{update && (
|
||||
<button className="primary wide" onClick={update}>
|
||||
Update Calio
|
||||
<ArrowUpRight size={17} />
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
<section className="account-row">
|
||||
<div>
|
||||
<ShieldCheck size={20} />
|
||||
<span>
|
||||
Your space. Your data.
|
||||
<small>Calio 0.1.0 · A personal nutrition journal</small>
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
className="text-button"
|
||||
onClick={async () => {
|
||||
try {
|
||||
await logout();
|
||||
} catch (err) {
|
||||
notify((err as Error).message);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<LogOut size={16} />
|
||||
Sign out
|
||||
</button>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
370
src/Trends.tsx
Normal file
370
src/Trends.tsx
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
import { useState } from "react";
|
||||
import {
|
||||
ArrowDownRight,
|
||||
ArrowUpRight,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Plus,
|
||||
Scale,
|
||||
Trash2,
|
||||
Pencil,
|
||||
Activity,
|
||||
} from "lucide-react";
|
||||
import type { Entry, JournalRecord, Settings, Weight, Metric } from "./types";
|
||||
import { metrics } from "./types";
|
||||
import {
|
||||
displayDate,
|
||||
number,
|
||||
offsetDay,
|
||||
recordsOf,
|
||||
today,
|
||||
weightValue,
|
||||
} from "./utils";
|
||||
import { totalNutrients } from "../shared/domain.js";
|
||||
import { Empty } from "./components";
|
||||
|
||||
export function Trends({
|
||||
records,
|
||||
settings,
|
||||
logWeight,
|
||||
editWeight,
|
||||
remove,
|
||||
}: {
|
||||
records: JournalRecord[];
|
||||
settings: Settings;
|
||||
logWeight: () => void;
|
||||
editWeight: (r: JournalRecord<Weight>) => void;
|
||||
remove: (r: JournalRecord) => void;
|
||||
}) {
|
||||
const [period, setPeriod] = useState(7);
|
||||
const [end, setEnd] = useState(today());
|
||||
const [metric, setMetric] = useState<Metric>("calories");
|
||||
const start = offsetDay(end, 1 - period);
|
||||
const entries = recordsOf<Entry>(records, "entry");
|
||||
const allWeights = recordsOf<Weight>(records, "weight").sort(
|
||||
(a, b) =>
|
||||
a.data.date.localeCompare(b.data.date) ||
|
||||
a.updatedAt.localeCompare(b.updatedAt),
|
||||
);
|
||||
const weights = allWeights.filter(
|
||||
(r) => r.data.date >= start && r.data.date <= end,
|
||||
);
|
||||
// One latest weigh-in per day for the trend; the journal retains every measurement.
|
||||
const dailyWeights = [
|
||||
...new Map(weights.map((r) => [r.data.date, r])).values(),
|
||||
];
|
||||
const days = Array.from({ length: period }, (_, i) => {
|
||||
const date = offsetDay(start, i);
|
||||
const logs = entries.filter((r) => r.data.date === date);
|
||||
return {
|
||||
date,
|
||||
logged: logs.length > 0,
|
||||
total: totalNutrients(logs.map((r) => r.data))[metric],
|
||||
};
|
||||
});
|
||||
const loggedDays = days.filter((d) => d.logged);
|
||||
const avg = loggedDays.length
|
||||
? loggedDays.reduce((sum, d) => sum + d.total, 0) / loggedDays.length
|
||||
: 0;
|
||||
const goal = settings.goals[metric];
|
||||
const maximum =
|
||||
Math.max(...days.map((d) => d.total), goal.enabled ? goal.target : 1, 1) *
|
||||
1.12;
|
||||
const chosen = metrics.find((m) => m.key === metric)!;
|
||||
const values = dailyWeights.map((r) =>
|
||||
weightValue(r.data.valueKg, settings.unit),
|
||||
);
|
||||
const minWeight = Math.min(...values) - 1;
|
||||
const maxWeight = Math.max(...values) + 1;
|
||||
const points = dailyWeights.map((r, i) => ({
|
||||
x:
|
||||
28 +
|
||||
((new Date(r.data.date).getTime() - new Date(start).getTime()) /
|
||||
((period - 1) * 86400000)) *
|
||||
544,
|
||||
y: 170 - ((values[i] - minWeight) / (maxWeight - minWeight)) * 140,
|
||||
}));
|
||||
const delta = values.length > 1 ? values.at(-1)! - values[0] : null;
|
||||
return (
|
||||
<>
|
||||
<div className="page-heading">
|
||||
<div>
|
||||
<span className="eyebrow">THE BIGGER PICTURE</span>
|
||||
<h1>
|
||||
Your rhythms<span>.</span>
|
||||
</h1>
|
||||
<p>Small moments. A little perspective.</p>
|
||||
</div>
|
||||
<button className="primary" onClick={logWeight}>
|
||||
<Plus size={18} />
|
||||
Log weight
|
||||
</button>
|
||||
</div>
|
||||
<div className="trend-controls">
|
||||
<div className="segmented">
|
||||
{[7, 30, 90, 365].map((n) => (
|
||||
<button
|
||||
key={n}
|
||||
className={period === n ? "active" : ""}
|
||||
onClick={() => setPeriod(n)}
|
||||
>
|
||||
{n === 7
|
||||
? "Week"
|
||||
: n === 30
|
||||
? "Month"
|
||||
: n === 90
|
||||
? "3 months"
|
||||
: "Year"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="date-controls">
|
||||
<button
|
||||
className="icon-button"
|
||||
aria-label="Previous period"
|
||||
onClick={() => setEnd(offsetDay(end, -period))}
|
||||
>
|
||||
<ChevronLeft size={18} />
|
||||
</button>
|
||||
<span>
|
||||
{displayDate(start, { month: "short", day: "numeric" })} –{" "}
|
||||
{displayDate(end, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
})}
|
||||
</span>
|
||||
<button
|
||||
className="icon-button"
|
||||
aria-label="Next period"
|
||||
disabled={end >= today()}
|
||||
onClick={() =>
|
||||
setEnd(
|
||||
offsetDay(end, period) > today()
|
||||
? today()
|
||||
: offsetDay(end, period),
|
||||
)
|
||||
}
|
||||
>
|
||||
<ChevronRight size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="trends-grid">
|
||||
<section className="card chart-card">
|
||||
<div className="card-title">
|
||||
<div>
|
||||
<span className="eyebrow">DAILY INTAKE</span>
|
||||
<h2>{chosen.label}</h2>
|
||||
</div>
|
||||
<select
|
||||
aria-label="Trend nutrient"
|
||||
value={metric}
|
||||
onChange={(e) => setMetric(e.target.value as Metric)}
|
||||
>
|
||||
{metrics.map((m) => (
|
||||
<option value={m.key} key={m.key}>
|
||||
{m.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="stat-large">
|
||||
{number(avg)} <span>{chosen.unit} / logged day</span>
|
||||
</div>
|
||||
<div
|
||||
className="bar-chart"
|
||||
role="img"
|
||||
aria-label={`${chosen.label}: ${number(avg)} ${chosen.unit} average over ${loggedDays.length} logged days`}
|
||||
>
|
||||
<div className="chart-grid-lines">
|
||||
<span>{number(maximum)}</span>
|
||||
<span>{number(maximum / 2)}</span>
|
||||
<span>0</span>
|
||||
</div>
|
||||
<div className="bars">
|
||||
{goal.enabled && (
|
||||
<div
|
||||
className="goal-line"
|
||||
style={{ bottom: `${(goal.target / maximum) * 100}%` }}
|
||||
>
|
||||
<span>Goal {number(goal.target)}</span>
|
||||
</div>
|
||||
)}
|
||||
{days.map((d) => (
|
||||
<div
|
||||
className={"bar-slot " + (!d.logged ? "unlogged" : "")}
|
||||
key={d.date}
|
||||
title={`${displayDate(d.date)}: ${d.logged ? number(d.total) + " " + chosen.unit : "Not logged"}`}
|
||||
>
|
||||
<div
|
||||
className="bar"
|
||||
style={{
|
||||
height: `${d.logged ? Math.max(1, (d.total / maximum) * 100) : 2}%`,
|
||||
background: d.logged ? chosen.color : undefined,
|
||||
}}
|
||||
/>
|
||||
{period === 7 && (
|
||||
<span>
|
||||
{displayDate(d.date, { weekday: "short" }).slice(0, 1)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<p className="chart-note">
|
||||
{loggedDays.length} of {period} days logged · Empty days are
|
||||
excluded from the average.
|
||||
</p>
|
||||
</section>
|
||||
<section className="card chart-card">
|
||||
<div className="card-title">
|
||||
<div>
|
||||
<span className="eyebrow">YOUR JOURNEY</span>
|
||||
<h2>Weight</h2>
|
||||
</div>
|
||||
<Scale size={22} className="muted" />
|
||||
</div>
|
||||
{dailyWeights.length ? (
|
||||
<>
|
||||
<div className="stat-large">
|
||||
{number(values.at(-1)!, 1)} <span>{settings.unit}</span>
|
||||
</div>
|
||||
<div className="weight-chart">
|
||||
<svg
|
||||
viewBox="0 0 600 210"
|
||||
role="img"
|
||||
aria-label={`${dailyWeights.length} weigh-ins, latest ${number(values.at(-1)!, 1)} ${settings.unit}`}
|
||||
>
|
||||
<line
|
||||
x1="28"
|
||||
x2="572"
|
||||
y1="30"
|
||||
y2="30"
|
||||
className="grid-line"
|
||||
/>
|
||||
<line
|
||||
x1="28"
|
||||
x2="572"
|
||||
y1="100"
|
||||
y2="100"
|
||||
className="grid-line"
|
||||
/>
|
||||
<line
|
||||
x1="28"
|
||||
x2="572"
|
||||
y1="170"
|
||||
y2="170"
|
||||
className="grid-line"
|
||||
/>
|
||||
<polyline
|
||||
points={points.map((p) => `${p.x},${p.y}`).join(" ")}
|
||||
fill="none"
|
||||
stroke="var(--accent)"
|
||||
strokeWidth="3"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
{points.map((p, i) => (
|
||||
<circle
|
||||
key={i}
|
||||
cx={p.x}
|
||||
cy={p.y}
|
||||
r="4"
|
||||
fill="var(--accent)"
|
||||
>
|
||||
<title>
|
||||
{dailyWeights[i].data.date}: {number(values[i], 1)}{" "}
|
||||
{settings.unit}
|
||||
</title>
|
||||
</circle>
|
||||
))}
|
||||
<text x="28" y="202">
|
||||
{displayDate(start, { month: "short", day: "numeric" })}
|
||||
</text>
|
||||
<text x="572" y="202" textAnchor="end">
|
||||
{displayDate(end, { month: "short", day: "numeric" })}
|
||||
</text>
|
||||
</svg>
|
||||
<div className="weight-axis">
|
||||
<span>{number(maxWeight, 1)}</span>
|
||||
<span>{number(minWeight, 1)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="chart-note">
|
||||
{delta === null ? (
|
||||
"Log another day to see a change over time."
|
||||
) : (
|
||||
<>
|
||||
{delta < 0 ? (
|
||||
<ArrowDownRight size={15} />
|
||||
) : (
|
||||
<ArrowUpRight size={15} />
|
||||
)}{" "}
|
||||
{number(Math.abs(delta), 1)} {settings.unit}{" "}
|
||||
{delta < 0 ? "down" : "up"} in this period
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<Empty
|
||||
icon={<Activity size={28} />}
|
||||
title="A starting point, whenever you’re ready"
|
||||
text="Your weigh-ins will become a simple picture of your progress."
|
||||
action={
|
||||
<button className="text-button" onClick={logWeight}>
|
||||
Log your first weight <ArrowUpRight size={16} />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
<section className="card weight-journal">
|
||||
<div className="card-title">
|
||||
<div>
|
||||
<span className="eyebrow">ONE CHECK-IN AT A TIME</span>
|
||||
<h2>Weight journal</h2>
|
||||
</div>
|
||||
<span className="pill">{weights.length} in this period</span>
|
||||
</div>
|
||||
{weights.length === 0 ? (
|
||||
<p className="muted">No weigh-ins in this date range.</p>
|
||||
) : (
|
||||
[...weights].reverse().map((r) => (
|
||||
<div className="journal-row" key={r.id}>
|
||||
<div className="food-avatar weight-avatar">
|
||||
<Scale size={19} />
|
||||
</div>
|
||||
<div className="row-copy">
|
||||
<strong>
|
||||
{number(weightValue(r.data.valueKg, settings.unit), 1)}{" "}
|
||||
{settings.unit}
|
||||
</strong>
|
||||
<small>
|
||||
{displayDate(r.data.date)}
|
||||
{r.data.notes ? " · " + r.data.notes : ""}
|
||||
</small>
|
||||
</div>
|
||||
<button
|
||||
className="icon-button"
|
||||
aria-label={`Edit weight ${r.data.date}`}
|
||||
onClick={() => editWeight(r)}
|
||||
>
|
||||
<Pencil size={16} />
|
||||
</button>
|
||||
<button
|
||||
className="icon-button danger-hover"
|
||||
aria-label={`Delete weight ${r.data.date}`}
|
||||
onClick={() => remove(r)}
|
||||
>
|
||||
<Trash2 size={16} />
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
);
|
||||
}
|
||||
775
src/components.tsx
Normal file
775
src/components.tsx
Normal file
|
|
@ -0,0 +1,775 @@
|
|||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import {
|
||||
X,
|
||||
ArrowUpRight,
|
||||
Plus,
|
||||
Minus,
|
||||
Leaf,
|
||||
Smartphone,
|
||||
RotateCcw,
|
||||
} from "lucide-react";
|
||||
import { bubbleCount } from "../shared/bubble-physics.js";
|
||||
import { useBubblePhysics } from "./useBubblePhysics";
|
||||
import {
|
||||
metrics,
|
||||
type Entry,
|
||||
type Food,
|
||||
type JournalRecord,
|
||||
type Meal,
|
||||
type Nutrients,
|
||||
type Plate,
|
||||
type Settings,
|
||||
type Weight,
|
||||
} from "./types";
|
||||
import { emptyNutrients } from "../shared/domain.js";
|
||||
import { saveRecord, putRecords } from "./store";
|
||||
import { displayDate, number, today, weightValue } from "./utils";
|
||||
|
||||
export function Modal({
|
||||
title,
|
||||
subtitle,
|
||||
close,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
close: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
useEffect(() => {
|
||||
const dialog = ref.current!;
|
||||
dialog.showModal();
|
||||
const listener = (event: Event) => {
|
||||
event.preventDefault();
|
||||
close();
|
||||
};
|
||||
dialog.addEventListener("cancel", listener);
|
||||
return () => {
|
||||
dialog.removeEventListener("cancel", listener);
|
||||
dialog.close();
|
||||
};
|
||||
}, [close]);
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
className="sheet"
|
||||
aria-labelledby="sheet-title"
|
||||
onClick={(event) => {
|
||||
if (event.target === event.currentTarget) {
|
||||
const r = event.currentTarget.getBoundingClientRect();
|
||||
if (
|
||||
event.clientX < r.left ||
|
||||
event.clientX > r.right ||
|
||||
event.clientY < r.top ||
|
||||
event.clientY > r.bottom
|
||||
)
|
||||
close();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="sheet-head">
|
||||
<div>
|
||||
<span className="eyebrow">A LITTLE EVERYDAY CARE</span>
|
||||
<h2 id="sheet-title">{title}</h2>
|
||||
{subtitle && <p>{subtitle}</p>}
|
||||
</div>
|
||||
<button
|
||||
className="icon-button"
|
||||
aria-label="Close dialog"
|
||||
onClick={close}
|
||||
>
|
||||
<X size={21} />
|
||||
</button>
|
||||
</div>
|
||||
{children}
|
||||
</dialog>
|
||||
);
|
||||
}
|
||||
export function CalorieOrb({
|
||||
value,
|
||||
goal,
|
||||
enabled,
|
||||
small = false,
|
||||
interactive = true,
|
||||
}: {
|
||||
value: number;
|
||||
goal: number;
|
||||
enabled: boolean;
|
||||
small?: boolean;
|
||||
interactive?: boolean;
|
||||
}) {
|
||||
const ratio = enabled ? Math.min(value / goal, 1) : Math.min(value / 2500, 1);
|
||||
const physics = useBubblePhysics(bubbleCount(value, goal, enabled));
|
||||
const readout = (
|
||||
<>
|
||||
<span className="eyebrow">
|
||||
{enabled
|
||||
? value > goal
|
||||
? "OVER YOUR GOAL"
|
||||
: "CALORIES REMAINING"
|
||||
: "CALORIES LOGGED"}
|
||||
</span>
|
||||
<strong>{number(enabled ? Math.abs(goal - value) : value)}</strong>
|
||||
<span className="orb-unit">kcal</span>
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<div className="orb-shell">
|
||||
<div
|
||||
className={
|
||||
"orb " +
|
||||
(small ? "orb-small" : "") +
|
||||
(enabled && value > goal ? " over" : "")
|
||||
}
|
||||
role="img"
|
||||
aria-label={`${number(value)} calories${enabled ? ` of ${number(goal)} calorie goal` : ""}`}
|
||||
>
|
||||
<svg viewBox="0 0 320 320" aria-hidden="true">
|
||||
<circle cx="160" cy="160" r="145" className="orb-track" />
|
||||
<circle
|
||||
cx="160"
|
||||
cy="160"
|
||||
r="145"
|
||||
className="orb-progress"
|
||||
strokeDasharray={`${enabled ? Math.min(value / goal, 1) * 911 : 0} 911`}
|
||||
transform="rotate(-90 160 160)"
|
||||
/>
|
||||
</svg>
|
||||
<canvas
|
||||
className="bubble-canvas"
|
||||
ref={physics.canvas}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{!small && ratio < 0.85 && (
|
||||
<div
|
||||
className={"orb-number " + (ratio > 0.47 ? "orb-number-high" : "")}
|
||||
>
|
||||
{readout}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{!small && ratio >= 0.85 && (
|
||||
<div className="orb-number orb-number-outside">{readout}</div>
|
||||
)}
|
||||
{interactive && !small && (
|
||||
<>
|
||||
<div className="orb-motion-controls">
|
||||
<button
|
||||
disabled={physics.reduced}
|
||||
aria-pressed={physics.enabled}
|
||||
onClick={() => void physics.toggleTilt()}
|
||||
>
|
||||
<Smartphone size={12} />
|
||||
{physics.reduced
|
||||
? "Reduced motion"
|
||||
: physics.motion === "on"
|
||||
? "Tilt enabled"
|
||||
: physics.motion === "waiting"
|
||||
? "Waiting for tilt…"
|
||||
: physics.enabled
|
||||
? "Turn tilt off"
|
||||
: "Enable tilt"}
|
||||
</button>
|
||||
<span />
|
||||
<button disabled={physics.reduced} onClick={physics.nudge}>
|
||||
<RotateCcw size={12} />
|
||||
Give a nudge
|
||||
</button>
|
||||
</div>
|
||||
{physics.motion === "denied" && (
|
||||
<p className="motion-help" role="status">
|
||||
Motion access was not granted. You can allow it in your browser’s
|
||||
website settings.
|
||||
</p>
|
||||
)}
|
||||
{physics.motion === "unavailable" && (
|
||||
<p className="motion-help" role="status">
|
||||
No tilt data yet. Falling bubbles still work on this device.
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function Empty({
|
||||
icon = <Leaf size={25} />,
|
||||
title,
|
||||
text,
|
||||
action,
|
||||
}: {
|
||||
icon?: ReactNode;
|
||||
title: string;
|
||||
text: string;
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="empty">
|
||||
<span className="empty-icon">{icon}</span>
|
||||
<h3>{title}</h3>
|
||||
<p>{text}</p>
|
||||
{action}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function NutrientFields({
|
||||
nutrients,
|
||||
set,
|
||||
}: {
|
||||
nutrients: Nutrients;
|
||||
set: (n: Nutrients) => void;
|
||||
}) {
|
||||
return (
|
||||
<div className="nutrient-fields">
|
||||
{metrics.map((metric) => (
|
||||
<label key={metric.key}>
|
||||
{metric.label}
|
||||
<span className="unit-input">
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
min="0"
|
||||
max="100000"
|
||||
step="any"
|
||||
required
|
||||
value={nutrients[metric.key]}
|
||||
onChange={(e) =>
|
||||
set({
|
||||
...nutrients,
|
||||
[metric.key]:
|
||||
e.target.value === ""
|
||||
? ("" as unknown as number)
|
||||
: +e.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span>{metric.unit}</span>
|
||||
</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function FoodEditor({
|
||||
close,
|
||||
date,
|
||||
meal,
|
||||
existing,
|
||||
foods,
|
||||
plates,
|
||||
mode = "log",
|
||||
notify,
|
||||
}: {
|
||||
close: () => void;
|
||||
date: string;
|
||||
meal: Meal;
|
||||
existing?: JournalRecord<Entry | Food>;
|
||||
foods: JournalRecord<Food>[];
|
||||
plates: JournalRecord<Plate>[];
|
||||
mode?: "log" | "food";
|
||||
notify: (text: string) => void;
|
||||
}) {
|
||||
const initial = existing?.data;
|
||||
const [tab, setTab] = useState<"manual" | "saved" | "plates">("manual");
|
||||
const [name, setName] = useState(initial?.name || "");
|
||||
const [serving, setServing] = useState(initial?.serving || "1 serving");
|
||||
const [nutrients, setNutrients] = useState<Nutrients>(
|
||||
initial?.nutrients || (emptyNutrients() as Nutrients),
|
||||
);
|
||||
const [quantity, setQuantity] = useState(
|
||||
existing?.type === "entry" ? (initial as Entry).quantity : 1,
|
||||
);
|
||||
const [selectedMeal, setMeal] = useState<Meal>(
|
||||
existing?.type === "entry" ? (initial as Entry).meal : meal,
|
||||
);
|
||||
const [selectedDate, setDate] = useState(
|
||||
existing?.type === "entry" ? (initial as Entry).date : date,
|
||||
);
|
||||
const [saveFood, setSaveFood] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const food = { name: name.trim(), serving: serving.trim(), nutrients };
|
||||
const items: Parameters<typeof putRecords>[0] = [
|
||||
{
|
||||
type: mode === "food" ? "food" : "entry",
|
||||
id: existing?.id,
|
||||
data:
|
||||
mode === "food"
|
||||
? food
|
||||
: { ...food, date: selectedDate, meal: selectedMeal, quantity },
|
||||
},
|
||||
];
|
||||
if (saveFood && mode === "log") items.push({ type: "food", data: food });
|
||||
await putRecords(items);
|
||||
notify(
|
||||
mode === "food" ? "Food saved to your library" : "Added to your day",
|
||||
);
|
||||
close();
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: "Could not save. Please try again.",
|
||||
);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
async function addPlate(plate: Plate) {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await putRecords(
|
||||
plate.items.map((item) => ({
|
||||
type: "entry",
|
||||
data: { ...item, date: selectedDate, meal: selectedMeal },
|
||||
})),
|
||||
);
|
||||
notify(`${plate.name} added to your day`);
|
||||
close();
|
||||
} catch {
|
||||
setError("Could not save this plate. Please try again.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Modal
|
||||
title={
|
||||
existing
|
||||
? "Edit " + (mode === "food" ? "food" : "entry")
|
||||
: mode === "food"
|
||||
? "A new favorite"
|
||||
: "What’s on your plate?"
|
||||
}
|
||||
subtitle={
|
||||
mode === "log"
|
||||
? displayDate(selectedDate, {
|
||||
weekday: "long",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
})
|
||||
: "Save the nutrition for one serving."
|
||||
}
|
||||
close={close}
|
||||
>
|
||||
{mode === "log" && !existing && (
|
||||
<div className="segmented">
|
||||
{(["manual", "saved", "plates"] as const).map((value) => (
|
||||
<button
|
||||
className={tab === value ? "active" : ""}
|
||||
key={value}
|
||||
onClick={() => setTab(value)}
|
||||
>
|
||||
{value === "manual"
|
||||
? "Quick entry"
|
||||
: value === "saved"
|
||||
? "My foods"
|
||||
: "My plates"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{mode === "log" && (
|
||||
<div className="form-row">
|
||||
<label>
|
||||
Day
|
||||
<input
|
||||
aria-label="Entry date"
|
||||
type="date"
|
||||
required
|
||||
value={selectedDate}
|
||||
onChange={(e) => setDate(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Meal
|
||||
<select
|
||||
value={selectedMeal}
|
||||
onChange={(e) => setMeal(e.target.value as Meal)}
|
||||
>
|
||||
{["Breakfast", "Lunch", "Dinner", "Snacks"].map((m) => (
|
||||
<option key={m}>{m}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
{tab !== "manual" ? (
|
||||
<div className="picker">
|
||||
<input
|
||||
type="search"
|
||||
placeholder={
|
||||
tab === "saved" ? "Find a saved food…" : "Find a plate…"
|
||||
}
|
||||
aria-label="Search library"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
/>
|
||||
{tab === "saved"
|
||||
? foods
|
||||
.filter((r) =>
|
||||
r.data.name.toLowerCase().includes(search.toLowerCase()),
|
||||
)
|
||||
.map((r) => (
|
||||
<button
|
||||
className="picker-row"
|
||||
key={r.id}
|
||||
onClick={() => {
|
||||
setName(r.data.name);
|
||||
setServing(r.data.serving);
|
||||
setNutrients(r.data.nutrients);
|
||||
setTab("manual");
|
||||
}}
|
||||
>
|
||||
<span>
|
||||
<strong>{r.data.name}</strong>
|
||||
<small>
|
||||
{r.data.serving} · {number(r.data.nutrients.calories)}{" "}
|
||||
kcal
|
||||
</small>
|
||||
</span>
|
||||
<ArrowUpRight size={18} />
|
||||
</button>
|
||||
))
|
||||
: plates
|
||||
.filter((r) =>
|
||||
r.data.name.toLowerCase().includes(search.toLowerCase()),
|
||||
)
|
||||
.map((r) => (
|
||||
<button
|
||||
disabled={busy || !selectedDate}
|
||||
className="picker-row"
|
||||
key={r.id}
|
||||
onClick={() => void addPlate(r.data)}
|
||||
>
|
||||
<span>
|
||||
<strong>{r.data.name}</strong>
|
||||
<small>
|
||||
{r.data.items.length}{" "}
|
||||
{r.data.items.length === 1 ? "food" : "foods"} · Add to{" "}
|
||||
{selectedMeal.toLowerCase()}
|
||||
</small>
|
||||
</span>
|
||||
<Plus size={18} />
|
||||
</button>
|
||||
))}
|
||||
{(tab === "saved" ? foods : plates).length === 0 && (
|
||||
<Empty
|
||||
title={
|
||||
tab === "saved"
|
||||
? "Your favorites live here"
|
||||
: "A plate makes it easy"
|
||||
}
|
||||
text={
|
||||
tab === "saved"
|
||||
? "Create a food in your library, or save one while logging."
|
||||
: "Combine your saved foods into a reusable plate in the library."
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={submit}>
|
||||
<label>
|
||||
Food name
|
||||
<input
|
||||
autoFocus
|
||||
required
|
||||
maxLength={160}
|
||||
placeholder="e.g. Greek yogurt & berries"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<div className="form-row">
|
||||
<label>
|
||||
Serving description
|
||||
<input
|
||||
required
|
||||
maxLength={100}
|
||||
value={serving}
|
||||
onChange={(e) => setServing(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{mode === "log" && (
|
||||
<label>
|
||||
Servings
|
||||
<input
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
min="0.001"
|
||||
max="1000"
|
||||
step="any"
|
||||
required
|
||||
value={quantity}
|
||||
onChange={(e) => setQuantity(+e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
<div className="section-caption">
|
||||
<span>Nutrition per serving</span>
|
||||
<span>From your label or recipe</span>
|
||||
</div>
|
||||
<NutrientFields nutrients={nutrients} set={setNutrients} />
|
||||
{mode === "log" && !existing && (
|
||||
<label className="check-row">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={saveFood}
|
||||
onChange={(e) => setSaveFood(e.target.checked)}
|
||||
/>
|
||||
Save this food to my library
|
||||
</label>
|
||||
)}
|
||||
{error && (
|
||||
<p className="error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button className="primary wide" disabled={busy}>
|
||||
{busy
|
||||
? "Saving…"
|
||||
: existing
|
||||
? "Save changes"
|
||||
: mode === "food"
|
||||
? "Save food"
|
||||
: `Add ${number(nutrients.calories * quantity)} kcal`}
|
||||
<Plus size={18} />
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
{tab !== "manual" && error && (
|
||||
<p className="error" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
export function PlateEditor({
|
||||
close,
|
||||
foods,
|
||||
existing,
|
||||
notify,
|
||||
}: {
|
||||
close: () => void;
|
||||
foods: JournalRecord<Food>[];
|
||||
existing?: JournalRecord<Plate>;
|
||||
notify: (text: string) => void;
|
||||
}) {
|
||||
const [name, setName] = useState(existing?.data.name || "");
|
||||
const [items, setItems] = useState<Plate["items"]>(
|
||||
existing?.data.items || [],
|
||||
);
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<Modal
|
||||
title={existing ? "Edit plate" : "Better together"}
|
||||
subtitle="A few favorites, ready in one tap."
|
||||
close={close}
|
||||
>
|
||||
<form
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
await saveRecord(
|
||||
"plate",
|
||||
{ name: name.trim(), items },
|
||||
existing?.id,
|
||||
);
|
||||
notify("Plate saved");
|
||||
close();
|
||||
} catch {
|
||||
setError("Could not save this plate. Check its name and servings.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<label>
|
||||
Plate name
|
||||
<input
|
||||
required
|
||||
autoFocus
|
||||
maxLength={160}
|
||||
placeholder="e.g. My usual breakfast"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{items.map((item, i) => (
|
||||
<div className="plate-item" key={i}>
|
||||
<span>
|
||||
<strong>{item.name}</strong>
|
||||
<small>{item.serving}</small>
|
||||
</span>
|
||||
<input
|
||||
aria-label={`Servings of ${item.name}`}
|
||||
type="number"
|
||||
min="0.001"
|
||||
max="1000"
|
||||
step="any"
|
||||
required
|
||||
value={item.quantity}
|
||||
onChange={(e) =>
|
||||
setItems(
|
||||
items.map((v, n) =>
|
||||
n === i ? { ...v, quantity: +e.target.value } : v,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-button"
|
||||
aria-label={`Remove ${item.name}`}
|
||||
onClick={() => setItems(items.filter((_, n) => n !== i))}
|
||||
>
|
||||
<Minus size={18} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<label>
|
||||
Add a saved food
|
||||
<select
|
||||
value=""
|
||||
onChange={(e) => {
|
||||
const food = foods.find((r) => r.id === e.target.value);
|
||||
if (food) setItems([...items, { ...food.data, quantity: 1 }]);
|
||||
}}
|
||||
>
|
||||
<option value="">Choose from your library…</option>
|
||||
{foods.map((r) => (
|
||||
<option key={r.id} value={r.id}>
|
||||
{r.data.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{foods.length === 0 && (
|
||||
<p className="muted">
|
||||
Save a food first, then combine your favorites here.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
className="primary wide"
|
||||
disabled={busy || items.length === 0 || items.length > 100}
|
||||
>
|
||||
Save plate
|
||||
<Plus size={18} />
|
||||
</button>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
export function WeightEditor({
|
||||
close,
|
||||
unit,
|
||||
existing,
|
||||
notify,
|
||||
}: {
|
||||
close: () => void;
|
||||
unit: Settings["unit"];
|
||||
existing?: JournalRecord<Weight>;
|
||||
notify: (text: string) => void;
|
||||
}) {
|
||||
const [date, setDate] = useState(existing?.data.date || today());
|
||||
const [value, setValue] = useState(
|
||||
existing ? +weightValue(existing.data.valueKg, unit).toFixed(2) : "",
|
||||
);
|
||||
const [notes, setNotes] = useState(existing?.data.notes || "");
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
return (
|
||||
<Modal
|
||||
title={existing ? "Edit weigh-in" : "A moment to check in"}
|
||||
subtitle="One measurement in a bigger picture."
|
||||
close={close}
|
||||
>
|
||||
<form
|
||||
onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
await saveRecord(
|
||||
"weight",
|
||||
{
|
||||
date,
|
||||
valueKg: unit === "lb" ? +value / 2.2046226218 : +value,
|
||||
notes,
|
||||
},
|
||||
existing?.id,
|
||||
);
|
||||
notify("Weight logged");
|
||||
close();
|
||||
} catch {
|
||||
setError("Could not save. Check the weight and date.");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="form-row">
|
||||
<label>
|
||||
Weight ({unit})
|
||||
<input
|
||||
autoFocus
|
||||
type="number"
|
||||
inputMode="decimal"
|
||||
step="any"
|
||||
min="0.1"
|
||||
max={unit === "lb" ? "2204" : "1000"}
|
||||
required
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Day
|
||||
<input
|
||||
type="date"
|
||||
required
|
||||
value={date}
|
||||
onChange={(e) => setDate(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<label>
|
||||
Note <span className="muted">(optional)</span>
|
||||
<textarea
|
||||
maxLength={500}
|
||||
placeholder="Anything you’d like to remember"
|
||||
value={notes}
|
||||
onChange={(e) => setNotes(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{error && (
|
||||
<p role="alert" className="error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<button className="primary wide" disabled={busy}>
|
||||
Save weigh-in
|
||||
<Plus size={18} />
|
||||
</button>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
9
src/main.tsx
Normal file
9
src/main.tsx
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import React from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { App } from "./App";
|
||||
import "./styles.css";
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
210
src/store.ts
Normal file
210
src/store.ts
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
import { openDB } from "idb";
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { compareRecords, recordSchema } from "../shared/domain.js";
|
||||
import type { JournalRecord, LocalState, RecordType } from "./types";
|
||||
|
||||
const blank: LocalState = {
|
||||
records: [],
|
||||
outbox: [],
|
||||
unlocked: false,
|
||||
lastSync: null,
|
||||
};
|
||||
let snapshot = blank;
|
||||
let syncState = {
|
||||
busy: false,
|
||||
error: "",
|
||||
needsLogin: false,
|
||||
online: navigator.onLine,
|
||||
};
|
||||
const listeners = new Set<() => void>();
|
||||
const syncListeners = new Set<() => void>();
|
||||
const db = openDB("calio-journal", 1, {
|
||||
upgrade(database) {
|
||||
database.createObjectStore("state");
|
||||
},
|
||||
});
|
||||
const channel =
|
||||
typeof BroadcastChannel !== "undefined"
|
||||
? new BroadcastChannel("calio-journal")
|
||||
: null;
|
||||
const emit = () => listeners.forEach((fn) => fn());
|
||||
const setSync = (value: Partial<typeof syncState>) => {
|
||||
syncState = { ...syncState, ...value };
|
||||
syncListeners.forEach((fn) => fn());
|
||||
};
|
||||
const subscribe = (fn: () => void) => {
|
||||
listeners.add(fn);
|
||||
return () => {
|
||||
listeners.delete(fn);
|
||||
};
|
||||
};
|
||||
const subscribeSync = (fn: () => void) => {
|
||||
syncListeners.add(fn);
|
||||
return () => {
|
||||
syncListeners.delete(fn);
|
||||
};
|
||||
};
|
||||
export const useJournal = () => useSyncExternalStore(subscribe, () => snapshot);
|
||||
export const useSyncStatus = () =>
|
||||
useSyncExternalStore(subscribeSync, () => syncState);
|
||||
export async function initStore() {
|
||||
snapshot = (await (await db).get("state", "journal")) || blank;
|
||||
emit();
|
||||
}
|
||||
channel?.addEventListener("message", () => {
|
||||
void initStore();
|
||||
});
|
||||
async function transaction(update: (state: LocalState) => LocalState) {
|
||||
const database = await db;
|
||||
const tx = database.transaction("state", "readwrite");
|
||||
const state = (await tx.store.get("journal")) || structuredClone(blank);
|
||||
const next = update(state);
|
||||
await tx.store.put(next, "journal");
|
||||
await tx.done;
|
||||
snapshot = next;
|
||||
emit();
|
||||
channel?.postMessage("changed");
|
||||
}
|
||||
export async function putRecords(
|
||||
items: { id?: string; type: RecordType; data: unknown; deleted?: boolean }[],
|
||||
) {
|
||||
await transaction((state) => {
|
||||
const records = new Map(state.records.map((record) => [record.id, record]));
|
||||
const pending = new Map(state.outbox.map((record) => [record.id, record]));
|
||||
for (const item of items) {
|
||||
const id = item.id || crypto.randomUUID();
|
||||
const previous = records.get(id);
|
||||
const updatedAt = new Date(
|
||||
Math.max(Date.now(), Date.parse(previous?.updatedAt || "") + 1 || 0),
|
||||
).toISOString();
|
||||
const record = {
|
||||
id,
|
||||
type: item.type,
|
||||
data: item.data,
|
||||
updatedAt,
|
||||
deleted: item.deleted || false,
|
||||
} as JournalRecord;
|
||||
recordSchema.parse(record);
|
||||
records.set(id, record);
|
||||
pending.set(id, record);
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
records: [...records.values()],
|
||||
outbox: [...pending.values()],
|
||||
};
|
||||
});
|
||||
void sync();
|
||||
}
|
||||
export const saveRecord = (type: RecordType, data: unknown, id?: string) =>
|
||||
putRecords([{ type, data, id }]);
|
||||
export const deleteRecord = (record: JournalRecord) =>
|
||||
putRecords([{ ...record, deleted: true }]);
|
||||
export async function api(path: string, body?: unknown) {
|
||||
const response = await fetch("/api" + path, {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
headers: { "Content-Type": "application/json", "X-Calio-Request": "1" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
const error = new Error(data.error || "Unable to connect") as Error & {
|
||||
status: number;
|
||||
};
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
export async function login(username: string, password: string) {
|
||||
await api("/login", { username, password });
|
||||
await transaction((state) => ({ ...state, unlocked: true }));
|
||||
setSync({ needsLogin: false, error: "" });
|
||||
navigator.storage?.persist?.().catch(() => {});
|
||||
await sync();
|
||||
}
|
||||
let running: Promise<void> | null = null;
|
||||
export function sync(): Promise<void> {
|
||||
if (running) return running;
|
||||
running = (async () => {
|
||||
if (!snapshot.unlocked) return;
|
||||
if (!navigator.onLine) {
|
||||
setSync({ online: false });
|
||||
return;
|
||||
}
|
||||
setSync({ busy: true, error: "" });
|
||||
try {
|
||||
// A single sync owner across tabs prevents redundant network work; IDB transactions
|
||||
// still arbitrate changes made while a request is in flight.
|
||||
const work = async () => {
|
||||
await initStore();
|
||||
do {
|
||||
const sent = snapshot.outbox.slice(0, 500);
|
||||
const result = await api("/sync", { records: sent });
|
||||
const remote = result.records as JournalRecord[];
|
||||
remote.forEach((record) => recordSchema.parse(record));
|
||||
await transaction((state) => {
|
||||
const records = new Map(
|
||||
state.records.map((record) => [record.id, record]),
|
||||
);
|
||||
for (const record of remote) {
|
||||
const local = records.get(record.id);
|
||||
if (!local || compareRecords(record, local) > 0)
|
||||
records.set(record.id, record);
|
||||
}
|
||||
const acknowledged = new Map(
|
||||
sent.map((record) => [record.id, record]),
|
||||
);
|
||||
const outbox = state.outbox.filter((record) => {
|
||||
const ack = acknowledged.get(record.id);
|
||||
return !ack || compareRecords(record, ack) !== 0;
|
||||
});
|
||||
return {
|
||||
...state,
|
||||
records: [...records.values()],
|
||||
outbox,
|
||||
lastSync: result.serverTime,
|
||||
};
|
||||
});
|
||||
} while (snapshot.outbox.length);
|
||||
};
|
||||
if (navigator.locks) await navigator.locks.request("calio-sync", work);
|
||||
else await work();
|
||||
setSync({ online: true, needsLogin: false });
|
||||
} catch (error) {
|
||||
const err = error as Error & { status?: number };
|
||||
setSync({
|
||||
error:
|
||||
err.status === 401 ? "" : err.message || "Connection unavailable",
|
||||
needsLogin: err.status === 401,
|
||||
});
|
||||
} finally {
|
||||
setSync({ busy: false });
|
||||
}
|
||||
})().finally(() => {
|
||||
running = null;
|
||||
});
|
||||
return running;
|
||||
}
|
||||
export async function logout() {
|
||||
await sync();
|
||||
if (snapshot.outbox.length)
|
||||
throw new Error(
|
||||
"Sync your pending changes before signing out, or export them first.",
|
||||
);
|
||||
await api("/logout", {});
|
||||
await transaction(() => structuredClone(blank));
|
||||
setSync({ needsLogin: false });
|
||||
}
|
||||
window.addEventListener("online", () => {
|
||||
setSync({ online: true });
|
||||
void sync();
|
||||
});
|
||||
window.addEventListener("offline", () => setSync({ online: false }));
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (!document.hidden) void sync();
|
||||
});
|
||||
setInterval(() => {
|
||||
if (!document.hidden) void sync();
|
||||
}, 60000);
|
||||
2851
src/styles.css
Normal file
2851
src/styles.css
Normal file
File diff suppressed because it is too large
Load diff
47
src/types.ts
Normal file
47
src/types.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
export type Metric =
|
||||
"calories" | "protein" | "carbs" | "fat" | "fiber" | "sugar" | "sodium";
|
||||
export type Nutrients = Record<Metric, number>;
|
||||
export type Food = { name: string; serving: string; nutrients: Nutrients };
|
||||
export type Meal = "Breakfast" | "Lunch" | "Dinner" | "Snacks";
|
||||
export type Entry = Food & { date: string; meal: Meal; quantity: number };
|
||||
export type Plate = { name: string; items: (Food & { quantity: number })[] };
|
||||
export type Weight = { date: string; valueKg: number; notes: string };
|
||||
export type Settings = {
|
||||
theme: "system" | "light" | "dark";
|
||||
accentColor?: string;
|
||||
unit: "kg" | "lb";
|
||||
goals: Record<Metric, { enabled: boolean; target: number }>;
|
||||
exportFormat: "markdown" | "csv" | "json";
|
||||
exportDays: "7" | "30" | "90" | "all";
|
||||
exportMetrics?: Metric[];
|
||||
exportWeight?: boolean;
|
||||
};
|
||||
export type RecordType = "entry" | "food" | "plate" | "weight" | "settings";
|
||||
export type JournalRecord<T = Entry | Food | Plate | Weight | Settings> = {
|
||||
id: string;
|
||||
type: RecordType;
|
||||
data: T;
|
||||
updatedAt: string;
|
||||
deleted: boolean;
|
||||
};
|
||||
export type LocalState = {
|
||||
records: JournalRecord[];
|
||||
outbox: JournalRecord[];
|
||||
unlocked: boolean;
|
||||
lastSync: string | null;
|
||||
};
|
||||
export const metrics: {
|
||||
key: Metric;
|
||||
label: string;
|
||||
unit: string;
|
||||
color: string;
|
||||
}[] = [
|
||||
{ key: "calories", label: "Calories", unit: "kcal", color: "var(--accent)" },
|
||||
{ key: "protein", label: "Protein", unit: "g", color: "#9c8fc2" },
|
||||
{ key: "carbs", label: "Carbs", unit: "g", color: "#c99d68" },
|
||||
{ key: "fat", label: "Fat", unit: "g", color: "#7ba8a0" },
|
||||
{ key: "fiber", label: "Fiber", unit: "g", color: "#94a66d" },
|
||||
{ key: "sugar", label: "Sugar", unit: "g", color: "#c48696" },
|
||||
{ key: "sodium", label: "Sodium", unit: "mg", color: "#83a2c0" },
|
||||
];
|
||||
export const meals: Meal[] = ["Breakfast", "Lunch", "Dinner", "Snacks"];
|
||||
233
src/useBubblePhysics.ts
Normal file
233
src/useBubblePhysics.ts
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
createBubbleWorld,
|
||||
screenGravity,
|
||||
DRAW_BUBBLE_RADIUS,
|
||||
} from "../shared/bubble-physics.js";
|
||||
|
||||
let tiltAllowedThisSession = false;
|
||||
type MotionStatus = "off" | "waiting" | "on" | "denied" | "unavailable";
|
||||
export function useBubblePhysics(count: number) {
|
||||
const canvas = useRef<HTMLCanvasElement>(null);
|
||||
const world = useRef<ReturnType<typeof createBubbleWorld> | null>(null);
|
||||
const kick = useRef<() => void>(() => {});
|
||||
const redraw = useRef<() => void>(() => {});
|
||||
const [enabled, setEnabled] = useState(tiltAllowedThisSession);
|
||||
const [motion, setMotion] = useState<MotionStatus>("off");
|
||||
const [reduced, setReduced] = useState(
|
||||
() => matchMedia("(prefers-reduced-motion: reduce)").matches,
|
||||
);
|
||||
const countRef = useRef(count);
|
||||
countRef.current = count;
|
||||
|
||||
useEffect(() => {
|
||||
const media = matchMedia("(prefers-reduced-motion: reduce)");
|
||||
const change = () => setReduced(media.matches);
|
||||
media.addEventListener("change", change);
|
||||
return () => media.removeEventListener("change", change);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const element = canvas.current!;
|
||||
const context = element.getContext("2d");
|
||||
if (!context) return;
|
||||
const simulation = createBubbleWorld(countRef.current);
|
||||
world.current = simulation;
|
||||
let frame = 0;
|
||||
let previous = 0;
|
||||
let accumulator = 0;
|
||||
let disposed = false;
|
||||
let topColor = "";
|
||||
let bottomColor = "";
|
||||
const palette = () => {
|
||||
const style = getComputedStyle(element);
|
||||
topColor = style.getPropertyValue("--orb-light").trim();
|
||||
bottomColor = style.getPropertyValue("--orb-dark").trim();
|
||||
draw();
|
||||
};
|
||||
function draw() {
|
||||
if (!context || disposed) return;
|
||||
context.setTransform(
|
||||
element.width / 320,
|
||||
0,
|
||||
0,
|
||||
element.height / 320,
|
||||
0,
|
||||
0,
|
||||
);
|
||||
context.clearRect(0, 0, 320, 320);
|
||||
const gradient = context.createLinearGradient(0, 20, 0, 300);
|
||||
gradient.addColorStop(0, topColor || "#b1bafa");
|
||||
gradient.addColorStop(1, bottomColor || "#8391ed");
|
||||
context.fillStyle = gradient;
|
||||
for (const ball of simulation.balls) {
|
||||
context.globalAlpha = 0.72 + (ball.id % 4) * 0.08;
|
||||
context.beginPath();
|
||||
context.arc(
|
||||
ball.position.x,
|
||||
ball.position.y,
|
||||
DRAW_BUBBLE_RADIUS,
|
||||
0,
|
||||
Math.PI * 2,
|
||||
);
|
||||
context.fill();
|
||||
}
|
||||
context.globalAlpha = 1;
|
||||
element.dataset.bubbles = String(simulation.balls.length);
|
||||
element.dataset.gravityX = simulation.engine.gravity.x.toFixed(3);
|
||||
element.dataset.gravityY = simulation.engine.gravity.y.toFixed(3);
|
||||
}
|
||||
const resize = () => {
|
||||
const size = element.getBoundingClientRect();
|
||||
const dpr = Math.min(devicePixelRatio || 1, 2);
|
||||
element.width = Math.round(size.width * dpr);
|
||||
element.height = Math.round(size.height * dpr);
|
||||
draw();
|
||||
};
|
||||
const observer = new ResizeObserver(resize);
|
||||
observer.observe(element);
|
||||
const theme = new MutationObserver(palette);
|
||||
theme.observe(document.documentElement, {
|
||||
attributes: true,
|
||||
attributeFilter: ["data-theme", "style"],
|
||||
});
|
||||
function tick(now: number) {
|
||||
frame = 0;
|
||||
if (document.hidden || disposed) {
|
||||
previous = 0;
|
||||
return;
|
||||
}
|
||||
accumulator += previous ? Math.min(now - previous, 50) : 1000 / 60;
|
||||
previous = now;
|
||||
while (accumulator >= 1000 / 60) {
|
||||
simulation.step();
|
||||
accumulator -= 1000 / 60;
|
||||
}
|
||||
draw();
|
||||
if (simulation.awake()) frame = requestAnimationFrame(tick);
|
||||
else previous = 0;
|
||||
}
|
||||
const start = () => {
|
||||
if (!frame && !document.hidden && !reduced && !disposed)
|
||||
frame = requestAnimationFrame(tick);
|
||||
};
|
||||
kick.current = start;
|
||||
redraw.current = draw;
|
||||
const visibility = () => {
|
||||
if (document.hidden) {
|
||||
cancelAnimationFrame(frame);
|
||||
frame = 0;
|
||||
previous = 0;
|
||||
accumulator = 0;
|
||||
} else start();
|
||||
};
|
||||
document.addEventListener("visibilitychange", visibility);
|
||||
palette();
|
||||
resize();
|
||||
start();
|
||||
return () => {
|
||||
disposed = true;
|
||||
cancelAnimationFrame(frame);
|
||||
observer.disconnect();
|
||||
theme.disconnect();
|
||||
document.removeEventListener("visibilitychange", visibility);
|
||||
simulation.dispose();
|
||||
world.current = null;
|
||||
kick.current = () => {};
|
||||
redraw.current = () => {};
|
||||
};
|
||||
}, [reduced]);
|
||||
|
||||
useEffect(() => {
|
||||
if (reduced) {
|
||||
world.current?.seed(count);
|
||||
redraw.current();
|
||||
} else {
|
||||
world.current?.setTarget(count);
|
||||
kick.current();
|
||||
}
|
||||
}, [count, reduced]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || reduced) {
|
||||
world.current?.gravity(0, 1);
|
||||
kick.current();
|
||||
return;
|
||||
}
|
||||
setMotion("waiting");
|
||||
let received = false;
|
||||
let lastBeta = 0;
|
||||
let lastGamma = 0;
|
||||
const apply = () => {
|
||||
const angle =
|
||||
screen.orientation?.angle ??
|
||||
(window as Window & { orientation?: number }).orientation ??
|
||||
0;
|
||||
const next = screenGravity(lastBeta, lastGamma, angle);
|
||||
if (world.current?.gravity(next.x, next.y)) kick.current();
|
||||
};
|
||||
const orientation = (event: DeviceOrientationEvent) => {
|
||||
if (
|
||||
document.hidden ||
|
||||
event.beta === null ||
|
||||
event.gamma === null ||
|
||||
!Number.isFinite(event.beta) ||
|
||||
!Number.isFinite(event.gamma)
|
||||
)
|
||||
return;
|
||||
lastBeta = event.beta;
|
||||
lastGamma = event.gamma;
|
||||
if (!received) {
|
||||
received = true;
|
||||
setMotion("on");
|
||||
}
|
||||
apply();
|
||||
};
|
||||
window.addEventListener("deviceorientation", orientation);
|
||||
screen.orientation?.addEventListener("change", apply);
|
||||
const timeout = setTimeout(() => {
|
||||
if (!received) setMotion("unavailable");
|
||||
}, 5000);
|
||||
return () => {
|
||||
clearTimeout(timeout);
|
||||
window.removeEventListener("deviceorientation", orientation);
|
||||
screen.orientation?.removeEventListener("change", apply);
|
||||
};
|
||||
}, [enabled, reduced]);
|
||||
|
||||
const toggleTilt = useCallback(async () => {
|
||||
if (enabled) {
|
||||
setEnabled(false);
|
||||
setMotion("off");
|
||||
tiltAllowedThisSession = false;
|
||||
return;
|
||||
}
|
||||
if (typeof DeviceOrientationEvent === "undefined") {
|
||||
setMotion("unavailable");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const sensor = DeviceOrientationEvent as typeof DeviceOrientationEvent & {
|
||||
requestPermission?: () => Promise<string>;
|
||||
};
|
||||
if (
|
||||
sensor.requestPermission &&
|
||||
(await sensor.requestPermission()) !== "granted"
|
||||
) {
|
||||
setMotion("denied");
|
||||
return;
|
||||
}
|
||||
tiltAllowedThisSession = true;
|
||||
setEnabled(true);
|
||||
} catch {
|
||||
setMotion("denied");
|
||||
}
|
||||
}, [enabled]);
|
||||
const nudge = useCallback(() => {
|
||||
if (!reduced) {
|
||||
world.current?.nudge();
|
||||
kick.current();
|
||||
}
|
||||
}, [reduced]);
|
||||
return { canvas, motion, enabled, reduced, toggleTilt, nudge };
|
||||
}
|
||||
205
src/utils.ts
Normal file
205
src/utils.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
import { totalNutrients } from "../shared/domain.js";
|
||||
import type { Entry, JournalRecord, Metric, Settings, Weight } from "./types";
|
||||
import { metrics } from "./types.ts";
|
||||
export const today = () => localDate(new Date());
|
||||
export function localDate(date: Date) {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
||||
}
|
||||
export const dayDate = (date: string) => new Date(date + "T12:00:00");
|
||||
export function offsetDay(date: string, offset: number) {
|
||||
const next = dayDate(date);
|
||||
next.setDate(next.getDate() + offset);
|
||||
return localDate(next);
|
||||
}
|
||||
export const displayDate = (
|
||||
date: string,
|
||||
options?: Intl.DateTimeFormatOptions,
|
||||
) =>
|
||||
dayDate(date).toLocaleDateString(
|
||||
undefined,
|
||||
options || { month: "long", day: "numeric", year: "numeric" },
|
||||
);
|
||||
export const number = (value: number, decimals = 0) =>
|
||||
value.toLocaleString(undefined, { maximumFractionDigits: decimals });
|
||||
export const weightValue = (kg: number, unit: Settings["unit"]) =>
|
||||
unit === "lb" ? kg * 2.2046226218 : kg;
|
||||
export function recordsOf<T>(records: JournalRecord[], type: string) {
|
||||
return records.filter(
|
||||
(r) => !r.deleted && r.type === type,
|
||||
) as JournalRecord<T>[];
|
||||
}
|
||||
export function downloadExport(
|
||||
records: JournalRecord[],
|
||||
settings: Settings,
|
||||
start: string,
|
||||
end: string,
|
||||
selected: Metric[],
|
||||
includeWeight: boolean,
|
||||
format: string,
|
||||
pending: number,
|
||||
) {
|
||||
const entries = selected.length
|
||||
? recordsOf<Entry>(records, "entry")
|
||||
.filter((r) => r.data.date >= start && r.data.date <= end)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
a.data.date.localeCompare(b.data.date) ||
|
||||
a.updatedAt.localeCompare(b.updatedAt),
|
||||
)
|
||||
: [];
|
||||
const weights = includeWeight
|
||||
? recordsOf<Weight>(records, "weight")
|
||||
.filter((r) => r.data.date >= start && r.data.date <= end)
|
||||
.sort((a, b) => a.data.date.localeCompare(b.data.date))
|
||||
: [];
|
||||
const days = [...new Set(entries.map((r) => r.data.date))]
|
||||
.sort()
|
||||
.map((date) => {
|
||||
const nutrients = totalNutrients(
|
||||
entries.filter((r) => r.data.date === date).map((r) => r.data),
|
||||
);
|
||||
return {
|
||||
date,
|
||||
...Object.fromEntries(
|
||||
selected.map((key) => [key, +nutrients[key].toFixed(2)]),
|
||||
),
|
||||
} as { date: string } & Record<Metric, number>;
|
||||
});
|
||||
const metadata = {
|
||||
schemaVersion: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
dateRange: { start, end },
|
||||
pendingChanges: pending,
|
||||
units: Object.fromEntries(
|
||||
selected.map((key) => [key, metrics.find((m) => m.key === key)!.unit]),
|
||||
),
|
||||
goals: Object.fromEntries(
|
||||
selected.map((key) => [key, settings.goals[key]]),
|
||||
),
|
||||
note: "Days without food entries are unlogged, not zero-intake days. Entry nutrients are totals for the recorded quantity. Weight is stored in kg.",
|
||||
};
|
||||
const logs = entries.map(
|
||||
(r) =>
|
||||
({
|
||||
id: r.id,
|
||||
date: r.data.date,
|
||||
meal: r.data.meal,
|
||||
name: r.data.name,
|
||||
serving: r.data.serving,
|
||||
quantity: r.data.quantity,
|
||||
...Object.fromEntries(
|
||||
selected.map((key) => [
|
||||
key,
|
||||
+(r.data.nutrients[key] * r.data.quantity).toFixed(2),
|
||||
]),
|
||||
),
|
||||
}) as {
|
||||
id: string;
|
||||
date: string;
|
||||
meal: string;
|
||||
name: string;
|
||||
serving: string;
|
||||
quantity: number;
|
||||
} & Record<Metric, number>,
|
||||
);
|
||||
let content: string;
|
||||
if (format === "json")
|
||||
content = JSON.stringify(
|
||||
{
|
||||
...metadata,
|
||||
dailyTotals: days,
|
||||
entries: logs,
|
||||
weights: weights.map((r) => ({ ...r.data, id: r.id })),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
else if (format === "csv") {
|
||||
const escape = (value: unknown) => {
|
||||
let text = String(value ?? "");
|
||||
if (/^[=+\-@\t\r]/.test(text)) text = "'" + text;
|
||||
return '"' + text.replaceAll('"', '""') + '"';
|
||||
};
|
||||
const header = [
|
||||
"record_type",
|
||||
"date",
|
||||
"meal",
|
||||
"name",
|
||||
"serving",
|
||||
"quantity",
|
||||
...selected.map((k) => k + "_" + metadata.units[k]),
|
||||
"weight_kg",
|
||||
"notes",
|
||||
];
|
||||
const rows = [
|
||||
...logs.map((r) => [
|
||||
"entry",
|
||||
r.date,
|
||||
r.meal,
|
||||
r.name,
|
||||
r.serving,
|
||||
r.quantity,
|
||||
...selected.map((k) => r[k]),
|
||||
"",
|
||||
"",
|
||||
]),
|
||||
...days.map((r) => [
|
||||
"daily_total",
|
||||
r.date,
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
...selected.map((k) => r[k]),
|
||||
"",
|
||||
"",
|
||||
]),
|
||||
...weights.map((r) => [
|
||||
"weight",
|
||||
r.data.date,
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
"",
|
||||
...selected.map(() => ""),
|
||||
r.data.valueKg,
|
||||
r.data.notes,
|
||||
]),
|
||||
];
|
||||
content =
|
||||
"\uFEFF" +
|
||||
[header, ...rows].map((row) => row.map(escape).join(",")).join("\r\n");
|
||||
} else {
|
||||
const clean = (value: string) =>
|
||||
value.replaceAll("|", "/").replace(/[\r\n]/g, " ");
|
||||
const sections = [
|
||||
`# Calio nutrition journal\n\n${start} to ${end}\n\n${metadata.note}\nPending local changes: ${pending}`,
|
||||
];
|
||||
if (selected.length) {
|
||||
sections.push("## Goals\n" + selected.map(k => `- ${k}: ${settings.goals[k].enabled ? settings.goals[k].target + " " + metadata.units[k] : "disabled"}`).join("\n"));
|
||||
sections.push([
|
||||
"## Daily totals (logged days)",
|
||||
`| Date | ${selected.map(k => k + " (" + metadata.units[k] + ")").join(" | ")} |`,
|
||||
`| --- | ${selected.map(() => "---").join(" | ")} |`,
|
||||
...days.map(d => "| " + [d.date, ...selected.map(k => d[k])].join(" | ") + " |"),
|
||||
].join("\n"));
|
||||
sections.push("## Food entries\n" + logs.map(r => `- ${r.date} · ${r.meal} · ${clean(r.name)} · ${r.quantity} × ${clean(r.serving)}: ${selected.map(k => `${r[k]} ${metadata.units[k]} ${k}`).join(", ")}`).join("\n"));
|
||||
}
|
||||
if (includeWeight) sections.push("## Weight (kg)\n" + weights.map(r => `- ${r.data.date}: ${number(r.data.valueKg, 2)} kg${r.data.notes ? " · " + clean(r.data.notes) : ""}`).join("\n"));
|
||||
content = sections.join("\n\n") + "\n";
|
||||
}
|
||||
const blob = new Blob([content], {
|
||||
type:
|
||||
format === "json"
|
||||
? "application/json"
|
||||
: format === "csv"
|
||||
? "text/csv;charset=utf-8"
|
||||
: "text/markdown;charset=utf-8",
|
||||
});
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = `calio-${start}-${end}.${format === "markdown" ? "md" : format}`;
|
||||
link.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||||
}
|
||||
1
src/vite-env.d.ts
vendored
Normal file
1
src/vite-env.d.ts
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
/// <reference types="vite/client" />
|
||||
176
tests/api.test.js
Normal file
176
tests/api.test.js
Normal file
|
|
@ -0,0 +1,176 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createApp } from "../server/app.js";
|
||||
import { openDatabase } from "../server/db.js";
|
||||
import { checkPassword, hashPassword } from "../server/auth.js";
|
||||
import { emptyNutrients } from "../shared/domain.js";
|
||||
|
||||
const password = "test-only-password-123";
|
||||
const origin = "http://localhost:3000";
|
||||
async function fixture(t, secureCookies = false) {
|
||||
const store = openDatabase(":memory:");
|
||||
const app = createApp({
|
||||
store,
|
||||
username: "test",
|
||||
passwordHash: hashPassword(password),
|
||||
origin,
|
||||
secureCookies,
|
||||
dist: ".local/nonexistent",
|
||||
});
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
await new Promise((resolve) => server.once("listening", resolve));
|
||||
const base = `http://127.0.0.1:${server.address().port}/api`;
|
||||
t.after(
|
||||
() =>
|
||||
new Promise((resolve) =>
|
||||
server.close(() => {
|
||||
store.close();
|
||||
resolve();
|
||||
}),
|
||||
),
|
||||
);
|
||||
const request = (path, body, cookie = "", customHeaders = {}) =>
|
||||
fetch(base + path, {
|
||||
method: body === undefined ? "GET" : "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Origin: origin,
|
||||
"X-Calio-Request": "1",
|
||||
Cookie: cookie,
|
||||
...customHeaders,
|
||||
},
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
const signIn = async () => {
|
||||
const response = await request("/login", { username: "test", password });
|
||||
assert.equal(response.status, 200);
|
||||
return response.headers.get("set-cookie").split(";")[0];
|
||||
};
|
||||
return { store, request, signIn };
|
||||
}
|
||||
test("passwords use salted scrypt hashes and reject incorrect values", () => {
|
||||
const hash = hashPassword(password);
|
||||
assert.notEqual(hashPassword(password), hash);
|
||||
assert.ok(checkPassword(password, hash));
|
||||
assert.equal(checkPassword("wrong", hash), false);
|
||||
assert.equal(checkPassword(password, "garbage"), false);
|
||||
});
|
||||
test("journal endpoints require authentication and never allow cross-origin writes", async (t) => {
|
||||
const { request, signIn } = await fixture(t);
|
||||
assert.equal((await request("/records")).status, 401);
|
||||
assert.equal((await request("/sync", { records: [] })).status, 401);
|
||||
const cookie = await signIn();
|
||||
assert.equal(
|
||||
(
|
||||
await request("/sync", { records: [] }, cookie, {
|
||||
Origin: "https://evil.example",
|
||||
})
|
||||
).status,
|
||||
403,
|
||||
);
|
||||
assert.equal(
|
||||
(await request("/sync", { records: [] }, cookie, { "X-Calio-Request": "" }))
|
||||
.status,
|
||||
403,
|
||||
);
|
||||
assert.equal((await request("/records", undefined, cookie)).status, 200);
|
||||
assert.equal(
|
||||
(await request("/records", undefined, cookie)).headers.get("cache-control"),
|
||||
"no-store",
|
||||
);
|
||||
});
|
||||
test("invalid credentials, schema errors, invalid clocks and oversized bodies are rejected", async (t) => {
|
||||
const { request, signIn } = await fixture(t);
|
||||
assert.equal(
|
||||
(await request("/login", { username: "test", password: "wrong" })).status,
|
||||
401,
|
||||
);
|
||||
const cookie = await signIn();
|
||||
assert.equal(
|
||||
(await request("/sync", { records: [{ id: "bad" }] }, cookie)).status,
|
||||
400,
|
||||
);
|
||||
const record = {
|
||||
id: "one",
|
||||
type: "entry",
|
||||
data: {
|
||||
date: "2026-10-20",
|
||||
meal: "Lunch",
|
||||
name: "Test",
|
||||
serving: "1 serving",
|
||||
quantity: 1,
|
||||
nutrients: emptyNutrients(),
|
||||
},
|
||||
updatedAt: new Date(Date.now() + 600000).toISOString(),
|
||||
deleted: false,
|
||||
};
|
||||
assert.equal(
|
||||
(await request("/sync", { records: [record] }, cookie)).status,
|
||||
400,
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await request(
|
||||
"/sync",
|
||||
{ records: [], padding: "a".repeat(2100000) },
|
||||
cookie,
|
||||
)
|
||||
).status,
|
||||
413,
|
||||
);
|
||||
});
|
||||
test("login issues secure HttpOnly SameSite cookies and logout revokes sessions", async (t) => {
|
||||
const { request } = await fixture(t, true);
|
||||
const response = await request("/login", { username: "test", password });
|
||||
const header = response.headers.get("set-cookie");
|
||||
assert.match(header, /__Host-calio=/);
|
||||
assert.match(header, /HttpOnly/);
|
||||
assert.match(header, /Secure/);
|
||||
assert.match(header, /SameSite=Strict/);
|
||||
const cookie = header.split(";")[0];
|
||||
assert.equal((await request("/session", undefined, cookie)).status, 200);
|
||||
assert.equal((await request("/logout", {}, cookie)).status, 200);
|
||||
assert.equal((await request("/session", undefined, cookie)).status, 401);
|
||||
});
|
||||
test("sync is idempotent and returns winning edits to a stale device", async (t) => {
|
||||
const { request, signIn } = await fixture(t);
|
||||
const cookie = await signIn();
|
||||
const record = {
|
||||
id: "one",
|
||||
type: "food",
|
||||
data: {
|
||||
name: "Oats",
|
||||
serving: "40 g",
|
||||
nutrients: { ...emptyNutrients(), calories: 150 },
|
||||
},
|
||||
updatedAt: "2026-01-01T10:00:00.000Z",
|
||||
deleted: false,
|
||||
};
|
||||
assert.equal(
|
||||
(await request("/sync", { records: [record] }, cookie)).status,
|
||||
200,
|
||||
);
|
||||
const changed = {
|
||||
...record,
|
||||
updatedAt: "2026-01-01T11:00:00.000Z",
|
||||
data: { ...record.data, name: "Updated oats" },
|
||||
};
|
||||
await request("/sync", { records: [changed] }, cookie);
|
||||
const result = await (
|
||||
await request("/sync", { records: [record, record] }, cookie)
|
||||
).json();
|
||||
assert.equal(result.records.length, 1);
|
||||
assert.deepEqual(result.records[0], changed);
|
||||
});
|
||||
test("login is rate limited", async (t) => {
|
||||
const { request } = await fixture(t);
|
||||
for (let i = 0; i < 10; i++)
|
||||
assert.equal(
|
||||
(await request("/login", { username: "bad", password: "wrong" })).status,
|
||||
401,
|
||||
);
|
||||
assert.equal(
|
||||
(await request("/login", { username: "test", password })).status,
|
||||
429,
|
||||
);
|
||||
});
|
||||
136
tests/client-sync.test.js
Normal file
136
tests/client-sync.test.js
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import "fake-indexeddb/auto";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { openDB } from "idb";
|
||||
import { compareRecords, emptyNutrients } from "../shared/domain.js";
|
||||
|
||||
// Exercise the real browser store against IndexedDB with controllable network timing.
|
||||
globalThis.window = new EventTarget();
|
||||
globalThis.document = Object.assign(new EventTarget(), { hidden: false });
|
||||
Object.defineProperty(globalThis, "navigator", {
|
||||
value: { onLine: false },
|
||||
configurable: true,
|
||||
});
|
||||
globalThis.BroadcastChannel = class {
|
||||
addEventListener() {}
|
||||
postMessage() {}
|
||||
};
|
||||
const originalInterval = globalThis.setInterval;
|
||||
globalThis.setInterval = () => 0;
|
||||
const client = await import("../src/store.ts");
|
||||
globalThis.setInterval = originalInterval;
|
||||
|
||||
const remote = new Map();
|
||||
let pause = null;
|
||||
let arrived = null;
|
||||
let fail = false;
|
||||
let unauthorized = false;
|
||||
globalThis.fetch = async (url, options) => {
|
||||
if (fail) throw new Error("Connection unavailable");
|
||||
if (unauthorized && url.endsWith("/sync"))
|
||||
return Response.json(
|
||||
{ error: "Sign in to sync your journal" },
|
||||
{ status: 401 },
|
||||
);
|
||||
if (url.endsWith("/login") || url.endsWith("/logout"))
|
||||
return Response.json({ ok: true });
|
||||
const { records } = JSON.parse(options.body);
|
||||
const gate = pause;
|
||||
pause = null;
|
||||
if (gate) {
|
||||
arrived();
|
||||
await gate;
|
||||
}
|
||||
for (const record of records) {
|
||||
const existing = remote.get(record.id);
|
||||
if (!existing || compareRecords(record, existing) > 0)
|
||||
remote.set(record.id, record);
|
||||
}
|
||||
return Response.json({
|
||||
records: [...remote.values()],
|
||||
serverTime: new Date().toISOString(),
|
||||
});
|
||||
};
|
||||
const food = (name) => ({
|
||||
name,
|
||||
serving: "1 serving",
|
||||
nutrients: { ...emptyNutrients(), calories: 100 },
|
||||
});
|
||||
const read = async () =>
|
||||
await (await openDB("calio-journal", 1)).get("state", "journal");
|
||||
|
||||
test("offline journal and outbox are atomic, in-flight edits remain queued, reconnect merges without duplication", async () => {
|
||||
await client.initStore();
|
||||
await client.login("test", "test-only-password"); // offline mock sign-in seeds the local unlocked flag.
|
||||
await client.saveRecord("food", food("First"), "food-one");
|
||||
let state = await read();
|
||||
assert.equal(state.records.length, 1);
|
||||
assert.equal(state.outbox.length, 1);
|
||||
assert.deepEqual(state.records[0], state.outbox[0]);
|
||||
let release;
|
||||
let signalArrival;
|
||||
pause = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const sent = new Promise((resolve) => {
|
||||
signalArrival = resolve;
|
||||
});
|
||||
arrived = signalArrival;
|
||||
navigator.onLine = true;
|
||||
const syncing = client.sync();
|
||||
await sent;
|
||||
// This write happens after the request captured the old version.
|
||||
await client.saveRecord("food", food("Edited while syncing"), "food-one");
|
||||
state = await read();
|
||||
assert.equal(state.outbox[0].data.name, "Edited while syncing");
|
||||
release();
|
||||
await syncing;
|
||||
state = await read();
|
||||
assert.equal(state.outbox.length, 0);
|
||||
assert.equal(state.records.length, 1);
|
||||
assert.equal(remote.get("food-one").data.name, "Edited while syncing");
|
||||
await client.sync();
|
||||
assert.equal(remote.size, 1);
|
||||
});
|
||||
test("network errors and expired sessions preserve all pending changes", async () => {
|
||||
navigator.onLine = false;
|
||||
await client.saveRecord("food", food("Retained"), "food-two");
|
||||
navigator.onLine = true;
|
||||
fail = true;
|
||||
await client.sync();
|
||||
assert.equal((await read()).outbox.length, 1);
|
||||
await assert.rejects(client.logout(), /pending changes/);
|
||||
assert.equal((await read()).unlocked, true);
|
||||
fail = false;
|
||||
unauthorized = true;
|
||||
await client.sync();
|
||||
assert.equal((await read()).outbox.length, 1);
|
||||
unauthorized = false;
|
||||
await client.sync();
|
||||
assert.equal((await read()).outbox.length, 0);
|
||||
});
|
||||
test("a newer remote deletion beats a stale local write and explicit logout clears device data", async () => {
|
||||
const state = await read();
|
||||
const old = state.records.find((r) => r.id === "food-two");
|
||||
remote.set(old.id, {
|
||||
...old,
|
||||
updatedAt: new Date(Date.parse(old.updatedAt) + 1000).toISOString(),
|
||||
deleted: true,
|
||||
});
|
||||
navigator.onLine = false;
|
||||
await client.saveRecord("food", food("Stale offline edit"), old.id);
|
||||
navigator.onLine = true;
|
||||
await client.sync();
|
||||
assert.equal(
|
||||
(await read()).records.find((r) => r.id === old.id).deleted,
|
||||
true,
|
||||
);
|
||||
assert.equal((await read()).outbox.length, 0);
|
||||
await client.logout();
|
||||
assert.deepEqual(await read(), {
|
||||
records: [],
|
||||
outbox: [],
|
||||
unlocked: false,
|
||||
lastSync: null,
|
||||
});
|
||||
});
|
||||
148
tests/domain.test.js
Normal file
148
tests/domain.test.js
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
compareRecords,
|
||||
defaultSettings,
|
||||
emptyNutrients,
|
||||
recordSchema,
|
||||
totalNutrients,
|
||||
} from "../shared/domain.js";
|
||||
import { openDatabase } from "../server/db.js";
|
||||
const sample = (
|
||||
id = "entry-1",
|
||||
time = "2026-10-20T10:00:00.000Z",
|
||||
data = {},
|
||||
) => ({
|
||||
id,
|
||||
type: "entry",
|
||||
updatedAt: time,
|
||||
deleted: false,
|
||||
data: {
|
||||
date: "2026-10-20",
|
||||
meal: "Breakfast",
|
||||
name: "Oats",
|
||||
serving: "40 g",
|
||||
quantity: 1,
|
||||
nutrients: { ...emptyNutrients(), calories: 150, protein: 5 },
|
||||
...data,
|
||||
},
|
||||
});
|
||||
|
||||
test("nutrition totals honor fractional servings without changing source foods", () => {
|
||||
const entry = sample().data;
|
||||
const total = totalNutrients([
|
||||
{ ...entry, quantity: 1.5 },
|
||||
{ ...entry, quantity: 0.5 },
|
||||
]);
|
||||
assert.equal(total.calories, 300);
|
||||
assert.equal(total.protein, 10);
|
||||
assert.equal(entry.nutrients.calories, 150);
|
||||
});
|
||||
test("schemas reject impossible dates, negative nutrition, unknown fields, and reserved IDs", () => {
|
||||
assert.equal(recordSchema.safeParse(sample()).success, true);
|
||||
assert.equal(recordSchema.safeParse(sample("settings")).success, false);
|
||||
assert.equal(
|
||||
recordSchema.safeParse(sample("x", undefined, { date: "2026-02-30" }))
|
||||
.success,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
recordSchema.safeParse(
|
||||
sample("x", undefined, {
|
||||
nutrients: { ...emptyNutrients(), protein: -1 },
|
||||
}),
|
||||
).success,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
recordSchema.safeParse(sample("x", undefined, { admin: true })).success,
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
recordSchema.safeParse({
|
||||
id: "settings",
|
||||
type: "settings",
|
||||
updatedAt: new Date().toISOString(),
|
||||
deleted: false,
|
||||
data: defaultSettings,
|
||||
}).success,
|
||||
true,
|
||||
);
|
||||
});
|
||||
test("same-millisecond conflicts resolve identically in either arrival order", () => {
|
||||
const a = sample();
|
||||
const b = sample("entry-1", a.updatedAt, { name: "Banana" });
|
||||
assert.equal(
|
||||
Math.sign(compareRecords(a, b)),
|
||||
-Math.sign(compareRecords(b, a)),
|
||||
);
|
||||
const left = openDatabase(":memory:");
|
||||
const right = openDatabase(":memory:");
|
||||
left.merge([a]);
|
||||
left.merge([b]);
|
||||
right.merge([b]);
|
||||
right.merge([a]);
|
||||
assert.deepEqual(left.all(), right.all());
|
||||
left.close();
|
||||
right.close();
|
||||
});
|
||||
test("independent offline additions survive, latest edits win, stale writes cannot resurrect deletions", () => {
|
||||
const store = openDatabase(":memory:");
|
||||
const first = sample();
|
||||
const newer = {
|
||||
...sample("entry-1", "2026-10-20T11:00:00.000Z"),
|
||||
deleted: true,
|
||||
};
|
||||
store.merge([first, sample("entry-2")]);
|
||||
store.merge([newer]);
|
||||
store.merge([first, first]);
|
||||
assert.equal(store.all().length, 2);
|
||||
assert.equal(store.all()[0].deleted, true);
|
||||
store.close();
|
||||
});
|
||||
test("batch is atomic on a type collision", () => {
|
||||
const store = openDatabase(":memory:");
|
||||
store.merge([sample()]);
|
||||
assert.throws(() =>
|
||||
store.merge([sample("entry-2"), { ...sample(), type: "food" }]),
|
||||
);
|
||||
assert.equal(store.all().length, 1);
|
||||
store.close();
|
||||
});
|
||||
test("opening the same database after an app update preserves records and sessions", () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "calio-db-"));
|
||||
const filename = join(directory, "calio.sqlite");
|
||||
try {
|
||||
const store = openDatabase(filename);
|
||||
store.merge([sample()]);
|
||||
store.db
|
||||
.prepare("INSERT INTO sessions VALUES (?,?)")
|
||||
.run("session", Date.now() + 60000);
|
||||
store.close();
|
||||
const reopened = openDatabase(filename);
|
||||
assert.deepEqual(reopened.all(), [sample()]);
|
||||
assert.ok(reopened.db.prepare("SELECT * FROM sessions").get());
|
||||
assert.equal(
|
||||
reopened.db.prepare("PRAGMA user_version").get().user_version,
|
||||
1,
|
||||
);
|
||||
reopened.close();
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
test("a newer database refuses an unsafe application downgrade", () => {
|
||||
const directory = mkdtempSync(join(tmpdir(), "calio-version-"));
|
||||
const filename = join(directory, "calio.sqlite");
|
||||
try {
|
||||
const store = openDatabase(filename);
|
||||
store.db.exec("PRAGMA user_version=2");
|
||||
store.close();
|
||||
assert.throws(() => openDatabase(filename), /newer Calio/);
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
93
tests/export.test.js
Normal file
93
tests/export.test.js
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { downloadExport, offsetDay, weightValue } from "../src/utils.ts";
|
||||
import { defaultSettings, emptyNutrients } from "../shared/domain.js";
|
||||
const record = (id, type, data, deleted = false) => ({
|
||||
id,
|
||||
type,
|
||||
data,
|
||||
deleted,
|
||||
updatedAt: "2026-10-20T10:00:00.000Z",
|
||||
});
|
||||
const entry = {
|
||||
date: "2026-10-20",
|
||||
meal: "Lunch",
|
||||
name: "=danger|\nfood",
|
||||
serving: "1 bowl",
|
||||
quantity: 1.5,
|
||||
nutrients: { ...emptyNutrients(), calories: 200, protein: 20 },
|
||||
};
|
||||
const records = [
|
||||
record("e1", "entry", entry),
|
||||
record("e2", "entry", { ...entry, date: "2026-10-19" }),
|
||||
record("deleted", "entry", entry, true),
|
||||
record("w", "weight", {
|
||||
date: "2026-10-20",
|
||||
valueKg: 75,
|
||||
notes: "=untrusted",
|
||||
}),
|
||||
];
|
||||
async function capture(
|
||||
format,
|
||||
selected = ["calories", "protein"],
|
||||
includeWeight = true,
|
||||
) {
|
||||
let blob;
|
||||
const original = URL.createObjectURL;
|
||||
const timer = globalThis.setTimeout;
|
||||
globalThis.document = { createElement: () => ({ click() {} }) };
|
||||
URL.createObjectURL = (value) => {
|
||||
blob = value;
|
||||
return "blob:test";
|
||||
};
|
||||
globalThis.setTimeout = () => 0;
|
||||
try {
|
||||
downloadExport(
|
||||
records,
|
||||
defaultSettings,
|
||||
"2026-10-20",
|
||||
"2026-10-20",
|
||||
selected,
|
||||
includeWeight,
|
||||
format,
|
||||
2,
|
||||
);
|
||||
return await blob.text();
|
||||
} finally {
|
||||
URL.createObjectURL = original;
|
||||
globalThis.setTimeout = timer;
|
||||
}
|
||||
}
|
||||
test("JSON export includes fractional serving totals, chosen dates/metrics, kg weights and pending status", async () => {
|
||||
const data = JSON.parse(await capture("json"));
|
||||
assert.equal(data.schemaVersion, 1);
|
||||
assert.equal(data.pendingChanges, 2);
|
||||
assert.equal(data.entries.length, 1);
|
||||
assert.equal(data.entries[0].calories, 300);
|
||||
assert.equal(data.entries[0].protein, 30);
|
||||
assert.equal("fat" in data.entries[0], false);
|
||||
assert.equal(data.weights[0].valueKg, 75);
|
||||
assert.equal(data.dailyTotals[0].calories, 300);
|
||||
});
|
||||
test("CSV quotes text and guards spreadsheet formula fields; Markdown keeps clean rows", async () => {
|
||||
const csv = await capture("csv");
|
||||
assert.match(csv, /"'=danger\|\nfood"/);
|
||||
assert.match(csv, /"'=untrusted"/);
|
||||
assert.match(csv, /"daily_total"/);
|
||||
const markdown = await capture("markdown");
|
||||
assert.match(markdown, /\| 2026-10-20 \| 300 \| 30 \|/);
|
||||
assert.match(markdown, /=danger\/ food/);
|
||||
assert.doesNotMatch(markdown, /2026-10-19/);
|
||||
});
|
||||
test("weight-only exports omit food records; excluding weight omits all weigh-ins", async () => {
|
||||
const weights = JSON.parse(await capture("json", [], true));
|
||||
assert.equal(weights.entries.length, 0);
|
||||
assert.equal(weights.weights.length, 1);
|
||||
const foods = JSON.parse(await capture("json", ["calories"], false));
|
||||
assert.equal(foods.weights.length, 0);
|
||||
});
|
||||
test("local date arithmetic crosses month/year boundaries and weight unit conversion round trips", () => {
|
||||
assert.equal(offsetDay("2026-01-01", -1), "2025-12-31");
|
||||
assert.equal(offsetDay("2024-02-28", 1), "2024-02-29");
|
||||
assert.ok(Math.abs(weightValue(75, "lb") / 2.2046226218 - 75) < 1e-10);
|
||||
});
|
||||
125
tests/physics.test.js
Normal file
125
tests/physics.test.js
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
bubbleCount,
|
||||
createBubbleWorld,
|
||||
screenGravity,
|
||||
MAX_BUBBLES,
|
||||
BUBBLE_RADIUS,
|
||||
DRAW_BUBBLE_RADIUS,
|
||||
VESSEL_RADIUS,
|
||||
} from "../shared/bubble-physics.js";
|
||||
|
||||
test("bubble count tracks calories, remains visible at small amounts, and caps over goal", () => {
|
||||
assert.equal(bubbleCount(0, 2000, true), 0);
|
||||
assert.equal(bubbleCount(1, 2000, true), 1);
|
||||
assert.equal(bubbleCount(1000, 2000, true), Math.round(MAX_BUBBLES / 2));
|
||||
assert.equal(bubbleCount(2000, 2000, true), MAX_BUBBLES);
|
||||
assert.equal(bubbleCount(20000, 2000, true), MAX_BUBBLES);
|
||||
});
|
||||
test("new bubbles enter at the top, fall, collide and stay inside the calorie vessel", () => {
|
||||
const world = createBubbleWorld(0, () => 0.5);
|
||||
world.setTarget(8);
|
||||
world.step(50);
|
||||
assert.equal(world.balls.length, 1);
|
||||
assert.ok(world.balls[0].position.y < 50);
|
||||
for (let i = 0; i < 400; i++) world.step();
|
||||
assert.equal(world.balls.length, 8);
|
||||
assert.ok(world.balls.every((ball) => ball.position.y > 220));
|
||||
for (const ball of world.balls)
|
||||
assert.ok(
|
||||
Math.hypot(ball.position.x - 160, ball.position.y - 160) <=
|
||||
VESSEL_RADIUS - DRAW_BUBBLE_RADIUS + 1,
|
||||
);
|
||||
for (let i = 0; i < world.balls.length; i++)
|
||||
for (let j = i + 1; j < world.balls.length; j++)
|
||||
assert.ok(
|
||||
Math.hypot(
|
||||
world.balls[i].position.x - world.balls[j].position.x,
|
||||
world.balls[i].position.y - world.balls[j].position.y,
|
||||
) >
|
||||
BUBBLE_RADIUS * 1.8,
|
||||
);
|
||||
world.dispose();
|
||||
});
|
||||
test("full and over-goal vessels remain bounded through repeated gravity reversals", () => {
|
||||
const world = createBubbleWorld(MAX_BUBBLES);
|
||||
assert.equal(world.balls.length, MAX_BUBBLES);
|
||||
assert.ok(BUBBLE_RADIUS - DRAW_BUBBLE_RADIUS >= 1);
|
||||
assert.ok(Math.min(...world.balls.map((ball) => ball.position.y)) < 30);
|
||||
assert.ok(Math.max(...world.balls.map((ball) => ball.position.y)) > 290);
|
||||
assert.ok(
|
||||
world.balls.some(
|
||||
(ball) => Math.hypot(ball.position.x - 160, ball.position.y - 160) < 2,
|
||||
),
|
||||
);
|
||||
for (const [x, y] of [
|
||||
[0, 1],
|
||||
[1, 0],
|
||||
[0, -1],
|
||||
[-1, 0],
|
||||
[0.6, 0.8],
|
||||
]) {
|
||||
world.gravity(x, y);
|
||||
for (let i = 0; i < 180; i++) world.step();
|
||||
for (const ball of world.balls)
|
||||
assert.ok(
|
||||
Number.isFinite(ball.position.x) &&
|
||||
Math.hypot(ball.position.x - 160, ball.position.y - 160) <=
|
||||
VESSEL_RADIUS - DRAW_BUBBLE_RADIUS + 1,
|
||||
);
|
||||
}
|
||||
world.setTarget(10);
|
||||
assert.equal(world.balls.length, 10);
|
||||
world.setTarget(0);
|
||||
assert.equal(world.balls.length, 0);
|
||||
world.dispose();
|
||||
});
|
||||
test("bubbles follow changing gravity and wake when nudged", () => {
|
||||
const world = createBubbleWorld(12);
|
||||
world.gravity(1, 0);
|
||||
for (let i = 0; i < 400; i++) world.step();
|
||||
assert.ok(
|
||||
world.balls.reduce((sum, ball) => sum + ball.position.x, 0) / 12 > 240,
|
||||
);
|
||||
world.gravity(-1, 0);
|
||||
for (let i = 0; i < 400; i++) world.step();
|
||||
assert.ok(
|
||||
world.balls.reduce((sum, ball) => sum + ball.position.x, 0) / 12 < 80,
|
||||
);
|
||||
world.nudge();
|
||||
assert.ok(world.awake());
|
||||
assert.ok(world.balls.some((ball) => ball.speed > 1));
|
||||
world.dispose();
|
||||
});
|
||||
test("a settled 100% vessel fills to the upper rim and retains a visible gap between dots", () => {
|
||||
const world = createBubbleWorld(MAX_BUBBLES);
|
||||
for (let i = 0; i < 700; i++) world.step();
|
||||
assert.ok(
|
||||
Math.min(...world.balls.map((ball) => ball.position.y)) -
|
||||
DRAW_BUBBLE_RADIUS <
|
||||
35,
|
||||
);
|
||||
for (let i = 0; i < world.balls.length; i++)
|
||||
for (let j = i + 1; j < world.balls.length; j++) {
|
||||
const distance = Math.hypot(
|
||||
world.balls[i].position.x - world.balls[j].position.x,
|
||||
world.balls[i].position.y - world.balls[j].position.y,
|
||||
);
|
||||
assert.ok(distance - 2 * DRAW_BUBBLE_RADIUS > 0.75);
|
||||
}
|
||||
world.dispose();
|
||||
});
|
||||
test("orientation projects gravity for portrait, landscape, upside-down and flat phones", () => {
|
||||
const upright = screenGravity(90, 0, 0);
|
||||
assert.ok(Math.abs(upright.x) < 1e-10);
|
||||
assert.ok(upright.y > 0.99);
|
||||
const inverted = screenGravity(-90, 0, 0);
|
||||
assert.ok(inverted.y < -0.99);
|
||||
const right = screenGravity(0, 90, 0);
|
||||
assert.ok(right.x > 0.99);
|
||||
const landscape = screenGravity(0, 90, 90);
|
||||
assert.ok(Math.abs(landscape.x) < 1e-10);
|
||||
assert.ok(landscape.y < -0.99);
|
||||
assert.deepEqual(screenGravity(0, 0, 0), { x: 0, y: 0.18 });
|
||||
});
|
||||
50
tests/publishing.test.js
Normal file
50
tests/publishing.test.js
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { publicationPlan, publishImage } from "../scripts/publish-image.js";
|
||||
const base = {
|
||||
CI_EVENT: "push",
|
||||
REPOSITORY: "Elijah/Calio",
|
||||
COMMIT_SHA: "a".repeat(40),
|
||||
TARGET_REF: "refs/heads/main",
|
||||
MAIN_BRANCH: "main",
|
||||
};
|
||||
test("each push publishes a commit image; only main promotes latest", () => {
|
||||
const main = publicationPlan(base);
|
||||
assert.equal(main.image, "git.elijahkuntz.com/elijah/calio");
|
||||
assert.deepEqual(main.tags, [base.COMMIT_SHA]);
|
||||
assert.equal(main.latest, true);
|
||||
const branch = publicationPlan({
|
||||
...base,
|
||||
TARGET_REF: "refs/heads/codex/new-ui",
|
||||
});
|
||||
assert.equal(branch.latest, false);
|
||||
assert.deepEqual(branch.tags, [base.COMMIT_SHA]);
|
||||
});
|
||||
test("release tags add a version without overwriting main latest", () => {
|
||||
assert.deepEqual(
|
||||
publicationPlan({ ...base, TARGET_REF: "refs/tags/v0.1.0" }).tags,
|
||||
[base.COMMIT_SHA, "v0.1.0"],
|
||||
);
|
||||
assert.equal(
|
||||
publicationPlan({ ...base, TARGET_REF: "refs/tags/v0.1.0" }).latest,
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(
|
||||
publicationPlan({ ...base, TARGET_REF: "refs/tags/test/snapshot" }).tags,
|
||||
[base.COMMIT_SHA],
|
||||
);
|
||||
});
|
||||
test("PRs never publish or require registry secrets; missing publishing credentials fail clearly", () => {
|
||||
assert.equal(publicationPlan({ ...base, CI_EVENT: "pull_request" }), null);
|
||||
assert.throws(() => publishImage(base), /FORGEJO_PAT/);
|
||||
});
|
||||
test("invalid image names and commit identifiers cannot enter Docker command arguments", () => {
|
||||
assert.throws(
|
||||
() => publicationPlan({ ...base, REPOSITORY: "bad/name;command" }),
|
||||
/REPOSITORY/,
|
||||
);
|
||||
assert.throws(
|
||||
() => publicationPlan({ ...base, COMMIT_SHA: "--help" }),
|
||||
/commit ID/,
|
||||
);
|
||||
});
|
||||
56
tests/theme.test.js
Normal file
56
tests/theme.test.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
accentPalette,
|
||||
accentPresets,
|
||||
contrastText,
|
||||
DEFAULT_ACCENT,
|
||||
} from "../shared/theme.js";
|
||||
import { recordSchema, defaultSettings } from "../shared/domain.js";
|
||||
|
||||
test("custom accents have matching derived colors in light and dark modes", () => {
|
||||
const light = accentPalette("#d780a2", false);
|
||||
const dark = accentPalette("#d780a2", true);
|
||||
assert.equal(light["--accent"], "#d780a2");
|
||||
assert.equal(dark["--accent"], "#d780a2");
|
||||
assert.notEqual(light["--accent-soft"], dark["--accent-soft"]);
|
||||
for (const color of Object.values(dark))
|
||||
assert.match(color, /^#[a-f0-9]{6}$/i);
|
||||
assert.equal(accentPalette("invalid", true)["--accent"], DEFAULT_ACCENT);
|
||||
});
|
||||
test("button text stays readable on extreme and preset accent colors", () => {
|
||||
assert.equal(contrastText("#ffffff"), "#000000");
|
||||
assert.equal(contrastText("#000000"), "#ffffff");
|
||||
for (const color of [
|
||||
...accentPresets.map((v) => v.color),
|
||||
"#808080",
|
||||
"#ff0000",
|
||||
"#00ff00",
|
||||
"#0000ff",
|
||||
]) {
|
||||
const palette = accentPalette(color, true);
|
||||
assert.ok(["#000000", "#ffffff"].includes(palette["--on-accent"]));
|
||||
}
|
||||
});
|
||||
test("accent preferences validate and older settings without an accent still load", () => {
|
||||
const record = {
|
||||
id: "settings",
|
||||
type: "settings",
|
||||
deleted: false,
|
||||
updatedAt: new Date().toISOString(),
|
||||
data: { ...defaultSettings, accentColor: "#12abcd" },
|
||||
};
|
||||
assert.equal(recordSchema.safeParse(record).success, true);
|
||||
assert.equal(
|
||||
recordSchema.safeParse({
|
||||
...record,
|
||||
data: { ...record.data, accentColor: "red;display:none" },
|
||||
}).success,
|
||||
false,
|
||||
);
|
||||
const { accentColor, ...older } = defaultSettings;
|
||||
assert.equal(
|
||||
recordSchema.safeParse({ ...record, data: older }).success,
|
||||
true,
|
||||
);
|
||||
});
|
||||
18
tsconfig.json
Normal file
18
tsconfig.json
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"allowJs": true,
|
||||
"checkJs": false,
|
||||
"esModuleInterop": true
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
24
unraid/calio.xml
Normal file
24
unraid/calio.xml
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Container version="2">
|
||||
<Name>calio</Name>
|
||||
<Repository>git.elijahkuntz.com/elijah/calio:latest</Repository>
|
||||
<Registry>https://git.elijahkuntz.com/Elijah/-/packages/container/calio</Registry>
|
||||
<Network>bridge</Network>
|
||||
<Shell>sh</Shell>
|
||||
<Privileged>false</Privileged>
|
||||
<ExtraParams>--user=99:100 --cap-drop=ALL --security-opt=no-new-privileges</ExtraParams>
|
||||
<WebUI/>
|
||||
<Overview>Single-user nutrition and weight journal with offline PWA support. Set APP_ORIGIN to the exact public HTTPS origin and open that address through your reverse proxy. Map /data to appdata and keep it across updates. The appdata directory must be writable by UID 99, GID 100. No Compose dependency.</Overview>
|
||||
<Project>https://git.elijahkuntz.com/Elijah/Calio</Project>
|
||||
<TemplateURL>https://git.elijahkuntz.com/Elijah/Calio/raw/branch/main/unraid/calio.xml</TemplateURL>
|
||||
<ReadMe>https://git.elijahkuntz.com/Elijah/Calio/src/branch/main/docs/UNRAID.md</ReadMe>
|
||||
<Icon>https://git.elijahkuntz.com/Elijah/Calio/raw/branch/main/public/icons/icon-192.png</Icon>
|
||||
<Category>Home: Other:</Category>
|
||||
<Config Name="Web port" Target="3000" Default="3080" Mode="tcp" Description="Container HTTP port. Forward the public HTTPS reverse proxy to this host port." Type="Port" Display="always" Required="true" Mask="false"/>
|
||||
<Config Name="Appdata" Target="/data" Default="/mnt/user/appdata/calio" Mode="rw" Description="Persistent SQLite journal, sessions and backups. Keep this mapping on updates. Must be writable by 99:100." Type="Path" Display="always" Required="true" Mask="false"/>
|
||||
<Config Name="Public HTTPS origin" Target="APP_ORIGIN" Default="" Description="Required: exact public HTTPS origin, for example https://calio.example.com. No trailing slash." Type="Variable" Display="always" Required="true" Mask="false"/>
|
||||
<Config Name="Username" Target="CALIO_USERNAME" Default="calio" Description="The one account used to sign in." Type="Variable" Display="always" Required="true" Mask="false"/>
|
||||
<Config Name="Password" Target="CALIO_PASSWORD" Default="" Description="Required: a unique password of at least 12 characters. Set only at runtime, never in the image or repository." Type="Variable" Display="always" Required="true" Mask="true"/>
|
||||
<Config Name="Secure cookies" Target="COOKIE_SECURE" Default="true" Description="Keep true when using the public HTTPS origin." Type="Variable" Display="advanced" Required="true" Mask="false"/>
|
||||
<Config Name="Timezone" Target="TZ" Default="America/Phoenix" Description="Container timezone. Journal dates follow the device's local calendar." Type="Variable" Display="advanced" Required="false" Mask="false"/>
|
||||
</Container>
|
||||
6
vite.config.ts
Normal file
6
vite.config.ts
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
server: { proxy: { "/api": "http://127.0.0.1:3000" } },
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue