Skip to content

Commit e96bb75

Browse files
PiquelChipsclaude
andcommitted
feat(auth): choose which part of a picture apps show
The profile's picture dialog now shows the chosen image under a circle, as apps show it, to drag and zoom before uploading. The form sends the square under the circle, in the image's upright pixels, and auth keeps that square instead of the centred one. Without a script the cropper stays hidden and auth keeps the centred square, as before. The cropper is a second embedded script, `assets/picture.js`, beside the passkey script. The pages' Content-Security-Policy allows both, and `blob:` images for the file being chosen. `PUT /account/picture` takes the same square as `?x=…&y=…&size=…`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 392351a commit e96bb75

20 files changed

Lines changed: 600 additions & 88 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ just build
2525
The executables are `target/release/auth-service` and `target/release/piquel-web`.
2626
Both embed the stylesheet (`crates/ui/assets/style/`, its parts joined into one
2727
file) and its typefaces (`crates/ui/assets/fonts`, under the SIL Open Font
28-
License); auth also embeds the passkey script (`apps/auth-service/assets/passkey.js`),
28+
License); auth also embeds its pages' scripts (`apps/auth-service/assets/`),
2929
and piquel-web the policies (`apps/web/assets/policies/`). Rebuild Rust after
3030
changing them.
3131

@@ -774,7 +774,7 @@ Use individual recipes while iterating:
774774
| --- | --- |
775775
| Full validation (format, Clippy/ESLint, unused code and dependencies, Rust/TypeScript checks, Rust and SDK unit tests, doc tests, audits) | `just validate` |
776776
| Format Rust and web / check formatting | `just fmt` / `just fmt-check` |
777-
| Rust / TypeScript checks (tsc, the passkey script's JSDoc types included) | `just rust check` / `just web check` |
777+
| Rust / TypeScript checks (tsc, the pages' scripts' JSDoc types included) | `just rust check` / `just web check` |
778778
| Clippy and ESLint, warnings denied; `publint` and `attw` on the built TypeScript SDK | `just lint` (`just rust lint` / `just web lint`) |
779779
| Unused Rust dependencies (cargo-machete); unused web files, exports and dependencies (knip, entry points in `knip.json`) | `just unused` (`just rust unused` / `just web unused`) |
780780
| Regenerate the SDK vectors / the TypeScript SDK's wire types | `just sdk-vectors` / `just sdk-types` |
@@ -802,7 +802,7 @@ Web code is formatted by Prettier and linted by type-aware ESLint (typescript-es
802802
`strictTypeChecked`), configured once at the repository root.
803803
Test recipes forward extra arguments to nextest or Playwright, including quoted
804804
filter expressions. `just auth run` forwards arguments to the auth binary.
805-
Cargo embeds the stylesheet, the passkey script and migrations during compilation.
805+
Cargo embeds the stylesheet, the pages' scripts and migrations during compilation.
806806

807807
Queries in `crates/database` are checked at compile time against
808808
`crates/database/.sqlx/`. Changing a query's text without `just db prepare` fails
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
/**
2+
* The picture script: it lets the profile's picture form choose which square of the
3+
* chosen image auth keeps. The image moves and zooms under a circle, as apps show
4+
* it, and the square under the circle, in the image's pixels, fills the form's
5+
* hidden inputs. Without the script they stay empty and auth keeps the centred
6+
* square. It exports nothing, and nothing compiles it: auth embeds this file as it
7+
* is, under a path naming its content, and `tsc` only checks its JSDoc types.
8+
*/
9+
10+
/** How far one arrow key moves the image, in screen pixels. */
11+
const STEP = 8;
12+
13+
/**
14+
* The cropper of one form: its image, its zoom, and the square it keeps, held as
15+
* the square's centre in the image's pixels.
16+
*/
17+
class Cropper {
18+
/** @param {HTMLFormElement} form */
19+
constructor(form) {
20+
this.file = query(form, 'input[type="file"]', HTMLInputElement);
21+
this.cropper = query(form, '[data-cropper]', HTMLElement);
22+
this.stage = query(form, '[data-crop-stage]', HTMLElement);
23+
this.image = query(form, '[data-crop-image]', HTMLImageElement);
24+
this.zoom = query(form, '[data-crop-zoom]', HTMLInputElement);
25+
/** The hidden inputs of the square's left edge, top edge and side. */
26+
this.fields = ['x', 'y', 'size'].map((part) =>
27+
query(form, `[data-crop="${part}"]`, HTMLInputElement)
28+
);
29+
/** The image's size and the square's centre, in its pixels. */
30+
this.width = 0;
31+
this.height = 0;
32+
this.centreX = 0;
33+
this.centreY = 0;
34+
/** @type {{ id: number; x: number; y: number } | null} The pointer dragging the image. */
35+
this.drag = null;
36+
/** @type {string | null} The URL of the file shown, revoked once replaced. */
37+
this.url = null;
38+
39+
this.file.addEventListener('change', () => {
40+
this.choose();
41+
});
42+
this.image.addEventListener('load', () => {
43+
this.loaded();
44+
});
45+
this.image.addEventListener('error', () => {
46+
this.reset();
47+
});
48+
this.zoom.addEventListener('input', () => {
49+
this.render();
50+
});
51+
this.stage.addEventListener('pointerdown', (event) => {
52+
this.grab(event);
53+
});
54+
this.stage.addEventListener('pointermove', (event) => {
55+
this.move(event);
56+
});
57+
for (const end of /** @type {const} */ (['pointerup', 'pointercancel'])) {
58+
this.stage.addEventListener(end, (event) => {
59+
if (event.pointerId === this.drag?.id) this.drag = null;
60+
});
61+
}
62+
this.stage.addEventListener('keydown', (event) => {
63+
this.key(event);
64+
});
65+
// The stage changes size with the window, and has none while its dialog is
66+
// closed.
67+
new ResizeObserver(() => {
68+
this.render();
69+
}).observe(this.stage);
70+
}
71+
72+
/** Shows the file just chosen, or nothing once none is. */
73+
choose() {
74+
// The last image's square must not go with the next one.
75+
this.reset();
76+
if (this.url) URL.revokeObjectURL(this.url);
77+
this.url = null;
78+
const file = this.file.files?.[0];
79+
if (!file) return;
80+
this.url = URL.createObjectURL(file);
81+
this.image.src = this.url;
82+
}
83+
84+
/** Starts on the image's centred square, at no zoom. */
85+
loaded() {
86+
this.width = this.image.naturalWidth;
87+
this.height = this.image.naturalHeight;
88+
this.centreX = this.width / 2;
89+
this.centreY = this.height / 2;
90+
this.zoom.value = '1';
91+
this.cropper.hidden = false;
92+
this.render();
93+
}
94+
95+
/** Hides the cropper and leaves the square to auth, until an image shows. */
96+
reset() {
97+
this.width = 0;
98+
this.cropper.hidden = true;
99+
for (const field of this.fields) field.value = '';
100+
}
101+
102+
/** The stage's side, in screen pixels. */
103+
side() {
104+
return this.stage.clientWidth;
105+
}
106+
107+
/** Screen pixels per image pixel: the image covers the stage, times the zoom. */
108+
scale() {
109+
return (this.side() / Math.min(this.width, this.height)) * Number(this.zoom.value);
110+
}
111+
112+
/** Places the image so the square stays inside it, and writes the square. */
113+
render() {
114+
const side = this.side();
115+
if (!this.width || !side) return;
116+
const scale = this.scale();
117+
const half = side / scale / 2;
118+
this.centreX = clamp(this.centreX, half, this.width - half);
119+
this.centreY = clamp(this.centreY, half, this.height - half);
120+
const left = side / 2 - this.centreX * scale;
121+
const top = side / 2 - this.centreY * scale;
122+
this.image.style.width = `${String(this.width * scale)}px`;
123+
this.image.style.transform = `translate(${String(left)}px, ${String(top)}px)`;
124+
const size = Math.max(1, Math.round(side / scale));
125+
const square = [
126+
clamp(Math.round(this.centreX - size / 2), 0, this.width - size),
127+
clamp(Math.round(this.centreY - size / 2), 0, this.height - size),
128+
size
129+
];
130+
this.fields.forEach((field, index) => (field.value = String(square[index])));
131+
}
132+
133+
/** Starts dragging with the primary pointer's main button. @param {PointerEvent} event */
134+
grab(event) {
135+
if (!event.isPrimary || event.button !== 0) return;
136+
this.stage.setPointerCapture(event.pointerId);
137+
this.drag = { id: event.pointerId, x: event.clientX, y: event.clientY };
138+
}
139+
140+
/** Moves the image with the pointer dragging it, and no other. @param {PointerEvent} event */
141+
move(event) {
142+
const drag = this.drag;
143+
if (drag?.id !== event.pointerId) return;
144+
this.pan(event.clientX - drag.x, event.clientY - drag.y);
145+
this.drag = { id: event.pointerId, x: event.clientX, y: event.clientY };
146+
}
147+
148+
/** Moves the image with the arrow keys. @param {KeyboardEvent} event */
149+
key(event) {
150+
/** @type {Partial<Record<string, [number, number]>>} */
151+
const moves = {
152+
ArrowLeft: [-STEP, 0],
153+
ArrowRight: [STEP, 0],
154+
ArrowUp: [0, -STEP],
155+
ArrowDown: [0, STEP]
156+
};
157+
const by = moves[event.key];
158+
if (!by) return;
159+
event.preventDefault();
160+
this.pan(...by);
161+
}
162+
163+
/**
164+
* Moves the image by `dx` and `dy` screen pixels, so the square moves the other way.
165+
* @param {number} dx
166+
* @param {number} dy
167+
*/
168+
pan(dx, dy) {
169+
const scale = this.scale();
170+
this.centreX -= dx / scale;
171+
this.centreY -= dy / scale;
172+
this.render();
173+
}
174+
}
175+
176+
/**
177+
* The element of `form` that `selector` names, which the page always renders, as a
178+
* `kind`.
179+
* @template {Element} T
180+
* @param {HTMLFormElement} form
181+
* @param {string} selector
182+
* @param {{ new (): T }} kind
183+
* @returns {T}
184+
*/
185+
function query(form, selector, kind) {
186+
const element = form.querySelector(selector);
187+
if (!(element instanceof kind)) throw new Error(`The picture form has no ${selector}.`);
188+
return element;
189+
}
190+
191+
/**
192+
* `value`, within `low` and `high`; `low` when the range is empty.
193+
* @param {number} value
194+
* @param {number} low
195+
* @param {number} high
196+
*/
197+
function clamp(value, low, high) {
198+
return Math.max(low, Math.min(value, high));
199+
}
200+
201+
for (const stage of document.querySelectorAll('[data-crop-stage]')) {
202+
const form = stage.closest('form');
203+
if (form) new Cropper(form);
204+
}

‎apps/auth-service/src/assets.rs‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//! The stylesheet, typefaces and passkey script of auth's pages, and the admin
1+
//! The stylesheet, typefaces and scripts of auth's pages, and the admin
22
//! dashboard's script, embedded under paths that never serve other content, so
33
//! browsers and shared caches keep them forever.
44
@@ -30,9 +30,14 @@ pub(crate) struct EmbeddedAssets;
3030
impl EmbeddedAssets {
3131
/// The stylesheet of auth's pages, `piquel-ui`'s.
3232
pub(crate) const STYLESHEET: Asset = piquel_ui::STYLESHEET;
33-
/// The passkey script, the one script of auth's pages.
33+
/// The passkey script, which runs the pages' passkey ceremonies.
3434
pub(crate) const SCRIPT: Asset =
3535
Asset::script("passkey", include_bytes!("../assets/passkey.js"));
36+
/// The picture script, which lets the profile's picture form choose its crop.
37+
pub(crate) const PICTURE_SCRIPT: Asset =
38+
Asset::script("picture", include_bytes!("../assets/picture.js"));
39+
/// The scripts every page of auth's own loads.
40+
pub(crate) const SCRIPTS: [Asset; 2] = [Self::SCRIPT, Self::PICTURE_SCRIPT];
3641
/// The admin dashboard's script, which confirms it with a passkey in a
3742
/// dialog on its page. Auth's own pages never load it.
3843
pub(crate) const DASHBOARD_SCRIPT: Asset =
@@ -51,7 +56,8 @@ impl EmbeddedAssets {
5156
pub(crate) fn serve(path: &str) -> Result<Response, ApiError> {
5257
let asset = Self::SHARED
5358
.into_iter()
54-
.chain([Self::SCRIPT, Self::DASHBOARD_SCRIPT])
59+
.chain(Self::SCRIPTS)
60+
.chain([Self::DASHBOARD_SCRIPT])
5561
.find(|asset| asset.path() == path)
5662
.ok_or(AssetError::NotFound)?;
5763
let headers = [(header::CONTENT_TYPE, asset.content_type())];
@@ -72,6 +78,10 @@ mod tests {
7278
for (asset, content_type) in [
7379
(EmbeddedAssets::STYLESHEET, "text/css; charset=utf-8"),
7480
(EmbeddedAssets::SCRIPT, "text/javascript; charset=utf-8"),
81+
(
82+
EmbeddedAssets::PICTURE_SCRIPT,
83+
"text/javascript; charset=utf-8",
84+
),
7585
(
7686
EmbeddedAssets::DASHBOARD_SCRIPT,
7787
"text/javascript; charset=utf-8",

0 commit comments

Comments
 (0)