diff --git a/crates/in-core/migrations/0002_ui.sql b/crates/in-core/migrations/0002_ui.sql new file mode 100644 index 0000000..b8dffd2 --- /dev/null +++ b/crates/in-core/migrations/0002_ui.sql @@ -0,0 +1,6 @@ +-- The person's UI density: 'ledger' or 'instrument', read by `root_layout` +-- into `data-ui`. The DEFAULT is the backfill: SQLite fills every existing +-- row with it as the column is added. Databases already carrying the column +-- never see this file applied piecemeal — they reach the declared shape +-- through `in reconcile`, whose copy map backfills the same value. +ALTER TABLE user ADD COLUMN ui TEXT NOT NULL DEFAULT 'ledger'; diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 63ad245..e460f32 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -93,6 +93,9 @@ pub struct User { /// file that can be restored still costs. Recomputed from the rows after /// every mutation, never blindly incremented. pub used_bytes: u64, + /// Display-only, the way `quota_bytes` is data: 'ledger' or 'instrument', + /// read by `root_layout` into `data-ui`. Nothing stored depends on it. + pub ui: String, pub created_at: OffsetDateTime, pub last_seen_at: Option, } @@ -358,6 +361,12 @@ pub trait Store: 'static + Send + Sync { /// layer reads this and treats the person as signed out. async fn set_user_disabled(&self, user_id: &str, disabled: bool) -> Result<()>; + /// Writes the person's UI density: `ledger` or `instrument`, read by + /// `root_layout` into `data-ui`. Anything else is refused with + /// [`StoreError::Corrupt`] — the same refusal a bad enum read from the + /// row gets, because a bad enum written is a corrupt row. + async fn set_user_ui(&self, id: &str, ui: &str) -> Result<()>; + // -- folders ----------------------------------------------------------- /// Creates a folder. A parent of another owner is [`StoreError::CrossOwner`], diff --git a/crates/in-core/src/store/reconcile.rs b/crates/in-core/src/store/reconcile.rs index 5aa2498..5a8ebb1 100644 --- a/crates/in-core/src/store/reconcile.rs +++ b/crates/in-core/src/store/reconcile.rs @@ -202,26 +202,34 @@ struct TableMap { columns: Vec<(&'static str, String)>, } -/// Builds the explicit column map. Every table maps every column to its old -/// self: In's first schema is the declared one, so a database old enough to -/// be reconciled carries the same columns, and the map is the receipt that -/// says nothing was dropped, renamed or defaulted on the way across. -fn build_maps() -> Vec { +/// Builds the explicit column map. Unchanged tables map every column to its +/// old self; the user table carries the migration-specific expression for +/// `ui`: a database old enough to predate the column starts on the schema's +/// own default rather than on an empty string, which no writer would ever +/// store and no reader would ever honour. +fn build_maps(old_has_ui: bool) -> Vec { vec![ TableMap { name: "user", - columns: old_cols(&[ - "id", - "oidc_sub", - "email", - "display_name", - "admin", - "disabled", - "quota_bytes", - "used_bytes", - "created_at", - "last_seen_at", - ]), + columns: { + let mut columns = old_cols(&[ + "id", + "oidc_sub", + "email", + "display_name", + "admin", + "disabled", + "quota_bytes", + "used_bytes", + ]); + columns.push(if old_has_ui { + ("ui", "old.ui".into()) + } else { + ("ui", "'ledger'".into()) + }); + columns.extend(old_cols(&["created_at", "last_seen_at"])); + columns + }, }, TableMap { name: "folder", @@ -363,14 +371,15 @@ async fn validate_maps(conn: &Connection, maps: &[TableMap]) -> Result<()> { /// main schema, in foreign-key-safe order: owners before folders, folders /// before the files and sessions that name them, everything before the /// shares that name all of it. -async fn copy_data(_old_conn: &Connection, new_conn: &Connection, path: &str) -> Result<()> { +async fn copy_data(old_conn: &Connection, new_conn: &Connection, path: &str) -> Result<()> { let escaped = path.replace('\'', "''"); new_conn .execute(&format!("ATTACH DATABASE '{}' AS old", escaped), ()) .await .map_err(|e| StoreError::Backend(e.to_string()))?; - let maps = build_maps(); + let old_has_ui = old_has_column(old_conn, "user", "ui").await?; + let maps = build_maps(old_has_ui); validate_maps(new_conn, &maps).await?; // Foreign keys stay off during the copy and are checked by `verify` @@ -555,12 +564,10 @@ fn backup_name(path: &str) -> Result { } } -/// A probe the copy plan can ask: whether the old database already carries -/// `column` on `table`. Unused while the declared schema is the first one — -/// every database old enough to be reconciled predates every column it -/// would probe — and kept because the second migration will need exactly -/// this question on its first day. -#[allow(dead_code)] +/// A probe the copy plan asks: whether the old database already carries +/// `column` on `table`. A column the second migration added is absent on a +/// database old enough to predate it, and the map backfills the default +/// instead of reading a column that is not there. async fn old_has_column(conn: &Connection, table: &str, column: &str) -> Result { let mut rows = conn .query(&format!("PRAGMA table_info({table})"), ()) diff --git a/crates/in-core/src/store/schema.rs b/crates/in-core/src/store/schema.rs index e34ab0b..f5fcf18 100644 --- a/crates/in-core/src/store/schema.rs +++ b/crates/in-core/src/store/schema.rs @@ -11,8 +11,12 @@ use turso::Connection; /// The declared migrations, in order. An empty database is built by applying /// them one after another; each one applies cleanly to what the ones before -/// it built, so their concatenation is itself a valid whole-schema script. -pub(crate) const MIGRATIONS: &[&str] = &[include_str!("../../migrations/0001_init.sql")]; +/// it built (`0002` is `ALTER`s), so their concatenation is itself a valid +/// whole-schema script. +pub(crate) const MIGRATIONS: &[&str] = &[ + include_str!("../../migrations/0001_init.sql"), + include_str!("../../migrations/0002_ui.sql"), +]; /// The whole declared schema — every migration applied in order — as one /// batch of SQL. diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 6799a1d..d972772 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -36,7 +36,7 @@ const UPLOADS_DIR: &str = "uploads"; const THUMB_SOURCE_CAP: u64 = 64 * 1024 * 1024; const USER_COLUMNS: &str = - "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, created_at, last_seen_at"; + "id, oidc_sub, email, display_name, admin, disabled, quota_bytes, used_bytes, ui, created_at, last_seen_at"; const FOLDER_COLUMNS: &str = "id, owner_id, parent_id, name, created_at, deleted_at"; const FILE_COLUMNS: &str = "id, owner_id, folder_id, name, mime, size_bytes, thumb_state, created_at, updated_at, deleted_at"; @@ -713,8 +713,9 @@ fn user_from(row: &Row) -> Result { disabled: row.get::(5).map_err(backend)? != 0, quota_bytes: row.get::(6).map_err(backend)?.max(0) as u64, used_bytes: row.get::(7).map_err(backend)?.max(0) as u64, - created_at: parse_stamp(&text(row, 8)?)?, - last_seen_at: opt_stamp(row, 9)?, + ui: text(row, 8)?, + created_at: parse_stamp(&text(row, 9)?)?, + last_seen_at: opt_stamp(row, 10)?, }) } @@ -946,6 +947,23 @@ impl Store for TursoStore { Ok(()) } + async fn set_user_ui(&self, id: &str, ui: &str) -> Result<()> { + if ui != "ledger" && ui != "instrument" { + return Err(StoreError::Corrupt(format!("ui {ui:?}"))); + } + let conn = self.conn.lock().await; + let n = conn + .execute("UPDATE user SET ui = ?1 WHERE id = ?2", params![ui, id]) + .await + .map_err(backend)?; + if n == 0 { + return Err(StoreError::NotFound); + } + drop(conn); + self.announce([Topic::Admin(id.to_string())]); + Ok(()) + } + async fn create_folder( &self, owner_id: &str, diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index 7372b38..ec21607 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -1120,3 +1120,68 @@ async fn add_share_user_needs_the_owner() { scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &stranger.id, true).await.unwrap(); assert!(scratch.store.can_see(ShareKind::File, &file.id, &stranger.id).await.unwrap()); } + +#[tokio::test] +async fn a_provisioned_user_wears_the_ledger_ui() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + assert_eq!(user.ui, "ledger"); +} + +#[tokio::test] +async fn the_ui_round_trips_and_refuses_what_is_not_offered() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + scratch.store.set_user_ui(&user.id, "instrument").await.unwrap(); + let back = scratch.store.user(&user.id).await.unwrap().unwrap(); + assert_eq!(back.ui, "instrument"); + // A value no settings screen offers is refused, and the row keeps what + // the last good write left — the same Corrupt the store answers a bad + // enum it reads. + assert!(matches!( + scratch.store.set_user_ui(&user.id, "dense").await, + Err(StoreError::Corrupt(_)) + )); + let kept = scratch.store.user(&user.id).await.unwrap().unwrap(); + assert_eq!(kept.ui, "instrument"); + assert!(matches!( + scratch.store.set_user_ui("no-such-user", "ledger").await, + Err(StoreError::NotFound) + )); +} + +#[tokio::test] +async fn a_first_migration_database_gains_the_ui_column_on_open() { + // A database built from 0001 alone — the shape In was deployed with — + // carries no `ui` column. Opening it with the current code reconciles it + // onto the declared schema, and its people arrive wearing the default. + let dir = std::env::temp_dir().join(format!("in-test-{}", Ulid::new())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("in.db").to_string_lossy().into_owned(); + { + let db = turso::Builder::new_local(&path).build().await.unwrap(); + let conn = db.connect().unwrap(); + conn.execute_batch(include_str!("../migrations/0001_init.sql")) + .await + .unwrap(); + conn.execute( + "INSERT INTO user (id, oidc_sub, email, display_name, admin, disabled, \ + quota_bytes, used_bytes, created_at, last_seen_at) \ + VALUES ('u-old', 'sub-old', 'old@example.com', 'Old', 1, 0, 100, 0, \ + '2026-08-01T00:00:00Z', '2026-08-01T00:00:00Z')", + (), + ) + .await + .unwrap(); + } + let storage = dir.join("storage"); + let store = TursoStore::open(&path, Some(&storage)).await.unwrap(); + let user = store.user_by_oidc_sub("sub-old").await.unwrap().unwrap(); + assert_eq!(user.ui, "ledger"); + // And the carried row takes a new preference like any other. + store.set_user_ui(&user.id, "instrument").await.unwrap(); + let back = store.user(&user.id).await.unwrap().unwrap(); + assert_eq!(back.ui, "instrument"); + drop(store); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index 17c47aa..66cda81 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -161,6 +161,7 @@ pub enum Key { ViewOnly, NoLinks, ManageLinks, + UiLabel, } pub fn t(lang: Lang, key: Key) -> &'static str { @@ -259,6 +260,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { ViewOnly => "View only — preview, no downloads", NoLinks => "No share links yet.", ManageLinks => "Share links", + UiLabel => "Interface", }, Lang::Tr => match key { Cancel => "Vazgeç", @@ -353,6 +355,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { ViewOnly => "Yalnızca görüntüleme — önizleme, indirme yok", NoLinks => "Henüz paylaşım bağlantısı yok.", ManageLinks => "Paylaşım bağlantıları", + UiLabel => "Arayüz", }, } } diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index 11571f9..68f38ef 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -850,12 +850,14 @@ const STYLE: Asset = asset!("assets/main.css"); #[layout("/")] async fn root_layout(cx: &Cx, slot: Result) -> Result { - // v1 has no per-user theme or language: every page renders light, and - // the language comes off the request's Accept-Language header. - let asking = match current_user(cx).await { - Ok(user) => user.is_some(), - Err(_) => false, + // The one per-user chrome knob: the UI density, read off the request's + // own user. Signed-out (or unreadable) renders ledger, the default. + let me = match current_user(cx).await { + Ok(user) => user.as_ref(), + Err(_) => None, }; + let asking = me.is_some(); + let ui = me.as_ref().map_or("ledger", |user| user.ui.as_str()); let lang = crate::i18n::lang(cx); let content = match slot { @@ -878,7 +880,7 @@ async fn root_layout(cx: &Cx, slot: Result) -> Result { let build = STYLE.id().as_u64().to_string(); view! { - + diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index 3a75a76..7c2b19b 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -212,6 +212,8 @@ pub enum Refusal { AncestorTrashed, /// The store failed to say. Never a sign-in prompt — see `require_user`. Unavailable, + /// The ui field was not one of the values the form offers. + BadUi, } impl Refusal { @@ -232,6 +234,7 @@ impl Refusal { Refusal::BadChunk => "That piece arrived damaged — send it again.".to_string(), Refusal::AncestorTrashed => "Restore the folder it is in first.".to_string(), Refusal::Unavailable => "Something went wrong.".to_string(), + Refusal::BadUi => "That interface choice is not offered.".to_string(), } } @@ -252,8 +255,9 @@ impl Refusal { Refusal::ShareRevoked => "Bu bağlantı artık çalışmıyor.".to_string(), Refusal::UploadExpired => "Bu yüklemenin süresi doldu — yeniden başlat.".to_string(), Refusal::BadChunk => "Bu parça bozuk geldi — yeniden gönder.".to_string(), - Refusal::AncestorTrashed => "Önce içinde olduğu klasörü geri yükle.".to_string(), Refusal::Unavailable => "Bir şeyler ters gitti.".to_string(), + Refusal::AncestorTrashed => "Önce içinde olduğu klasörü geri yükle.".to_string(), + Refusal::BadUi => "Bu arayüz seçeneği sunulmuyor.".to_string(), } } @@ -274,6 +278,7 @@ impl Refusal { "bad-chunk" => Refusal::BadChunk, "ancestor-trashed" => Refusal::AncestorTrashed, "unavailable" => Refusal::Unavailable, + "bad-ui" => Refusal::BadUi, _ => return None, }) } @@ -298,6 +303,7 @@ impl Refusal { Refusal::BadChunk => "bad-chunk", Refusal::AncestorTrashed => "ancestor-trashed", Refusal::Unavailable => "unavailable", + Refusal::BadUi => "bad-ui", } } } diff --git a/crates/in-web/src/settings.rs b/crates/in-web/src/settings.rs index e97ac16..feda860 100644 --- a/crates/in-web/src/settings.rs +++ b/crates/in-web/src/settings.rs @@ -117,6 +117,29 @@ async fn set_disabled(cx: &Cx, Form(input): Form) -> Redirect { } } +#[derive(Deserialize)] +struct UiForm { + ui: String, +} + +/// Switches the reader's own interface between the ledger and the +/// instrument. Anything else is refused — the form only ever offers the +/// two, so another value is a hand-built post, not a typo. +#[route(POST "/api/settings/ui")] +async fn set_ui(cx: &Cx, Form(input): Form) -> Redirect { + let user = match require_user(cx).await { + Ok(user) => user, + Err(refusal) => return redirect_back(cx, "ui", Some(refusal)), + }; + if input.ui != "ledger" && input.ui != "instrument" { + return redirect_back(cx, "ui", Some(Refusal::BadUi)); + } + match app(cx).store.set_user_ui(&user.id, &input.ui).await { + Ok(()) => redirect_back(cx, "ui", None), + Err(error) => redirect_back(cx, "ui", Some(refusal_of(error))), + } +} + /// The reader's profile and quota, their live share links, and — for an /// admin — every account with its quota and kill switch. #[page("/settings")] @@ -157,92 +180,139 @@ async fn settings(cx: &Cx) -> Result { let origin = app(cx).config.listen_url(); view! { cx => -
- (topbar(cx, NavPage::Settings, &fresh, language).await?) -

(t(language, Key::Settings))

- (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable"]).await?) - if let Some(token) = created { + (topbar(cx, NavPage::Settings, &fresh, language).await?) +
+
+

(t(language, Key::Settings))

+ (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "ui"]).await?) + if let Some(token) = created { +
+
+

(t(language, Key::LinkCreated))

+
+
+

(t(language, Key::CopyLinkOnce))

+ +
+
+ }
-

(t(language, Key::LinkCreated))

+
+

(t(language, Key::Profile))

+
-

(t(language, Key::CopyLinkOnce))

- + + +
+ (t(language, Key::QuotaUsage)) + (format!("{} {} {}", human_bytes(fresh.used_bytes), t(language, Key::QuotaOf), human_bytes(fresh.quota_bytes))) +
+
+
+
+
+ +
+ +
+
- } -
-

(t(language, Key::Profile))

-
-

(t(language, Key::DisplayName)) (fresh.display_name.clone())

-

(t(language, Key::EmailAddress)) (fresh.email.clone())

-

- (t(language, Key::QuotaUsage)) - (format!("{} {} {}", human_bytes(fresh.used_bytes), t(language, Key::QuotaOf), human_bytes(fresh.quota_bytes))) -

-
-
-
-
-
-
-

(t(language, Key::ManageLinks))

-
- if live_links.is_empty() { -

(t(language, Key::NoLinks))

- } - for link in live_links { -
- (format!("{} · {}", link.kind.as_str(), link.target_id.clone())) - (expiry_line(language, link.expires_at)) - (if link.can_download { t(language, Key::CanDownload) } else { t(language, Key::ViewOnly) }) -
- - -
-
- } -
-
- if fresh.admin {
-

(t(language, Key::AdminPanel))

+
+

(t(language, Key::ManageLinks))

+
-
- for listed in &users { -
- (listed.display_name.clone()) - (listed.email.clone()) - (format!("{} {} {}", human_bytes(listed.used_bytes), t(language, Key::QuotaOf), human_bytes(listed.quota_bytes))) - if listed.admin { - (t(language, Key::AdminBadge)) - } - if listed.disabled { - (t(language, Key::DisabledBadge)) - } -
- - - -
- if listed.id != fresh.id { -
- - if listed.disabled { - - - } else { - - - } -
- } -
- } -
+ if live_links.is_empty() { +

(t(language, Key::NoLinks))

+ } + for link in live_links { +
+ (format!("{} · {}", link.kind.as_str(), link.target_id.clone())) + (expiry_line(language, link.expires_at)) + (if link.can_download { t(language, Key::CanDownload) } else { t(language, Key::ViewOnly) }) +
+ + +
+
+ }
- } -
+ if fresh.admin { +
+
+

(t(language, Key::AdminPanel))

+
+
+
+ + + + + + + + + + + for listed in &users { + + + + + + + } + +
(t(language, Key::NameColumn))(t(language, Key::EmailAddress))
+ + (listed.display_name.clone()) + if listed.admin { + (t(language, Key::AdminBadge)) + } + if listed.disabled { + (t(language, Key::DisabledBadge)) + } + + (listed.email.clone()) +
+ + + +
+ if listed.id != fresh.id { +
+ + if listed.disabled { + + + } else { + + + } +
+ } +
+
+
+
+ } +
+ + (crate::dropdown::dropdown_script(cx).await?) } } diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index b69af62..07923c0 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -1896,3 +1896,92 @@ async fn a_refused_upload_carries_a_well_formed_query() { assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("already taken"), "{}", page.text()); } + +// -- settings ui picker -------------------------------------------------------- + +#[tokio::test] +async fn settings_ui_picker_round_trips() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-ui", "ui@in.test", "Ui").await; + let me = owner_of(&app, "sub-ui").await; + + // The ledger is the default, worn on `` from the first render. + assert_eq!(app.store.user(&me).await.unwrap().unwrap().ui, "ledger"); + let page = app.get("/settings", Some(&cookie)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(page.text().contains("data-ui=\"ledger\""), "{}", page.text()); + + // Picking the instrument writes the row and re-renders the chrome. + let answer = app + .post("/api/settings/ui", Some(&cookie), &[("ui", "instrument")]) + .await; + assert!(answer.accepted(), "ui refused: {:?}", answer.location); + assert_eq!( + app.store.user(&me).await.unwrap().unwrap().ui, + "instrument" + ); + let page = app.get("/settings", Some(&cookie)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!( + page.text().contains("data-ui=\"instrument\""), + "{}", + page.text() + ); + assert!(page.text().contains("name=\"ui\""), "{}", page.text()); + + // And back again. + let answer = app + .post("/api/settings/ui", Some(&cookie), &[("ui", "ledger")]) + .await; + assert!(answer.accepted(), "ui refused: {:?}", answer.location); + assert_eq!(app.store.user(&me).await.unwrap().unwrap().ui, "ledger"); +} + +#[tokio::test] +async fn settings_ui_rejects_unknown_values() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-ui-bad", "uibad@in.test", "UiBad").await; + let me = owner_of(&app, "sub-ui-bad").await; + + let answer = app + .post("/api/settings/ui", Some(&cookie), &[("ui", "mosaic")]) + .await; + assert!(answer.refused("bad-ui", "ui"), "{:?}", answer.location); + assert_eq!(app.store.user(&me).await.unwrap().unwrap().ui, "ledger"); + + // The carried refusal renders under the picker form. + let page = app + .get(answer.location.as_deref().unwrap(), Some(&cookie)) + .await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!( + page.text().contains("That interface choice is not offered."), + "{}", + page.text() + ); + + // Signed out, the same post asks to sign in first. + let answer = app + .post("/api/settings/ui", None, &[("ui", "instrument")]) + .await; + assert!(answer.refused("sign-in-first", "ui"), "{:?}", answer.location); +} + +#[tokio::test] +async fn settings_panels_nest_inside_the_stage() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-stage", "stage@in.test", "Stage").await; + let page = app.get("/settings", Some(&admin)).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + let body = page.text(); + let stage = body + .find("
") + .expect("no settings-stage"); + let close = body.find("
").expect("no main close"); + for marker in ["panel-head", "member-table", "name=\"ui\""] { + let at = body.find(marker).unwrap_or_else(|| panic!("no {marker}")); + assert!(stage < at && at < close, "{marker} escapes the stage"); + } + // The admin register is a table now: one named column per fact. + assert!(body.contains("