Compare commits
71
Commits
428716e479
...
v0.3.19
@@ -1,133 +0,0 @@
|
|||||||
name: Deploy
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
deploy:
|
|
||||||
runs-on: bare
|
|
||||||
env:
|
|
||||||
# The bare runner's own systemd service intentionally has a minimal
|
|
||||||
# PATH/HOME (no rustup default toolchain in reach) - point it at the
|
|
||||||
# shared toolchain install directly rather than assuming an ambient
|
|
||||||
# dev shell environment.
|
|
||||||
CARGO_HOME: /var/local/cargo
|
|
||||||
RUSTUP_HOME: /var/local/rustup
|
|
||||||
PATH: /var/local/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/bin
|
|
||||||
# Shared with interactive dev builds (see ~/.config/fish/config.fish)
|
|
||||||
# so a crate compiled once, by either a manual build or CI, is
|
|
||||||
# cached for the other - real cache hits, not just a warm toolchain.
|
|
||||||
# SCCACHE_SERVER_PORT deliberately differs from the interactive
|
|
||||||
# dev shell's (4227): sccache's server is discovered by a fixed
|
|
||||||
# TCP port shared by every local user, so if both contexts used
|
|
||||||
# the same port, whichever one's server happened to be running
|
|
||||||
# would silently "win" and serve build requests it doesn't have
|
|
||||||
# filesystem permission for. Separate ports keep each context's
|
|
||||||
# own server answering its own requests; the cache directory
|
|
||||||
# (not the server process) is what's actually shared.
|
|
||||||
SCCACHE_DIR: /var/local/sccache
|
|
||||||
SCCACHE_SERVER_PORT: "4228"
|
|
||||||
CARGO_TARGET_DIR: /var/local/cargo-target
|
|
||||||
# cargo-leptos's own downloaded tools (wasm-bindgen, wasm-opt) cache
|
|
||||||
# under $XDG_CACHE_HOME - left at its default that resolves inside
|
|
||||||
# this unit's systemd StateDirectory, files it creates there end up
|
|
||||||
# owned by the kernel's overflow "nobody" uid instead of the
|
|
||||||
# runner's own dynamic uid (a StateDirectory quirk, not something
|
|
||||||
# in our control), so a later run can't execute what an earlier run
|
|
||||||
# downloaded. Redirecting it to our own known-good shared dir avoids
|
|
||||||
# that entirely.
|
|
||||||
XDG_CACHE_HOME: /var/local/leptos-cache
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
|
|
||||||
# SITE_NAME is read via option_env! (src/app.rs) - compile-time,
|
|
||||||
# not a runtime env var - so it has to be set here, not just in
|
|
||||||
# the "Write service env" step below.
|
|
||||||
- name: Build
|
|
||||||
run: SITE_NAME=${{ vars.PORTAL_SITE_NAME }} cargo leptos build --release
|
|
||||||
|
|
||||||
# cargo-leptos only builds the leptos bin-target ("portal") - the
|
|
||||||
# question-lint utility binary needs its own plain cargo build.
|
|
||||||
- name: Build question-lint
|
|
||||||
run: cargo build --release --bin question_lint --features ssr
|
|
||||||
|
|
||||||
- name: Ship release
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
rel="/srv/app/uhhm-portal/releases/${{ github.sha }}"
|
|
||||||
mkdir -p "$rel"
|
|
||||||
cp "$CARGO_TARGET_DIR/release/portal" "$rel/uhhm-portal"
|
|
||||||
# questions' own CI execs this directly by path (same bare-metal
|
|
||||||
# runner/host as this job, no artifact download needed) instead
|
|
||||||
# of running its own hand-maintained yq/jq subset of these rules.
|
|
||||||
cp "$CARGO_TARGET_DIR/release/question_lint" "$rel/question_lint"
|
|
||||||
# site-root ("target/site" in Cargo.toml) is project-relative,
|
|
||||||
# not affected by CARGO_TARGET_DIR - only the plain `cargo build`
|
|
||||||
# outputs (release/, front/) move with that override.
|
|
||||||
cp -r target/site "$rel/site"
|
|
||||||
ln -sfn "$rel" /srv/app/uhhm-portal/current
|
|
||||||
|
|
||||||
# Sourced from this repo's own Settings -> Actions Variables/Secrets,
|
|
||||||
# not typed onto the host by hand - see the infrastructure repo's
|
|
||||||
# deploy-runner plan for the exact names/values to configure once.
|
|
||||||
- name: Write service env
|
|
||||||
run: |
|
|
||||||
cat > /etc/app/uhhm-portal.env <<EOF
|
|
||||||
NATS_URL=${{ secrets.PORTAL_NATS_URL }}
|
|
||||||
KANIDM_URL=${{ vars.PORTAL_KANIDM_URL }}
|
|
||||||
OAUTH2_CLIENT_ID=${{ vars.PORTAL_OAUTH2_CLIENT_ID }}
|
|
||||||
OAUTH2_CLIENT_SECRET=${{ secrets.PORTAL_OAUTH2_CLIENT_SECRET }}
|
|
||||||
PUBLIC_URL=${{ vars.PORTAL_PUBLIC_URL }}
|
|
||||||
COOKIE_SECURE=true
|
|
||||||
CONTENT_REPO=https://project.uhhm.no/uhhm/questions
|
|
||||||
CONTENT_BRANCH=main
|
|
||||||
SITE_NAME=${{ vars.PORTAL_SITE_NAME }}
|
|
||||||
LEPTOS_SITE_ADDR=0.0.0.0:3010
|
|
||||||
# Cargo.toml's site-root ("target/site") is a build-time path;
|
|
||||||
# the deploy layout copies the bundle to releases/<sha>/site
|
|
||||||
# (no target/ prefix) - override so the running binary looks
|
|
||||||
# in the right place for /pkg/*.
|
|
||||||
LEPTOS_SITE_ROOT=site
|
|
||||||
AUTOMATION_READ_TOKEN=${{ secrets.PORTAL_AUTOMATION_READ_TOKEN }}
|
|
||||||
# Read-only (read:user,read:repository,read:organization),
|
|
||||||
# used only by the GiteaStarred/GiteaOrgRepos resource sources
|
|
||||||
# (src/resource.rs) - the repo-contents/repo-info calls
|
|
||||||
# content loading already makes stay anonymous.
|
|
||||||
GITEA_API_TOKEN=${{ secrets.PORTAL_GITEA_API_TOKEN }}
|
|
||||||
EOF
|
|
||||||
|
|
||||||
# No sudo: the runner's own unit sets NoNewPrivileges=yes, which
|
|
||||||
# blocks setuid escalation outright (sudo can't work at all under
|
|
||||||
# it, regardless of sudoers config) - systemctl talks to PID1 over
|
|
||||||
# D-Bus instead, authorized by a polkit rule scoped to deploy-runner
|
|
||||||
# + this unit pattern (see /etc/polkit-1/rules.d/10-deploy-runner.rules
|
|
||||||
# on the host).
|
|
||||||
- name: Restart service
|
|
||||||
run: systemctl restart app@uhhm-portal.service
|
|
||||||
|
|
||||||
# No sudo here either - the runner is already in the `docker` group,
|
|
||||||
# so it can talk to the Docker socket directly.
|
|
||||||
# Apex and www are separate cookie scopes (no shared Domain
|
|
||||||
# attribute on the session cookie), but Kanidm's redirect_uri is
|
|
||||||
# fixed to PUBLIC_URL - a login started on the other host set its
|
|
||||||
# session cookie there, then landed on PUBLIC_URL's callback with
|
|
||||||
# an empty session ("no login in progress"). Redirecting www to
|
|
||||||
# the naked domain keeps every visit on one canonical host
|
|
||||||
# instead - PUBLIC_URL (repo variable) is set to https://{$DOMAIN}
|
|
||||||
# to match.
|
|
||||||
- name: Update Caddy routing
|
|
||||||
run: |
|
|
||||||
cat > /etc/caddy/services.d/uhhm-portal.caddy <<'EOF'
|
|
||||||
www.{$DOMAIN} {
|
|
||||||
redir https://{$DOMAIN}{uri} permanent
|
|
||||||
}
|
|
||||||
|
|
||||||
{$DOMAIN} {
|
|
||||||
reverse_proxy host.docker.internal:3010
|
|
||||||
log {
|
|
||||||
output file /var/log/caddy/www.log
|
|
||||||
}
|
|
||||||
}
|
|
||||||
EOF
|
|
||||||
docker exec caddy caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile
|
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
name: Publish release
|
||||||
|
|
||||||
|
# Portal does not deploy itself. Cutting a version is deliberate:
|
||||||
|
# `cargo release <level>` bumps Cargo.toml, commits, tags v<semver>,
|
||||||
|
# and pushes; this workflow reacts to the tag and publishes the
|
||||||
|
# artifact as a Gitea release. Each content repo (uhhm/questions,
|
||||||
|
# redoal/questions) pins PORTAL_RELEASE to one of these tags in its
|
||||||
|
# own deploy workflow - bumping the pin there is what rolls a version
|
||||||
|
# out to a site. Plain main pushes only run test.yml.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags: ["v*"]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: bare
|
||||||
|
env:
|
||||||
|
# The bare runner's own systemd service intentionally has a minimal
|
||||||
|
# PATH/HOME (no rustup default toolchain in reach) - point it at the
|
||||||
|
# shared toolchain install directly rather than assuming an ambient
|
||||||
|
# dev shell environment.
|
||||||
|
CARGO_HOME: /var/local/cargo
|
||||||
|
RUSTUP_HOME: /var/local/rustup
|
||||||
|
PATH: /var/local/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/bin
|
||||||
|
# Shared with interactive dev builds (see ~/.config/fish/config.fish)
|
||||||
|
# so a crate compiled once, by either a manual build or CI, is
|
||||||
|
# cached for the other - real cache hits, not just a warm toolchain.
|
||||||
|
# SCCACHE_SERVER_PORT deliberately differs from the interactive
|
||||||
|
# dev shell's (4227): sccache's server is discovered by a fixed
|
||||||
|
# TCP port shared by every local user, so if both contexts used
|
||||||
|
# the same port, whichever one's server happened to be running
|
||||||
|
# would silently "win" and serve build requests it doesn't have
|
||||||
|
# filesystem permission for. Separate ports keep each context's
|
||||||
|
# own server answering its own requests; the cache directory
|
||||||
|
# (not the server process) is what's actually shared.
|
||||||
|
SCCACHE_DIR: /var/local/sccache
|
||||||
|
SCCACHE_SERVER_PORT: "4228"
|
||||||
|
CARGO_TARGET_DIR: /var/local/cargo-target
|
||||||
|
# cargo-leptos's own downloaded tools (wasm-bindgen, wasm-opt) cache
|
||||||
|
# under $XDG_CACHE_HOME - left at its default that resolves inside
|
||||||
|
# this unit's systemd StateDirectory, files it creates there end up
|
||||||
|
# owned by the kernel's overflow "nobody" uid instead of the
|
||||||
|
# runner's own dynamic uid (a StateDirectory quirk, not something
|
||||||
|
# in our control), so a later run can't execute what an earlier run
|
||||||
|
# downloaded. Redirecting it to our own known-good shared dir avoids
|
||||||
|
# that entirely.
|
||||||
|
XDG_CACHE_HOME: /var/local/leptos-cache
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
# SITE_NAME is read via option_env! (src/app.rs) - compile-time,
|
||||||
|
# not a runtime env var. It is only the last-resort fallback name:
|
||||||
|
# each instance's site.yaml (content-driven branding) overrides it,
|
||||||
|
# so one artifact serves every site.
|
||||||
|
- name: Build
|
||||||
|
run: SITE_NAME=${{ vars.PORTAL_SITE_NAME }} cargo leptos build --release
|
||||||
|
|
||||||
|
# cargo-leptos only builds the leptos bin-target ("portal") - the
|
||||||
|
# question-lint utility binary needs its own plain cargo build.
|
||||||
|
- name: Build question-lint
|
||||||
|
run: cargo build --release --bin question_lint --features ssr
|
||||||
|
|
||||||
|
- name: Package
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
tag="${{ github.ref_name }}"
|
||||||
|
stage=$(mktemp -d)
|
||||||
|
cp "$CARGO_TARGET_DIR/release/portal" "$stage/portal"
|
||||||
|
cp "$CARGO_TARGET_DIR/release/question_lint" "$stage/question_lint"
|
||||||
|
# hash-files = true: leptos resolves hash.txt next to the running
|
||||||
|
# binary, so it ships beside portal in the release dir.
|
||||||
|
cp "$CARGO_TARGET_DIR/release/hash.txt" "$stage/hash.txt"
|
||||||
|
# site-root ("target/site" in Cargo.toml) is project-relative,
|
||||||
|
# not affected by CARGO_TARGET_DIR - only the plain `cargo build`
|
||||||
|
# outputs (release/, front/) move with that override.
|
||||||
|
cp -r target/site "$stage/site"
|
||||||
|
tar -C "$stage" -czf "portal-$tag.tar.gz" portal question_lint hash.txt site
|
||||||
|
rm -rf "$stage"
|
||||||
|
|
||||||
|
# The run's own ephemeral token has write access to this repo -
|
||||||
|
# no long-lived PAT to manage. The tag already exists (cargo
|
||||||
|
# release pushed it), so the release attaches to it; a re-run
|
||||||
|
# finds the existing release instead of failing.
|
||||||
|
- name: Publish release
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
tag="${{ github.ref_name }}"
|
||||||
|
api="${{ github.server_url }}/api/v1/repos/${{ github.repository }}"
|
||||||
|
auth="Authorization: token ${{ secrets.GITHUB_TOKEN }}"
|
||||||
|
subject=$(git log -1 --format=%s)
|
||||||
|
body=$(printf '{"tag_name":"%s","name":"%s"}' \
|
||||||
|
"$tag" "$tag: $(echo "$subject" | sed 's/"/\\"/g')")
|
||||||
|
id=$(curl -sf -X POST -H "$auth" -H 'Content-Type: application/json' \
|
||||||
|
-d "$body" "$api/releases" | jq .id) \
|
||||||
|
|| id=$(curl -sf -H "$auth" "$api/releases/tags/$tag" | jq .id)
|
||||||
|
# Replace the asset if a re-run already uploaded one.
|
||||||
|
for aid in $(curl -sf -H "$auth" "$api/releases/$id/assets" | jq '.[].id'); do
|
||||||
|
curl -sf -X DELETE -H "$auth" "$api/releases/$id/assets/$aid"
|
||||||
|
done
|
||||||
|
curl -sf -X POST -H "$auth" \
|
||||||
|
-F "attachment=@portal-$tag.tar.gz" \
|
||||||
|
"$api/releases/$id/assets?name=portal-$tag.tar.gz" > /dev/null
|
||||||
|
echo "published $tag"
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
name: Test
|
||||||
|
|
||||||
|
# Publishing only happens on v* tags (publish.yml), so this is what
|
||||||
|
# keeps plain main pushes honest between releases.
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: bare
|
||||||
|
env:
|
||||||
|
# Same shared-toolchain/cache story as publish.yml.
|
||||||
|
CARGO_HOME: /var/local/cargo
|
||||||
|
RUSTUP_HOME: /var/local/rustup
|
||||||
|
PATH: /var/local/cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/bin
|
||||||
|
SCCACHE_DIR: /var/local/sccache
|
||||||
|
SCCACHE_SERVER_PORT: "4228"
|
||||||
|
CARGO_TARGET_DIR: /var/local/cargo-target
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Test
|
||||||
|
run: cargo test --features ssr
|
||||||
@@ -1 +1,2 @@
|
|||||||
/target
|
/target
|
||||||
|
.claude/
|
||||||
|
|||||||
Generated
+20
-1
@@ -2948,7 +2948,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "portal"
|
name = "portal"
|
||||||
version = "0.1.0"
|
version = "0.3.19"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"arc-swap",
|
"arc-swap",
|
||||||
@@ -2970,6 +2970,7 @@ dependencies = [
|
|||||||
"leptos_router",
|
"leptos_router",
|
||||||
"openidconnect",
|
"openidconnect",
|
||||||
"proptest",
|
"proptest",
|
||||||
|
"pulldown-cmark",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml",
|
"serde_yaml",
|
||||||
@@ -3104,6 +3105,24 @@ dependencies = [
|
|||||||
"unarray",
|
"unarray",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pulldown-cmark"
|
||||||
|
version = "0.13.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags 2.13.1",
|
||||||
|
"memchr",
|
||||||
|
"pulldown-cmark-escape",
|
||||||
|
"unicase",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "pulldown-cmark-escape"
|
||||||
|
version = "0.11.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quick-error"
|
name = "quick-error"
|
||||||
version = "1.2.3"
|
version = "1.2.3"
|
||||||
|
|||||||
+20
-2
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "portal"
|
name = "portal"
|
||||||
version = "0.1.0"
|
version = "0.3.19"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
@@ -12,6 +12,9 @@ leptos_meta = { version = "0.8" }
|
|||||||
leptos_router = { version = "0.8" }
|
leptos_router = { version = "0.8" }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
# Inline markdown for content descriptions (links, emphasis, code) -
|
||||||
|
# runs on both server and client renders, so not feature-gated.
|
||||||
|
pulldown-cmark = { version = "0.13", default-features = false, features = ["html"] }
|
||||||
|
|
||||||
# --- server only ---
|
# --- server only ---
|
||||||
leptos_axum = { version = "0.8", optional = true }
|
leptos_axum = { version = "0.8", optional = true }
|
||||||
@@ -19,7 +22,7 @@ axum = { version = "0.8", features = ["multipart"], optional = true }
|
|||||||
aws-sdk-s3 = { version = "1", optional = true }
|
aws-sdk-s3 = { version = "1", optional = true }
|
||||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "signal"], optional = true }
|
tokio = { version = "1", features = ["rt-multi-thread", "macros", "signal"], optional = true }
|
||||||
tower = { version = "0.5", optional = true }
|
tower = { version = "0.5", optional = true }
|
||||||
tower-http = { version = "0.6", features = ["fs"], optional = true }
|
tower-http = { version = "0.6", features = ["fs", "set-header"], optional = true }
|
||||||
tower-sessions = { version = "0.14", optional = true }
|
tower-sessions = { version = "0.14", optional = true }
|
||||||
async-nats = { version = "0.38", optional = true }
|
async-nats = { version = "0.38", optional = true }
|
||||||
arc-swap = { version = "1", optional = true }
|
arc-swap = { version = "1", optional = true }
|
||||||
@@ -131,3 +134,18 @@ bin-default-features = false
|
|||||||
lib-features = ["hydrate"]
|
lib-features = ["hydrate"]
|
||||||
lib-default-features = false
|
lib-default-features = false
|
||||||
lib-profile-release = "wasm-release"
|
lib-profile-release = "wasm-release"
|
||||||
|
# Content-hashed pkg names (portal.<hash>.js/wasm/css) + hash.txt: a
|
||||||
|
# freshly served page can never reference a stale cached bundle - an
|
||||||
|
# iPhone kept a heuristically-cached portal.js across three releases
|
||||||
|
# and paired it with new wasm, silently killing hydration. Runtime
|
||||||
|
# needs LEPTOS_HASH_FILES=true (set in each content repo's deploy env).
|
||||||
|
hash-files = true
|
||||||
|
|
||||||
|
# cargo release <level> is how a portal version is cut: bump, commit,
|
||||||
|
# tag v{{version}}, push. CI (publish.yml) reacts to the tag and
|
||||||
|
# publishes the release artifact; nothing on crates.io.
|
||||||
|
[package.metadata.release]
|
||||||
|
publish = false
|
||||||
|
push = true
|
||||||
|
tag-name = "v{{version}}"
|
||||||
|
pre-release-commit-message = "Release {{version}}"
|
||||||
|
|||||||
@@ -1,17 +1,61 @@
|
|||||||
# portal
|
# portal
|
||||||
|
|
||||||
The question runtime behind [uhhm.no](https://uhhm.no). Every page,
|
A content-driven question engine: one Rust binary that turns a Git
|
||||||
form, review desk, and state machine it serves is declared in the
|
repo of YAML into a live site — pages, forms, review desks, and state
|
||||||
[`questions`](https://project.uhhm.no/uhhm/questions) content repo —
|
machines, with a durable event-sourced record of every answer
|
||||||
this codebase is the engine that renders, enforces, and records, and
|
underneath. The engine special-cases nothing: everything a site
|
||||||
it special-cases none of it.
|
serves is declared in its content repo, and the same build serves any
|
||||||
|
number of sites.
|
||||||
|
|
||||||
|
Point an instance at a content repo and that repo *is* the site:
|
||||||
|
pages, copy, state graphs, branding, and even the landing hero
|
||||||
|
(`site.yaml`: title, wordmark, and `hero: {kind: module, module:
|
||||||
|
hero.js}` — a JavaScript module the content repo ships, served
|
||||||
|
same-origin at `/site/<path>`, that portal mounts at parse time and
|
||||||
|
stops on navigation; the YES canvas and redoal's sine swings are both
|
||||||
|
content, not engine). Content
|
||||||
|
pushes hot-reload every running instance; instances differ only by
|
||||||
|
env vars. [uhhm.no](https://uhhm.no)
|
||||||
|
([uhhm/questions](https://project.uhhm.no/uhhm/questions)) and
|
||||||
|
[redoal.com](https://redoal.com)
|
||||||
|
([redoal/questions](https://project.uhhm.no/redoal/questions)) are
|
||||||
|
two faces of the same binary, deployed from the same release
|
||||||
|
artifact.
|
||||||
|
|
||||||
|
It composes with the surrounding stack rather than bundling it: Gitea
|
||||||
|
hosts and serves the content, NATS JetStream stores events and
|
||||||
|
projections, Kanidm provides identity, and anything downstream
|
||||||
|
(automations, newsletters, onboarding) subscribes to the answer
|
||||||
|
stream.
|
||||||
|
|
||||||
## What the engine provides
|
## What the engine provides
|
||||||
|
|
||||||
- **Content-driven pages** (`src/content.rs`, `src/app.rs`): YAML
|
- **Content-driven pages** (`src/content.rs`, `src/app.rs`): YAML
|
||||||
loaded from Gitea at boot and hot-swapped on a NATS reload signal;
|
loaded from Gitea at boot and hot-swapped on a NATS reload signal;
|
||||||
a bad push keeps the last-good content serving. A page's `id` is
|
a bad push keeps the last-good content serving. The `questions/`
|
||||||
its URL; `qualifies` gates it to a Kanidm group.
|
tree IS the router — file paths become URLs, `_section.yaml`
|
||||||
|
applies criteria to a whole directory, `[name].yaml` pages serve
|
||||||
|
any `/dir/<value>` with the segment fed into resource keys, and
|
||||||
|
`requires_chain` gates a page on verifiable answer provenance next
|
||||||
|
to `qualifies`' Kanidm-group identity gate (see
|
||||||
|
`docs/design/filesystem-routes.md`).
|
||||||
|
- **Gesture and voice fields** (`gesture.js`, `voice.js`): a stroke
|
||||||
|
becomes a redoal gesture key through a relay (ADR-0013/0015 in the
|
||||||
|
redoal repo) - the input shows the key's own decode under the
|
||||||
|
stroke, who is at a similar shape now, and *places* with recordings
|
||||||
|
the visitor can pick to make that key theirs; a voice field records
|
||||||
|
in the browser and leaves the audio at a key. Actions may be
|
||||||
|
templated from the answer (`/shape/{curve.key}`) onto dynamic
|
||||||
|
pages, whose URL segment also fills `value: "{key}"` presets and
|
||||||
|
`url` resource sources; resource items with an https `audio` field
|
||||||
|
render a player.
|
||||||
|
- **Announced pages** (`src/announce.rs`): a question with an
|
||||||
|
`event: {starts, duration, place}` window is announced in the
|
||||||
|
header (not the footer nav) while the window is open, becomes a
|
||||||
|
followup when it closes, and its record in the runtime-owned
|
||||||
|
`portal_events` bucket moves to `awaiting_summary` - a "post what
|
||||||
|
happened" task any review desk can read, published on NATS like a
|
||||||
|
decision. A one-minute sweeper keeps it all idempotent.
|
||||||
- **State machines as content** (`src/aggregates/`): `aggregates.yaml`
|
- **State machines as content** (`src/aggregates/`): `aggregates.yaml`
|
||||||
declares each bucket's states and legal transitions; the engine
|
declares each bucket's states and legal transitions; the engine
|
||||||
replays a record's event history and refuses undeclared moves, with
|
replays a record's event history and refuses undeclared moves, with
|
||||||
@@ -28,8 +72,13 @@ it special-cases none of it.
|
|||||||
lineage; `?chain=` links carry it, and self-service transitions
|
lineage; `?chain=` links carry it, and self-service transitions
|
||||||
(unsubscribe) authorize by holding one.
|
(unsubscribe) authorize by holding one.
|
||||||
- **Live resources** (`src/resource.rs`): content can pull a KV
|
- **Live resources** (`src/resource.rs`): content can pull a KV
|
||||||
bucket, Gitea starred/org repos, or any public JSON URL (SSRF
|
bucket, Gitea starred/org repos/releases, or any public JSON URL
|
||||||
fail-closed), reshaped by a content-declared `jq` filter.
|
(SSRF fail-closed), reshaped by a content-declared `jq` filter.
|
||||||
|
- **Input kinds as content**: a requirement's `type:` picks the
|
||||||
|
widget — plain fields, a rich-text editor, or a `gesture` drawing
|
||||||
|
canvas that can connect to a redoal relay so similar strokes echo
|
||||||
|
between visitors live. Submitted values are arbitrary JSON; the
|
||||||
|
engine records what the widget produced.
|
||||||
- **Review desks**: any Kv resource with `transitions` renders rows
|
- **Review desks**: any Kv resource with `transitions` renders rows
|
||||||
with per-state action buttons and one shared confirm per
|
with per-state action buttons and one shared confirm per
|
||||||
alternative — owners walk records through their graphs without
|
alternative — owners walk records through their graphs without
|
||||||
@@ -38,9 +87,10 @@ it special-cases none of it.
|
|||||||
## Binaries
|
## Binaries
|
||||||
|
|
||||||
- `portal` — the server (Leptos SSR + hydrate, Axum underneath).
|
- `portal` — the server (Leptos SSR + hydrate, Axum underneath).
|
||||||
- `question_lint` — headless content validation, run by the
|
- `question_lint` — headless content validation, shipped inside every
|
||||||
`questions` repo's CI against a prebuilt copy this repo's deploy
|
release artifact so each content repo's CI lints with the exact
|
||||||
publishes; also works offline: `question_lint --path <dir>`.
|
portal version its instance runs; also works offline:
|
||||||
|
`question_lint --path <dir>`.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
@@ -50,17 +100,58 @@ cargo test --features ssr # engine tests
|
|||||||
cargo build --features ssr --bin question_lint
|
cargo build --features ssr --bin question_lint
|
||||||
```
|
```
|
||||||
|
|
||||||
Runtime configuration is env vars (see `src/main.rs` and
|
Runtime configuration is env vars (see `src/main.rs`, and each
|
||||||
`.gitea/workflows/deploy.yml`): `NATS_URL`, `CONTENT_REPO`/
|
content repo's `.gitea/workflows/deploy.yml` for the values in
|
||||||
`CONTENT_BRANCH`, Kanidm OIDC (`KANIDM_URL`, `OAUTH2_CLIENT_*`),
|
production): `NATS_URL`, `CONTENT_REPO`/`CONTENT_BRANCH`, Kanidm OIDC
|
||||||
optional `GARAGE_*` for uploads, `GITEA_API_TOKEN` for authenticated
|
(`KANIDM_URL`, `OAUTH2_CLIENT_*`), optional `GARAGE_*` for uploads,
|
||||||
resource pulls, `AUTOMATION_READ_TOKEN` for the automation KV read
|
`GITEA_API_TOKEN` for authenticated resource pulls,
|
||||||
endpoint.
|
`AUTOMATION_READ_TOKEN` for the automation KV read endpoint.
|
||||||
|
|
||||||
## Deploy
|
## Release and deploy
|
||||||
|
|
||||||
Pushing `main` triggers `.gitea/workflows/deploy.yml` on the
|
Portal doesn't deploy itself — it publishes versions, and each site
|
||||||
bare-metal runner: release build, ship to
|
decides when to take one. The whole day-to-day surface is two
|
||||||
`/srv/app/uhhm-portal/releases/<sha>`, flip the `current` symlink,
|
commands:
|
||||||
restart `app@uhhm-portal`, reload Caddy. Content changes never come
|
|
||||||
through here — they hot-reload live from the `questions` repo.
|
**Cut a release** (here):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cargo release patch # or minor / major
|
||||||
|
```
|
||||||
|
|
||||||
|
That bumps `Cargo.toml`, tags `v<version>`, and pushes; CI
|
||||||
|
(`.gitea/workflows/publish.yml`) reacts to the tag, builds once, and
|
||||||
|
attaches `portal-v<version>.tar.gz` (`portal` + `question_lint` +
|
||||||
|
`hash.txt` + `site/`) to the Gitea release. Pkg files are
|
||||||
|
content-hashed (`hash-files = true`; instances run with
|
||||||
|
`LEPTOS_HASH_FILES=true`), so a freshly served page can never pair a
|
||||||
|
stale cached bundle with new wasm. Plain pushes to `main` only run the
|
||||||
|
tests (`test.yml`) — nothing reaches production from this repo.
|
||||||
|
|
||||||
|
**Roll it out** (in a content repo): edit one line in that repo's
|
||||||
|
`.gitea/workflows/deploy.yml` —
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
env:
|
||||||
|
PORTAL_RELEASE: v0.1.1 # <- bump, commit, push
|
||||||
|
```
|
||||||
|
|
||||||
|
Its CI downloads the pinned artifact, ships
|
||||||
|
`/srv/app/<instance>/releases/<tag>`, flips `current`, rewrites the
|
||||||
|
instance env from that repo's own Actions variables/secrets, restarts
|
||||||
|
`app@<instance>`, and refreshes the Caddy route. Every rollout is a
|
||||||
|
commit, so reverting a bad version is `git revert` + push. Sites
|
||||||
|
upgrade independently: uhhm.no (uhhm/questions → `app@uhhm-portal`,
|
||||||
|
:3010) and redoal.com (redoal/questions → `app@redoal-portal`,
|
||||||
|
:3020) can pin different versions.
|
||||||
|
|
||||||
|
Content changes never come through any of this — they hot-reload
|
||||||
|
live from the content repos over NATS.
|
||||||
|
|
||||||
|
**Add a site**: new content repo with a copy of an existing
|
||||||
|
`deploy.yml` (change `INSTANCE`, port, domains), Actions variables
|
||||||
|
(`KANIDM_URL`, `OAUTH2_CLIENT_ID`, `PUBLIC_URL`, `SITE_NAME`) and
|
||||||
|
secrets (`NATS_URL`, `OAUTH2_CLIENT_SECRET`,
|
||||||
|
`PORTAL_GITEA_API_TOKEN` — Gitea reserves the `GITEA_` prefix for
|
||||||
|
secret names), a Kanidm OAuth2 client, and DNS. `site.yaml` in the
|
||||||
|
content repo handles all branding; no portal changes needed.
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# Filesystem routes, sections, and where chains fit
|
||||||
|
|
||||||
|
Status: implemented in v0.2.0 (2026-08-24) — all three phases, with
|
||||||
|
one deviation: dynamic-page params substitute into resource keys via
|
||||||
|
server-side `resolve_question` at lookup time (get_question,
|
||||||
|
find_feature, submit_answer all resolve concrete paths), so no param
|
||||||
|
threading exists client-side. The user-facing routing contract is
|
||||||
|
documented in uhhm/questions' README ("Routing: the tree is the
|
||||||
|
router"); this file stays as the design rationale.
|
||||||
|
|
||||||
|
## What exists today, precisely
|
||||||
|
|
||||||
|
- A question's `id` doubles as its URL. Filenames are meaningless:
|
||||||
|
`questions/` is loaded as a **flat** directory (both the Gitea
|
||||||
|
loader and `question_lint --path`), every `*.yaml` becomes a
|
||||||
|
`Question` keyed by its own declared `id`.
|
||||||
|
- Hierarchy exists only as strings: `action: /proposed` edges, plus a
|
||||||
|
manual `followup: true` flag that hides post-submission pages from
|
||||||
|
the nav. The graph is invisible in a repo listing — you open every
|
||||||
|
file to learn the flow. (uhhm's actual graph: `/` fans out to three
|
||||||
|
followups; `/develop` → `/develop-proposal` → `/proposed` is a
|
||||||
|
two-step flow flattened into three top-level files.)
|
||||||
|
- Criteria are per-file: `qualifies: <kanidm-group>` on a question,
|
||||||
|
`requires_group` on a resource. Gating a whole area means
|
||||||
|
repeating the flag in every file of that area.
|
||||||
|
- Chains are query-string lineage: submitting hashes
|
||||||
|
`(question, parents, responses, ts)` into `chain_hash`, the next
|
||||||
|
page is `action + ?chain=<hash>`, and holding a chain is itself a
|
||||||
|
capability (`self_transition` + email second factor). `chain.rs`
|
||||||
|
reserves DAG shape (multiple parents) but nothing produces it yet.
|
||||||
|
- `Question.route` is a declared-but-never-read field — a fossil of
|
||||||
|
this exact idea.
|
||||||
|
|
||||||
|
## The proposal, in three phases
|
||||||
|
|
||||||
|
### Phase 1 — the tree is the router
|
||||||
|
|
||||||
|
Directory structure becomes the URL structure, next-js style:
|
||||||
|
|
||||||
|
```
|
||||||
|
questions/
|
||||||
|
index.yaml → /
|
||||||
|
applied.yaml → /applied
|
||||||
|
develop/
|
||||||
|
index.yaml → /develop
|
||||||
|
proposal.yaml → /develop/proposal
|
||||||
|
proposed.yaml → /develop/proposed
|
||||||
|
review/
|
||||||
|
index.yaml → /review
|
||||||
|
```
|
||||||
|
|
||||||
|
- `id:` becomes optional and **derived from the path** (`index.yaml`
|
||||||
|
names its directory). An explicit `id:` still wins so both content
|
||||||
|
repos keep working unchanged; lint warns when it disagrees with the
|
||||||
|
path, and the field can retire later along with `route`.
|
||||||
|
- `action:` accepts **relative references**: `action: proposed`
|
||||||
|
resolves against the file's directory, `action: /subscribed` stays
|
||||||
|
absolute. Resolution happens at load time, so validation and the
|
||||||
|
runtime see absolute ids exactly as today. A flow directory becomes
|
||||||
|
self-contained: rename `develop/` and every internal edge moves
|
||||||
|
with it.
|
||||||
|
- **`followup:` is inferred**: `index.yaml` files are nav pages,
|
||||||
|
non-index files are followups unless they say `nav: true`. This
|
||||||
|
matches the real content exactly (uhhm's four `followup: true`
|
||||||
|
files are precisely its non-index leaf pages) and deletes a flag
|
||||||
|
people must remember.
|
||||||
|
- Loader: switch from the per-directory contents API to Gitea's git
|
||||||
|
trees API (`/git/trees/{branch}?recursive=true`) — one request for
|
||||||
|
the whole tree instead of one per directory, which the flat loader
|
||||||
|
should be using anyway.
|
||||||
|
|
||||||
|
### Phase 2 — sections: criteria scoped by URL prefix
|
||||||
|
|
||||||
|
A `_section.yaml` in any directory applies to everything beneath it
|
||||||
|
(underscore = not a page, like next's private folders):
|
||||||
|
|
||||||
|
```
|
||||||
|
questions/review/_section.yaml:
|
||||||
|
qualifies: portal_owners
|
||||||
|
responsible: { name: Bendik, contact: … }
|
||||||
|
```
|
||||||
|
|
||||||
|
This is the URL/criteria interplay actually worth having: **a URL
|
||||||
|
prefix becomes a trust boundary**. "Everything under /review is
|
||||||
|
owner-only" is one line in one place, instead of a flag per file that
|
||||||
|
drifts. Per-question `qualifies` still overrides (tighter or looser —
|
||||||
|
lint should warn on looser). Sections are also the natural home for
|
||||||
|
shared `responsible` contacts and, later, per-section branding
|
||||||
|
accents.
|
||||||
|
|
||||||
|
### Phase 3 — dynamic segments, and chains stay out of the path
|
||||||
|
|
||||||
|
Two criteria axes exist: **who you are** (Kanidm group) and **what
|
||||||
|
you've done** (holding a chain). Phase 2 scopes the first by prefix;
|
||||||
|
phase 3 does the same for the second, plus gives records addresses:
|
||||||
|
|
||||||
|
- `[record].yaml` — a dynamic segment, one YAML file rendered per
|
||||||
|
record: `questions/review/[record].yaml` serves `/review/<key>`,
|
||||||
|
with the param available to the page's `ResourceSpec.key`. Today a
|
||||||
|
single record is only reachable through a desk row or a
|
||||||
|
`?chain=` link; this gives every record a real, gated URL —
|
||||||
|
linkable from review desks, automations, and n8n notifications.
|
||||||
|
- `requires_chain: <question-ref>` (page- or section-level): the page
|
||||||
|
only renders for a visitor whose chain tip answers the referenced
|
||||||
|
question. Today's followup pages are soft-hidden (out of nav) but
|
||||||
|
fully reachable; this makes "you must have come from X" an actual
|
||||||
|
criterion, declared with a relative ref like actions are.
|
||||||
|
|
||||||
|
**Deliberately not proposed: encoding the chain in the path.** The
|
||||||
|
page tree is static structure; the chain is runtime lineage and a
|
||||||
|
bearer capability. Putting it in the path makes it look canonical and
|
||||||
|
shareable — exactly what a capability URL shouldn't invite — and a
|
||||||
|
DAG (the reserved multi-parent shape) doesn't linearize into a path
|
||||||
|
anyway. `?chain=` stays a query parameter: pages keep one canonical
|
||||||
|
URL, lineage rides along only when it's actually held.
|
||||||
|
|
||||||
|
## Migration
|
||||||
|
|
||||||
|
Phase 1 is fully backward compatible (explicit `id` wins, flat repos
|
||||||
|
are just trees of depth one). The content repos migrate by `git mv`:
|
||||||
|
uhhm's develop flow nests under `develop/`, its followups either stay
|
||||||
|
top-level (`/applied` keeps its URL) or move with their flows if URL
|
||||||
|
churn is acceptable; redoal's three files are already the tree. Lint
|
||||||
|
learns the same resolution rules in the same commit, so a bad
|
||||||
|
reference stays a caught push, never a 404.
|
||||||
|
|
||||||
|
## Order of value
|
||||||
|
|
||||||
|
Phase 1 is cheap and pays immediately (the repo listing becomes the
|
||||||
|
sitemap). Phase 2 is small and unlocks gated areas properly. Phase 3
|
||||||
|
is the real feature work — `[record]` pages change what desks and
|
||||||
|
automations can link to — and can wait until something concrete needs
|
||||||
|
it.
|
||||||
+612
@@ -0,0 +1,612 @@
|
|||||||
|
// The `type: gesture` requirement widget: draw one stroke on a canvas,
|
||||||
|
// and the stroke becomes the field's value. Mirrors the two house
|
||||||
|
// patterns at once:
|
||||||
|
//
|
||||||
|
// - prosekit-editor.js's hidden-input bridge: the widget writes JSON
|
||||||
|
// into a paired hidden <input> and fires a real bubbling `input`
|
||||||
|
// event, so the Rust side reuses the exact same RwSignal/on:input
|
||||||
|
// wiring every other field kind uses - no bespoke value channel.
|
||||||
|
// - yes.js's lifecycle: mountGesture returns a handle whose stop()
|
||||||
|
// tears everything down (socket, listeners, rAF), because SPA
|
||||||
|
// navigation never unloads the document.
|
||||||
|
//
|
||||||
|
// When a relay URL is given, the widget also speaks the redoal-relay
|
||||||
|
// protocol (ADR-0013 in the redoal repo): announce the stroke, receive
|
||||||
|
// an ack carrying the stroke's gesture key plus the key's own decoded
|
||||||
|
// path - "what the network heard", drawn as a ghost under the stroke
|
||||||
|
// when the key is v2 or later (ADR-0014's ordered turning chain; a v1
|
||||||
|
// key's histogram decode is a blob and stays hidden) - and receive
|
||||||
|
// echoes of similar strokes other visitors drew, shown as thumbnails.
|
||||||
|
// Everything network is best-effort: no relay, refused connection, or
|
||||||
|
// a dropped socket all degrade to a plain offline drawing input.
|
||||||
|
//
|
||||||
|
// Canvas colors can't come from CSS custom properties (same
|
||||||
|
// constraint yes.js documents), so the widget carries its own copy of
|
||||||
|
// the palette for both themes - any palette change must land here AND
|
||||||
|
// in style/main.css.
|
||||||
|
|
||||||
|
const THEMES = {
|
||||||
|
dark: {
|
||||||
|
stroke: '#8ec2c0',
|
||||||
|
echo: '#8ec2c0',
|
||||||
|
ghost: 'rgba(255, 255, 255, 0.28)',
|
||||||
|
},
|
||||||
|
light: {
|
||||||
|
stroke: '#47807e',
|
||||||
|
echo: '#47807e',
|
||||||
|
ghost: 'rgba(29, 29, 27, 0.30)',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const MIN_POINT_DISTANCE = 3; // css px between recorded points
|
||||||
|
const MAX_ECHOES = 8;
|
||||||
|
const RECONNECT_BASE_MS = 1000;
|
||||||
|
const RECONNECT_MAX_MS = 30000;
|
||||||
|
|
||||||
|
// ── Convergence animation (ink → what the network heard) ──────────
|
||||||
|
//
|
||||||
|
// When the ack lands, a glowing copy of the stroke peels off and
|
||||||
|
// converges point-by-point onto the key's decoded path: a wave of
|
||||||
|
// "being understood" travels from the stroke's start to its end,
|
||||||
|
// and the ghost materializes where the light settles. WebGL point
|
||||||
|
// sprites with additive glow on a dedicated overlay canvas; the 2d
|
||||||
|
// layer underneath never changes its final render, so losing WebGL
|
||||||
|
// (or prefers-reduced-motion) degrades to exactly today's behavior.
|
||||||
|
const CONVERGE_MS = 1500;
|
||||||
|
const CONVERGE_FADE_MS = 450;
|
||||||
|
const CONVERGE_POINTS = 128;
|
||||||
|
const CONVERGE_STAGGER = 0.6; // fraction of the timeline spent on the travelling wave
|
||||||
|
|
||||||
|
const GLOW_VERT = `
|
||||||
|
attribute vec2 aFrom;
|
||||||
|
attribute vec2 aTo;
|
||||||
|
attribute float aIndex;
|
||||||
|
uniform float uT;
|
||||||
|
uniform vec2 uResolution;
|
||||||
|
uniform float uDpr;
|
||||||
|
varying float vLife;
|
||||||
|
void main() {
|
||||||
|
float lead = aIndex * ${CONVERGE_STAGGER};
|
||||||
|
float p = clamp((uT * ${1.0 + CONVERGE_STAGGER} - lead), 0.0, 1.0);
|
||||||
|
float e = p < 0.5 ? 4.0 * p * p * p : 1.0 - pow(-2.0 * p + 2.0, 3.0) / 2.0;
|
||||||
|
vec2 pos = mix(aFrom, aTo, e);
|
||||||
|
vec2 clip = (pos / uResolution) * 2.0 - 1.0;
|
||||||
|
gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);
|
||||||
|
float pulse = 1.0 + 1.4 * sin(3.14159 * p);
|
||||||
|
gl_PointSize = 9.0 * uDpr * pulse;
|
||||||
|
vLife = p;
|
||||||
|
}`;
|
||||||
|
|
||||||
|
const GLOW_FRAG = `
|
||||||
|
precision mediump float;
|
||||||
|
uniform vec3 uColor;
|
||||||
|
uniform float uAlpha;
|
||||||
|
varying float vLife;
|
||||||
|
void main() {
|
||||||
|
vec2 d = gl_PointCoord - 0.5;
|
||||||
|
float fall = exp(-dot(d, d) * 18.0);
|
||||||
|
float breathe = 0.55 + 0.45 * sin(3.14159 * vLife);
|
||||||
|
gl_FragColor = vec4(uColor, 1.0) * (fall * uAlpha * breathe);
|
||||||
|
}`;
|
||||||
|
|
||||||
|
// Uniform arc-length resample of a pixel-space polyline to n points.
|
||||||
|
function resamplePx(points, n) {
|
||||||
|
if (points.length === 1) return Array(n).fill(points[0]);
|
||||||
|
const dists = [0];
|
||||||
|
for (let i = 1; i < points.length; i++) {
|
||||||
|
const dx = points[i][0] - points[i - 1][0];
|
||||||
|
const dy = points[i][1] - points[i - 1][1];
|
||||||
|
dists.push(dists[i - 1] + Math.hypot(dx, dy));
|
||||||
|
}
|
||||||
|
const total = dists[dists.length - 1] || 1;
|
||||||
|
const out = [];
|
||||||
|
let seg = 0;
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const target = (i / (n - 1)) * total;
|
||||||
|
while (seg < points.length - 2 && dists[seg + 1] < target) seg++;
|
||||||
|
const span = dists[seg + 1] - dists[seg] || 1;
|
||||||
|
const t = (target - dists[seg]) / span;
|
||||||
|
out.push([
|
||||||
|
points[seg][0] + (points[seg + 1][0] - points[seg][0]) * t,
|
||||||
|
points[seg][1] + (points[seg + 1][1] - points[seg][1]) * t,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
class GestureWidget {
|
||||||
|
constructor(container, hidden, relayUrl) {
|
||||||
|
this.container = container;
|
||||||
|
this.hidden = hidden || null;
|
||||||
|
this.relayUrl = relayUrl || '';
|
||||||
|
this.ghost = null;
|
||||||
|
this.ownKey = null;
|
||||||
|
this.selected = null; // {key, path, distance} - a place the visitor picked
|
||||||
|
this.seenKeys = new Set();
|
||||||
|
this.points = [];
|
||||||
|
this.drawing = false;
|
||||||
|
this.stopped = false;
|
||||||
|
this.ws = null;
|
||||||
|
this.reconnectDelay = RECONNECT_BASE_MS;
|
||||||
|
this.reconnectTimer = null;
|
||||||
|
this.pendingAnnounce = null;
|
||||||
|
|
||||||
|
this.canvas = document.createElement('canvas');
|
||||||
|
this.canvas.className = 'gesture-canvas';
|
||||||
|
container.appendChild(this.canvas);
|
||||||
|
// Overlay for the convergence glow; sized with the main canvas,
|
||||||
|
// inert to pointers, empty until an ack arrives.
|
||||||
|
this.glow = document.createElement('canvas');
|
||||||
|
this.glow.className = 'gesture-glow';
|
||||||
|
this.glow.style.position = 'absolute';
|
||||||
|
this.glow.style.pointerEvents = 'none';
|
||||||
|
if (!container.style.position) container.style.position = 'relative';
|
||||||
|
container.appendChild(this.glow);
|
||||||
|
this.gl = null;
|
||||||
|
this.animFrame = null;
|
||||||
|
this.converging = false;
|
||||||
|
this.echoes = document.createElement('div');
|
||||||
|
this.echoes.className = 'gesture-echoes';
|
||||||
|
this.echoes.setAttribute('role', 'listbox');
|
||||||
|
this.echoes.setAttribute('aria-label', 'places near your shape');
|
||||||
|
container.appendChild(this.echoes);
|
||||||
|
this.empty = document.createElement('p');
|
||||||
|
this.empty.className = 'gesture-empty';
|
||||||
|
container.appendChild(this.empty);
|
||||||
|
if (this.relayUrl) {
|
||||||
|
this.status = document.createElement('span');
|
||||||
|
this.status.className = 'gesture-status offline';
|
||||||
|
this.status.setAttribute('aria-label', 'relay connection');
|
||||||
|
container.appendChild(this.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
this._themeQuery = window.matchMedia('(prefers-color-scheme: light)');
|
||||||
|
this._onTheme = () => this.render();
|
||||||
|
this._themeQuery.addEventListener('change', this._onTheme);
|
||||||
|
|
||||||
|
this._onResize = () => { this.sizeCanvas(); this.render(); };
|
||||||
|
window.addEventListener('resize', this._onResize);
|
||||||
|
this.sizeCanvas();
|
||||||
|
|
||||||
|
this._onDown = (e) => this.beginStroke(e);
|
||||||
|
this._onMove = (e) => this.extendStroke(e);
|
||||||
|
this._onUp = (e) => this.endStroke(e);
|
||||||
|
this.canvas.addEventListener('pointerdown', this._onDown);
|
||||||
|
this.canvas.addEventListener('pointermove', this._onMove);
|
||||||
|
this.canvas.addEventListener('pointerup', this._onUp);
|
||||||
|
this.canvas.addEventListener('pointercancel', this._onUp);
|
||||||
|
|
||||||
|
if (this.relayUrl) this.connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
theme() {
|
||||||
|
return this._themeQuery.matches ? THEMES.light : THEMES.dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
sizeCanvas() {
|
||||||
|
const rect = this.canvas.getBoundingClientRect();
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
this.canvas.width = Math.max(1, Math.round(rect.width * dpr));
|
||||||
|
this.canvas.height = Math.max(1, Math.round(rect.height * dpr));
|
||||||
|
this.ctx = this.canvas.getContext('2d');
|
||||||
|
this.ctx.scale(dpr, dpr);
|
||||||
|
this.cssWidth = rect.width;
|
||||||
|
this.cssHeight = rect.height;
|
||||||
|
this.glow.style.left = `${this.canvas.offsetLeft}px`;
|
||||||
|
this.glow.style.top = `${this.canvas.offsetTop}px`;
|
||||||
|
this.glow.style.width = `${rect.width}px`;
|
||||||
|
this.glow.style.height = `${rect.height}px`;
|
||||||
|
this.glow.width = this.canvas.width;
|
||||||
|
this.glow.height = this.canvas.height;
|
||||||
|
this.cancelConvergence(); // buffers are in old pixels
|
||||||
|
}
|
||||||
|
|
||||||
|
pos(e) {
|
||||||
|
const rect = this.canvas.getBoundingClientRect();
|
||||||
|
return { x: e.clientX - rect.left, y: e.clientY - rect.top };
|
||||||
|
}
|
||||||
|
|
||||||
|
beginStroke(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
this.canvas.setPointerCapture(e.pointerId);
|
||||||
|
// One stroke only - a new pointerdown replaces the old drawing
|
||||||
|
// (and any ghost from the previous round).
|
||||||
|
this.drawing = true;
|
||||||
|
this.cancelConvergence();
|
||||||
|
this.ghost = null;
|
||||||
|
this.ownKey = null;
|
||||||
|
this.selected = null;
|
||||||
|
this.seenKeys.clear();
|
||||||
|
this.echoes.replaceChildren();
|
||||||
|
this.empty.textContent = '';
|
||||||
|
this.points = [this.pos(e)];
|
||||||
|
this.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
extendStroke(e) {
|
||||||
|
if (!this.drawing) return;
|
||||||
|
const p = this.pos(e);
|
||||||
|
const last = this.points[this.points.length - 1];
|
||||||
|
const dx = p.x - last.x, dy = p.y - last.y;
|
||||||
|
if (Math.sqrt(dx * dx + dy * dy) < MIN_POINT_DISTANCE) return;
|
||||||
|
this.points.push(p);
|
||||||
|
this.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
endStroke() {
|
||||||
|
if (!this.drawing) return;
|
||||||
|
this.drawing = false;
|
||||||
|
if (this.points.length < 2) return;
|
||||||
|
const normalized = this.normalized();
|
||||||
|
this.setValue({ points: normalized, key: null });
|
||||||
|
this.announce(normalized);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Canvas-frame normalization into the -1..1 square (the relay
|
||||||
|
// re-normalizes around the stroke itself before keying - this
|
||||||
|
// just bounds the payload and keeps the stored value
|
||||||
|
// resolution-independent).
|
||||||
|
normalized() {
|
||||||
|
const half = Math.max(this.cssWidth, this.cssHeight) / 2;
|
||||||
|
const cx = this.cssWidth / 2, cy = this.cssHeight / 2;
|
||||||
|
return this.points.map((p) => [
|
||||||
|
Math.round(((p.x - cx) / half) * 10000) / 10000,
|
||||||
|
Math.round(((p.y - cy) / half) * 10000) / 10000,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
setValue(value) {
|
||||||
|
if (!this.hidden) return;
|
||||||
|
this.hidden.value = JSON.stringify(value);
|
||||||
|
this.hidden.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Relay ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
connect() {
|
||||||
|
if (this.stopped) return;
|
||||||
|
let ws;
|
||||||
|
try {
|
||||||
|
ws = new WebSocket(this.relayUrl);
|
||||||
|
} catch {
|
||||||
|
this.scheduleReconnect();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.ws = ws;
|
||||||
|
ws.addEventListener('open', () => {
|
||||||
|
if (this.stopped) return;
|
||||||
|
this.reconnectDelay = RECONNECT_BASE_MS;
|
||||||
|
this.status?.classList.replace('offline', 'live');
|
||||||
|
if (this.pendingAnnounce) {
|
||||||
|
ws.send(JSON.stringify({ type: 'announce', points: this.pendingAnnounce }));
|
||||||
|
this.pendingAnnounce = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ws.addEventListener('message', (e) => this.onMessage(e));
|
||||||
|
ws.addEventListener('close', () => {
|
||||||
|
this.status?.classList.replace('live', 'offline');
|
||||||
|
this.ws = null;
|
||||||
|
this.scheduleReconnect();
|
||||||
|
});
|
||||||
|
// 'error' is always followed by 'close'; nothing to do here.
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleReconnect() {
|
||||||
|
if (this.stopped || this.reconnectTimer) return;
|
||||||
|
this.reconnectTimer = setTimeout(() => {
|
||||||
|
this.reconnectTimer = null;
|
||||||
|
this.connect();
|
||||||
|
}, this.reconnectDelay);
|
||||||
|
this.reconnectDelay = Math.min(this.reconnectDelay * 2, RECONNECT_MAX_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
announce(points) {
|
||||||
|
if (!this.relayUrl) return;
|
||||||
|
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
|
||||||
|
this.ws.send(JSON.stringify({ type: 'announce', points }));
|
||||||
|
} else {
|
||||||
|
this.pendingAnnounce = points;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMessage(e) {
|
||||||
|
let msg;
|
||||||
|
try {
|
||||||
|
msg = JSON.parse(e.data);
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (msg.type === 'ack') {
|
||||||
|
this.ownKey = msg.key;
|
||||||
|
// Version nibble is the key's first hex digit.
|
||||||
|
const version = parseInt((msg.key || '0')[0], 16);
|
||||||
|
this.ownGhost = version >= 2 && Array.isArray(msg.path) ? msg.path : null;
|
||||||
|
this.applySelection();
|
||||||
|
// Places arrive right after the ack; say so if none do.
|
||||||
|
clearTimeout(this.emptyTimer);
|
||||||
|
this.emptyTimer = setTimeout(() => {
|
||||||
|
if (!this.echoes.children.length) this.empty.textContent = msg.empty || 'Nothing kept at this shape yet.';
|
||||||
|
}, 1500);
|
||||||
|
} else if (msg.type === 'echo' || msg.type === 'place') {
|
||||||
|
if (!msg.key || this.seenKeys.has(msg.key)) return;
|
||||||
|
this.seenKeys.add(msg.key);
|
||||||
|
this.empty.textContent = '';
|
||||||
|
this.addEchoThumbnail(msg);
|
||||||
|
}
|
||||||
|
// 'error' frames are intentionally silent: the widget is a
|
||||||
|
// form field first, and a rate-limited announce shouldn't
|
||||||
|
// alarm anyone mid-form.
|
||||||
|
}
|
||||||
|
|
||||||
|
// The key the input carries: the visitor's own, or the place they
|
||||||
|
// picked (selection re-derives the key - the ghost under the
|
||||||
|
// stroke becomes that place's decode, and the answer records both).
|
||||||
|
applySelection() {
|
||||||
|
if (this.points.length < 2) return;
|
||||||
|
const points = this.normalized();
|
||||||
|
const before = this.ghost;
|
||||||
|
if (this.selected) {
|
||||||
|
this.ghost = this.selected.path;
|
||||||
|
this.setValue({ points, key: this.selected.key, own_key: this.ownKey, selected_from: this.ownKey, selected_distance: this.selected.distance });
|
||||||
|
} else {
|
||||||
|
this.ghost = this.ownGhost || null;
|
||||||
|
this.setValue({ points, key: this.ownKey });
|
||||||
|
}
|
||||||
|
if (this.ghost && this.ghost !== before) this.startConvergence(this.ghost);
|
||||||
|
for (const el of this.echoes.children) {
|
||||||
|
el.classList.toggle('selected', !!this.selected && el.dataset.key === this.selected.key);
|
||||||
|
el.setAttribute('aria-selected', String(!!this.selected && el.dataset.key === this.selected.key));
|
||||||
|
}
|
||||||
|
this.render();
|
||||||
|
}
|
||||||
|
|
||||||
|
select(thumb) {
|
||||||
|
const key = thumb.dataset.key;
|
||||||
|
if (this.selected && this.selected.key === key) {
|
||||||
|
this.selected = null;
|
||||||
|
} else {
|
||||||
|
this.selected = { key, path: JSON.parse(thumb.dataset.path), distance: Number(thumb.dataset.distance) };
|
||||||
|
// The relay counts picks per place for ranking.
|
||||||
|
if (this.ws && this.ws.readyState === WebSocket.OPEN && this.ownKey) {
|
||||||
|
this.ws.send(JSON.stringify({ type: 'select', key, from: this.ownKey, distance: this.selected.distance }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.applySelection();
|
||||||
|
}
|
||||||
|
|
||||||
|
addEchoThumbnail(msg) {
|
||||||
|
const thumb = document.createElement('canvas');
|
||||||
|
thumb.className = 'gesture-echo' + (msg.type === 'place' ? ' place' : '');
|
||||||
|
thumb.dataset.key = msg.key;
|
||||||
|
thumb.dataset.path = JSON.stringify(msg.path || []);
|
||||||
|
thumb.dataset.distance = String(msg.distance || 0);
|
||||||
|
thumb.setAttribute('role', 'option');
|
||||||
|
thumb.setAttribute('tabindex', '0');
|
||||||
|
thumb.setAttribute('aria-selected', 'false');
|
||||||
|
thumb.title = msg.type === 'place'
|
||||||
|
? `A place with ${msg.recordings || 0} recording${msg.recordings === 1 ? '' : 's'} - tap to make it your address`
|
||||||
|
: 'Someone at this shape right now';
|
||||||
|
thumb.addEventListener('click', () => this.select(thumb));
|
||||||
|
thumb.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.select(thumb); } });
|
||||||
|
// Closer strokes render stronger; 500 is comfortably past the
|
||||||
|
// relay's default threshold, so everything stays visible.
|
||||||
|
const strength = Math.max(0.35, Math.min(1, 1 - msg.distance / 500));
|
||||||
|
thumb.style.setProperty('--echo-strength', String(strength));
|
||||||
|
this.echoes.prepend(thumb);
|
||||||
|
while (this.echoes.children.length > MAX_ECHOES) {
|
||||||
|
this.echoes.lastChild.remove();
|
||||||
|
}
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
const rect = thumb.getBoundingClientRect();
|
||||||
|
thumb.width = Math.max(1, Math.round(rect.width * dpr));
|
||||||
|
thumb.height = Math.max(1, Math.round(rect.height * dpr));
|
||||||
|
const ctx = thumb.getContext('2d');
|
||||||
|
ctx.scale(dpr, dpr);
|
||||||
|
this.drawPath(ctx, msg.path, rect.width, rect.height, this.theme().echo, 1.5, 0.15);
|
||||||
|
// A timeout, not requestAnimationFrame: the class must land on
|
||||||
|
// a later tick for the opacity transition to run, and rAF
|
||||||
|
// doesn't tick at all in headless engines.
|
||||||
|
setTimeout(() => thumb.classList.add('shown'), 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Convergence ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
initGlow() {
|
||||||
|
if (this.gl) return this.gl;
|
||||||
|
const gl = this.glow.getContext('webgl', { alpha: true, premultipliedAlpha: true });
|
||||||
|
if (!gl) return null;
|
||||||
|
const compile = (type, src) => {
|
||||||
|
const s = gl.createShader(type);
|
||||||
|
gl.shaderSource(s, src);
|
||||||
|
gl.compileShader(s);
|
||||||
|
return s;
|
||||||
|
};
|
||||||
|
const prog = gl.createProgram();
|
||||||
|
gl.attachShader(prog, compile(gl.VERTEX_SHADER, GLOW_VERT));
|
||||||
|
gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, GLOW_FRAG));
|
||||||
|
gl.linkProgram(prog);
|
||||||
|
if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) return null;
|
||||||
|
gl.useProgram(prog);
|
||||||
|
this.gl = gl;
|
||||||
|
this.glProg = prog;
|
||||||
|
this.glLoc = {
|
||||||
|
aFrom: gl.getAttribLocation(prog, 'aFrom'),
|
||||||
|
aTo: gl.getAttribLocation(prog, 'aTo'),
|
||||||
|
aIndex: gl.getAttribLocation(prog, 'aIndex'),
|
||||||
|
uT: gl.getUniformLocation(prog, 'uT'),
|
||||||
|
uResolution: gl.getUniformLocation(prog, 'uResolution'),
|
||||||
|
uDpr: gl.getUniformLocation(prog, 'uDpr'),
|
||||||
|
uColor: gl.getUniformLocation(prog, 'uColor'),
|
||||||
|
uAlpha: gl.getUniformLocation(prog, 'uAlpha'),
|
||||||
|
};
|
||||||
|
this.glBufFrom = gl.createBuffer();
|
||||||
|
this.glBufTo = gl.createBuffer();
|
||||||
|
this.glBufIndex = gl.createBuffer();
|
||||||
|
return gl;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The ghost's pixel frame - same fit drawPath uses.
|
||||||
|
ghostToPx(path) {
|
||||||
|
const scale = (Math.min(this.cssWidth, this.cssHeight) / 2) * 0.8;
|
||||||
|
const cx = this.cssWidth / 2, cy = this.cssHeight / 2;
|
||||||
|
return path.map(([x, y]) => [cx + x * scale, cy + y * scale]);
|
||||||
|
}
|
||||||
|
|
||||||
|
startConvergence(targetPath) {
|
||||||
|
this.cancelConvergence();
|
||||||
|
if (!targetPath || this.points.length < 2) return;
|
||||||
|
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
|
||||||
|
const gl = this.initGlow();
|
||||||
|
if (!gl) return;
|
||||||
|
|
||||||
|
const dpr = window.devicePixelRatio || 1;
|
||||||
|
const from = resamplePx(this.points.map((p) => [p.x, p.y]), CONVERGE_POINTS);
|
||||||
|
const to = resamplePx(this.ghostToPx(targetPath), CONVERGE_POINTS);
|
||||||
|
const f = new Float32Array(CONVERGE_POINTS * 2);
|
||||||
|
const t = new Float32Array(CONVERGE_POINTS * 2);
|
||||||
|
const idx = new Float32Array(CONVERGE_POINTS);
|
||||||
|
for (let i = 0; i < CONVERGE_POINTS; i++) {
|
||||||
|
f[i * 2] = from[i][0] * dpr;
|
||||||
|
f[i * 2 + 1] = from[i][1] * dpr;
|
||||||
|
t[i * 2] = to[i][0] * dpr;
|
||||||
|
t[i * 2 + 1] = to[i][1] * dpr;
|
||||||
|
idx[i] = i / (CONVERGE_POINTS - 1);
|
||||||
|
}
|
||||||
|
const bind = (buf, data, loc, size) => {
|
||||||
|
gl.bindBuffer(gl.ARRAY_BUFFER, buf);
|
||||||
|
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
|
||||||
|
gl.enableVertexAttribArray(loc);
|
||||||
|
gl.vertexAttribPointer(loc, size, gl.FLOAT, false, 0, 0);
|
||||||
|
};
|
||||||
|
gl.useProgram(this.glProg);
|
||||||
|
bind(this.glBufFrom, f, this.glLoc.aFrom, 2);
|
||||||
|
bind(this.glBufTo, t, this.glLoc.aTo, 2);
|
||||||
|
bind(this.glBufIndex, idx, this.glLoc.aIndex, 1);
|
||||||
|
gl.viewport(0, 0, this.glow.width, this.glow.height);
|
||||||
|
gl.uniform2f(this.glLoc.uResolution, this.glow.width, this.glow.height);
|
||||||
|
gl.uniform1f(this.glLoc.uDpr, dpr);
|
||||||
|
|
||||||
|
const light = this._themeQuery.matches;
|
||||||
|
const color = light ? [0x47 / 255, 0x80 / 255, 0x7e / 255] : [0x8e / 255, 0xc2 / 255, 0xc0 / 255];
|
||||||
|
gl.uniform3f(this.glLoc.uColor, color[0], color[1], color[2]);
|
||||||
|
// Additive light on the dark ground; normal ink on the light one.
|
||||||
|
gl.enable(gl.BLEND);
|
||||||
|
if (light) gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
|
||||||
|
else gl.blendFunc(gl.ONE, gl.ONE);
|
||||||
|
|
||||||
|
this.converging = true;
|
||||||
|
this.render();
|
||||||
|
const started = performance.now();
|
||||||
|
const step = (now) => {
|
||||||
|
const raw = (now - started) / CONVERGE_MS;
|
||||||
|
if (raw >= 1) {
|
||||||
|
// Deposit the ghost, then let the glow breathe out.
|
||||||
|
if (this.converging) {
|
||||||
|
this.converging = false;
|
||||||
|
this.render();
|
||||||
|
}
|
||||||
|
const fade = (now - started - CONVERGE_MS) / CONVERGE_FADE_MS;
|
||||||
|
if (fade >= 1) {
|
||||||
|
this.cancelConvergence();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
gl.clearColor(0, 0, 0, 0);
|
||||||
|
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||||
|
gl.uniform1f(this.glLoc.uT, 1);
|
||||||
|
gl.uniform1f(this.glLoc.uAlpha, 0.32 * (1 - fade));
|
||||||
|
gl.drawArrays(gl.POINTS, 0, CONVERGE_POINTS);
|
||||||
|
} else {
|
||||||
|
gl.clearColor(0, 0, 0, 0);
|
||||||
|
gl.clear(gl.COLOR_BUFFER_BIT);
|
||||||
|
// Trailing passes give the wave a comet tail.
|
||||||
|
for (const [lag, alpha] of [[0, 0.32], [0.035, 0.16], [0.07, 0.08], [0.105, 0.04]]) {
|
||||||
|
gl.uniform1f(this.glLoc.uT, Math.max(0, raw - lag));
|
||||||
|
gl.uniform1f(this.glLoc.uAlpha, alpha);
|
||||||
|
gl.drawArrays(gl.POINTS, 0, CONVERGE_POINTS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.animFrame = requestAnimationFrame(step);
|
||||||
|
};
|
||||||
|
this.animFrame = requestAnimationFrame(step);
|
||||||
|
}
|
||||||
|
|
||||||
|
cancelConvergence() {
|
||||||
|
if (this.animFrame) cancelAnimationFrame(this.animFrame);
|
||||||
|
this.animFrame = null;
|
||||||
|
if (this.converging) {
|
||||||
|
this.converging = false;
|
||||||
|
this.render();
|
||||||
|
}
|
||||||
|
if (this.gl) {
|
||||||
|
this.gl.clearColor(0, 0, 0, 0);
|
||||||
|
this.gl.clear(this.gl.COLOR_BUFFER_BIT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Rendering ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
// Draw a normalized (-1..1) path fitted into w×h with padding.
|
||||||
|
drawPath(ctx, path, w, h, color, width, pad) {
|
||||||
|
if (!path || path.length < 2) return;
|
||||||
|
const scale = (Math.min(w, h) / 2) * (1 - pad);
|
||||||
|
const cx = w / 2, cy = h / 2;
|
||||||
|
ctx.strokeStyle = color;
|
||||||
|
ctx.lineWidth = width;
|
||||||
|
ctx.lineCap = 'round';
|
||||||
|
ctx.lineJoin = 'round';
|
||||||
|
ctx.beginPath();
|
||||||
|
path.forEach(([x, y], i) => {
|
||||||
|
const px = cx + x * scale, py = cy + y * scale;
|
||||||
|
if (i === 0) ctx.moveTo(px, py);
|
||||||
|
else ctx.lineTo(px, py);
|
||||||
|
});
|
||||||
|
ctx.stroke();
|
||||||
|
}
|
||||||
|
|
||||||
|
render() {
|
||||||
|
if (!this.ctx) return;
|
||||||
|
const t = this.theme();
|
||||||
|
this.ctx.clearRect(0, 0, this.cssWidth, this.cssHeight);
|
||||||
|
if (this.ghost && !this.converging) {
|
||||||
|
this.drawPath(this.ctx, this.ghost, this.cssWidth, this.cssHeight, t.ghost, 2, 0.2);
|
||||||
|
}
|
||||||
|
if (this.points.length >= 1) {
|
||||||
|
this.ctx.strokeStyle = t.stroke;
|
||||||
|
this.ctx.lineWidth = 2;
|
||||||
|
this.ctx.lineCap = 'round';
|
||||||
|
this.ctx.lineJoin = 'round';
|
||||||
|
this.ctx.beginPath();
|
||||||
|
this.points.forEach((p, i) => {
|
||||||
|
if (i === 0) this.ctx.moveTo(p.x, p.y);
|
||||||
|
else this.ctx.lineTo(p.x, p.y);
|
||||||
|
});
|
||||||
|
this.ctx.stroke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
this.stopped = true;
|
||||||
|
if (this.animFrame) cancelAnimationFrame(this.animFrame);
|
||||||
|
clearTimeout(this.emptyTimer);
|
||||||
|
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
||||||
|
if (this.ws) {
|
||||||
|
// The close event still fires, but scheduleReconnect
|
||||||
|
// no-ops once stopped is set.
|
||||||
|
try { this.ws.close(); } catch { /* already dead */ }
|
||||||
|
this.ws = null;
|
||||||
|
}
|
||||||
|
window.removeEventListener('resize', this._onResize);
|
||||||
|
this._themeQuery.removeEventListener('change', this._onTheme);
|
||||||
|
this.canvas.removeEventListener('pointerdown', this._onDown);
|
||||||
|
this.canvas.removeEventListener('pointermove', this._onMove);
|
||||||
|
this.canvas.removeEventListener('pointerup', this._onUp);
|
||||||
|
this.canvas.removeEventListener('pointercancel', this._onUp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mountGesture(container, hidden, relayUrl) {
|
||||||
|
// Dev convenience: `?relay=ws://127.0.0.1:9040` points every widget
|
||||||
|
// on the page at a local relay (prod relays reject foreign Origins).
|
||||||
|
const override = new URLSearchParams(window.location.search).get('relay');
|
||||||
|
return new GestureWidget(container, hidden, override || relayUrl);
|
||||||
|
}
|
||||||
+9
-4
@@ -129,15 +129,17 @@ function defineGiteaRepoEmbed() {
|
|||||||
'data-description': description,
|
'data-description': description,
|
||||||
'data-url': url,
|
'data-url': url,
|
||||||
style:
|
style:
|
||||||
'display:block;border:1px solid #ddd;border-radius:8px;' +
|
'display:block;border:0.06em solid #ddd;border-radius:0.5em;' +
|
||||||
'padding:12px 16px;margin:8px 0;font-family:inherit;',
|
'padding:0.75em 1em;margin:0.5em 0;font-family:inherit;',
|
||||||
},
|
},
|
||||||
[
|
[
|
||||||
'a',
|
'a',
|
||||||
{ href: url, style: 'font-weight:600;text-decoration:none;color:inherit;' },
|
{ href: url, style: 'font-weight:600;text-decoration:none;color:inherit;' },
|
||||||
`${owner}/${repo}`,
|
`${owner}/${repo}`,
|
||||||
],
|
],
|
||||||
['div', { style: 'opacity:0.7;font-size:0.9em;margin-top:4px;' }, description],
|
// Solid mid-gray, not opacity - dim on both the newsletter's
|
||||||
|
// light client background and this app's dark paper.
|
||||||
|
['div', { style: 'color:#9a9a9a;font-size:0.9rem;margin-top:0.25em;' }, description],
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -283,8 +285,11 @@ function buildToolbar(editor) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function mountEditor(container, hiddenInput, initial) {
|
export function mountEditor(container, hiddenInput, initial) {
|
||||||
|
// Only the structural stylesheet (placeholder, lists, gap cursor).
|
||||||
|
// Deliberately NOT prosekit/basic/typography.css: it sizes content in
|
||||||
|
// fixed px, which fights the app's responsive root font-size. All
|
||||||
|
// editor typography lives in our own stylesheet, in rem.
|
||||||
ensureStylesheet('https://esm.sh/prosekit/basic/style.css')
|
ensureStylesheet('https://esm.sh/prosekit/basic/style.css')
|
||||||
ensureStylesheet('https://esm.sh/prosekit/basic/typography.css')
|
|
||||||
|
|
||||||
const extension = union(
|
const extension = union(
|
||||||
defineBasicExtension(),
|
defineBasicExtension(),
|
||||||
|
|||||||
@@ -30,6 +30,12 @@ pub struct AggregateSchema {
|
|||||||
pub event_for_state: HashMap<String, String>,
|
pub event_for_state: HashMap<String, String>,
|
||||||
pub state_for_event: HashMap<String, String>,
|
pub state_for_event: HashMap<String, String>,
|
||||||
pub transitions: HashMap<String, Vec<String>>,
|
pub transitions: HashMap<String, Vec<String>>,
|
||||||
|
/// Names what consumes this bucket's answers when no page in the
|
||||||
|
/// content repo reads it (e.g. "n8n newsletter compose").
|
||||||
|
/// Free-text - it exists so `validate_questions`' attended-bucket
|
||||||
|
/// rule has an explicit, auditable opt-out instead of a silent
|
||||||
|
/// one, and so the next reader knows where the answers go.
|
||||||
|
pub attended_by: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AggregateSchema {
|
impl AggregateSchema {
|
||||||
@@ -57,6 +63,8 @@ struct RawAggregateSchema {
|
|||||||
states: HashMap<String, RawState>,
|
states: HashMap<String, RawState>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
transitions: HashMap<String, Vec<String>>,
|
transitions: HashMap<String, Vec<String>>,
|
||||||
|
#[serde(default)]
|
||||||
|
attended_by: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, serde::Deserialize)]
|
#[derive(Debug, serde::Deserialize)]
|
||||||
@@ -123,6 +131,7 @@ pub fn parse_aggregates_yaml(raw: &str) -> anyhow::Result<HashMap<String, Aggreg
|
|||||||
event_for_state,
|
event_for_state,
|
||||||
state_for_event,
|
state_for_event,
|
||||||
transitions: raw_schema.transitions,
|
transitions: raw_schema.transitions,
|
||||||
|
attended_by: raw_schema.attended_by,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+159
@@ -0,0 +1,159 @@
|
|||||||
|
//! Announced pages (`Question.event`): keeps one `portal_events` record
|
||||||
|
//! per event question and, once a window closes, moves it to
|
||||||
|
//! `awaiting_summary` - the "post what happened" task - publishing the
|
||||||
|
//! transition on `portal.answers.submitted` like any desk decision, so
|
||||||
|
//! the desktop notifier and n8n hear it. Runs on a one-minute tick;
|
||||||
|
//! every step is idempotent, so a restart or a content reload in the
|
||||||
|
//! middle changes nothing.
|
||||||
|
|
||||||
|
use crate::answers::{store_answer, Answer};
|
||||||
|
use crate::content::EVENTS_BUCKET;
|
||||||
|
use crate::events::{emit_answer_submitted, AnswerSubmitted};
|
||||||
|
use crate::server::AppState;
|
||||||
|
|
||||||
|
/// Alternative name stamped on the auto-created record and on the
|
||||||
|
/// transition event - what an n8n workflow gates on.
|
||||||
|
pub const EVENT_ALTERNATIVE: &str = "Announced";
|
||||||
|
pub const SUMMARY_DUE_LABEL: &str = "Summary due";
|
||||||
|
|
||||||
|
/// Record id for an event question: its id with `/` folded to `-`
|
||||||
|
/// (`/events/opening` -> `events-opening`), so one page is one record
|
||||||
|
/// however many times the sweeper runs.
|
||||||
|
pub fn record_id(question_id: &str) -> String {
|
||||||
|
question_id.trim_matches('/').replace('/', "-")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(state: AppState) {
|
||||||
|
let mut tick = tokio::time::interval(std::time::Duration::from_secs(60));
|
||||||
|
loop {
|
||||||
|
tick.tick().await;
|
||||||
|
if let Err(e) = sweep(&state).await {
|
||||||
|
tracing::warn!(error = %e, "event sweep failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pass: create missing records, close ended windows.
|
||||||
|
pub async fn sweep(state: &AppState) -> anyhow::Result<()> {
|
||||||
|
let now_ms = chrono::Utc::now().timestamp_millis();
|
||||||
|
let questions = state.questions.load();
|
||||||
|
let events: Vec<_> = questions.values().filter(|q| q.event.is_some()).cloned().collect();
|
||||||
|
if events.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let aggregates = state.aggregates.load();
|
||||||
|
let schema = aggregates
|
||||||
|
.get(EVENTS_BUCKET)
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("no {EVENTS_BUCKET} schema"))?;
|
||||||
|
let store = match state.jetstream.get_key_value(EVENTS_BUCKET).await {
|
||||||
|
Ok(store) => Some(store),
|
||||||
|
Err(_) => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for q in events {
|
||||||
|
let event = q.event.as_ref().expect("filtered");
|
||||||
|
let (starts, ends) = match event.window_ms() {
|
||||||
|
Ok(w) => w,
|
||||||
|
Err(_) => continue, // validated on load; belt and braces
|
||||||
|
};
|
||||||
|
let id = record_id(&q.id);
|
||||||
|
let existing: Option<Answer> = match &store {
|
||||||
|
Some(store) => store
|
||||||
|
.get(&id)
|
||||||
|
.await?
|
||||||
|
.and_then(|bytes| serde_json::from_slice(&bytes).ok()),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let responses = serde_json::json!({
|
||||||
|
"name": q.name,
|
||||||
|
"starts": event.starts,
|
||||||
|
"starts_ms": starts,
|
||||||
|
"ends_ms": ends,
|
||||||
|
"place": event.place,
|
||||||
|
"page": q.id,
|
||||||
|
});
|
||||||
|
|
||||||
|
let answer = match existing {
|
||||||
|
None => {
|
||||||
|
store_answer(
|
||||||
|
&state.jetstream,
|
||||||
|
&aggregates,
|
||||||
|
EVENTS_BUCKET,
|
||||||
|
id.clone(),
|
||||||
|
&q.id,
|
||||||
|
EVENT_ALTERNATIVE,
|
||||||
|
&responses,
|
||||||
|
now_ms,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(question = %q.id, "event record created");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Some(a) => a,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Content is the source of truth while the window is still
|
||||||
|
// open: a corrected date or place flows into the record, so the
|
||||||
|
// followup fires on the schedule the page actually announces.
|
||||||
|
if answer.state == schema.initial && answer.responses != responses {
|
||||||
|
let mut refreshed = answer.clone();
|
||||||
|
refreshed.responses = responses.clone();
|
||||||
|
if let Some(store) = &store {
|
||||||
|
store.put(&id, serde_json::to_vec(&refreshed)?.into()).await?;
|
||||||
|
tracing::info!(question = %q.id, "event record refreshed from content");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if answer.state == schema.initial && now_ms >= ends {
|
||||||
|
let target = "awaiting_summary";
|
||||||
|
let payload = serde_json::json!({ "to": target, "item": id, "by": "portal" });
|
||||||
|
match crate::aggregates::transition(&state.jetstream, schema, &id, target, payload.clone(), now_ms).await {
|
||||||
|
Ok(_) => {}
|
||||||
|
Err(crate::aggregates::TransitionError::UnknownAggregate) => {
|
||||||
|
crate::aggregates::reseed(&state.jetstream, schema, &id, &answer.state, now_ms)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
crate::aggregates::transition(&state.jetstream, schema, &id, target, payload.clone(), now_ms)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("{e}"))?;
|
||||||
|
}
|
||||||
|
Err(e) => return Err(anyhow::anyhow!("{e}")),
|
||||||
|
}
|
||||||
|
let mut answer = answer;
|
||||||
|
answer.state = target.to_string();
|
||||||
|
answer.decided_ms = Some(now_ms);
|
||||||
|
answer.decided_by = Some("portal".to_string());
|
||||||
|
let store = state.jetstream.get_key_value(EVENTS_BUCKET).await?;
|
||||||
|
store.put(&id, serde_json::to_vec(&answer)?.into()).await?;
|
||||||
|
|
||||||
|
let parent_hashes = vec![id.clone()];
|
||||||
|
let chain_hash = crate::chain::hash_node(&q.id, &parent_hashes, &payload, now_ms);
|
||||||
|
emit_answer_submitted(
|
||||||
|
&state.nats,
|
||||||
|
&AnswerSubmitted {
|
||||||
|
chain_hash,
|
||||||
|
parent_hashes,
|
||||||
|
question_id: q.id.clone(),
|
||||||
|
alternative: SUMMARY_DUE_LABEL.to_string(),
|
||||||
|
responses: payload,
|
||||||
|
timestamp_ms: now_ms,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
tracing::info!(question = %q.id, "event ended - summary due");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::record_id;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn record_id_is_stable_and_flat() {
|
||||||
|
assert_eq!(record_id("/events/opening"), "events-opening");
|
||||||
|
assert_eq!(record_id("/"), "");
|
||||||
|
assert_eq!(record_id("/opening"), "opening");
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -101,7 +101,7 @@ pub struct TransitionItem {
|
|||||||
/// (the shared per-alternative Confirm button). Items are independent
|
/// (the shared per-alternative Confirm button). Items are independent
|
||||||
/// - per-item CAS, no cross-item transaction - so one failure doesn't
|
/// - per-item CAS, no cross-item transaction - so one failure doesn't
|
||||||
/// roll back the others; failures are collected and reported together.
|
/// roll back the others; failures are collected and reported together.
|
||||||
#[server]
|
#[server(endpoint = "transition_answers")]
|
||||||
pub async fn transition_answers(
|
pub async fn transition_answers(
|
||||||
question_id: String,
|
question_id: String,
|
||||||
alternative: String,
|
alternative: String,
|
||||||
@@ -289,7 +289,7 @@ async fn apply_transition(
|
|||||||
/// itself. Deliberately returns the same generic error for "no such
|
/// itself. Deliberately returns the same generic error for "no such
|
||||||
/// item" and "email doesn't match", so an unsubscribe link can't be
|
/// item" and "email doesn't match", so an unsubscribe link can't be
|
||||||
/// used to probe which hashes or emails exist.
|
/// used to probe which hashes or emails exist.
|
||||||
#[server]
|
#[server(endpoint = "self_transition_answer")]
|
||||||
pub async fn self_transition_answer(
|
pub async fn self_transition_answer(
|
||||||
question_id: String,
|
question_id: String,
|
||||||
alternative: String,
|
alternative: String,
|
||||||
|
|||||||
+643
-100
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -19,7 +19,7 @@ pub struct User {
|
|||||||
pub const SESSION_USER_KEY: &str = "user";
|
pub const SESSION_USER_KEY: &str = "user";
|
||||||
|
|
||||||
/// Returns the currently signed-in user, if any.
|
/// Returns the currently signed-in user, if any.
|
||||||
#[server]
|
#[server(endpoint = "current_user")]
|
||||||
pub async fn current_user() -> Result<Option<User>, ServerFnError> {
|
pub async fn current_user() -> Result<Option<User>, ServerFnError> {
|
||||||
let session: tower_sessions::Session = leptos_axum::extract().await?;
|
let session: tower_sessions::Session = leptos_axum::extract().await?;
|
||||||
let user = session
|
let user = session
|
||||||
|
|||||||
+66
-15
@@ -32,12 +32,15 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let (questions, aggregates_map) = if let Some(dir) = path {
|
let (questions, aggregates_map, site) = if let Some(dir) = path {
|
||||||
(load_from_dir(&dir)?, load_aggregates_from_dir(&dir)?)
|
(load_from_dir(&dir)?, load_aggregates_from_dir(&dir)?, load_site_from_dir(&dir)?)
|
||||||
} else if let Some(repo_url) = repo {
|
} else if let Some(repo_url) = repo {
|
||||||
let questions = content::load_questions_from_gitea(&repo_url, &branch, &subdir).await?;
|
let questions = content::load_questions_from_gitea(&repo_url, &branch, &subdir).await?;
|
||||||
let aggregates_map = content::load_aggregates_from_gitea(&repo_url, &branch).await?;
|
let aggregates_map = content::load_aggregates_from_gitea(&repo_url, &branch).await?;
|
||||||
(questions, aggregates_map)
|
// load_site_from_gitea already validates; a missing file is
|
||||||
|
// the default config, same as at portal boot.
|
||||||
|
let site = content::load_site_from_gitea(&repo_url, &branch).await?;
|
||||||
|
(questions, aggregates_map, site)
|
||||||
} else {
|
} else {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"usage: question-lint --repo <gitea-url> [--branch main] [--subdir questions] | --path <local-dir>"
|
"usage: question-lint --repo <gitea-url> [--branch main] [--subdir questions] | --path <local-dir>"
|
||||||
@@ -45,8 +48,25 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
std::process::exit(2);
|
std::process::exit(2);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if let Err(e) = site.validate() {
|
||||||
|
eprintln!("FAIL: {e}");
|
||||||
|
std::process::exit(1);
|
||||||
|
}
|
||||||
|
let aggregates_map = content::with_builtin_aggregates(aggregates_map);
|
||||||
match content::validate_questions(&questions, &aggregates_map) {
|
match content::validate_questions(&questions, &aggregates_map) {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
|
// The runtime's own event desk: a repo announcing pages
|
||||||
|
// (Question.event) should read portal_events somewhere, or
|
||||||
|
// "post what happened" tasks pile up unseen. Warn, don't
|
||||||
|
// fail - the runtime creates the records either way.
|
||||||
|
if questions.values().any(|q| q.event.is_some())
|
||||||
|
&& !content::bucket_is_read(&questions, content::EVENTS_BUCKET)
|
||||||
|
{
|
||||||
|
eprintln!(
|
||||||
|
"WARN: pages carry `event:` but no kv resource reads bucket {:?} - add a desk so summaries get posted",
|
||||||
|
content::EVENTS_BUCKET
|
||||||
|
);
|
||||||
|
}
|
||||||
println!(
|
println!(
|
||||||
"OK: {} question(s), {} aggregate(s) valid",
|
"OK: {} question(s), {} aggregate(s) valid",
|
||||||
questions.len(),
|
questions.len(),
|
||||||
@@ -61,6 +81,22 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The offline counterpart to `content::load_site_from_gitea` -
|
||||||
|
/// `site.yaml` lives at the repo root like `aggregates.yaml`, and is
|
||||||
|
/// just as optional locally: missing means default branding.
|
||||||
|
fn load_site_from_dir(dir: &str) -> anyhow::Result<content::SiteConfig> {
|
||||||
|
let site_path = std::path::Path::new(dir)
|
||||||
|
.parent()
|
||||||
|
.unwrap_or_else(|| std::path::Path::new("."))
|
||||||
|
.join("site.yaml");
|
||||||
|
if !site_path.exists() {
|
||||||
|
return Ok(content::SiteConfig::default());
|
||||||
|
}
|
||||||
|
let raw = std::fs::read_to_string(&site_path)
|
||||||
|
.map_err(|e| anyhow::anyhow!("reading {}: {e}", site_path.display()))?;
|
||||||
|
serde_yaml::from_str(&raw).map_err(|e| anyhow::anyhow!("parsing {}: {e}", site_path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
/// The offline counterpart to `content::load_aggregates_from_gitea` -
|
/// The offline counterpart to `content::load_aggregates_from_gitea` -
|
||||||
/// `aggregates.yaml` lives at the repo root, one level up from the
|
/// `aggregates.yaml` lives at the repo root, one level up from the
|
||||||
/// pages directory `--path` names, so `dir`'s parent is where it's
|
/// pages directory `--path` names, so `dir`'s parent is where it's
|
||||||
@@ -85,23 +121,38 @@ fn load_aggregates_from_dir(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The offline counterpart to `content::load_questions_from_gitea` -
|
/// The offline counterpart to `content::load_questions_from_gitea` -
|
||||||
/// same "every `*.yaml` file becomes a `Question` keyed by its own
|
/// the same recursive tree walk and `content::build_questions`
|
||||||
/// `id`" shape, just reading a local checkout instead of Gitea's API,
|
/// pipeline (derived ids, relative refs, sections, followup
|
||||||
|
/// inference), just reading a local checkout instead of Gitea's API,
|
||||||
/// for linting a branch that hasn't been pushed yet.
|
/// for linting a branch that hasn't been pushed yet.
|
||||||
fn load_from_dir(
|
fn load_from_dir(
|
||||||
dir: &str,
|
dir: &str,
|
||||||
) -> anyhow::Result<std::collections::HashMap<String, content::Question>> {
|
) -> anyhow::Result<std::collections::HashMap<String, content::Question>> {
|
||||||
let mut out = std::collections::HashMap::new();
|
let base = std::path::Path::new(dir);
|
||||||
|
let mut files = Vec::new();
|
||||||
|
collect_yaml(base, base, &mut files)?;
|
||||||
|
content::build_questions(&files)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_yaml(
|
||||||
|
base: &std::path::Path,
|
||||||
|
dir: &std::path::Path,
|
||||||
|
out: &mut Vec<(String, String)>,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
for entry in std::fs::read_dir(dir)? {
|
for entry in std::fs::read_dir(dir)? {
|
||||||
let entry = entry?;
|
let path = entry?.path();
|
||||||
let path = entry.path();
|
if path.is_dir() {
|
||||||
if path.extension().and_then(|e| e.to_str()) != Some("yaml") {
|
collect_yaml(base, &path, out)?;
|
||||||
continue;
|
} else if path.extension().and_then(|e| e.to_str()) == Some("yaml") {
|
||||||
|
let rel = path
|
||||||
|
.strip_prefix(base)
|
||||||
|
.expect("walked paths sit under their base")
|
||||||
|
.to_string_lossy()
|
||||||
|
.replace('\\', "/");
|
||||||
|
let raw = std::fs::read_to_string(&path)
|
||||||
|
.map_err(|e| anyhow::anyhow!("reading {}: {e}", path.display()))?;
|
||||||
|
out.push((rel, raw));
|
||||||
}
|
}
|
||||||
let raw = std::fs::read_to_string(&path)?;
|
|
||||||
let question: content::Question = serde_yaml::from_str(&raw)
|
|
||||||
.map_err(|e| anyhow::anyhow!("parsing {}: {e}", path.display()))?;
|
|
||||||
out.insert(question.id.clone(), question);
|
|
||||||
}
|
}
|
||||||
Ok(out)
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,60 @@ use sha2::{Digest, Sha256};
|
|||||||
/// submitted responses, and a timestamp. Parents are sorted first so the
|
/// submitted responses, and a timestamp. Parents are sorted first so the
|
||||||
/// hash doesn't depend on the order multiple parents happened to arrive
|
/// hash doesn't depend on the order multiple parents happened to arrive
|
||||||
/// in.
|
/// in.
|
||||||
|
/// Where submitted chain nodes are indexed - hash → which question was
|
||||||
|
/// answered. Small on purpose (no responses), and shared by every
|
||||||
|
/// portal instance on the JetStream (hashes are globally unique, so
|
||||||
|
/// cross-site collisions can't happen). This is what lets
|
||||||
|
/// `requires_chain` pages verify a visitor's `?chain=` actually ends
|
||||||
|
/// at the question they claim to have answered.
|
||||||
|
pub const CHAIN_BUCKET: &str = "portal_chains";
|
||||||
|
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct ChainNode {
|
||||||
|
pub question_id: String,
|
||||||
|
pub timestamp_ms: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Indexes one submitted node. Best-effort by design (the caller logs
|
||||||
|
/// and continues): the NATS event is the durable record, this is a
|
||||||
|
/// lookup convenience.
|
||||||
|
pub async fn record_node(
|
||||||
|
js: &async_nats::jetstream::Context,
|
||||||
|
chain_hash: &str,
|
||||||
|
question_id: &str,
|
||||||
|
timestamp_ms: i64,
|
||||||
|
) -> anyhow::Result<()> {
|
||||||
|
let store = match js.get_key_value(CHAIN_BUCKET).await {
|
||||||
|
Ok(store) => store,
|
||||||
|
Err(_) => {
|
||||||
|
js.create_key_value(async_nats::jetstream::kv::Config {
|
||||||
|
bucket: CHAIN_BUCKET.to_string(),
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let node = ChainNode {
|
||||||
|
question_id: question_id.to_string(),
|
||||||
|
timestamp_ms,
|
||||||
|
};
|
||||||
|
store.put(chain_hash, serde_json::to_vec(&node)?.into()).await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Looks a chain hash up - `None` covers both "no such node" and
|
||||||
|
/// "bucket not created yet" (no submissions anywhere), which read the
|
||||||
|
/// same to a `requires_chain` check: the claimed lineage can't be
|
||||||
|
/// verified, so the gate stays shut.
|
||||||
|
pub async fn lookup_node(
|
||||||
|
js: &async_nats::jetstream::Context,
|
||||||
|
chain_hash: &str,
|
||||||
|
) -> Option<ChainNode> {
|
||||||
|
let store = js.get_key_value(CHAIN_BUCKET).await.ok()?;
|
||||||
|
let bytes = store.get(chain_hash).await.ok()??;
|
||||||
|
serde_json::from_slice(&bytes).ok()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn hash_node(
|
pub fn hash_node(
|
||||||
question_id: &str,
|
question_id: &str,
|
||||||
parent_hashes: &[String],
|
parent_hashes: &[String],
|
||||||
|
|||||||
+1292
-39
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,9 @@ pub mod resource;
|
|||||||
#[cfg(feature = "ssr")]
|
#[cfg(feature = "ssr")]
|
||||||
pub mod aggregates;
|
pub mod aggregates;
|
||||||
|
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub mod announce;
|
||||||
|
|
||||||
#[cfg(feature = "ssr")]
|
#[cfg(feature = "ssr")]
|
||||||
pub mod server;
|
pub mod server;
|
||||||
|
|
||||||
|
|||||||
+33
-3
@@ -29,12 +29,17 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
.unwrap_or_else(|_| "https://project.uhhm.no/uhhm/questions".to_string());
|
.unwrap_or_else(|_| "https://project.uhhm.no/uhhm/questions".to_string());
|
||||||
let content_branch = std::env::var("CONTENT_BRANCH").unwrap_or_else(|_| "main".to_string());
|
let content_branch = std::env::var("CONTENT_BRANCH").unwrap_or_else(|_| "main".to_string());
|
||||||
let gitea_base = content::gitea_api_base(&content_repo)?;
|
let gitea_base = content::gitea_api_base(&content_repo)?;
|
||||||
let aggregates = content::load_aggregates_from_gitea(&content_repo, &content_branch).await?;
|
let content_raw_base = content::gitea_raw_base(&content_repo)?;
|
||||||
|
let aggregates = content::with_builtin_aggregates(
|
||||||
|
content::load_aggregates_from_gitea(&content_repo, &content_branch).await?,
|
||||||
|
);
|
||||||
let questions = content::load_questions_from_gitea(&content_repo, &content_branch, "questions").await?;
|
let questions = content::load_questions_from_gitea(&content_repo, &content_branch, "questions").await?;
|
||||||
content::validate_questions(&questions, &aggregates)?;
|
content::validate_questions(&questions, &aggregates)?;
|
||||||
|
let site = content::load_site_from_gitea(&content_repo, &content_branch).await?;
|
||||||
tracing::info!(count = questions.len(), repo = %content_repo, branch = %content_branch, "loaded content");
|
tracing::info!(count = questions.len(), repo = %content_repo, branch = %content_branch, "loaded content");
|
||||||
let questions = Arc::new(arc_swap::ArcSwap::from_pointee(questions));
|
let questions = Arc::new(arc_swap::ArcSwap::from_pointee(questions));
|
||||||
let aggregates = Arc::new(arc_swap::ArcSwap::from_pointee(aggregates));
|
let aggregates = Arc::new(arc_swap::ArcSwap::from_pointee(aggregates));
|
||||||
|
let site = Arc::new(arc_swap::ArcSwap::from_pointee(site));
|
||||||
|
|
||||||
let nats_url =
|
let nats_url =
|
||||||
std::env::var("NATS_URL").unwrap_or_else(|_| "nats://127.0.0.1:4222".to_string());
|
std::env::var("NATS_URL").unwrap_or_else(|_| "nats://127.0.0.1:4222".to_string());
|
||||||
@@ -65,10 +70,11 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
tokio::spawn(content::watch_for_reload(
|
tokio::spawn(content::watch_for_reload(
|
||||||
nats.clone(),
|
nats.clone(),
|
||||||
content_repo,
|
content_repo,
|
||||||
content_branch,
|
content_branch.clone(),
|
||||||
"questions".to_string(),
|
"questions".to_string(),
|
||||||
questions.clone(),
|
questions.clone(),
|
||||||
aggregates.clone(),
|
aggregates.clone(),
|
||||||
|
site.clone(),
|
||||||
));
|
));
|
||||||
|
|
||||||
let state = AppState {
|
let state = AppState {
|
||||||
@@ -77,11 +83,18 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
jetstream,
|
jetstream,
|
||||||
questions,
|
questions,
|
||||||
aggregates,
|
aggregates,
|
||||||
|
site,
|
||||||
gitea_base,
|
gitea_base,
|
||||||
|
content_raw_base,
|
||||||
|
content_branch: content_branch.clone(),
|
||||||
oidc: oidc_state,
|
oidc: oidc_state,
|
||||||
garage,
|
garage,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Announced pages: keep their desk records current, close ended
|
||||||
|
// windows (see announce.rs).
|
||||||
|
tokio::spawn(portal::announce::run(state.clone()));
|
||||||
|
|
||||||
// Dev-friendly defaults: in-memory sessions, secure cookies only when
|
// Dev-friendly defaults: in-memory sessions, secure cookies only when
|
||||||
// COOKIE_SECURE=true (set it behind TLS in production) - same
|
// COOKIE_SECURE=true (set it behind TLS in production) - same
|
||||||
// defaults cnats uses. SameSite=Lax (tower-sessions defaults to
|
// defaults cnats uses. SameSite=Lax (tower-sessions defaults to
|
||||||
@@ -134,8 +147,25 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
.route("/api/{*fn_name}", any(server_fn_handler))
|
.route("/api/{*fn_name}", any(server_fn_handler))
|
||||||
.route("/upload", post(upload::upload))
|
.route("/upload", post(upload::upload))
|
||||||
.route("/gitea-repo", get(content::gitea_repo_handler))
|
.route("/gitea-repo", get(content::gitea_repo_handler))
|
||||||
|
// Content-shipped assets (hero module etc.), same-origin.
|
||||||
|
.route("/site/{*path}", get(content::site_asset_handler))
|
||||||
.route("/automation/kv/{bucket}", get(content::automation_kv_handler))
|
.route("/automation/kv/{bucket}", get(content::automation_kv_handler))
|
||||||
.nest_service("/pkg", ServeDir::new(pkg_dir))
|
// no-cache = "revalidate before reuse", not "don't cache":
|
||||||
|
// pkg files keep the same names across releases (portal.js,
|
||||||
|
// portal.wasm), and without this browsers heuristically cache
|
||||||
|
// them - a stale wasm from the previous release then talks to
|
||||||
|
// a server whose server-fn wire format has moved on and every
|
||||||
|
// page renders as its error branch. A 304 per load is the
|
||||||
|
// price of never shipping that skew again.
|
||||||
|
.nest_service(
|
||||||
|
"/pkg",
|
||||||
|
tower::ServiceBuilder::new()
|
||||||
|
.layer(tower_http::set_header::SetResponseHeaderLayer::overriding(
|
||||||
|
axum::http::header::CACHE_CONTROL,
|
||||||
|
axum::http::HeaderValue::from_static("no-cache"),
|
||||||
|
))
|
||||||
|
.service(ServeDir::new(pkg_dir)),
|
||||||
|
)
|
||||||
.nest_service("/fonts", ServeDir::new(fonts_dir))
|
.nest_service("/fonts", ServeDir::new(fonts_dir))
|
||||||
.route_service("/favicon-light.svg", ServeFile::new(favicon_light_path))
|
.route_service("/favicon-light.svg", ServeFile::new(favicon_light_path))
|
||||||
.route_service("/favicon-dark.svg", ServeFile::new(favicon_dark_path))
|
.route_service("/favicon-dark.svg", ServeFile::new(favicon_dark_path))
|
||||||
|
|||||||
+90
-23
@@ -16,7 +16,7 @@ use leptos::prelude::*;
|
|||||||
/// fetch (`GiteaStarred`/`GiteaOrgRepos`/`Url`), the mechanism behind
|
/// fetch (`GiteaStarred`/`GiteaOrgRepos`/`Url`), the mechanism behind
|
||||||
/// "a resource parameterized by other form fields"; a `Kv` resource
|
/// "a resource parameterized by other form fields"; a `Kv` resource
|
||||||
/// ignores them entirely, same as today.
|
/// ignores them entirely, same as today.
|
||||||
#[server]
|
#[server(endpoint = "get_resource")]
|
||||||
pub async fn get_resource(
|
pub async fn get_resource(
|
||||||
question_id: String,
|
question_id: String,
|
||||||
alternative: String,
|
alternative: String,
|
||||||
@@ -49,7 +49,7 @@ pub async fn get_resource(
|
|||||||
/// of whether it's displayed read-only or offered as choices to pick
|
/// of whether it's displayed read-only or offered as choices to pick
|
||||||
/// from, so this deliberately doesn't duplicate the source-dispatch or
|
/// from, so this deliberately doesn't duplicate the source-dispatch or
|
||||||
/// jq-shaping logic - see `fetch_resource_value`.
|
/// jq-shaping logic - see `fetch_resource_value`.
|
||||||
#[server]
|
#[server(endpoint = "get_requirement_options")]
|
||||||
pub async fn get_requirement_options(
|
pub async fn get_requirement_options(
|
||||||
question_id: String,
|
question_id: String,
|
||||||
alternative: String,
|
alternative: String,
|
||||||
@@ -80,7 +80,7 @@ pub async fn get_requirement_options(
|
|||||||
/// `get_requirement_options`: fetches the resource a bound field
|
/// `get_requirement_options`: fetches the resource a bound field
|
||||||
/// loads its value from, parameterized by the watched sibling's value
|
/// loads its value from, parameterized by the watched sibling's value
|
||||||
/// (already inside `params`, keyed by the bind's param name).
|
/// (already inside `params`, keyed by the bind's param name).
|
||||||
#[server]
|
#[server(endpoint = "get_requirement_binding")]
|
||||||
pub async fn get_requirement_binding(
|
pub async fn get_requirement_binding(
|
||||||
question_id: String,
|
question_id: String,
|
||||||
alternative: String,
|
alternative: String,
|
||||||
@@ -122,11 +122,12 @@ fn find_feature(
|
|||||||
alternative: &str,
|
alternative: &str,
|
||||||
feature_name: &str,
|
feature_name: &str,
|
||||||
) -> Result<crate::content::Feature, ServerFnError> {
|
) -> Result<crate::content::Feature, ServerFnError> {
|
||||||
let question = state
|
// resolve_question, not a plain map get: a dynamic page's client
|
||||||
.questions
|
// holds its concrete path as the question id, and resolution is
|
||||||
.load()
|
// also what substitutes the URL segment into the page's resource
|
||||||
.get(question_id)
|
// keys - so this lookup is where a `/review/<record>` page's
|
||||||
.cloned()
|
// feature acquires its record-specific key.
|
||||||
|
let question = crate::content::resolve_question(&state.questions.load(), question_id)
|
||||||
.ok_or_else(|| ServerFnError::new("unknown question"))?;
|
.ok_or_else(|| ServerFnError::new("unknown question"))?;
|
||||||
question
|
question
|
||||||
.alternatives
|
.alternatives
|
||||||
@@ -220,6 +221,10 @@ async fn fetch_resource_value(
|
|||||||
ResourceSource::GiteaOrgRepos { org } => {
|
ResourceSource::GiteaOrgRepos { org } => {
|
||||||
fetch_gitea_json(state, &format!("/api/v1/orgs/{org}/repos"), params).await?
|
fetch_gitea_json(state, &format!("/api/v1/orgs/{org}/repos"), params).await?
|
||||||
}
|
}
|
||||||
|
ResourceSource::GiteaReleases { owner, repo } => {
|
||||||
|
fetch_gitea_json(state, &format!("/api/v1/repos/{owner}/{repo}/releases"), params)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
ResourceSource::Url { url } => fetch_url_json(url, params).await?,
|
ResourceSource::Url { url } => fetch_url_json(url, params).await?,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -442,10 +447,14 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
/// A canned, Gitea-API-shaped fixture - the same fields the real
|
/// A canned, Gitea-API-shaped fixture - the same fields the real
|
||||||
/// `/users/{username}/starred` endpoint returns - run through the
|
/// `/users/{username}/starred` endpoint returns (Gitea 1.27:
|
||||||
|
/// `stars_count`, not GitHub's `stargazers_count`; `website` is ""
|
||||||
|
/// when the repo's Website setting is empty) - run through the
|
||||||
/// filter `index.yaml`'s "What we've built" resource actually
|
/// filter `index.yaml`'s "What we've built" resource actually
|
||||||
/// declares, confirming the `jaq` integration produces the shape
|
/// declares, confirming the `jaq` integration produces the shape
|
||||||
/// the frontend showcase card expects.
|
/// the frontend showcase card expects: the Website setting wins
|
||||||
|
/// over the repo url, and a private repo without one gets a null
|
||||||
|
/// url (unlinked card) instead of a link that 404s for visitors.
|
||||||
#[test]
|
#[test]
|
||||||
fn jq_shapes_gitea_repo_list_for_the_showcase() {
|
fn jq_shapes_gitea_repo_list_for_the_showcase() {
|
||||||
let input = serde_json::json!([
|
let input = serde_json::json!([
|
||||||
@@ -453,28 +462,86 @@ mod tests {
|
|||||||
"name": "cnats",
|
"name": "cnats",
|
||||||
"description": "A NATS-backed chat client",
|
"description": "A NATS-backed chat client",
|
||||||
"html_url": "https://project.uhhm.no/bl/cnats",
|
"html_url": "https://project.uhhm.no/bl/cnats",
|
||||||
"stargazers_count": 3,
|
"website": "",
|
||||||
|
"stars_count": 3,
|
||||||
"private": false
|
"private": false
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "portal",
|
"name": "secret-product",
|
||||||
"description": "This app",
|
"description": "Private repo advertised via its homepage",
|
||||||
"html_url": "https://project.uhhm.no/uhhm/portal",
|
"html_url": "https://project.uhhm.no/uhhm/secret-product",
|
||||||
"stargazers_count": 1,
|
"website": "https://secret-product.example",
|
||||||
"private": false
|
"stars_count": 2,
|
||||||
|
"private": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "internal-tool",
|
||||||
|
"description": "Private repo with no homepage",
|
||||||
|
"html_url": "https://project.uhhm.no/uhhm/internal-tool",
|
||||||
|
"website": "",
|
||||||
|
"stars_count": 1,
|
||||||
|
"private": true
|
||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
let filter = ".[] | {name: .name, description: .description, url: .html_url, stars: .stargazers_count}";
|
let filter = r#".[] | {name: .name, description: .description,
|
||||||
|
stars: .stars_count,
|
||||||
|
url: (if .website != null and .website != "" then .website
|
||||||
|
elif .private then null
|
||||||
|
else .html_url end)}"#;
|
||||||
|
|
||||||
|
let shaped = apply_jq(filter, &input).expect("filter runs");
|
||||||
|
let items = shaped.as_array().expect("array output");
|
||||||
|
assert_eq!(items.len(), 3);
|
||||||
|
// Public without a website still links to the repo.
|
||||||
|
assert_eq!(items[0]["name"], "cnats");
|
||||||
|
assert_eq!(items[0]["url"], "https://project.uhhm.no/bl/cnats");
|
||||||
|
assert_eq!(items[0]["stars"], 3);
|
||||||
|
// Private with a website links there, never to the repo.
|
||||||
|
assert_eq!(items[1]["url"], "https://secret-product.example");
|
||||||
|
// Private without a website gets no link at all.
|
||||||
|
assert_eq!(items[2]["url"], serde_json::Value::Null);
|
||||||
|
// The filter never mentions `private` - confirms shaping
|
||||||
|
// actually drops fields, not just passes the object through.
|
||||||
|
assert!(items[0].get("private").is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gitea-1.27-shaped release fixtures through the filter
|
||||||
|
/// redoal/questions' "Our Composition" feature declares. While the
|
||||||
|
/// repo is private the filter pins `url: null` - a private
|
||||||
|
/// release's html_url 404s for anonymous visitors, so the card
|
||||||
|
/// must render an unlinked heading instead.
|
||||||
|
#[test]
|
||||||
|
fn jq_shapes_gitea_release_list_for_redoal() {
|
||||||
|
let input = serde_json::json!([
|
||||||
|
{
|
||||||
|
"name": "varde bring-up",
|
||||||
|
"tag_name": "v0.3.0",
|
||||||
|
"body": "Embedded varde-core on iOS.",
|
||||||
|
"published_at": "2026-08-16T09:00:00Z",
|
||||||
|
"html_url": "https://project.uhhm.no/redoal/redoal/releases/tag/v0.3.0",
|
||||||
|
"draft": false,
|
||||||
|
"prerelease": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "first echo",
|
||||||
|
"tag_name": "v0.1.0",
|
||||||
|
"body": "Gesture keys round-trip.",
|
||||||
|
"published_at": "2026-05-01T09:00:00Z",
|
||||||
|
"html_url": "https://project.uhhm.no/redoal/redoal/releases/tag/v0.1.0",
|
||||||
|
"draft": false,
|
||||||
|
"prerelease": false
|
||||||
|
}
|
||||||
|
]);
|
||||||
|
let filter = ".[] | {name: .name, description: .body, tag: .tag_name, published: .published_at, url: null}";
|
||||||
|
|
||||||
let shaped = apply_jq(filter, &input).expect("filter runs");
|
let shaped = apply_jq(filter, &input).expect("filter runs");
|
||||||
let items = shaped.as_array().expect("array output");
|
let items = shaped.as_array().expect("array output");
|
||||||
assert_eq!(items.len(), 2);
|
assert_eq!(items.len(), 2);
|
||||||
assert_eq!(items[0]["name"], "cnats");
|
assert_eq!(items[0]["name"], "varde bring-up");
|
||||||
assert_eq!(items[0]["url"], "https://project.uhhm.no/bl/cnats");
|
assert_eq!(items[0]["tag"], "v0.3.0");
|
||||||
assert_eq!(items[0]["stars"], 3);
|
assert_eq!(items[0]["description"], "Embedded varde-core on iOS.");
|
||||||
// The filter never mentions `private` - confirms shaping
|
assert_eq!(items[0]["url"], serde_json::Value::Null, "no public link while private");
|
||||||
// actually drops fields, not just passes the object through.
|
assert!(items[0].get("html_url").is_none());
|
||||||
assert!(items[0].get("private").is_none());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -28,11 +28,20 @@ pub struct AppState {
|
|||||||
/// with no entry here isn't event-sourced - plain KV mutate-in-place
|
/// with no entry here isn't event-sourced - plain KV mutate-in-place
|
||||||
/// still works (see `answers.rs`).
|
/// still works (see `answers.rs`).
|
||||||
pub aggregates: Arc<ArcSwap<HashMap<String, crate::aggregates::AggregateSchema>>>,
|
pub aggregates: Arc<ArcSwap<HashMap<String, crate::aggregates::AggregateSchema>>>,
|
||||||
|
/// Site branding from the content repo's optional `site.yaml`
|
||||||
|
/// (title, wordmark, hero kind) - hot-swapped with `questions`/
|
||||||
|
/// `aggregates` on the same reload. Default = the historical uhhm
|
||||||
|
/// look.
|
||||||
|
pub site: Arc<ArcSwap<crate::content::SiteConfig>>,
|
||||||
/// `scheme://host` of the Gitea instance content is loaded from
|
/// `scheme://host` of the Gitea instance content is loaded from
|
||||||
/// (see `content::gitea_api_base`) - kept alongside `questions`
|
/// (see `content::gitea_api_base`) - kept alongside `questions`
|
||||||
/// rather than re-derived per call, since `resolve_gitea_repo` needs
|
/// rather than re-derived per call, since `resolve_gitea_repo` needs
|
||||||
/// it too and has no other reason to see `CONTENT_REPO` itself.
|
/// it too and has no other reason to see `CONTENT_REPO` itself.
|
||||||
pub gitea_base: String,
|
pub gitea_base: String,
|
||||||
|
/// `{gitea}/api/v1/repos/{owner}/{repo}/raw` and the branch - what
|
||||||
|
/// `content::site_asset_handler` proxies content-shipped assets from.
|
||||||
|
pub content_raw_base: String,
|
||||||
|
pub content_branch: String,
|
||||||
pub oidc: Arc<oidc::Oidc>,
|
pub oidc: Arc<oidc::Oidc>,
|
||||||
/// `None` when `GARAGE_*` env vars aren't set - uploads are the one
|
/// `None` when `GARAGE_*` env vars aren't set - uploads are the one
|
||||||
/// optional feature, everything else works without Garage.
|
/// optional feature, everything else works without Garage.
|
||||||
|
|||||||
+404
-99
@@ -47,20 +47,67 @@
|
|||||||
--accent-soft: rgba(142, 194, 192, 0.16);
|
--accent-soft: rgba(142, 194, 192, 0.16);
|
||||||
|
|
||||||
--paper: #0a0a0a;
|
--paper: #0a0a0a;
|
||||||
--paper-raised: #161616;
|
|
||||||
--ink: #ededed;
|
--ink: #ededed;
|
||||||
--ink-dim: #9a9a9a;
|
--ink-dim: #9a9a9a;
|
||||||
--line: #2a2a2a;
|
--line: #2a2a2a;
|
||||||
|
|
||||||
|
/* Cards float over a sticky hero piece - translucent so the piece
|
||||||
|
reads faintly through them (paired with backdrop-filter on
|
||||||
|
.alt-card), shadowed so their edge against the animated backdrop
|
||||||
|
is a soft lift rather than a hard contrast line. */
|
||||||
|
--card-bg: rgba(22, 22, 22, 0.35);
|
||||||
|
--card-bg-opaque: rgba(22, 22, 22, 0.84);
|
||||||
|
--card-shadow: rgba(0, 0, 0, 0.5);
|
||||||
|
|
||||||
|
--error: #ff6b6b;
|
||||||
|
/* Behind .hero-copy: dark halo on dark stock, paper halo on light. */
|
||||||
|
--hero-glow: rgba(0, 0, 0, 0.8);
|
||||||
|
|
||||||
--heading: "Quicksand", var(--sans);
|
--heading: "Quicksand", var(--sans);
|
||||||
--sans: -apple-system, "SF Pro Text", ui-sans-serif, "Segoe UI", system-ui, sans-serif;
|
--sans: -apple-system, "SF Pro Text", ui-sans-serif, "Segoe UI", system-ui, sans-serif;
|
||||||
|
|
||||||
--radius: 1.1rem;
|
--radius: 1.1rem;
|
||||||
|
|
||||||
|
/* The single place absolute units are allowed: this IS the base every
|
||||||
|
other length derives from (rem/em everywhere else - px is banned in
|
||||||
|
stylesheets). First line is the fallback for engines without lvmin. */
|
||||||
font-size: 17px;
|
font-size: 17px;
|
||||||
font-size: max(12px, calc(2.1lvmin + 3pt));
|
font-size: max(12px, calc(2.1lvmin + 3pt));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Light theme: the same muted-press idea on white stock - warm paper,
|
||||||
|
near-black ink, and the accent deepened from dusty cyan to a teal
|
||||||
|
ink that actually carries as text on light paper (the dark theme's
|
||||||
|
#8ec2c0 washes out there). Canvas-drawing modules (gesture.js, and
|
||||||
|
content-shipped hero modules) mirror this palette on their own,
|
||||||
|
since canvas paint can't read CSS vars. */
|
||||||
|
@media (prefers-color-scheme: light) {
|
||||||
|
:root {
|
||||||
|
--accent: #47807e;
|
||||||
|
--accent-soft: rgba(71, 128, 126, 0.16);
|
||||||
|
|
||||||
|
--paper: #f6f5f1;
|
||||||
|
--ink: #1d1d1b;
|
||||||
|
--ink-dim: #6d6c66;
|
||||||
|
--line: #d9d7cf;
|
||||||
|
|
||||||
|
--card-bg: rgba(252, 251, 248, 0.35);
|
||||||
|
--card-bg-opaque: rgba(252, 251, 248, 0.84);
|
||||||
|
--card-shadow: rgba(50, 48, 42, 0.18);
|
||||||
|
|
||||||
|
--error: #a83a32;
|
||||||
|
--hero-glow: rgba(246, 245, 241, 0.85);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The wordmark SVG is a hardcoded white stroke (also used raw in
|
||||||
|
dark contexts elsewhere) - flip it to ink here rather than fork
|
||||||
|
the asset. */
|
||||||
|
.wordmark img {
|
||||||
|
filter: invert(0.92);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
* {
|
* {
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
@@ -112,7 +159,7 @@ main.not-found {
|
|||||||
/* hero */
|
/* hero */
|
||||||
|
|
||||||
.hero {
|
.hero {
|
||||||
max-width: 780px;
|
max-width: 46rem;
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
padding: 4rem 1.5rem 2.5rem;
|
padding: 4rem 1.5rem 2.5rem;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -148,80 +195,75 @@ main.not-found {
|
|||||||
max-width: 46ch;
|
max-width: 46ch;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* the actual "YES - Rasterized Lines" piece live at uhhm.no (see
|
/* A content-shipped hero module (site.yaml hero.kind: module) draws
|
||||||
public/yes.js) - landing page only. Full-viewport so it's a real
|
into .hero-piece; the module owns its look (it may restyle .hero
|
||||||
moment, not a thumbnail; hero-copy overlays near the bottom rather
|
itself). Portal only reserves the box so the copy doesn't jump when
|
||||||
than interrupting the canvas. */
|
the module mounts - plain-vh fallback first, as everywhere. */
|
||||||
|
.hero-module .hero-piece {
|
||||||
.hero-yes {
|
|
||||||
position: relative;
|
position: relative;
|
||||||
max-width: none;
|
|
||||||
width: 100%;
|
width: 100%;
|
||||||
/* svh here is only the pre-JS/no-JS fallback (and first paint before
|
min-height: 55vh;
|
||||||
yes.js's constructor runs). Once yes.js mounts, it overwrites this
|
min-height: 55svh;
|
||||||
with an inline `height: <px>` frozen from a single measurement -
|
|
||||||
see setupCanvas()'s comment in yes.js for why: on real mobile
|
|
||||||
Safari, content bottom-aligned inside this box kept sliding down
|
|
||||||
as the address bar collapsed even with a spec'd-stable viewport
|
|
||||||
unit here, so the box's actual height can't be trusted to stay
|
|
||||||
put on that unit alone. An inline style set from JS always wins
|
|
||||||
the cascade over this rule, so that frozen number is what
|
|
||||||
actually governs once the page is interactive.
|
|
||||||
Plain-vh fallback declared first - an engine without svh support
|
|
||||||
ignores the invalid second line rather than falling through to
|
|
||||||
auto height, which would collapse this to the height of its
|
|
||||||
in-flow content and clip the canvas via overflow:hidden below. */
|
|
||||||
height: 100vh;
|
|
||||||
height: 100svh;
|
|
||||||
padding: 0;
|
|
||||||
justify-content: flex-end;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.hero-canvas {
|
/* announcements - live event pages, a strip above the hero copy.
|
||||||
position: absolute;
|
Header, not footer: the one place a page claims attention before
|
||||||
inset: 0;
|
the question is asked. */
|
||||||
}
|
.announce {
|
||||||
|
width: 100%;
|
||||||
.hero-canvas canvas {
|
display: flex;
|
||||||
position: absolute;
|
flex-wrap: wrap;
|
||||||
top: 0;
|
justify-content: center;
|
||||||
left: 0;
|
gap: 0.6rem 1.2rem;
|
||||||
cursor: pointer;
|
margin: -2rem 0 0.5rem;
|
||||||
}
|
font-size: 0.88rem;
|
||||||
|
|
||||||
.hero-canvas #rasterCanvas {
|
|
||||||
mix-blend-mode: overlay;
|
|
||||||
opacity: 0.5;
|
|
||||||
}
|
|
||||||
|
|
||||||
.hero-yes .hero-copy {
|
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
padding: 0 1.5rem 3.5rem;
|
|
||||||
gap: 0.6rem;
|
|
||||||
text-shadow: 0 2px 24px rgba(0, 0, 0, 0.8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Softens the otherwise hard cut where the full-bleed canvas meets the
|
.announce-item {
|
||||||
page background right below it - fades to the same --paper color
|
display: inline-flex;
|
||||||
over the last few ems instead of stopping dead. Non-interactive so
|
flex-wrap: wrap;
|
||||||
it never steals clicks meant for the canvas underneath. */
|
align-items: baseline;
|
||||||
.hero-yes::after {
|
gap: 0.35rem 0.7rem;
|
||||||
content: "";
|
padding: 0.45rem 0.9rem;
|
||||||
position: absolute;
|
border: 0.06rem solid var(--line);
|
||||||
left: 0;
|
border-left: 0.2rem solid var(--accent);
|
||||||
right: 0;
|
border-radius: 0.3rem;
|
||||||
bottom: 0;
|
color: var(--ink);
|
||||||
height: 8rem;
|
text-decoration: none;
|
||||||
background: linear-gradient(to bottom, transparent, var(--paper));
|
background: var(--paper);
|
||||||
pointer-events: none;
|
transition: border-color 120ms;
|
||||||
z-index: 1;
|
}
|
||||||
|
|
||||||
|
.announce-item:hover,
|
||||||
|
.announce-item[aria-current="page"] {
|
||||||
|
border-color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.announce-name {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.announce-when {
|
||||||
|
color: var(--ink-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.announce-relative {
|
||||||
|
color: var(--accent);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
font-size: 0.72rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* alternatives */
|
/* alternatives */
|
||||||
|
|
||||||
|
/* position + z-index on these three: everything that scrolls over the
|
||||||
|
sticky canvas must be a positioned box above the hero's z-index 0,
|
||||||
|
or the (positioned) hero would paint over it. */
|
||||||
.alternatives {
|
.alternatives {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
max-width: 75ch;
|
max-width: 75ch;
|
||||||
margin: 0 auto 5rem;
|
margin: 0 auto 5rem;
|
||||||
padding: 0 1.5rem;
|
padding: 0 1.5rem;
|
||||||
@@ -229,7 +271,13 @@ main.not-found {
|
|||||||
gap: 1.25rem;
|
gap: 1.25rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 700px) {
|
.question-nav,
|
||||||
|
.question-responsible {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 43.75rem) {
|
||||||
.alternatives {
|
.alternatives {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
gap: 3.5rem;
|
gap: 3.5rem;
|
||||||
@@ -263,7 +311,7 @@ main.not-found {
|
|||||||
.question-nav a {
|
.question-nav a {
|
||||||
color: var(--ink-dim);
|
color: var(--ink-dim);
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
border-bottom: 1px solid var(--line);
|
border-bottom: 0.06rem solid var(--line);
|
||||||
}
|
}
|
||||||
|
|
||||||
.question-nav a:hover {
|
.question-nav a:hover {
|
||||||
@@ -292,10 +340,25 @@ main.not-found {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.alt-card {
|
.alt-card {
|
||||||
background: var(--paper-raised);
|
background: var(--card-bg);
|
||||||
border: 1px solid var(--line);
|
/* Frosted glass over the animated canvas behind: the blur is what
|
||||||
|
keeps text on a translucent card readable while the piece still
|
||||||
|
reads through it in color and motion. */
|
||||||
|
-webkit-backdrop-filter: blur(0.8rem);
|
||||||
|
backdrop-filter: blur(0.8rem);
|
||||||
|
border: 0.06rem solid var(--line);
|
||||||
border-radius: var(--radius);
|
border-radius: var(--radius);
|
||||||
padding: 1.75rem 1.9rem;
|
padding: 1.75rem 1.9rem;
|
||||||
|
box-shadow: 0 1.1rem 2.4rem var(--card-shadow);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Without backdrop blur, 0.55-alpha cards put text straight over the
|
||||||
|
moving canvas - illegible. Engines lacking the filter get a
|
||||||
|
near-opaque card instead. */
|
||||||
|
@supports not ((backdrop-filter: blur(1rem)) or (-webkit-backdrop-filter: blur(1rem))) {
|
||||||
|
.alt-card {
|
||||||
|
background: var(--card-bg-opaque);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.alt-image {
|
.alt-image {
|
||||||
@@ -363,14 +426,13 @@ main.not-found {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.feature {
|
.feature {
|
||||||
border-left: 3px solid var(--feature-accent, transparent);
|
border-left: 0.18rem solid var(--feature-accent, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
.feature-icon {
|
.feature-icon {
|
||||||
float: left;
|
|
||||||
width: 1.3rem;
|
width: 1.3rem;
|
||||||
height: 1.3rem;
|
height: 1.3rem;
|
||||||
margin: 0.1rem 0.6rem 0.4rem 0;
|
margin-top: 0.1rem;
|
||||||
background-color: var(--feature-accent, currentColor);
|
background-color: var(--feature-accent, currentColor);
|
||||||
mask-repeat: no-repeat;
|
mask-repeat: no-repeat;
|
||||||
mask-size: contain;
|
mask-size: contain;
|
||||||
@@ -380,11 +442,117 @@ main.not-found {
|
|||||||
-webkit-mask-position: center;
|
-webkit-mask-position: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* With an icon the feature is two columns: the icon in the first,
|
||||||
|
everything else - name, description, fields, resources - in the
|
||||||
|
second, so every line of text shares one left edge instead of
|
||||||
|
wrapping back under the icon. */
|
||||||
|
.feature:has(> .feature-icon) {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1.3rem minmax(0, 1fr);
|
||||||
|
column-gap: 0.7rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.feature:has(> .feature-icon) > .feature-icon {
|
||||||
|
grid-column: 1;
|
||||||
|
grid-row: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.feature:has(> .feature-icon) > :not(.feature-icon) {
|
||||||
|
grid-column: 2;
|
||||||
|
}
|
||||||
|
|
||||||
.feature h3 {
|
.feature h3 {
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
margin-bottom: 0.15em;
|
margin-bottom: 0.15em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* voice field (voice.js): a record button, a status line, a preview */
|
||||||
|
.voice-wrap {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.6rem 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.voice-button {
|
||||||
|
font: inherit;
|
||||||
|
padding: 0.55rem 1.1rem;
|
||||||
|
border: 0.06rem solid var(--accent);
|
||||||
|
border-radius: 2rem;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--ink);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.voice-button:hover:not(:disabled) {
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--paper);
|
||||||
|
}
|
||||||
|
|
||||||
|
.voice-button.recording {
|
||||||
|
background: var(--accent);
|
||||||
|
color: var(--paper);
|
||||||
|
animation: voice-pulse 1.2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.voice-button:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes voice-pulse {
|
||||||
|
50% { opacity: 0.6; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.voice-status {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--ink-dim);
|
||||||
|
}
|
||||||
|
|
||||||
|
.voice-preview,
|
||||||
|
.item-card-audio {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 28rem;
|
||||||
|
margin-top: 0.4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* display:block above would beat the hidden attribute */
|
||||||
|
.voice-preview[hidden] {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* links inside markdown descriptions */
|
||||||
|
.alt-description a,
|
||||||
|
.feature p a {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
border-bottom: 0.06rem solid var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alt-description a:hover,
|
||||||
|
.feature p a:hover {
|
||||||
|
color: var(--accent);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* images inside markdown descriptions: full-width figures in the
|
||||||
|
card's flow, framed like the rest of the press sheet */
|
||||||
|
.alt-description img,
|
||||||
|
.item-card-description img,
|
||||||
|
.feature p img {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
margin: 0.6rem 0 0.2rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
border: 0.06rem solid var(--line);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alt-description code,
|
||||||
|
.feature p code {
|
||||||
|
font-size: 0.9em;
|
||||||
|
}
|
||||||
|
|
||||||
.feature p {
|
.feature p {
|
||||||
color: var(--ink-dim);
|
color: var(--ink-dim);
|
||||||
font-size: 0.95rem;
|
font-size: 0.95rem;
|
||||||
@@ -413,7 +581,7 @@ textarea {
|
|||||||
font: inherit;
|
font: inherit;
|
||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
background: var(--paper);
|
background: var(--paper);
|
||||||
border: 1px solid var(--line);
|
border: 0.06rem solid var(--line);
|
||||||
border-radius: 0.6rem;
|
border-radius: 0.6rem;
|
||||||
padding: 0.65rem 0.8rem;
|
padding: 0.65rem 0.8rem;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -438,21 +606,148 @@ input:focus,
|
|||||||
textarea:focus {
|
textarea:focus {
|
||||||
outline: none;
|
outline: none;
|
||||||
border-color: var(--accent);
|
border-color: var(--accent);
|
||||||
box-shadow: 0 0 0 3px var(--accent-soft);
|
box-shadow: 0 0 0 0.18rem var(--accent-soft);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* One placeholder treatment for every input-like surface: solid
|
||||||
|
ink-dim, no translucency. opacity: 1 also undoes the UA's own
|
||||||
|
placeholder dimming (Firefox) and ProseKit's 0.3 on its
|
||||||
|
placeholder pseudo-element, which read far dimmer than the
|
||||||
|
native inputs next to it. */
|
||||||
|
::placeholder,
|
||||||
|
.prosekit-editor .prosekit-placeholder::before,
|
||||||
|
.prosekit-editor.prosekit-placeholder::before {
|
||||||
|
color: var(--ink-dim);
|
||||||
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prosekit-wrap {
|
.prosekit-wrap {
|
||||||
background: var(--paper);
|
background: var(--paper);
|
||||||
border: 1px solid var(--line);
|
border: 0.06rem solid var(--line);
|
||||||
border-radius: 0.6rem;
|
border-radius: 0.6rem;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* The gesture drawing field (gesture.js). Stroke/ghost/echo colors
|
||||||
|
live in the JS module's own palette table - canvas can't read these
|
||||||
|
custom properties - so palette changes go there AND here. */
|
||||||
|
.gesture-wrap {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The canvas is created by JS only after wasm hydration - reserve its
|
||||||
|
3/2 box until then so content below doesn't jump. Scoped to :empty
|
||||||
|
on purpose: on the mounted wrap (a stretched item inside the flex
|
||||||
|
.field) the same aspect-ratio turned the echo strip's extra height
|
||||||
|
into extra WIDTH and the whole card ballooned past the viewport
|
||||||
|
after the first stroke. */
|
||||||
|
.gesture-wrap:empty {
|
||||||
|
aspect-ratio: 3 / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-canvas {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
aspect-ratio: 3 / 2;
|
||||||
|
background: var(--paper);
|
||||||
|
border: 0.06rem solid var(--line);
|
||||||
|
border-radius: 0.6rem;
|
||||||
|
cursor: crosshair;
|
||||||
|
/* Load-bearing on touch: without it the browser pans instead of
|
||||||
|
letting the stroke happen. */
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Results overlay the canvas instead of growing the widget - the
|
||||||
|
page never jumps when places arrive (or don't). */
|
||||||
|
.gesture-echoes {
|
||||||
|
position: absolute;
|
||||||
|
left: 0.6rem;
|
||||||
|
right: 0.6rem;
|
||||||
|
bottom: 0.6rem;
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-echoes:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-echo {
|
||||||
|
width: 3rem;
|
||||||
|
height: 3rem;
|
||||||
|
background: var(--paper);
|
||||||
|
border: 0.06rem solid var(--line);
|
||||||
|
border-radius: 0.4rem;
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.5s ease;
|
||||||
|
pointer-events: auto;
|
||||||
|
box-shadow: 0 0.15rem 0.6rem rgba(0, 0, 0, 0.18);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-echo.shown {
|
||||||
|
opacity: var(--echo-strength, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* places are pickable: the pick re-derives the input's key */
|
||||||
|
.gesture-echo {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: opacity 0.5s ease, border-color 120ms, transform 120ms;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-echo:hover,
|
||||||
|
.gesture-echo:focus-visible {
|
||||||
|
border-color: var(--accent);
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-echo.selected {
|
||||||
|
border-color: var(--accent);
|
||||||
|
box-shadow: 0 0 0 0.12rem var(--accent);
|
||||||
|
transform: translateY(-0.1rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-empty {
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0.7rem;
|
||||||
|
margin: 0;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--ink-dim);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-empty:empty {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-status {
|
||||||
|
position: absolute;
|
||||||
|
top: 0.55rem;
|
||||||
|
right: 0.55rem;
|
||||||
|
width: 0.45rem;
|
||||||
|
height: 0.45rem;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--ink-dim);
|
||||||
|
opacity: 0.35;
|
||||||
|
transition: opacity 0.3s ease, background 0.3s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gesture-status.live {
|
||||||
|
background: var(--accent);
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
.prosekit-toolbar {
|
.prosekit-toolbar {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 0.2rem;
|
gap: 0.2rem;
|
||||||
padding: 0.4rem;
|
padding: 0.4rem;
|
||||||
border-bottom: 1px solid var(--line);
|
border-bottom: 0.06rem solid var(--line);
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -461,7 +756,7 @@ textarea:focus {
|
|||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
color: var(--ink-dim);
|
color: var(--ink-dim);
|
||||||
background: transparent;
|
background: transparent;
|
||||||
border: 1px solid transparent;
|
border: 0.06rem solid transparent;
|
||||||
border-radius: 0.4rem;
|
border-radius: 0.4rem;
|
||||||
padding: 0.3rem 0.55rem;
|
padding: 0.3rem 0.55rem;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
@@ -491,60 +786,63 @@ textarea:focus {
|
|||||||
|
|
||||||
.prosekit-wrap:focus-within {
|
.prosekit-wrap:focus-within {
|
||||||
border-color: var(--accent);
|
border-color: var(--accent);
|
||||||
box-shadow: 0 0 0 3px var(--accent-soft);
|
box-shadow: 0 0 0 0.18rem var(--accent-soft);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ProseKit's typography.css (loaded from esm.sh at mount time) sets
|
/* The editor's whole type scale, in rem. ProseKit's own typography.css
|
||||||
fixed px font sizes on .ProseMirror, so they ignore the responsive
|
is deliberately not loaded (it sizes content in fixed px - see
|
||||||
root font-size. Re-state them in rem/em at the same proportions,
|
mountEditor in prosekit-editor.js), so these rules are the only
|
||||||
with .prosekit-editor prefixed so these win on specificity. */
|
typography the editor gets, on top of UA defaults (em-based, they
|
||||||
.prosekit-editor .ProseMirror p {
|
scale fine for lists/blockquote/code). NOTE: editor.mount() turns the
|
||||||
|
.prosekit-editor div itself into the .ProseMirror root, so content
|
||||||
|
elements are its direct children - no .ProseMirror in the selector. */
|
||||||
|
.prosekit-editor p {
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
margin: 0 0 0.6em;
|
margin: 0 0 0.6em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prosekit-editor .ProseMirror p:last-child {
|
.prosekit-editor p:last-child {
|
||||||
margin-bottom: 0;
|
margin-bottom: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prosekit-editor .ProseMirror h1 {
|
.prosekit-editor h1 {
|
||||||
font-size: 2.5rem;
|
font-size: 2.5rem;
|
||||||
line-height: 1.1;
|
line-height: 1.1;
|
||||||
margin: 0.9em 0 0.1em;
|
margin: 0.9em 0 0.1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prosekit-editor .ProseMirror h2 {
|
.prosekit-editor h2 {
|
||||||
font-size: 1.875rem;
|
font-size: 1.875rem;
|
||||||
line-height: 1.3;
|
line-height: 1.3;
|
||||||
margin: 1.05em 0 0.13em;
|
margin: 1.05em 0 0.13em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prosekit-editor .ProseMirror h3 {
|
.prosekit-editor h3 {
|
||||||
font-size: 1.5rem;
|
font-size: 1.5rem;
|
||||||
line-height: 1.33;
|
line-height: 1.33;
|
||||||
margin: 0.9em 0 0.04em;
|
margin: 0.9em 0 0.04em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prosekit-editor .ProseMirror h4 {
|
.prosekit-editor h4 {
|
||||||
font-size: 1.25rem;
|
font-size: 1.25rem;
|
||||||
line-height: 1.3;
|
line-height: 1.3;
|
||||||
margin: 0.8em 0 0.05em;
|
margin: 0.8em 0 0.05em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prosekit-editor .ProseMirror h5 {
|
.prosekit-editor h5 {
|
||||||
font-size: 1.125rem;
|
font-size: 1.125rem;
|
||||||
line-height: 1.22;
|
line-height: 1.22;
|
||||||
margin: 0.78em 0 0.06em;
|
margin: 0.78em 0 0.06em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prosekit-editor .ProseMirror h6 {
|
.prosekit-editor h6 {
|
||||||
font-size: 1rem;
|
font-size: 1rem;
|
||||||
line-height: 1.25;
|
line-height: 1.25;
|
||||||
margin: 0.75em 0 0.06em;
|
margin: 0.75em 0 0.06em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.prosekit-editor .ProseMirror :is(h1, h2, h3, h4, h5, h6):first-child {
|
.prosekit-editor :is(h1, h2, h3, h4, h5, h6):first-child {
|
||||||
margin-top: 0;
|
margin-top: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -552,7 +850,7 @@ textarea:focus {
|
|||||||
font-family: var(--sans);
|
font-family: var(--sans);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
font-size: 0.95rem;
|
font-size: 0.95rem;
|
||||||
color: #0a0a0a;
|
color: var(--paper);
|
||||||
background: var(--accent);
|
background: var(--accent);
|
||||||
border: none;
|
border: none;
|
||||||
border-radius: 0.7rem;
|
border-radius: 0.7rem;
|
||||||
@@ -566,7 +864,7 @@ textarea:focus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.alt-submit:active {
|
.alt-submit:active {
|
||||||
transform: translateY(1px);
|
transform: translateY(0.06em);
|
||||||
}
|
}
|
||||||
|
|
||||||
.alt-submit:disabled {
|
.alt-submit:disabled {
|
||||||
@@ -574,6 +872,13 @@ textarea:focus {
|
|||||||
cursor: wait;
|
cursor: wait;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A content-disabled alternative (`disabled: true`): announced, not
|
||||||
|
yet takeable - reads as a promise, not as a stuck form. */
|
||||||
|
.alt-submit.soon:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
.gate-card {
|
.gate-card {
|
||||||
text-align: center;
|
text-align: center;
|
||||||
}
|
}
|
||||||
@@ -591,13 +896,13 @@ textarea:focus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.resource-error {
|
.resource-error {
|
||||||
color: #ff6b6b;
|
color: var(--error);
|
||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.resource-raw {
|
.resource-raw {
|
||||||
background: var(--paper);
|
background: var(--paper);
|
||||||
border: 1px solid var(--line);
|
border: 0.06rem solid var(--line);
|
||||||
border-radius: 0.6rem;
|
border-radius: 0.6rem;
|
||||||
padding: 0.8rem;
|
padding: 0.8rem;
|
||||||
font-size: 0.82rem;
|
font-size: 0.82rem;
|
||||||
@@ -611,7 +916,7 @@ textarea:focus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.answer-row {
|
.answer-row {
|
||||||
border: 1px solid var(--line);
|
border: 0.06rem solid var(--line);
|
||||||
border-radius: 0.8rem;
|
border-radius: 0.8rem;
|
||||||
padding: 1rem 1.1rem;
|
padding: 1rem 1.1rem;
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -624,7 +929,7 @@ textarea:focus {
|
|||||||
|
|
||||||
.answer-fields {
|
.answer-fields {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
grid-template-columns: repeat(auto-fill, minmax(10.5rem, 1fr));
|
||||||
gap: 0.5rem 1rem;
|
gap: 0.5rem 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -674,7 +979,7 @@ textarea:focus {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.item-card {
|
.item-card {
|
||||||
border: 1px solid var(--line);
|
border: 0.06rem solid var(--line);
|
||||||
border-radius: 0.8rem;
|
border-radius: 0.8rem;
|
||||||
padding: 1rem 1.1rem;
|
padding: 1rem 1.1rem;
|
||||||
display: grid;
|
display: grid;
|
||||||
@@ -736,8 +1041,8 @@ textarea:focus {
|
|||||||
font-size: 0.85rem;
|
font-size: 0.85rem;
|
||||||
color: var(--ink);
|
color: var(--ink);
|
||||||
background: var(--paper);
|
background: var(--paper);
|
||||||
border: 1px solid var(--line);
|
border: 0.06rem solid var(--line);
|
||||||
border-radius: 999px;
|
border-radius: 999rem;
|
||||||
padding: 0.4rem 0.9rem;
|
padding: 0.4rem 0.9rem;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: border-color 120ms, color 120ms, background 120ms;
|
transition: border-color 120ms, color 120ms, background 120ms;
|
||||||
@@ -759,7 +1064,7 @@ textarea:focus {
|
|||||||
cursor: not-allowed;
|
cursor: not-allowed;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 640px) {
|
@media (max-width: 40rem) {
|
||||||
.hero {
|
.hero {
|
||||||
padding: 3rem 1.25rem 2rem;
|
padding: 3rem 1.25rem 2rem;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
// A `type: voice` requirement: leave a recording at a gesture key.
|
||||||
|
// Same contract as gesture.js - portal mounts it with the field's
|
||||||
|
// hidden input and the relay URL, and calls stop() on navigation.
|
||||||
|
//
|
||||||
|
// The browser records with MediaRecorder (whatever container it
|
||||||
|
// likes), decodes that to PCM with WebAudio, resamples to mono 48 kHz,
|
||||||
|
// and ships one binary frame `[0x01][20-byte key][i16le PCM]` to the
|
||||||
|
// relay, which encodes with the one recording codec, signs as itself,
|
||||||
|
// keeps it and announces it (ADR-0015).
|
||||||
|
//
|
||||||
|
// Nothing leaves the browser until the alternative's own submit
|
||||||
|
// ("Keep it here") is pressed: the widget intercepts that click,
|
||||||
|
// uploads, sets the field's value to {key, digest, duration_ms} on
|
||||||
|
// the relay's confirmation, and only then lets the submit through.
|
||||||
|
// A relay error keeps the recording for another try and submits
|
||||||
|
// nothing.
|
||||||
|
//
|
||||||
|
// Palette: colors come from the page's custom properties, no copy here.
|
||||||
|
|
||||||
|
const MAX_SECONDS = 60;
|
||||||
|
const SAMPLE_RATE = 48000;
|
||||||
|
|
||||||
|
class VoiceWidget {
|
||||||
|
constructor(container, hidden, relayUrl, key) {
|
||||||
|
this.container = container;
|
||||||
|
this.hidden = hidden || null;
|
||||||
|
this.relayUrl = relayUrl || '';
|
||||||
|
this.key = (key || '').trim();
|
||||||
|
this.stopped = false;
|
||||||
|
this.recorder = null;
|
||||||
|
this.stream = null;
|
||||||
|
this.chunks = [];
|
||||||
|
this.ws = null;
|
||||||
|
|
||||||
|
this.button = document.createElement('button');
|
||||||
|
this.button.type = 'button';
|
||||||
|
this.button.className = 'voice-button';
|
||||||
|
this.button.textContent = 'Record';
|
||||||
|
this.status = document.createElement('span');
|
||||||
|
this.status.className = 'voice-status';
|
||||||
|
this.preview = document.createElement('audio');
|
||||||
|
this.preview.className = 'voice-preview';
|
||||||
|
this.preview.controls = true;
|
||||||
|
this.preview.hidden = true;
|
||||||
|
container.append(this.button, this.status, this.preview);
|
||||||
|
|
||||||
|
this._onClick = () => this.toggle();
|
||||||
|
this.button.addEventListener('click', this._onClick);
|
||||||
|
this.pcm = null; // decoded, ready to upload
|
||||||
|
this.published = null;
|
||||||
|
this.passthrough = false;
|
||||||
|
// The alternative's submit button: hold it until the recording
|
||||||
|
// is kept at the relay.
|
||||||
|
this.card = container.closest('.alt-card');
|
||||||
|
this._onSubmit = (e) => this.onSubmitClick(e);
|
||||||
|
if (this.card) this.card.addEventListener('click', this._onSubmit, true);
|
||||||
|
if (!this.key || this.key.length !== 40) {
|
||||||
|
this.button.disabled = true;
|
||||||
|
this.say('This page has no address to leave a voice at.');
|
||||||
|
} else if (!navigator.mediaDevices || !window.MediaRecorder) {
|
||||||
|
this.button.disabled = true;
|
||||||
|
this.say('Recording needs a browser with a microphone API.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
say(text) {
|
||||||
|
this.status.textContent = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
async toggle() {
|
||||||
|
if (this.recorder && this.recorder.state === 'recording') {
|
||||||
|
this.recorder.stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||||
|
} catch {
|
||||||
|
this.say('Microphone access was declined.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.chunks = [];
|
||||||
|
this.recorder = new MediaRecorder(this.stream);
|
||||||
|
this.recorder.addEventListener('dataavailable', (e) => { if (e.data.size) this.chunks.push(e.data); });
|
||||||
|
this.recorder.addEventListener('stop', () => this.finish());
|
||||||
|
this.recorder.start();
|
||||||
|
this.button.textContent = 'Stop';
|
||||||
|
this.button.classList.add('recording');
|
||||||
|
this.say(`Recording — up to ${MAX_SECONDS} seconds.`);
|
||||||
|
this.capTimer = setTimeout(() => { if (this.recorder && this.recorder.state === 'recording') this.recorder.stop(); }, MAX_SECONDS * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async finish() {
|
||||||
|
clearTimeout(this.capTimer);
|
||||||
|
this.button.textContent = 'Record again';
|
||||||
|
this.button.classList.remove('recording');
|
||||||
|
if (this.stream) { this.stream.getTracks().forEach((t) => t.stop()); this.stream = null; }
|
||||||
|
const blob = new Blob(this.chunks, { type: this.recorder.mimeType || 'audio/webm' });
|
||||||
|
if (!blob.size) { this.say('Nothing was recorded.'); return; }
|
||||||
|
this.preview.src = URL.createObjectURL(blob);
|
||||||
|
this.preview.hidden = false;
|
||||||
|
this.published = null;
|
||||||
|
this.setValue(null);
|
||||||
|
try {
|
||||||
|
this.pcm = await this.toPcm16(await blob.arrayBuffer());
|
||||||
|
} catch (e) {
|
||||||
|
this.pcm = null;
|
||||||
|
this.say('Could not decode the recording — try once more.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.say(`${Math.round(this.pcm.length / 2 / SAMPLE_RATE)} s recorded. Listen back, then press the button below to keep it here.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubmitClick(e) {
|
||||||
|
const button = e.target.closest && e.target.closest('.alt-submit');
|
||||||
|
if (!button || this.passthrough) return;
|
||||||
|
if (this.published) return; // already kept: let the submit go
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
if (!this.pcm) {
|
||||||
|
this.say(this.recorder && this.recorder.state === 'recording' ? 'Stop the recording first.' : 'Record something first.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.say('Sending to the relay…');
|
||||||
|
this.upload(this.pcm, () => {
|
||||||
|
// The relay confirmed: now the answer itself is submitted.
|
||||||
|
this.passthrough = true;
|
||||||
|
button.click();
|
||||||
|
this.passthrough = false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode → mono 48 kHz Float32 → Int16 little-endian bytes.
|
||||||
|
async toPcm16(buffer) {
|
||||||
|
const ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||||||
|
const decoded = await ctx.decodeAudioData(buffer);
|
||||||
|
await ctx.close();
|
||||||
|
const frames = Math.ceil(decoded.duration * SAMPLE_RATE);
|
||||||
|
const offline = new OfflineAudioContext(1, frames, SAMPLE_RATE);
|
||||||
|
const src = offline.createBufferSource();
|
||||||
|
src.buffer = decoded;
|
||||||
|
src.connect(offline.destination);
|
||||||
|
src.start();
|
||||||
|
const rendered = await offline.startRendering();
|
||||||
|
const f32 = rendered.getChannelData(0);
|
||||||
|
const out = new Uint8Array(f32.length * 2);
|
||||||
|
const view = new DataView(out.buffer);
|
||||||
|
for (let i = 0; i < f32.length; i++) {
|
||||||
|
const s = Math.max(-1, Math.min(1, f32[i]));
|
||||||
|
view.setInt16(i * 2, s < 0 ? s * 32768 : s * 32767, true);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
upload(pcm, onPublished) {
|
||||||
|
if (!this.relayUrl) { this.say('No relay to send to.'); return; }
|
||||||
|
const frame = new Uint8Array(1 + 20 + pcm.length);
|
||||||
|
frame[0] = 1;
|
||||||
|
for (let i = 0; i < 20; i++) frame[1 + i] = parseInt(this.key.substr(i * 2, 2), 16);
|
||||||
|
frame.set(pcm, 21);
|
||||||
|
const ws = new WebSocket(this.relayUrl);
|
||||||
|
ws.binaryType = 'arraybuffer';
|
||||||
|
this.ws = ws;
|
||||||
|
ws.addEventListener('open', () => ws.send(frame));
|
||||||
|
ws.addEventListener('message', (e) => {
|
||||||
|
let msg; try { msg = JSON.parse(e.data); } catch { return; }
|
||||||
|
if (msg.type === 'published') {
|
||||||
|
this.published = { key: this.key, digest: msg.digest, duration_ms: msg.duration_ms };
|
||||||
|
this.setValue(this.published);
|
||||||
|
this.say(`Kept at this address — ${Math.round(msg.duration_ms / 1000)} s.`);
|
||||||
|
this.button.disabled = true;
|
||||||
|
ws.close();
|
||||||
|
if (onPublished) onPublished();
|
||||||
|
} else if (msg.type === 'error') {
|
||||||
|
this.say((msg.message || 'The relay declined the recording.') + ' Your recording is still here — try again.');
|
||||||
|
ws.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ws.addEventListener('error', () => this.say('The relay could not be reached. Your recording is still here — try again.'));
|
||||||
|
ws.addEventListener('close', (e) => {
|
||||||
|
if (!this.published && e.code !== 1000 && e.code !== 1005) {
|
||||||
|
this.say('The relay closed the connection. Your recording is still here — try again.');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setValue(value) {
|
||||||
|
if (!this.hidden) return;
|
||||||
|
this.hidden.value = value ? JSON.stringify(value) : '';
|
||||||
|
this.hidden.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
}
|
||||||
|
|
||||||
|
stop() {
|
||||||
|
this.stopped = true;
|
||||||
|
clearTimeout(this.capTimer);
|
||||||
|
if (this.recorder && this.recorder.state === 'recording') this.recorder.stop();
|
||||||
|
if (this.stream) this.stream.getTracks().forEach((t) => t.stop());
|
||||||
|
if (this.ws) this.ws.close();
|
||||||
|
this.button.removeEventListener('click', this._onClick);
|
||||||
|
if (this.card) this.card.removeEventListener('click', this._onSubmit, true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mountVoice(container, hidden, relayUrl, key) {
|
||||||
|
return new VoiceWidget(container, hidden, relayUrl, key);
|
||||||
|
}
|
||||||
@@ -1,490 +0,0 @@
|
|||||||
// Ported from ~/repos/webpage/content/visualize/ah.html ("YES - Rasterized
|
|
||||||
// Lines"), the piece currently live at uhhm.no - kept as the actual asset,
|
|
||||||
// not reinvented. Two changes from the original: exported as a class (no
|
|
||||||
// auto-init on `window load`, since Leptos controls when this mounts) and
|
|
||||||
// a `stop()` method that actually breaks the requestAnimationFrame loop -
|
|
||||||
// the original ran forever once started, fine for a static page that's
|
|
||||||
// the whole document, not fine in an SPA where this hero mounts/unmounts
|
|
||||||
// as you navigate.
|
|
||||||
|
|
||||||
export class RasterizedYES {
|
|
||||||
constructor() {
|
|
||||||
this.rasterCanvas = document.getElementById('rasterCanvas');
|
|
||||||
this.lineCanvas = document.getElementById('lineCanvas');
|
|
||||||
|
|
||||||
// The Rust side only constructs this once it's confirmed (via a
|
|
||||||
// NodeRef) that the canvas is mounted, but that guard has shown
|
|
||||||
// a real gap on fast client-side re-navigation back to `/` -
|
|
||||||
// this is the actual failure point, so it gets its own defense
|
|
||||||
// rather than depending on getting that timing exactly right
|
|
||||||
// from the other side of the wasm boundary. Leaving the
|
|
||||||
// instance otherwise-inert (no crash, no animation) rather than
|
|
||||||
// throwing mid-render - `stop()` already tolerates a partially
|
|
||||||
// (non-)initialized instance.
|
|
||||||
if (!this.rasterCanvas || !this.lineCanvas) {
|
|
||||||
console.warn('RasterizedYES: canvas not in DOM yet, skipping');
|
|
||||||
this.destroyed = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.rasterCtx = this.rasterCanvas.getContext('2d');
|
|
||||||
this.lineCtx = this.lineCanvas.getContext('2d');
|
|
||||||
|
|
||||||
this.lines = [];
|
|
||||||
this.rasterData = null;
|
|
||||||
this.isActive = true;
|
|
||||||
this.destroyed = false;
|
|
||||||
this.time = 0;
|
|
||||||
|
|
||||||
this.mouseX = 0.5;
|
|
||||||
this.mouseY = 0.5;
|
|
||||||
this.containmentStrength = 0.5;
|
|
||||||
this.wiggleAmount = 0.5;
|
|
||||||
|
|
||||||
// .hero-canvas is inset:0 inside this - freezing an inline
|
|
||||||
// height here (below) is what actually locks the box, not
|
|
||||||
// just reading its rect.
|
|
||||||
this.heroEl = this.rasterCanvas.closest('.hero');
|
|
||||||
|
|
||||||
this.setupCanvas();
|
|
||||||
this.setupResizeHandler();
|
|
||||||
this.setupMouseTracking();
|
|
||||||
this.setupClickHandler();
|
|
||||||
this.rasterizeText();
|
|
||||||
this.initializeLines();
|
|
||||||
this.animate();
|
|
||||||
}
|
|
||||||
|
|
||||||
stop() {
|
|
||||||
this.destroyed = true;
|
|
||||||
if (this._resizeHandler) {
|
|
||||||
window.removeEventListener('resize', this._resizeHandler);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reading .hero-canvas's rendered rect (a prior attempt at this)
|
|
||||||
// only helps if that rect actually stays put - and on real mobile
|
|
||||||
// Safari it didn't: .hero-copy (bottom-aligned via flexbox inside
|
|
||||||
// .hero-yes) kept sliding down as the address bar collapsed, even
|
|
||||||
// with a spec'd-stable viewport unit (svh, then lvh) driving the
|
|
||||||
// box's height. Either the browser isn't holding up its end, or
|
|
||||||
// something in the cascade is still landing on a live value - not
|
|
||||||
// provable from here without the device. Rather than keep
|
|
||||||
// guessing at which CSS viewport unit actually holds still, yes.js
|
|
||||||
// becomes the source of truth instead: it freezes .hero-yes's
|
|
||||||
// rendered height to a literal inline px value once, up front. An
|
|
||||||
// inline style always wins the cascade over the stylesheet's
|
|
||||||
// `height: 100svh`, so once this runs, nothing the browser does
|
|
||||||
// with that unit afterward can move the box - the number is fixed
|
|
||||||
// in the DOM, not recomputed from a unit at all.
|
|
||||||
setupCanvas() {
|
|
||||||
const pixelRatio = window.devicePixelRatio || 1;
|
|
||||||
const width = window.innerWidth;
|
|
||||||
const height = window.innerHeight;
|
|
||||||
|
|
||||||
if (this.heroEl) {
|
|
||||||
this.heroEl.style.height = height + 'px';
|
|
||||||
}
|
|
||||||
|
|
||||||
this.rasterCanvas.style.width = width + 'px';
|
|
||||||
this.rasterCanvas.style.height = height + 'px';
|
|
||||||
this.lineCanvas.style.width = width + 'px';
|
|
||||||
this.lineCanvas.style.height = height + 'px';
|
|
||||||
|
|
||||||
this.rasterCanvas.width = width * pixelRatio;
|
|
||||||
this.rasterCanvas.height = height * pixelRatio;
|
|
||||||
this.lineCanvas.width = width * pixelRatio;
|
|
||||||
this.lineCanvas.height = height * pixelRatio;
|
|
||||||
|
|
||||||
this.rasterCtx.scale(pixelRatio, pixelRatio);
|
|
||||||
this.lineCtx.scale(pixelRatio, pixelRatio);
|
|
||||||
|
|
||||||
this.displayWidth = width;
|
|
||||||
this.displayHeight = height;
|
|
||||||
this.pixelRatio = pixelRatio;
|
|
||||||
}
|
|
||||||
|
|
||||||
setupResizeHandler() {
|
|
||||||
// Gate on width, not height: mobile Safari's address-bar
|
|
||||||
// animation changes window.innerHeight continuously with no
|
|
||||||
// real layout change to react to (that's the live value this
|
|
||||||
// whole method exists to stop trusting). A genuine resize -
|
|
||||||
// orientation change, desktop window drag - always changes
|
|
||||||
// width too, so that's the real signal to re-freeze on.
|
|
||||||
this._resizeHandler = () => {
|
|
||||||
if (window.innerWidth === this.displayWidth) return;
|
|
||||||
this.setupCanvas();
|
|
||||||
this.rasterizeText();
|
|
||||||
};
|
|
||||||
window.addEventListener('resize', this._resizeHandler);
|
|
||||||
}
|
|
||||||
|
|
||||||
setupMouseTracking() {
|
|
||||||
const updatePosition = (clientX, clientY) => {
|
|
||||||
this.mouseX = clientX / this.displayWidth;
|
|
||||||
this.mouseY = clientY / this.displayHeight;
|
|
||||||
this.containmentStrength = 0.1 + (this.mouseX * 0.9);
|
|
||||||
this.wiggleAmount = 0.1 + (this.mouseY * 1.9);
|
|
||||||
};
|
|
||||||
|
|
||||||
window.addEventListener('mousemove', (e) => {
|
|
||||||
updatePosition(e.clientX, e.clientY);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Scoped to the canvas itself, not `window` (see below), and
|
|
||||||
// no longer calling preventDefault(): the original standalone
|
|
||||||
// page was the whole document, so blocking default touch
|
|
||||||
// behavior was harmless (nothing else to scroll to). Embedded
|
|
||||||
// as a hero above a longer page, .hero-yes covers the entire
|
|
||||||
// first screen - preventDefault() here was fighting the
|
|
||||||
// browser's own native scroll for any touch gesture starting
|
|
||||||
// in that region, which is what actually caused scrolling to
|
|
||||||
// jump/stutter (only once this component had mounted and
|
|
||||||
// attached these listeners - a plain page scroll never needed
|
|
||||||
// default prevented in the first place, just the position for
|
|
||||||
// the cosmetic line-cluster tracking below).
|
|
||||||
this.lineCanvas.addEventListener('touchmove', (e) => {
|
|
||||||
if (e.touches.length > 0) {
|
|
||||||
const touch = e.touches[0];
|
|
||||||
updatePosition(touch.clientX, touch.clientY);
|
|
||||||
}
|
|
||||||
}, { passive: true });
|
|
||||||
|
|
||||||
this.lineCanvas.addEventListener('touchstart', (e) => {
|
|
||||||
if (e.touches.length > 0) {
|
|
||||||
const touch = e.touches[0];
|
|
||||||
updatePosition(touch.clientX, touch.clientY);
|
|
||||||
}
|
|
||||||
}, { passive: true });
|
|
||||||
|
|
||||||
this.mouseX = 0.5;
|
|
||||||
this.mouseY = 0.5;
|
|
||||||
this.containmentStrength = 0.55;
|
|
||||||
this.wiggleAmount = 1.05;
|
|
||||||
}
|
|
||||||
|
|
||||||
setupClickHandler() {
|
|
||||||
this.lineCanvas.addEventListener('click', () => {
|
|
||||||
this.restartAnimation();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
restartAnimation() {
|
|
||||||
this.time = 0;
|
|
||||||
this.lineCtx.fillStyle = '#0a0a0a';
|
|
||||||
this.lineCtx.fillRect(0, 0, this.displayWidth, this.displayHeight);
|
|
||||||
this.initializeLines();
|
|
||||||
this.isActive = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
rasterizeText() {
|
|
||||||
const width = this.displayWidth;
|
|
||||||
const height = this.displayHeight;
|
|
||||||
|
|
||||||
const aspectRatio = width / height;
|
|
||||||
let fontSize;
|
|
||||||
if (aspectRatio < 1) {
|
|
||||||
fontSize = width * 0.4;
|
|
||||||
} else {
|
|
||||||
fontSize = height * 0.5;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.fontSize = fontSize;
|
|
||||||
|
|
||||||
this.rasterCtx.font = `bold ${fontSize}px Arial, sans-serif`;
|
|
||||||
this.rasterCtx.textAlign = 'left';
|
|
||||||
this.rasterCtx.textBaseline = 'middle';
|
|
||||||
|
|
||||||
const fullTextMetrics = this.rasterCtx.measureText('YES');
|
|
||||||
const textWidth = fullTextMetrics.width;
|
|
||||||
const textStartX = (width - textWidth) / 2;
|
|
||||||
const textY = height / 2;
|
|
||||||
|
|
||||||
const letters = ['Y', 'E', 'S'];
|
|
||||||
this.letterPositions = [];
|
|
||||||
let currentX = textStartX;
|
|
||||||
|
|
||||||
for (let i = 0; i < letters.length; i++) {
|
|
||||||
const letterMetrics = this.rasterCtx.measureText(letters[i]);
|
|
||||||
this.letterPositions[i] = {
|
|
||||||
x: currentX,
|
|
||||||
y: textY,
|
|
||||||
width: letterMetrics.width,
|
|
||||||
centerX: currentX + letterMetrics.width / 2
|
|
||||||
};
|
|
||||||
currentX += letterMetrics.width;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.letterRasters = [];
|
|
||||||
|
|
||||||
for (let i = 0; i < 3; i++) {
|
|
||||||
this.rasterCtx.fillStyle = '#111';
|
|
||||||
this.rasterCtx.fillRect(0, 0, width, height);
|
|
||||||
|
|
||||||
this.rasterCtx.fillStyle = '#ffffff';
|
|
||||||
this.rasterCtx.fillText(letters[i], this.letterPositions[i].x, this.letterPositions[i].y);
|
|
||||||
|
|
||||||
this.letterRasters[i] = this.rasterCtx.getImageData(0, 0, this.rasterCanvas.width, this.rasterCanvas.height);
|
|
||||||
}
|
|
||||||
|
|
||||||
this.rasterCtx.fillStyle = '#111';
|
|
||||||
this.rasterCtx.fillRect(0, 0, width, height);
|
|
||||||
this.rasterCtx.fillStyle = '#ffffff';
|
|
||||||
this.rasterCtx.fillText('YES', textStartX, textY);
|
|
||||||
|
|
||||||
this.rasterData = this.rasterCtx.getImageData(0, 0, this.rasterCanvas.width, this.rasterCanvas.height);
|
|
||||||
}
|
|
||||||
|
|
||||||
isInSpecificLetter(x, y, letterIndex) {
|
|
||||||
const canvasX = x * this.pixelRatio;
|
|
||||||
const canvasY = y * this.pixelRatio;
|
|
||||||
|
|
||||||
if (!this.letterRasters || !this.letterRasters[letterIndex] ||
|
|
||||||
canvasX < 0 || canvasY < 0 ||
|
|
||||||
canvasX >= this.rasterCanvas.width || canvasY >= this.rasterCanvas.height) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const index = (Math.floor(canvasY) * this.rasterCanvas.width + Math.floor(canvasX)) * 4;
|
|
||||||
const red = this.letterRasters[letterIndex].data[index];
|
|
||||||
return red > 128;
|
|
||||||
}
|
|
||||||
|
|
||||||
initializeLines() {
|
|
||||||
this.lines = [];
|
|
||||||
const numLines = 60;
|
|
||||||
|
|
||||||
const letterCentroids = this.calculateLetterCentroids();
|
|
||||||
|
|
||||||
for (let i = 0; i < numLines; i++) {
|
|
||||||
const letterIndex = Math.floor(i / (numLines / 3));
|
|
||||||
let startX, startY, centerX, centerY;
|
|
||||||
|
|
||||||
if (letterCentroids[letterIndex]) {
|
|
||||||
centerX = letterCentroids[letterIndex].x;
|
|
||||||
centerY = letterCentroids[letterIndex].y;
|
|
||||||
|
|
||||||
const startVariation = this.fontSize * 0.1;
|
|
||||||
startX = centerX + (Math.random() - 0.5) * startVariation;
|
|
||||||
startY = centerY + (Math.random() - 0.5) * startVariation;
|
|
||||||
|
|
||||||
if (!this.isInSpecificLetter(startX, startY, letterIndex)) {
|
|
||||||
const nearestPoint = this.findNearestSpecificLetterPixel(startX, startY, letterIndex);
|
|
||||||
if (nearestPoint) {
|
|
||||||
startX = nearestPoint.x;
|
|
||||||
startY = nearestPoint.y;
|
|
||||||
} else {
|
|
||||||
startX = centerX;
|
|
||||||
startY = centerY;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const letterPos = this.letterPositions[letterIndex];
|
|
||||||
startX = letterPos.centerX;
|
|
||||||
startY = letterPos.y;
|
|
||||||
centerX = startX;
|
|
||||||
centerY = startY;
|
|
||||||
}
|
|
||||||
|
|
||||||
const colors = [
|
|
||||||
'hsl(180, 90%, 70%)',
|
|
||||||
'hsl(300, 90%, 70%)',
|
|
||||||
'hsl(60, 90%, 70%)'
|
|
||||||
];
|
|
||||||
|
|
||||||
this.lines.push({
|
|
||||||
relativeX: (startX - centerX) / this.fontSize,
|
|
||||||
relativeY: (startY - centerY) / this.fontSize,
|
|
||||||
prevRelativeX: (startX - centerX) / this.fontSize,
|
|
||||||
prevRelativeY: (startY - centerY) / this.fontSize,
|
|
||||||
angle: Math.random() * Math.PI * 2,
|
|
||||||
color: colors[letterIndex],
|
|
||||||
letterIndex: letterIndex,
|
|
||||||
lastSeenInside: { x: (startX - centerX) / this.fontSize, y: (startY - centerY) / this.fontSize },
|
|
||||||
outsideDuration: 0
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
calculateLetterCentroids() {
|
|
||||||
const centroids = [];
|
|
||||||
|
|
||||||
for (let letterIndex = 0; letterIndex < 3; letterIndex++) {
|
|
||||||
let sumX = 0, sumY = 0, count = 0;
|
|
||||||
|
|
||||||
const letterPos = this.letterPositions[letterIndex];
|
|
||||||
const searchStartX = Math.max(0, letterPos.x - this.fontSize * 0.1);
|
|
||||||
const searchEndX = Math.min(this.displayWidth, letterPos.x + letterPos.width + this.fontSize * 0.1);
|
|
||||||
const searchStartY = Math.max(0, letterPos.y - this.fontSize * 0.6);
|
|
||||||
const searchEndY = Math.min(this.displayHeight, letterPos.y + this.fontSize * 0.6);
|
|
||||||
|
|
||||||
const step = Math.max(1, Math.floor(this.fontSize * 0.02));
|
|
||||||
for (let y = searchStartY; y <= searchEndY; y += step) {
|
|
||||||
for (let x = searchStartX; x <= searchEndX; x += step) {
|
|
||||||
if (this.isInSpecificLetter(x, y, letterIndex)) {
|
|
||||||
sumX += x;
|
|
||||||
sumY += y;
|
|
||||||
count++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (count > 0) {
|
|
||||||
centroids[letterIndex] = {
|
|
||||||
x: sumX / count,
|
|
||||||
y: sumY / count
|
|
||||||
};
|
|
||||||
} else {
|
|
||||||
centroids[letterIndex] = {
|
|
||||||
x: letterPos.centerX,
|
|
||||||
y: letterPos.y
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return centroids;
|
|
||||||
}
|
|
||||||
|
|
||||||
updateLines() {
|
|
||||||
this.time += 0.016;
|
|
||||||
if (!this.isActive) return;
|
|
||||||
|
|
||||||
const letterCentroids = this.calculateLetterCentroids();
|
|
||||||
|
|
||||||
this.lines.forEach(line => {
|
|
||||||
line.prevRelativeX = line.relativeX;
|
|
||||||
line.prevRelativeY = line.relativeY;
|
|
||||||
|
|
||||||
const centroid = letterCentroids[line.letterIndex];
|
|
||||||
if (!centroid) return;
|
|
||||||
|
|
||||||
const currentX = centroid.x + line.relativeX * this.fontSize;
|
|
||||||
const currentY = centroid.y + line.relativeY * this.fontSize;
|
|
||||||
|
|
||||||
const currentlyInside = this.isInSpecificLetter(currentX, currentY, line.letterIndex);
|
|
||||||
|
|
||||||
if (currentlyInside) {
|
|
||||||
line.outsideDuration = 0;
|
|
||||||
line.lastSeenInside = { x: line.relativeX, y: line.relativeY };
|
|
||||||
} else {
|
|
||||||
line.outsideDuration++;
|
|
||||||
}
|
|
||||||
|
|
||||||
const visionDistance = 0.08 * this.fontSize;
|
|
||||||
const centerX = currentX + Math.cos(line.angle) * visionDistance;
|
|
||||||
const centerY = currentY + Math.sin(line.angle) * visionDistance;
|
|
||||||
const leftX = currentX + Math.cos(line.angle - 0.4) * visionDistance;
|
|
||||||
const leftY = currentY + Math.sin(line.angle - 0.4) * visionDistance;
|
|
||||||
const rightX = currentX + Math.cos(line.angle + 0.4) * visionDistance;
|
|
||||||
const rightY = currentY + Math.sin(line.angle + 0.4) * visionDistance;
|
|
||||||
|
|
||||||
const centerSees = this.isInSpecificLetter(centerX, centerY, line.letterIndex);
|
|
||||||
const leftSees = this.isInSpecificLetter(leftX, leftY, line.letterIndex);
|
|
||||||
const rightSees = this.isInSpecificLetter(rightX, rightY, line.letterIndex);
|
|
||||||
|
|
||||||
let speed = 0.02;
|
|
||||||
|
|
||||||
const attractionThreshold = Math.floor(15 + (1 - this.containmentStrength) * 45);
|
|
||||||
|
|
||||||
if (line.outsideDuration > attractionThreshold) {
|
|
||||||
const targetX = line.lastSeenInside.x;
|
|
||||||
const targetY = line.lastSeenInside.y;
|
|
||||||
const deltaX = targetX - line.relativeX;
|
|
||||||
const deltaY = targetY - line.relativeY;
|
|
||||||
const angleToTarget = Math.atan2(deltaY, deltaX);
|
|
||||||
|
|
||||||
let angleDiff = angleToTarget - line.angle;
|
|
||||||
while (angleDiff > Math.PI) angleDiff -= 2 * Math.PI;
|
|
||||||
while (angleDiff < -Math.PI) angleDiff += 2 * Math.PI;
|
|
||||||
|
|
||||||
const baseAttraction = Math.min(0.4, line.outsideDuration / 80);
|
|
||||||
const attractionStrength = baseAttraction * this.containmentStrength;
|
|
||||||
line.angle += angleDiff * attractionStrength;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (centerSees) {
|
|
||||||
const baseWiggle = 0.15;
|
|
||||||
line.angle += (Math.random() - 0.5) * baseWiggle * this.wiggleAmount;
|
|
||||||
} else {
|
|
||||||
speed *= (0.3 + this.containmentStrength * 0.4);
|
|
||||||
|
|
||||||
const baseTurnStrength = 0.3 + (this.containmentStrength * 0.4);
|
|
||||||
const randomTurnAmount = 0.2 * this.wiggleAmount;
|
|
||||||
|
|
||||||
if (leftSees && !rightSees) {
|
|
||||||
line.angle -= baseTurnStrength + Math.random() * randomTurnAmount;
|
|
||||||
} else if (rightSees && !leftSees) {
|
|
||||||
line.angle += baseTurnStrength + Math.random() * randomTurnAmount;
|
|
||||||
} else {
|
|
||||||
const randomTurn = (Math.random() - 0.5) * (0.8 + this.wiggleAmount * 0.7);
|
|
||||||
line.angle += randomTurn;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
line.relativeX += Math.cos(line.angle) * speed;
|
|
||||||
line.relativeY += Math.sin(line.angle) * speed;
|
|
||||||
|
|
||||||
line.relativeX = Math.max(-1.7, Math.min(1.7, line.relativeX));
|
|
||||||
line.relativeY = Math.max(-1.7, Math.min(1.7, line.relativeY));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
findNearestSpecificLetterPixel(x, y, letterIndex) {
|
|
||||||
const searchRadius = this.fontSize * 0.08;
|
|
||||||
const step = Math.max(1, Math.floor(this.fontSize * 0.01));
|
|
||||||
let nearestPoint = null;
|
|
||||||
let nearestDistance = Infinity;
|
|
||||||
|
|
||||||
for (let dy = -searchRadius; dy <= searchRadius; dy += step) {
|
|
||||||
for (let dx = -searchRadius; dx <= searchRadius; dx += step) {
|
|
||||||
const testX = x + dx;
|
|
||||||
const testY = y + dy;
|
|
||||||
|
|
||||||
if (this.isInSpecificLetter(testX, testY, letterIndex)) {
|
|
||||||
const distance = Math.sqrt(dx * dx + dy * dy);
|
|
||||||
if (distance < nearestDistance) {
|
|
||||||
nearestDistance = distance;
|
|
||||||
nearestPoint = { x: testX, y: testY };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nearestPoint;
|
|
||||||
}
|
|
||||||
|
|
||||||
draw() {
|
|
||||||
this.lineCtx.fillStyle = 'rgba(10, 10, 10, 0.03)';
|
|
||||||
this.lineCtx.fillRect(0, 0, this.displayWidth, this.displayHeight);
|
|
||||||
|
|
||||||
const letterCentroids = this.calculateLetterCentroids();
|
|
||||||
|
|
||||||
this.lines.forEach(line => {
|
|
||||||
const centroid = letterCentroids[line.letterIndex];
|
|
||||||
if (!centroid) return;
|
|
||||||
|
|
||||||
const currentX = centroid.x + line.relativeX * this.fontSize;
|
|
||||||
const currentY = centroid.y + line.relativeY * this.fontSize;
|
|
||||||
const prevX = centroid.x + line.prevRelativeX * this.fontSize;
|
|
||||||
const prevY = centroid.y + line.prevRelativeY * this.fontSize;
|
|
||||||
|
|
||||||
if (prevX === currentX && prevY === currentY) return;
|
|
||||||
|
|
||||||
this.lineCtx.strokeStyle = line.color.replace('70%)', '80%, 0.8)');
|
|
||||||
this.lineCtx.lineWidth = this.fontSize * 0.003;
|
|
||||||
this.lineCtx.lineCap = 'round';
|
|
||||||
|
|
||||||
this.lineCtx.beginPath();
|
|
||||||
this.lineCtx.moveTo(prevX, prevY);
|
|
||||||
this.lineCtx.lineTo(currentX, currentY);
|
|
||||||
this.lineCtx.stroke();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
animate() {
|
|
||||||
if (this.destroyed) return;
|
|
||||||
this.updateLines();
|
|
||||||
this.draw();
|
|
||||||
requestAnimationFrame(() => this.animate());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user