From 4cd43f863a8d6f2c9931f44a0c7ccdf24214b298 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 13:18:10 +0300 Subject: [PATCH] feat: auto-postfix names, aligned rows, human-unit limits, styled viewer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - names: nothing refuses on collisions anymore — folders and files take 'name (2)' / 'name (2).txt' across create, rename, move, restore and upload finish; StoreError::NameTaken and Refusal::NameTaken removed - rows: hard single-line geometry (name ellipsises, details and buttons nowrap); Options menu anchors opaque above rows — the panel corner-clip was amputating it; Empty-the-trash wears the house danger button - pages: drive/trash/shared/viewer/settings move to the wide stage - settings: upload limit vs storage quota are unmistakable — help line, 'Current limit: 1.0 GiB', MiB/GiB unit selects, no raw-byte inputs; members table columns can no longer collapse addresses vertically - viewer: media fills a centered 960px house card, Back/Download head row, details panel aligned to the card - upload status lives in the persistent corner stack on every page and keeps updating across soft navigations; fix progress-row selector that threw on numeric data-upload values and killed uploads --- crates/in-core/src/store/mod.rs | 42 ++-- crates/in-core/src/store/turso_store.rs | 295 +++++++++++++++++++----- crates/in-core/tests/store.rs | 137 ++++++++--- crates/in-web/src/drive.rs | 244 +++++++++----------- crates/in-web/src/files.rs | 20 +- crates/in-web/src/i18n.rs | 17 +- crates/in-web/src/layout.rs | 74 ++++++ crates/in-web/src/server.rs | 6 - crates/in-web/src/settings.rs | 125 +++++++--- crates/in-web/src/share.rs | 13 +- crates/in-web/src/trash.rs | 8 +- crates/in-web/src/upload.rs | 1 - crates/in-web/tests/http.rs | 98 ++++---- style/main.scss | 169 +++++++++++++- 14 files changed, 871 insertions(+), 378 deletions(-) diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 5e446b1..333e673 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -35,9 +35,6 @@ pub use reconcile::{ReconcileOptions, reconcile}; /// leak the distinction exists to prevent. #[derive(Debug, thiserror::Error)] pub enum StoreError { - /// The name is already taken among the live siblings. - #[error("that name is already taken here")] - NameTaken, /// The database refused the write or could not be read. #[error("database: {0}")] Backend(String), @@ -382,7 +379,9 @@ pub trait Store: 'static + Send + Sync { // -- folders ----------------------------------------------------------- /// Creates a folder. A parent of another owner is [`StoreError::CrossOwner`], - /// not a refusal — the asker named a thing that is not theirs. + /// not a refusal — the asker named a thing that is not theirs. A live + /// sibling wearing the name is no refusal either: the folder takes the + /// first free `name (2)` postfix instead. async fn create_folder( &self, owner_id: &str, @@ -394,12 +393,14 @@ pub trait Store: 'static + Send + Sync { /// means for its screen. async fn folder(&self, id: &str) -> Result>; - /// Renames a folder. Names are labels, never identities: a live sibling - /// may already wear the name, and the rename still lands. + /// Renames a folder. A live sibling wearing the name is no refusal: the + /// rename lands on the first free `name (2)` postfix instead. async fn rename_folder(&self, id: &str, name: &str) -> Result<()>; /// Moves a folder. Into its own descendant is [`StoreError::Cycle`]; - /// across owners is [`StoreError::CrossOwner`]. + /// across owners is [`StoreError::CrossOwner`]. A live child of the + /// destination wearing the folder's name is no obstacle: the move lands + /// on the first free `name (2)` postfix. async fn move_folder(&self, id: &str, parent_id: Option<&str>) -> Result<()>; /// Trashes a folder: the folder, every descendant folder and every file @@ -415,11 +416,11 @@ pub trait Store: 'static + Send + Sync { parent_id: Option<&str>, ) -> Result; - // -- files ------------------------------------------------------------- - /// Stores small bytes straight through: sanitises the name, checks the /// quota, sniffs the mime (never trusting the uploader), writes the - /// file, attempts a thumbnail for images and video, and recomputes usage. The + /// file, attempts a thumbnail for images and video, and recomputes usage. A + /// live sibling wearing the name is no refusal: the file takes the first + /// free `stem (2).ext` postfix instead. The /// chunked upload's finish is the same pipeline over assembled chunks. async fn insert_file( &self, @@ -432,10 +433,13 @@ pub trait Store: 'static + Send + Sync { /// One file's row, still without its bytes. async fn file(&self, id: &str) -> Result>; - /// Renames a file. A name a live sibling wears is [`StoreError::NameTaken`]. + /// Renames a file. A live sibling wearing the name is no refusal: the + /// rename lands on the first free `stem (2).ext` postfix instead. async fn rename_file(&self, id: &str, name: &str) -> Result<()>; - /// Moves a file. Across owners is [`StoreError::CrossOwner`]. + /// Moves a file. Across owners is [`StoreError::CrossOwner`]. A live + /// child of the destination wearing the file's name is no obstacle: the + /// move lands on the first free `stem (2).ext` postfix. async fn move_file(&self, id: &str, folder_id: Option<&str>) -> Result<()>; /// Trashes a file. The bytes stay on disk — and counting toward quota — @@ -464,16 +468,18 @@ pub trait Store: 'static + Send + Sync { async fn list_trash(&self, owner_id: &str) -> Result; /// Restores a trashed file. Refused with [`StoreError::AncestorTrashed`] - /// while any ancestor folder is still trashed, and with - /// [`StoreError::NameTaken`] while a live sibling wears its name. + /// while any ancestor folder is still trashed. A live sibling wearing + /// the name is no refusal: the restore lands on the first free + /// `stem (2).ext` postfix instead. async fn restore_file(&self, id: &str) -> Result<()>; /// Restores a trashed folder and everything under it that it took with /// it — descendants wearing the folder's own trash timestamp. Anything /// trashed individually before the folder keeps its earlier moment and /// stays trashed. Refused with [`StoreError::AncestorTrashed`] while any - /// ancestor folder is still trashed; a live sibling wearing the name is - /// no refusal — folder names may repeat. + /// ancestor folder is still trashed. A live sibling wearing the name is + /// no refusal: the restored folder takes the first free `name (2)` + /// postfix instead. async fn restore_folder(&self, id: &str) -> Result<()>; /// Purges one trashed file for good: the row goes and the bytes and @@ -612,7 +618,9 @@ pub trait Store: 'static + Send + Sync { /// Assembles a session's chunks in order, rechecks the quota, sniffs the /// mime (never trusting anything the uploader said), writes the file, /// attempts a thumbnail for images and video, inserts the row and marks the session - /// done — and returns the file. A session whose chunks do not add up, or + /// done — and returns the file. A live sibling wearing the session's + /// name is no refusal: the file takes the first free `stem (2).ext` + /// postfix instead. A session whose chunks do not add up, or /// whose owner filled their quota while it was arriving, is refused with /// the chunks still staged for another attempt. async fn finish_upload(&self, id: &str) -> Result; diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 591fdb2..2f141c2 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -459,6 +459,50 @@ pub(crate) fn label_of(name: &str) -> String { trimmed } } +/// The longest name the store keeps whole: the drive forms carry +/// `maxlength="255"`, so a postfix (` (2)`, `.txt`) truncates the base to +/// fit rather than growing the name past what the UI accepts. +pub(crate) const MAX_NAME_CHARS: usize = 255; + +/// The first `max` characters of `s`, on a character boundary — never +/// splitting a multi-byte character the way a byte slice would. +fn truncate_chars(s: &str, max: usize) -> &str { + if s.chars().count() <= max { + return s; + } + match s.char_indices().nth(max) { + Some((idx, _)) => &s[..idx], + None => s, + } +} + +/// Splits a file name at its LAST dot into stem and extension (dot kept on +/// the extension): `report.txt` is `("report", ".txt")`, `archive.tar.gz` +/// is `("archive.tar", ".gz")`. No dot, a leading dot only (`.gitignore`), +/// or a trailing dot (`foo.`) is no split — the whole name is the stem — +/// so the postfix never lands in front of a dotfile's only dot. +fn split_file_name(name: &str) -> (&str, &str) { + match name.rfind('.') { + Some(at) if at > 0 && at + 1 < name.len() => (&name[..at], &name[at..]), + _ => (name, ""), + } +} + +/// `report.txt` at 2 is `report (2).txt`; `name` at 2 is `name (2)`. The +/// stem is truncated so stem + postfix + extension fits [`MAX_NAME_CHARS`]. +fn postfixed_file_name(want: &str, n: u32) -> String { + let suffix = format!(" ({n})"); + let (stem, ext) = split_file_name(want); + let keep = MAX_NAME_CHARS.saturating_sub(suffix.chars().count() + ext.chars().count()); + format!("{}{}{}", truncate_chars(stem, keep), suffix, ext) +} + +/// `Name` at 2 is `Name (2)`, truncated to fit [`MAX_NAME_CHARS`]. +fn postfixed_folder_name(want: &str, n: u32) -> String { + let suffix = format!(" ({n})"); + let keep = MAX_NAME_CHARS.saturating_sub(suffix.chars().count()); + format!("{}{}", truncate_chars(want, keep), suffix) +} /// Addresses match case-insensitively: the provider may capitalise what /// the row stored, so both sides fold before comparing. Provisioning folds @@ -671,15 +715,6 @@ fn backend(e: E) -> StoreError { StoreError::Backend(e.to_string()) } -/// Whether this engine error is a uniqueness refusal rather than a -/// malfunction. The store checks names before writing, so this is only ever -/// the backstop for a race two Immediate transactions could not serialise — -/// and it answers with the name the check would have used. -fn is_constraint_violation(e: &turso::Error) -> bool { - let text = e.to_string().to_lowercase(); - text.contains("constraint") || text.contains("unique") -} - fn now_text() -> Result { stamp(OffsetDateTime::now_utc()) } @@ -983,15 +1018,17 @@ impl Store for TursoStore { name: &str, ) -> Result { let name = label_of(name); - // IMMEDIATE: the parent check and the insert are one write set, so a - // parent trashed mid-create still refuses. Names are not checked: - // two folders may wear one name in one place. + // IMMEDIATE: the parent check, the name search and the insert are + // one write set, so a parent trashed mid-create still refuses. A + // live sibling wearing the name is no refusal: the folder takes the + // first free `name (2)` postfix instead. let mut conn = self.tx_conn().await?; let tx = conn .transaction_with_behavior(TransactionBehavior::Immediate) .await .map_err(backend)?; check_live_parent(&tx, owner_id, parent_id).await?; + let name = free_folder_name(&tx, owner_id, parent_id, &name, None).await?; let id = Ulid::new().to_string(); let now = now_text()?; tx.execute( @@ -1000,7 +1037,7 @@ impl Store for TursoStore { params![id.clone(), owner_id, parent_id, name, now], ) .await - .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + .map_err(backend)?; let mut rows = tx .query( &format!("SELECT {FOLDER_COLUMNS} FROM folder WHERE id = ?1"), @@ -1035,9 +1072,14 @@ impl Store for TursoStore { if folder.deleted_at.is_some() { return Err(StoreError::NotFound); } + // A live sibling wearing the name is no refusal: the rename lands + // on the first free `name (2)` postfix instead. + let name = + free_folder_name(&tx, &folder.owner_id, folder.parent_id.as_deref(), &name, Some(id)) + .await?; tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id]) .await - .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + .map_err(backend)?; refresh_usage(&tx, &folder.owner_id).await?; tx.commit().await.map_err(backend)?; self.announce([Topic::Library(folder.owner_id)]); @@ -1066,12 +1108,16 @@ impl Store for TursoStore { } cursor = parent_of(&tx, ¤t).await?; } + // A live child of the destination wearing the folder's name is no + // obstacle: the move lands on the first free `name (2)` postfix. + let name = + free_folder_name(&tx, &folder.owner_id, parent_id, &folder.name, Some(id)).await?; tx.execute( - "UPDATE folder SET parent_id = ?1 WHERE id = ?2", - params![parent_id, id], + "UPDATE folder SET parent_id = ?1, name = ?2 WHERE id = ?3", + params![parent_id, name, id], ) .await - .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + .map_err(backend)?; refresh_usage(&tx, &folder.owner_id).await?; tx.commit().await.map_err(backend)?; self.announce([Topic::Library(folder.owner_id)]); @@ -1219,9 +1265,9 @@ impl Store for TursoStore { check_live_parent(&tx, owner_id, folder_id).await?; let (quota, used) = check_quota(&tx, owner_id).await?; fit_quota(quota, used, size)?; - if file_name_taken(&tx, owner_id, folder_id, &name, None).await? { - return Err(StoreError::NameTaken); - } + // A live sibling wearing the name is no refusal: the file takes the + // first free `stem (2).ext` postfix instead. + let name = free_file_name(&tx, owner_id, folder_id, &name, None).await?; let mime = sniff::sniff(bytes).to_string(); let (thumb_state, thumb_bytes) = thumb_for(&mime, size, Some(bytes)); // The bytes land first, temp-plus-rename, then the row says they are @@ -1269,7 +1315,7 @@ impl Store for TursoStore { // a name nothing points at. let _ = std::fs::remove_file(&path); let _ = std::fs::remove_file(thumb_path(&self.storage, &id)); - return Err(map_constraint(e, StoreError::NameTaken)); + return Err(backend(e)); } refresh_usage(&tx, owner_id).await?; let mut rows = tx @@ -1306,17 +1352,17 @@ impl Store for TursoStore { if file.deleted_at.is_some() { return Err(StoreError::NotFound); } - if file_name_taken(&tx, &file.owner_id, file.folder_id.as_deref(), &name, Some(id)).await? - { - return Err(StoreError::NameTaken); - } + // A live sibling wearing the name is no refusal: the rename lands + // on the first free `stem (2).ext` postfix instead. + let name = + free_file_name(&tx, &file.owner_id, file.folder_id.as_deref(), &name, Some(id)).await?; let now = now_text()?; tx.execute( "UPDATE file SET name = ?1, updated_at = ?2 WHERE id = ?3", params![name, now, id], ) .await - .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + .map_err(backend)?; refresh_usage(&tx, &file.owner_id).await?; tx.commit().await.map_err(backend)?; self.announce([Topic::Library(file.owner_id)]); @@ -1334,16 +1380,16 @@ impl Store for TursoStore { return Err(StoreError::NotFound); } check_live_parent(&tx, &file.owner_id, folder_id).await?; - if file_name_taken(&tx, &file.owner_id, folder_id, &file.name, Some(id)).await? { - return Err(StoreError::NameTaken); - } + // A live child of the destination wearing the file's name is no + // obstacle: the move lands on the first free `stem (2).ext` postfix. + let name = free_file_name(&tx, &file.owner_id, folder_id, &file.name, Some(id)).await?; let now = now_text()?; tx.execute( - "UPDATE file SET folder_id = ?1, updated_at = ?2 WHERE id = ?3", - params![folder_id, now, id], + "UPDATE file SET folder_id = ?1, name = ?2, updated_at = ?3 WHERE id = ?4", + params![folder_id, name, now, id], ) .await - .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + .map_err(backend)?; refresh_usage(&tx, &file.owner_id).await?; tx.commit().await.map_err(backend)?; self.announce([Topic::Library(file.owner_id)]); @@ -1509,24 +1555,23 @@ impl Store for TursoStore { if let Some(folder_id) = file.folder_id.as_deref() { ancestor_trashed(&tx, folder_id).await?; } - if file_name_taken( + // A live sibling wearing the name is no refusal: the restore lands + // on the first free `stem (2).ext` postfix instead. + let name = free_file_name( &tx, &file.owner_id, file.folder_id.as_deref(), &file.name, Some(id), ) - .await? - { - return Err(StoreError::NameTaken); - } + .await?; let now = now_text()?; tx.execute( - "UPDATE file SET deleted_at = NULL, updated_at = ?1 WHERE id = ?2", - params![now, id], + "UPDATE file SET name = ?1, deleted_at = NULL, updated_at = ?2 WHERE id = ?3", + params![name, now, id], ) .await - .map_err(|e| map_constraint(e, StoreError::NameTaken))?; + .map_err(backend)?; refresh_usage(&tx, &file.owner_id).await?; tx.commit().await.map_err(backend)?; self.announce([ @@ -1582,6 +1627,21 @@ impl Store for TursoStore { ) .await .map_err(backend)?; + // A live sibling wearing the folder's name is no refusal: the + // restored folder takes the first free `name (2)` postfix. The + // cascade below needs no fix-up — no live row can sit under a + // trashed folder, so only this top folder can collide. + let name = free_folder_name( + &tx, + &folder.owner_id, + folder.parent_id.as_deref(), + &folder.name, + Some(id), + ) + .await?; + tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id]) + .await + .map_err(backend)?; refresh_usage(&tx, &folder.owner_id).await?; tx.commit().await.map_err(backend)?; self.announce([ @@ -2304,28 +2364,29 @@ impl Store for TursoStore { .transaction_with_behavior(TransactionBehavior::Immediate) .await .map_err(backend)?; - let vetted: Result<()> = async { + let vetted: Result = async { check_live_parent(&tx, &session.owner_id, session.folder_id.as_deref()).await?; let (quota, used) = check_quota(&tx, &session.owner_id).await?; fit_quota(quota, used, session.size_bytes)?; - if file_name_taken( + // A live sibling wearing the session's name is no refusal: the + // finished file takes the first free `stem (2).ext` postfix. + free_file_name( &tx, &session.owner_id, session.folder_id.as_deref(), &session.name, None, ) - .await? - { - return Err(StoreError::NameTaken); - } - Ok(()) + .await } .await; - if let Err(e) = vetted { - let _ = std::fs::remove_file(&tmp); - return Err(e); - } + let name = match vetted { + Ok(name) => name, + Err(e) => { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + }; if std::fs::rename(&tmp, &dest).is_err() { let _ = std::fs::remove_file(&tmp); return Err(StoreError::Backend("could not place the assembled file".into())); @@ -2353,7 +2414,7 @@ impl Store for TursoStore { file_id.clone(), session.owner_id.as_str(), session.folder_id.as_deref(), - session.name.as_str(), + name.as_str(), mime, session.size_bytes as i64, stored_thumb.as_str(), @@ -2367,7 +2428,7 @@ impl Store for TursoStore { // is what failed. let _ = std::fs::remove_file(&dest); let _ = std::fs::remove_file(thumb_path(&self.storage, &file_id)); - return Err(map_constraint(e, StoreError::NameTaken)); + return Err(backend(e)); } tx.execute( "UPDATE upload_session SET state = 'done', received_bytes = ?1 WHERE id = ?2", @@ -2590,6 +2651,95 @@ async fn file_name_taken( Ok(rows.next().await.map_err(backend)?.is_some()) } +/// Whether a live sibling folder already wears `name` — the folder half of +/// [`file_name_taken`], over `parent_id` (NULL is the root) instead of +/// `folder_id`. Same rules: trash does not count, `exclude` skips the row +/// being renamed, moved or restored. +async fn folder_name_taken( + conn: &Connection, + owner_id: &str, + parent_id: Option<&str>, + name: &str, + exclude: Option<&str>, +) -> Result { + let exclude = exclude.unwrap_or(""); + let mut rows = match parent_id { + Some(parent) => { + conn.query( + "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id = ?2 \ + AND name = ?3 AND deleted_at IS NULL AND id <> ?4", + params![owner_id, parent, name, exclude], + ) + .await + .map_err(backend)? + } + None => { + conn.query( + "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id IS NULL \ + AND name = ?2 AND deleted_at IS NULL AND id <> ?3", + params![owner_id, name, exclude], + ) + .await + .map_err(backend)? + } + }; + Ok(rows.next().await.map_err(backend)?.is_some()) +} + +/// The name a new or renamed file actually takes: `want` when no live +/// sibling wears it, else the first free `stem (2).ext` postfix — `(3)`, +/// `(4)`, … when `(2)` is taken too. Runs inside the caller's write +/// transaction, so the check and the write are one write set. +async fn free_file_name( + conn: &Connection, + owner_id: &str, + folder_id: Option<&str>, + want: &str, + exclude: Option<&str>, +) -> Result { + if !file_name_taken(conn, owner_id, folder_id, want, exclude).await? { + return Ok(want.to_string()); + } + let mut n = 2u32; + loop { + let candidate = postfixed_file_name(want, n); + if !file_name_taken(conn, owner_id, folder_id, &candidate, exclude).await? { + return Ok(candidate); + } + // Unreachable in practice — four billion live siblings — but the + // loop must be total, so exhaustion is a backend error, never a + // name refusal. + n = n + .checked_add(1) + .ok_or_else(|| StoreError::Backend("too many siblings".into()))?; + } +} + +/// The folder half of [`free_file_name`]: `want` when free, else the first +/// free `want (2)` postfix. +async fn free_folder_name( + conn: &Connection, + owner_id: &str, + parent_id: Option<&str>, + want: &str, + exclude: Option<&str>, +) -> Result { + if !folder_name_taken(conn, owner_id, parent_id, want, exclude).await? { + return Ok(want.to_string()); + } + let mut n = 2u32; + loop { + let candidate = postfixed_folder_name(want, n); + if !folder_name_taken(conn, owner_id, parent_id, &candidate, exclude).await? { + return Ok(candidate); + } + // Unreachable in practice — see `free_file_name` — but total. + n = n + .checked_add(1) + .ok_or_else(|| StoreError::Backend("too many siblings".into()))?; + } +} + /// Refuses with [`StoreError::AncestorTrashed`] while any folder at or above /// `folder_id` wears trash. The walk starts at the folder itself, so callers /// pass the parent chain's head and get the whole ancestry vetted. @@ -2848,16 +2998,6 @@ fn thumb_for(mime: &str, size: u64, bytes: Option<&[u8]>) -> (ThumbState, Option } } -/// A uniqueness refusal is the name check's answer, not a malfunction: the -/// backstop for a race two Immediate transactions could not serialise. -fn map_constraint(e: turso::Error, taken: StoreError) -> StoreError { - if is_constraint_violation(&e) { - taken - } else { - backend(e) - } -} - #[cfg(test)] mod tests { use super::*; @@ -2904,4 +3044,33 @@ mod tests { assert_eq!(like_pattern("100%"), "%100\\%%"); assert_eq!(like_pattern("a_b\\c"), "%a\\_b\\\\c%"); } + + #[test] + fn postfixes_split_at_the_last_dot() { + assert_eq!(postfixed_file_name("report.txt", 2), "report (2).txt"); + assert_eq!(postfixed_file_name("archive.tar.gz", 2), "archive.tar (2).gz"); + assert_eq!(postfixed_file_name("name", 2), "name (2)"); + assert_eq!(postfixed_file_name("name", 3), "name (3)"); + // A leading dot is the whole stem, not an extension: dotfiles keep + // their name whole and wear the postfix at the end. + assert_eq!(postfixed_file_name(".gitignore", 2), ".gitignore (2)"); + assert_eq!(postfixed_folder_name("New folder", 2), "New folder (2)"); + } + + #[test] + fn postfixes_fit_the_name_cap() { + let long = "a".repeat(300); + let file = postfixed_file_name(&format!("{long}.txt"), 2); + assert_eq!(file.chars().count(), MAX_NAME_CHARS); + assert!(file.ends_with(" (2).txt")); + let folder = postfixed_folder_name(&long, 2); + assert_eq!(folder.chars().count(), MAX_NAME_CHARS); + assert!(folder.ends_with(" (2)")); + // Multi-byte stems truncate on a character boundary, never mid-rune. + let wide = "é".repeat(300); + let cut = postfixed_folder_name(&wide, 2); + assert_eq!(cut.chars().count(), MAX_NAME_CHARS); + assert!(cut.ends_with(" (2)")); + assert!(cut.starts_with("é")); + } } \ No newline at end of file diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index 9db63c7..2a290b6 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -169,7 +169,7 @@ async fn quota_and_disablement_round_trip() { } #[tokio::test] -async fn folders_allow_duplicate_names_among_live_siblings() { +async fn folders_postfix_onto_live_sibling_names() { let scratch = Scratch::open().await; let user = alice(&scratch.store).await; let root = scratch @@ -184,18 +184,23 @@ async fn folders_allow_duplicate_names_among_live_siblings() { .unwrap(); assert_eq!(kid.parent_id.as_deref(), Some(root.id.as_str())); - // A live sibling wearing the name is no refusal: folders share names. + // A live sibling wearing the name is no refusal: the second folder + // takes the first free postfix, the next one the one after. let twin = scratch.store.create_folder(&user.id, None, "root").await.unwrap(); assert_ne!(twin.id, root.id); + assert_eq!(twin.name, "root (2)"); + let third = scratch.store.create_folder(&user.id, None, "root").await.unwrap(); + assert_eq!(third.name, "root (3)"); // Same name in a different directory is a different name, as before. - scratch + let away = scratch .store .create_folder(&user.id, Some(&root.id), "root") .await .unwrap(); + assert_eq!(away.name, "root"); let listing = scratch.store.list_children(&user.id, None).await.unwrap(); - assert_eq!(listing.folders.len(), 2); + assert_eq!(listing.folders.len(), 3); let listing = scratch .store .list_children(&user.id, Some(&root.id)) @@ -512,13 +517,16 @@ async fn a_trashed_folder_name_restores_beside_a_live_twin() { let user = alice(&scratch.store).await; let first = scratch.store.create_folder(&user.id, None, "x").await.unwrap(); scratch.store.delete_folder(&first.id).await.unwrap(); - // Deleting frees the name, and restoring beside the squatter is fine: - // folder names may repeat. + // Deleting frees the name, and restoring beside the squatter postfixes + // instead of refusing or duplicating. scratch.store.create_folder(&user.id, None, "x").await.unwrap(); scratch.store.restore_folder(&first.id).await.unwrap(); let listing = scratch.store.list_children(&user.id, None).await.unwrap(); - assert_eq!(listing.folders.iter().filter(|folder| folder.name == "x").count(), 2); + assert_eq!(listing.folders.len(), 2); + assert!(listing.folders.iter().any(|folder| folder.name == "x")); + assert!(listing.folders.iter().any(|folder| folder.name == "x (2)")); } + #[tokio::test] async fn used_bytes_counts_trash_and_purge_frees_it() { let scratch = Scratch::open().await; @@ -1215,19 +1223,19 @@ async fn a_second_migration_database_gains_the_preference_columns_on_open() { } #[tokio::test] -async fn renaming_or_moving_a_folder_onto_a_live_sibling_name_succeeds() { +async fn renaming_or_moving_a_folder_onto_a_live_sibling_name_postfixes() { let scratch = Scratch::open().await; let user = alice(&scratch.store).await; let parent = scratch.store.create_folder(&user.id, None, "parent").await.unwrap(); let other = scratch.store.create_folder(&user.id, None, "other").await.unwrap(); - // Renaming onto a live sibling's name lands. + // Renaming onto a live sibling's name lands on the first free postfix. scratch.store.rename_folder(&other.id, "parent").await.unwrap(); let back: Folder = scratch.store.folder(&other.id).await.unwrap().unwrap(); - assert_eq!(back.name, "parent"); + assert_eq!(back.name, "parent (2)"); // Moving under a parent is refused for strangers and the trashed, but - // never for a name: a live child wearing the name is no obstacle. + // never for a name: a live child wearing the name is postfixed. let kid = scratch .store .create_folder(&user.id, Some(&parent.id), "kid") @@ -1237,33 +1245,100 @@ async fn renaming_or_moving_a_folder_onto_a_live_sibling_name_succeeds() { scratch.store.move_folder(&kid.id, None).await.unwrap(); let back: Folder = scratch.store.folder(&kid.id).await.unwrap().unwrap(); assert_eq!(back.parent_id, None); + assert_eq!(back.name, "kid (2)"); let listing = scratch.store.list_children(&user.id, None).await.unwrap(); - assert_eq!(listing.folders.iter().filter(|folder| folder.name == "kid").count(), 2); + assert_eq!(listing.folders.len(), 4); + assert!(listing.folders.iter().any(|folder| folder.name == "kid")); + assert!(listing.folders.iter().any(|folder| folder.name == "kid (2)")); } #[tokio::test] -async fn file_names_stay_unique_among_live_siblings() { +async fn file_upload_collisions_postfix_at_the_last_dot() { let scratch = Scratch::open().await; let user = alice(&scratch.store).await; - let first = scratch.store.insert_file(&user.id, None, "note", b"one").await.unwrap(); - // A live sibling wearing the name still refuses: files, unlike folders, - // keep one name per directory. - assert!(matches!( - scratch.store.insert_file(&user.id, None, "note", b"two").await, - Err(StoreError::NameTaken) - )); - let other = scratch.store.insert_file(&user.id, None, "other", b"two").await.unwrap(); - assert!(matches!( - scratch.store.rename_file(&other.id, "note").await, - Err(StoreError::NameTaken) - )); - // Trashing frees the name; restoring onto a squatter still refuses. + let first = scratch.store.insert_file(&user.id, None, "report.txt", b"one").await.unwrap(); + assert_eq!(first.name, "report.txt"); + // A live sibling wearing the name is no refusal: the postfix splits at + // the last dot, and the (2) slot occupied steps on to (3). + let second = scratch.store.insert_file(&user.id, None, "report.txt", b"two").await.unwrap(); + assert_eq!(second.name, "report (2).txt"); + let third = scratch.store.insert_file(&user.id, None, "report.txt", b"three").await.unwrap(); + assert_eq!(third.name, "report (3).txt"); +} + +#[tokio::test] +async fn extension_less_file_collisions_postfix_at_the_end() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + scratch.store.insert_file(&user.id, None, "note", b"one").await.unwrap(); + let second = scratch.store.insert_file(&user.id, None, "note", b"two").await.unwrap(); + assert_eq!(second.name, "note (2)"); +} + +#[tokio::test] +async fn file_rename_onto_a_sibling_name_postfixes() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + scratch.store.insert_file(&user.id, None, "report.txt", b"one").await.unwrap(); + scratch.store.insert_file(&user.id, None, "report (2).txt", b"two").await.unwrap(); + let other = scratch.store.insert_file(&user.id, None, "other.txt", b"three").await.unwrap(); + // Both the plain name and (2) are taken: the rename steps on to (3). + scratch.store.rename_file(&other.id, "report.txt").await.unwrap(); + let back = scratch.store.file(&other.id).await.unwrap().unwrap(); + assert_eq!(back.name, "report (3).txt"); + // Renaming onto a free name keeps it whole. + scratch.store.rename_file(&other.id, "fresh.txt").await.unwrap(); + let back = scratch.store.file(&other.id).await.unwrap().unwrap(); + assert_eq!(back.name, "fresh.txt"); +} + +#[tokio::test] +async fn file_move_into_a_folder_with_a_name_twin_postfixes() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let folder = scratch.store.create_folder(&user.id, None, "docs").await.unwrap(); + scratch.store.insert_file(&user.id, Some(&folder.id), "report.txt", b"inside").await.unwrap(); + let loose = scratch.store.insert_file(&user.id, None, "report.txt", b"loose").await.unwrap(); + // Same name in a different directory is fine; moving it next to its + // twin postfixes instead of refusing. + scratch.store.move_file(&loose.id, Some(&folder.id)).await.unwrap(); + let back = scratch.store.file(&loose.id).await.unwrap().unwrap(); + assert_eq!(back.folder_id.as_deref(), Some(folder.id.as_str())); + assert_eq!(back.name, "report (2).txt"); +} + +#[tokio::test] +async fn file_restore_onto_a_squatter_postfixes() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let first = scratch.store.insert_file(&user.id, None, "note.txt", b"one").await.unwrap(); + // Trashing frees the name: the next upload takes it plain. scratch.store.delete_file(&first.id).await.unwrap(); - scratch.store.insert_file(&user.id, None, "note", b"three").await.unwrap(); - assert!(matches!( - scratch.store.restore_file(&first.id).await, - Err(StoreError::NameTaken) - )); + let squatter = scratch.store.insert_file(&user.id, None, "note.txt", b"squatter").await.unwrap(); + assert_eq!(squatter.name, "note.txt"); + // Restoring onto the squatter postfixes instead of refusing. + scratch.store.restore_file(&first.id).await.unwrap(); + let back = scratch.store.file(&first.id).await.unwrap().unwrap(); + assert_eq!(back.name, "note (2).txt"); +} + +#[tokio::test] +async fn finish_upload_onto_a_taken_name_postfixes() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + scratch.store.insert_file(&user.id, None, "clip.txt", b"taken").await.unwrap(); + let bytes = b"arriving"; + let session = scratch + .store + .create_upload_session(&user.id, None, "clip.txt", bytes.len() as u64) + .await + .unwrap(); + scratch.store.record_chunk(&session.id, 0, bytes).await.unwrap(); + // The session keeps the user's literal name; the finished file wears + // the first free postfix. + let file = scratch.store.finish_upload(&session.id).await.unwrap(); + assert_eq!(file.name, "clip (2).txt"); + assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), bytes); } #[tokio::test] diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs index 8e8646f..d6316f3 100644 --- a/crates/in-web/src/drive.rs +++ b/crates/in-web/src/drive.rs @@ -32,7 +32,6 @@ use crate::server::{Refusal, app, back_to, refusal_of, require_user}; /// the leak the distinction exists to prevent. fn store_refusal(error: StoreError) -> Refusal { match error { - StoreError::NameTaken => Refusal::NameTaken, StoreError::QuotaExceeded => Refusal::QuotaExceeded, StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound, // A move nesting a folder inside its own descendant. @@ -426,7 +425,7 @@ async fn drive(cx: &Cx) -> Result { view! { cx => (topbar(cx, NavPage::Drive, &user, language).await?) -
+
if let Some(query) = asked.as_deref() {

(t(language, Key::SearchResults)) (format!(" “{query}”"))

@@ -515,16 +514,6 @@ async fn drive(cx: &Cx) -> Result {
- // The persistent notice stack: client-side upload errors and - // completions render here and stay until dismissed. The region - // itself is server HTML, but every card is client-made - // (`__inAdded`) and mirrored in `window.__inNotices`, which the - // status script re-renders on every `in:wire` — so the cards - // survive both swap paths (the live morph keeps client-made - // nodes; the full replace rebuilds them from the array, which - // lives on `window` and outlives the body). -
if let Some(refusal) = refusal {

(refusal.message_in(language))

} @@ -540,8 +529,9 @@ async fn drive(cx: &Cx) -> Result { // The upload control sits outside the list so the + menu's // "Upload files" label and the page-wide drop handler find it on // every drive view, folder or search. The input stays hidden via - // the file-upload-input rule; the progress list below it carries - // the per-upload bars the script builds. + // the file-upload-input rule; live progress rows go to the + // document shell's `#in-status` corner stack, which every page + // carries, so they stay visible across soft navigations.
Result {
-
// The full-page drop affordance: hidden until a file drag is // over the window, pointer-transparent so it never blocks the // drop itself. @@ -680,7 +669,6 @@ async fn drive(cx: &Cx) -> Result {
(crate::dropdown::dropdown_script(cx).await?) (upload_script(cx).await?) - (status_script(cx).await?) } } @@ -715,7 +703,8 @@ fn query_value(query: &str, key: &str) -> Option { /// The upload control's client half: files under 8 MiB ride one multipart /// post, files at or over it are split into the chunked protocol's calls — /// and every upload, small or big, draws the same live progress row (name, -/// bar, percent) into `#upload-progress-list`. +/// bar, percent) into the persistent `#in-status` corner stack, which the +/// document shell renders on every page. /// /// The form wears `data-hard` so the soft-nav's multipart replay leaves it /// alone — two uploaders racing the same bytes would double-insert, and the @@ -723,9 +712,10 @@ fn query_value(query: &str, key: &str) -> Option { /// form posts plainly and the 303 lands back on the folder. /// /// Failures never append inline notes anymore: they go through -/// `window.__inNotify` into the persistent stack ([`status_script`]), which -/// survives the swaps that used to wipe them. Completions announce there -/// too, then the page navigates to the landing the post answered. +/// `window.__inNotify` into the persistent stack +/// ([`crate::layout::status_script`]), which survives the swaps that used to +/// wipe them. Completions announce there too, then the page navigates to the +/// landing the post answered. /// /// The same block carries the `?edit=` row's focus: the rename input the /// server renders open gets focused with its name selected on arrival, so a @@ -748,37 +738,92 @@ async fn upload_script(cx: &Cx) -> Result { if (window.__inUpload) { return; } \ window.__inUpload = true; \ var LIMIT = 8388608; \ - function progressList() { return document.getElementById('upload-progress-list'); } \ + function upBox() { return document.getElementById('in-status'); } \ + function upSeq() { window.__inUpSeq = (window.__inUpSeq || 0) + 1; return window.__inUpSeq; } \ + /* Rows are found by walking `[data-upload]` and comparing the \ + attribute in script: a selector with an interpolated value would \ + need double quotes inside this Rust string, so it is avoided. */ \ + function findRow(box, id) { \ + var rows = box.querySelectorAll('[data-upload]'); \ + for (var i = 0; i < rows.length; i++) { \ + if (rows[i].getAttribute('data-upload') == String(id)) { return rows[i]; } \ + } \ + return null; \ + } \ + /* The in-flight mirror: progress rows are client-made (`__inAdded`, \ + so the live morph keeps them) and mirrored here, so the full-replace \ + path — which rebuilds the body on every soft navigation — re-renders \ + them from this array on `in:wire` instead of losing sight of the \ + upload. Progress ticks only ever write the mirror, then paint the \ + live row if it is still connected; a tick landing mid-swap paints \ + on the next wire. Full page loads cannot preserve an in-flight bar \ + — the completion card still announces on landing. */ \ + function renderUploads() { \ + var box = upBox(); \ + if (!box) { return; } \ + if (!window.__inUploads) { window.__inUploads = []; } \ + var seen = {}; \ + window.__inUploads.forEach(function (u) { \ + seen[u.id] = true; \ + var row = findRow(box, u.id); \ + if (!row) { \ + row = document.createElement('div'); \ + row.className = 'upload-progress-row'; \ + row.setAttribute('data-upload', String(u.id)); \ + if (u.name) { row.setAttribute('aria-label', u.name); } \ + var name = document.createElement('span'); \ + name.className = 'upload-progress-name'; \ + name.textContent = u.name || ''; \ + var track = document.createElement('div'); \ + track.className = 'upload-progress'; \ + var fill = document.createElement('div'); \ + fill.className = 'upload-progress-fill'; \ + track.appendChild(fill); \ + var pct = document.createElement('span'); \ + pct.className = 'upload-progress-pct'; \ + row.appendChild(name); \ + row.appendChild(track); \ + row.appendChild(pct); \ + box.appendChild(window.__inAdded(row)); \ + } \ + var text = Math.min(100, Math.round(u.frac * 100)) + '%'; \ + var fillNow = row.querySelector('.upload-progress-fill'); \ + var pctNow = row.querySelector('.upload-progress-pct'); \ + if (fillNow) { fillNow.style.width = text; } \ + if (pctNow) { pctNow.textContent = text; } \ + }); \ + box.querySelectorAll('[data-upload]').forEach(function (row) { \ + if (!seen[row.getAttribute('data-upload')]) { row.remove(); } \ + }); \ + } \ function bar(label) { \ - var row = document.createElement('div'); \ - row.className = 'upload-progress-row'; \ - var name = document.createElement('span'); \ - name.className = 'upload-progress-name'; \ - name.textContent = label || ''; \ - var track = document.createElement('div'); \ - track.className = 'upload-progress'; \ - var fill = document.createElement('div'); \ - fill.className = 'upload-progress-fill'; \ - track.appendChild(fill); \ - var pct = document.createElement('span'); \ - pct.className = 'upload-progress-pct'; \ - pct.textContent = '0%'; \ - row.appendChild(name); \ - row.appendChild(track); \ - row.appendChild(pct); \ - if (label) { row.setAttribute('aria-label', label); } \ - var list = progressList(); \ - if (list) { list.appendChild(window.__inAdded(row)); } \ - return { row: row, fill: fill, pct: pct }; \ + if (!window.__inUploads) { window.__inUploads = []; } \ + var u = { id: upSeq(), name: label || '', frac: 0 }; \ + window.__inUploads.push(u); \ + renderUploads(); \ + return u; \ } \ - function setProgress(ui, frac) { \ + function setProgress(u, frac) { \ + u.frac = frac; \ + var box = upBox(); \ + var row = box && findRow(box, u.id); \ + if (!row) { renderUploads(); return; } \ var text = Math.min(100, Math.round(frac * 100)) + '%'; \ - ui.fill.style.width = text; \ - ui.pct.textContent = text; \ + var fill = row.querySelector('.upload-progress-fill'); \ + var pct = row.querySelector('.upload-progress-pct'); \ + if (fill) { fill.style.width = text; } \ + if (pct) { pct.textContent = text; } \ } \ - function dropRow(ui) { \ - if (ui.row.parentNode) { ui.row.parentNode.removeChild(ui.row); } \ + function dropRow(u) { \ + if (window.__inUploads) { \ + window.__inUploads = window.__inUploads.filter(function (x) { return x.id !== u.id; }); \ + } \ + var box = upBox(); \ + var row = box && findRow(box, u.id); \ + if (row) { row.remove(); } \ } \ + document.addEventListener('in:wire', renderUploads); \ + renderUploads(); \ function notify(kind, message) { \ if (window.__inNotify) { window.__inNotify(kind, message); } \ } \ @@ -937,73 +982,6 @@ async fn upload_script(cx: &Cx) -> Result { view! { cx => } } -/// The persistent notice stack's client half: upload errors and completions -/// that must stay until dismissed. -/// -/// How the cards survive the swaps: every card is registered through -/// `__inAdded`, so the live path's morph — which pairs only server-rendered -/// nodes and leaves client-made ones alone — keeps them where they are. The -/// full-replace path (navigations, form posts) rebuilds the body and would -/// drop them, so every notice is also mirrored in `window.__inNotices`, -/// which lives on the document's `window` and outlives any one body; the -/// `in:wire` pass `swap()` runs after every paint re-renders the stack from -/// that array. Dismissing (the ✕, labelled from the stack's -/// `data-dismiss-label`) drops the notice from both. Nothing here -/// auto-times out. -/// -/// The server-rendered `?refusal` banner needs no such route: it rides the -/// redirect URL the swap just painted, so both paths re-render it from the -/// server's own bytes. -async fn status_script(cx: &Cx) -> Result { - use topcoat::view::Unescaped; - const JS: &str = "\ - (function () { \ - if (window.__inStatus) { return; } \ - window.__inStatus = true; \ - if (!window.__inNotices) { window.__inNotices = []; } \ - var seq = 0; \ - window.__inNotices.forEach(function (n) { if (n.id > seq) { seq = n.id; } }); \ - function box() { return document.getElementById('in-status'); } \ - function dismissLabel() { \ - var b = box(); \ - return (b && b.getAttribute('data-dismiss-label')) || 'dismiss'; \ - } \ - window.__inNotify = function (kind, text) { \ - seq++; \ - window.__inNotices.push({ id: seq, kind: kind, text: text }); \ - render(); \ - }; \ - function render() { \ - var target = box(); \ - if (!target) { return; } \ - target.querySelectorAll('[data-notice]').forEach(function (old) { old.remove(); }); \ - window.__inNotices.forEach(function (n) { \ - var card = document.createElement('div'); \ - card.className = 'in-status-card in-status-' + n.kind; \ - card.setAttribute('data-notice', String(n.id)); \ - var text = document.createElement('span'); \ - text.className = 'in-status-text'; \ - text.textContent = n.text; \ - var shut = document.createElement('button'); \ - shut.type = 'button'; \ - shut.className = 'in-status-dismiss'; \ - shut.textContent = '✕'; \ - shut.setAttribute('aria-label', dismissLabel()); \ - shut.addEventListener('click', function () { \ - window.__inNotices = window.__inNotices.filter(function (x) { return x.id !== n.id; }); \ - card.remove(); \ - }); \ - card.appendChild(text); \ - card.appendChild(shut); \ - target.appendChild(window.__inAdded(card)); \ - }); \ - } \ - document.addEventListener('in:wire', render); \ - render(); \ - })();"; - view! { cx => } -} - #[derive(serde::Deserialize)] struct CreateFolderForm { #[serde(default)] @@ -1047,10 +1025,9 @@ async fn create_folder(cx: &Cx, Form(input): Form) -> Redirect } } -/// The + menu's quick create: the first free generic name, then a 303 to the -/// folder view with that row in its rename form. The loop is the -/// collision-suffixing (`New folder 2`, …), bounded so a pathological tree -/// answers unavailable instead of spinning. +/// The + menu's quick create: a generic name, then a 303 to the folder view +/// with that row in its rename form. The store postfixes a colliding name +/// itself, so one attempt always answers. async fn quick_folder( cx: &Cx, store: &std::sync::Arc, @@ -1058,29 +1035,20 @@ async fn quick_folder( parent: Option<&str>, ) -> Redirect { let base = t(lang(cx).await, Key::NewFolder).to_string(); - for attempt in 0..64u32 { - let name = if attempt == 0 { - base.clone() - } else { - format!("{} {}", base, attempt + 1) - }; - match store.create_folder(owner_id, parent, &name).await { - Ok(folder) => { - let location = match parent { - Some(parent) => format!("/drive?folder={parent}&edit={}", folder.id), - None => format!("/drive?edit={}", folder.id), - }; - return Ok(( - StatusCode::SEE_OTHER, - [(header::LOCATION, location)], - Json(None), - )); - } - Err(StoreError::NameTaken) => {} - Err(error) => return redirect(cx, Some(store_refusal(error))), + match store.create_folder(owner_id, parent, &base).await { + Ok(folder) => { + let location = match parent { + Some(parent) => format!("/drive?folder={parent}&edit={}", folder.id), + None => format!("/drive?edit={}", folder.id), + }; + Ok(( + StatusCode::SEE_OTHER, + [(header::LOCATION, location)], + Json(None), + )) } + Err(error) => redirect(cx, Some(store_refusal(error))), } - redirect(cx, Some(Refusal::Unavailable)) } #[derive(serde::Deserialize)] diff --git a/crates/in-web/src/files.rs b/crates/in-web/src/files.rs index 9f62583..863dcd6 100644 --- a/crates/in-web/src/files.rs +++ b/crates/in-web/src/files.rs @@ -35,7 +35,6 @@ path_param!(id); /// [`Refusal::NotFound`], same as a missing id. fn store_refusal(error: StoreError) -> Refusal { match error { - StoreError::NameTaken => Refusal::NameTaken, StoreError::QuotaExceeded => Refusal::QuotaExceeded, StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound, StoreError::UploadExpired => Refusal::UploadExpired, @@ -472,16 +471,22 @@ async fn view_file(cx: &Cx) -> Result { view! { cx => (topbar(cx, NavPage::Drive, &user, language).await?) -
-

(t(language, Key::BackToDrive))

-

(entry_chip(cx, &file).await?) (file.name.clone())

+
+ +

(entry_chip(cx, &file).await?) (file.name.clone())

(meta)

if may_download { match viewer_kind(&file.mime) { Some(ViewerKind::Image) => (file.name.clone()), Some(ViewerKind::Video) => , - Some(ViewerKind::Audio) => , + Some(ViewerKind::Audio) =>
, Some(ViewerKind::Pdf) =>

(t(language, Key::PreviewUnavailable))

, @@ -499,10 +504,7 @@ async fn view_file(cx: &Cx) -> Result {
} - if may_download { -

(t(language, Key::Download))

- } -
+

(t(language, Key::FileDetails))

diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index 80021da..9a941df 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -198,9 +198,10 @@ pub enum Key { KindAll, KindFolders, KindFiles, - // Wave-2 trash/share extras (TrashShareBuild owns this block). SortDeleted, SortOwner, + // Settings limits redesign (SettingsBuild owns this block). + UploadLimitHelp, } pub fn t(lang: Lang, key: Key) -> &'static str { @@ -289,7 +290,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { AdminPanel => "Everyone", AllUsers => "Everyone", SetQuota => "Set the quota", - QuotaBytes => "Quota in bytes", + QuotaBytes => "Storage quota", DisableUser => "Disable", EnableUser => "Enable", DisabledBadge => "disabled", @@ -308,9 +309,9 @@ pub fn t(lang: Lang, key: Key) -> &'static str { Saved => "Saved.", UploadedLabel => "Uploaded", DownloadsLabel => "Downloads", - UploadLimits => "Upload limits", + UploadLimits => "Upload limit", CurrentUploadLimit => "Current limit", - MaxUploadBytes => "Limit in bytes", + MaxUploadBytes => "Upload limit", Options => "Options", DropFilesToUpload => "Drop files to upload", Dismiss => "Dismiss", @@ -325,6 +326,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { KindFiles => "Files", SortDeleted => "Deleted", SortOwner => "Owner", + UploadLimitHelp => "The most one uploaded file may be. Applies to everyone.", }, Lang::Tr => match key { Cancel => "Vazgeç", @@ -409,7 +411,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { AdminPanel => "Herkes", AllUsers => "Herkes", SetQuota => "Kotayı ayarla", - QuotaBytes => "Bayt olarak kota", + QuotaBytes => "Depolama kotası", DisableUser => "Devre dışı bırak", EnableUser => "Etkinleştir", DisabledBadge => "devre dışı", @@ -428,9 +430,9 @@ pub fn t(lang: Lang, key: Key) -> &'static str { Saved => "Kaydedildi.", UploadedLabel => "Yüklendi", DownloadsLabel => "İndirme", - UploadLimits => "Yükleme sınırları", + UploadLimits => "Yükleme sınırı", CurrentUploadLimit => "Geçerli sınır", - MaxUploadBytes => "Bayt olarak sınır", + MaxUploadBytes => "Yükleme sınırı", Options => "Seçenekler", DropFilesToUpload => "Yüklemek için dosyaları bırakın", Dismiss => "Kapat", @@ -445,6 +447,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { KindFiles => "Dosyalar", SortDeleted => "Silindi", SortOwner => "Sahibi", + UploadLimitHelp => "Tek bir dosyanın alabileceği en büyük boyut. Herkes için geçerlidir.", }, } } diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index a300fc5..a88270c 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -868,6 +868,73 @@ pub async fn escape_script(cx: &Cx) -> Result { })();"; view! { cx => } } +/// The persistent notice stack's client half: upload errors and completions +/// that must stay until dismissed. Emitted from the document shell so every +/// page carries the stack — an upload started on the drive keeps its home +/// when the reader soft-navigates to the trash mid-flight. +/// +/// How the cards survive the swaps: every card is registered through +/// `__inAdded`, so the live path's morph — which pairs only server-rendered +/// nodes and leaves client-made ones alone — keeps them where they are. The +/// full-replace path (navigations, form posts) rebuilds the body and would +/// drop them, so every notice is also mirrored in `window.__inNotices`, +/// which lives on the document's `window` and outlives any one body; the +/// `in:wire` pass `swap()` runs after every paint re-renders the stack from +/// that array. Dismissing (the ✕, labelled from the stack's +/// `data-dismiss-label`) drops the notice from both. Nothing here +/// auto-times out. +/// +/// The server-rendered `?refusal` banner needs no such route: it rides the +/// redirect URL the swap just painted, so both paths re-render it from the +/// server's own bytes. +pub async fn status_script(cx: &Cx) -> Result { + const JS: &str = "\ + (function () { \ + if (window.__inStatus) { return; } \ + window.__inStatus = true; \ + if (!window.__inNotices) { window.__inNotices = []; } \ + var seq = 0; \ + window.__inNotices.forEach(function (n) { if (n.id > seq) { seq = n.id; } }); \ + function box() { return document.getElementById('in-status'); } \ + function dismissLabel() { \ + var b = box(); \ + return (b && b.getAttribute('data-dismiss-label')) || 'dismiss'; \ + } \ + window.__inNotify = function (kind, text) { \ + seq++; \ + window.__inNotices.push({ id: seq, kind: kind, text: text }); \ + render(); \ + }; \ + function render() { \ + var target = box(); \ + if (!target) { return; } \ + target.querySelectorAll('[data-notice]').forEach(function (old) { old.remove(); }); \ + window.__inNotices.forEach(function (n) { \ + var card = document.createElement('div'); \ + card.className = 'in-status-card in-status-' + n.kind; \ + card.setAttribute('data-notice', String(n.id)); \ + var text = document.createElement('span'); \ + text.className = 'in-status-text'; \ + text.textContent = n.text; \ + var shut = document.createElement('button'); \ + shut.type = 'button'; \ + shut.className = 'in-status-dismiss'; \ + shut.textContent = '✕'; \ + shut.setAttribute('aria-label', dismissLabel()); \ + shut.addEventListener('click', function () { \ + window.__inNotices = window.__inNotices.filter(function (x) { return x.id !== n.id; }); \ + card.remove(); \ + }); \ + card.appendChild(text); \ + card.appendChild(shut); \ + target.appendChild(window.__inAdded(card)); \ + }); \ + } \ + document.addEventListener('in:wire', render); \ + render(); \ + })();"; + view! { cx => } +} /// Every path that matches no page raises a `NotFoundError`, so it renders /// through `root_layout`'s catch below rather than the router's bare default. @@ -939,6 +1006,13 @@ async fn root_layout(cx: &Cx, slot: Result) -> Result { // would just reconnect against that refusal forever. if asking { (live_script(cx).await?) } (content) + // The persistent corner stack: client-made upload progress + // rows and notice cards live here, marked `__inAdded` and + // mirrored on `window`, so both swap paths keep them while + // the reader moves between pages mid-upload. +
+ (status_script(cx).await?) } diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index f5fb738..5507b4b 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -194,8 +194,6 @@ pub enum Refusal { NotFound, /// The bytes would not fit the remaining quota. QuotaExceeded, - /// A sibling already carries that name. - NameTaken, /// A folder with children stays until it is emptied. FolderNotEmpty, /// The target belongs to somebody else. Answered like [`Refusal::NotFound`] @@ -233,7 +231,6 @@ impl Refusal { Refusal::Forbidden => "Not permitted.".to_string(), Refusal::NotFound => "No such file or folder.".to_string(), Refusal::QuotaExceeded => "Over quota.".to_string(), - Refusal::NameTaken => "That name is already taken here.".to_string(), Refusal::FolderNotEmpty => "That folder still has files in it.".to_string(), // Same sentence as NotFound: a cross-owner probe must not learn // the target exists. @@ -262,7 +259,6 @@ impl Refusal { Refusal::Forbidden => "İzin verilmiyor.".to_string(), Refusal::NotFound => "Böyle bir dosya ya da klasör yok.".to_string(), Refusal::QuotaExceeded => "Kota doldu.".to_string(), - Refusal::NameTaken => "Bu ad burada zaten var.".to_string(), Refusal::FolderNotEmpty => "Bu klasörde hâlâ dosyalar var.".to_string(), Refusal::CrossOwner => "Böyle bir dosya ya da klasör yok.".to_string(), Refusal::ShareRevoked => "Bu bağlantı artık çalışmıyor.".to_string(), @@ -287,7 +283,6 @@ impl Refusal { "forbidden" => Refusal::Forbidden, "not-found" => Refusal::NotFound, "quota-exceeded" => Refusal::QuotaExceeded, - "name-taken" => Refusal::NameTaken, "folder-not-empty" => Refusal::FolderNotEmpty, "cross-owner" => Refusal::CrossOwner, "share-revoked" => Refusal::ShareRevoked, @@ -316,7 +311,6 @@ impl Refusal { Refusal::Forbidden => "forbidden", Refusal::NotFound => "not-found", Refusal::QuotaExceeded => "quota-exceeded", - Refusal::NameTaken => "name-taken", Refusal::FolderNotEmpty => "folder-not-empty", Refusal::CrossOwner => "cross-owner", Refusal::ShareRevoked => "share-revoked", diff --git a/crates/in-web/src/settings.rs b/crates/in-web/src/settings.rs index f4cd42c..d3fe6d9 100644 --- a/crates/in-web/src/settings.rs +++ b/crates/in-web/src/settings.rs @@ -49,6 +49,49 @@ fn quota_percent(user: &User) -> u8 { (user.used_bytes.saturating_mul(100) / user.quota_bytes).min(100) as u8 } +/// One mebibyte / gibibyte in bytes: the only two units the limit forms speak. +/// Raw bytes never reach the browser — the panel shows `human_bytes` and the +/// forms post a decimal amount plus one of these units, converted back here. +const MIB_BYTES: f64 = 1_048_576.0; +const GIB_BYTES: f64 = 1_073_741_824.0; + +/// The `(amount, unit)` pair a human-unit form field defaults to: gibibytes +/// once the value reaches one, mebiBytes below it, so `2 GiB` edits as `2` +/// GiB rather than `2048` MiB, while a small `512 MiB` cap stays addressable. +fn bytes_as_unit(bytes: u64) -> (String, &'static str) { + if bytes >= GIB_BYTES as u64 { + (trim_amount(bytes as f64 / GIB_BYTES), "GiB") + } else { + (trim_amount(bytes as f64 / MIB_BYTES), "MiB") + } +} + +/// A form amount for a number input: two decimals at most, trailing zeros +/// (and a bare point) trimmed, so the field reads `2` and `2.5`, never +/// `2.00` or `2.5000000001`. +fn trim_amount(value: f64) -> String { + let rounded = (value * 100.0).round() / 100.0; + let text = format!("{rounded:.2}"); + text.trim_end_matches('0').trim_end_matches('.').to_string() +} + +/// The bytes an `(amount, unit)` pair names, or `None` when the pair is not +/// a usable limit: an unknown unit, or an amount that is not a finite +/// positive number. Callers decide whether zero passes (quota) or not +/// (upload limit). +fn unit_bytes(amount: &str, unit: &str) -> Option { + let per = match unit { + "MiB" => MIB_BYTES, + "GiB" => GIB_BYTES, + _ => return None, + }; + let value: f64 = amount.trim().parse().ok()?; + if !value.is_finite() || value < 0.0 { + return None; + } + Some((value * per).round() as u64) +} + type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>; /// Back to settings, the refusal (if any) on the query — or `saved=` @@ -67,51 +110,62 @@ fn redirect_back(cx: &Cx, call: &str, refusal: Option) -> Redirect { #[derive(Deserialize)] struct QuotaForm { user_id: String, - quota_bytes: u64, + #[serde(default)] + quota: String, + #[serde(default)] + quota_unit: String, } -/// Sets one account's byte ceiling. The bytes it already holds are untouched — -/// a quota lowered under current usage refuses new uploads until the person -/// frees space, rather than deleting anything. +/// Sets one account's byte ceiling from a human-unit pair (`quota` amount in +/// `quota_unit` MiB/GiB), converted to bytes for the store. The bytes already +/// held are untouched — a quota lowered under current usage refuses new +/// uploads until the person frees space, rather than deleting anything. #[route(POST "/api/settings/quota")] async fn set_quota(cx: &Cx, Form(input): Form) -> Redirect { if let Err(refusal) = require_admin(cx).await { return redirect_back(cx, "quota", Some(refusal)); } - match app(cx).store.set_user_quota(&input.user_id, input.quota_bytes).await { - Ok(()) => redirect_back(cx, "quota", None), - Err(error) => redirect_back(cx, "quota", Some(refusal_of(error))), + match unit_bytes(&input.quota, &input.quota_unit) { + Some(quota_bytes) => match app(cx).store.set_user_quota(&input.user_id, quota_bytes).await { + Ok(()) => redirect_back(cx, "quota", None), + Err(error) => redirect_back(cx, "quota", Some(refusal_of(error))), + }, + None => redirect_back(cx, "quota", Some(Refusal::BadLimit)), } } #[derive(Deserialize)] struct UploadLimitForm { - max_upload_bytes: u64, + #[serde(default)] + max_upload: String, + #[serde(default)] + max_upload_unit: String, } - -/// Sets the instance-wide per-file upload ceiling, in bytes — the same unit -/// the `max_upload_bytes` instance setting stores, so the round trip is -/// exact: what the panel shows is what a save writes back. The bytes already -/// held are untouched — a ceiling lowered under an existing file refuses new -/// uploads past it, rather than deleting anything. +/// Sets the instance-wide per-file upload ceiling from a human-unit pair +/// (`max_upload` amount in `max_upload_unit` MiB/GiB), converted to bytes +/// for the `max_upload_bytes` instance setting — so `2 GiB` stores +/// `2147483648` and the panel reads it back as `2.0 GiB`. The fallback chain +/// in [`crate::server::effective_upload_limit`] is untouched, and zero (or +/// anything unparseable) is refused with `BadLimit`: an install must always +/// have a positive per-file ceiling. #[route(POST "/api/settings/upload-limit")] async fn set_upload_limit(cx: &Cx, Form(input): Form) -> Redirect { if let Err(refusal) = require_admin(cx).await { return redirect_back(cx, "upload-limit", Some(refusal)); } - if input.max_upload_bytes == 0 { - return redirect_back(cx, "upload-limit", Some(Refusal::BadLimit)); - } - match app(cx) - .store - .set_setting( - crate::server::MAX_UPLOAD_SETTING, - &input.max_upload_bytes.to_string(), - ) - .await - { - Ok(()) => redirect_back(cx, "upload-limit", None), - Err(error) => redirect_back(cx, "upload-limit", Some(refusal_of(error))), + match unit_bytes(&input.max_upload, &input.max_upload_unit) { + Some(bytes) if bytes > 0 => match app(cx) + .store + .set_setting( + crate::server::MAX_UPLOAD_SETTING, + &bytes.to_string(), + ) + .await + { + Ok(()) => redirect_back(cx, "upload-limit", None), + Err(error) => redirect_back(cx, "upload-limit", Some(refusal_of(error))), + }, + _ => redirect_back(cx, "upload-limit", Some(Refusal::BadLimit)), } } @@ -244,7 +298,7 @@ async fn settings(cx: &Cx) -> Result { cx => (topbar(cx, NavPage::Settings, &fresh, language).await?)
-
+

(t(language, Key::Settings))

(refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "upload-limit"]).await?) if let Some(token) = created { @@ -334,9 +388,14 @@ async fn settings(cx: &Cx) -> Result {

(t(language, Key::UploadLimits))

-

(format!("{}: {}", t(language, Key::CurrentUploadLimit), human_bytes(limit)))

+

(t(language, Key::UploadLimitHelp))

- + (format!("{}: {}", t(language, Key::CurrentUploadLimit), human_bytes(limit))) + +
@@ -376,7 +435,11 @@ async fn settings(cx: &Cx) -> Result {
- + +
if listed.id != fresh.id { diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs index 1fc52d3..ccc993f 100644 --- a/crates/in-web/src/share.rs +++ b/crates/in-web/src/share.rs @@ -87,7 +87,6 @@ fn redirect_back(cx: &Cx, nowhere: &str, call: &str, refusal: Option) - pub(crate) fn refusal_of(error: StoreError) -> Refusal { match error { StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound, - StoreError::NameTaken => Refusal::NameTaken, StoreError::QuotaExceeded => Refusal::QuotaExceeded, StoreError::AncestorTrashed => Refusal::AncestorTrashed, _ => Refusal::Unavailable, @@ -726,7 +725,7 @@ async fn folder_card( view! { cx => (wordmark(cx).await?) -
+

(here.name.clone())

@@ -737,11 +736,11 @@ async fn folder_card( match row { PublicEntry::Folder(folder) => , PublicEntry::File(file) =>
(public_chip(cx, &format!("{base}?folder={at}&file={}&thumb=1", file.id), file).await?) - (file.name.clone()) + (file.name.clone()) (crate::settings::human_bytes(file.size_bytes))
if link.can_download { @@ -961,7 +960,7 @@ async fn shared(cx: &Cx) -> Result { view! { cx => (topbar(cx, NavPage::Shared, &user, language).await?) -
+

(t(language, Key::SharedWithMe))

@@ -1016,13 +1015,13 @@ async fn shared(cx: &Cx) -> Result {
if row.item.kind == ShareKind::Folder { - (row.item.name.clone()) + (row.item.name.clone()) } else { match &row.file { Some(file) => (shared_chip(cx, file).await?), None => , } - (row.item.name.clone()) + (row.item.name.clone()) }
(shared_details(language, row)) diff --git a/crates/in-web/src/trash.rs b/crates/in-web/src/trash.rs index 71c90a1..0f116e8 100644 --- a/crates/in-web/src/trash.rs +++ b/crates/in-web/src/trash.rs @@ -307,7 +307,7 @@ async fn trash(cx: &Cx) -> Result { view! { cx => (topbar(cx, NavPage::Trash, &user, language).await?) -
+

(t(language, Key::Trash))

@@ -348,7 +348,7 @@ async fn trash(cx: &Cx) -> Result { (refusal_banner(cx, language, &["restore", "purge", "empty"]).await?) if !nothing_trashed { - + }
@@ -368,7 +368,7 @@ async fn trash(cx: &Cx) -> Result { match row { TrashEntry::Folder(folder) =>
- (folder.name.clone()) + (folder.name.clone()) (trash_details(language, row))
@@ -384,7 +384,7 @@ async fn trash(cx: &Cx) -> Result {
, TrashEntry::File(file) =>
(trash_chip(cx, file).await?) - (file.name.clone()) + (file.name.clone()) (trash_details(language, row))
diff --git a/crates/in-web/src/upload.rs b/crates/in-web/src/upload.rs index d7d4a53..3d4e474 100644 --- a/crates/in-web/src/upload.rs +++ b/crates/in-web/src/upload.rs @@ -60,7 +60,6 @@ fn store_refusal(error: StoreError) -> Refusal { StoreError::UploadExpired => Refusal::UploadExpired, StoreError::BadChunk => Refusal::BadChunk, StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound, - StoreError::NameTaken => Refusal::NameTaken, _ => Refusal::Unavailable, } } diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index a1522e3..2551d19 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -1848,18 +1848,18 @@ async fn settings_quota_and_disable_guards() { assert_eq!(page.status, StatusCode::OK, "{}", page.text()); assert!(page.text().contains("ada@in.test"), "{}", page.text()); - // Admin sets Bob's quota. + // Admin sets Bob's quota in human units: 2 GiB lands as 2147483648 bytes. let answer = app .post( "/api/settings/quota", Some(&admin), - &[("user_id", &bob_id), ("quota_bytes", "123456")], + &[("user_id", &bob_id), ("quota", "2"), ("quota_unit", "GiB")], ) .await; assert!(answer.accepted(), "quota refused: {:?}", answer.location); assert_eq!( app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes, - 123456 + 2147483648 ); // A non-admin is refused the same call. @@ -1867,7 +1867,11 @@ async fn settings_quota_and_disable_guards() { .post( "/api/settings/quota", Some(&bob), - &[("user_id", &bob_id), ("quota_bytes", "999")], + &[ + ("user_id", &bob_id), + ("quota", "999"), + ("quota_unit", "MiB"), + ], ) .await; assert!( @@ -1931,7 +1935,7 @@ async fn signed_out_mutations_ask_to_sign_in() { ( "/api/settings/quota", "quota", - &[("user_id", "x"), ("quota_bytes", "1")][..], + &[("user_id", "x"), ("quota", "1"), ("quota_unit", "GiB")][..], ), ] { let answer = app.post(path, None, form).await; @@ -2258,42 +2262,29 @@ async fn view_only_public_thumb_serves_webp() { } #[tokio::test] -async fn a_refused_upload_carries_a_well_formed_query() { +async fn a_name_collision_upload_lands_postfixed() { let app = TestApp::build().await; let cookie = app.sign_in("sub-dupe", "dupe@in.test", "Dupe").await; - // One file in, then the same name again: the refusal redirect must join - // the feedback pairs with `?`, not `&` — a `/drive&refusal=...` Location - // is a different path entirely and 404s (observed live). - for _ in 0..2 { - app.post_multipart( - "/files", - Some(&cookie), - &[("folder_id", "")], - &[("same.txt", "text/plain", b"first or second")], - ) - .await; + // Three uploads under one name: none is refused — the later ones land + // with a postfix before the extension instead of wasting the upload. + for body in [b"first" as &[u8], b"second", b"third"] { + let answer = app + .post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("same.txt", "text/plain", body)], + ) + .await; + assert!(answer.accepted(), "upload refused: {:?}", answer.location); } - let answer = app - .post_multipart( - "/files", - Some(&cookie), - &[("folder_id", "")], - &[("same.txt", "text/plain", b"third")], - ) - .await; - let location = answer.location.expect("no Location on the refusal"); - assert_eq!(answer.status, StatusCode::SEE_OTHER); - assert!( - location.starts_with("/drive?"), - "refusal Location was: {location}" - ); - assert!(location.contains("refusal=name-taken"), "{location}"); - // And the browser that follows it lands on the drive page, not the 404. - let page = app.get(&location, Some(&cookie)).await; + let page = app.get("/drive", Some(&cookie)).await; assert_eq!(page.status, StatusCode::OK, "{}", page.text()); - assert!(page.text().contains("already taken"), "{}", page.text()); + assert!(page.text().contains("same.txt"), "{}", page.text()); + assert!(page.text().contains("same (2).txt"), "{}", page.text()); + assert!(page.text().contains("same (3).txt"), "{}", page.text()); } // -- settings preferences ------------------------------------------------------ @@ -2549,7 +2540,7 @@ fn assert_stage_nests(body: &str, markers: &[&str]) { "content still sits in the shell: {body}" ); let stage = body - .find("
") + .find("
").expect("no main close"); assert!(stage < close, "unclosed stage"); @@ -2931,8 +2922,8 @@ async fn drive_quick_create_names_and_edits() { .unwrap(); assert_eq!(folder_id(&app, &me, None, "New folder").await, edit); - // Duplicate folder names are allowed: a second quick create takes the - // same generic name on a new row instead of suffixing. + // A second quick create never refuses: the store postfixes the generic + // name instead of duplicating it. let answer = app .post("/api/folder/create", Some(&cookie), &[("parent_id", "")]) .await; @@ -2949,13 +2940,14 @@ async fn drive_quick_create_names_and_edits() { .unwrap(); assert_ne!(edit, edit2, "second quick create reused the row"); let root = app.store.list_children(&me, None).await.unwrap(); - assert_eq!( - root.folders - .iter() - .filter(|folder| folder.name == "New folder") - .count(), - 2, - "second quick create did not repeat the generic name" + let names: Vec<&str> = root + .folders + .iter() + .map(|folder| folder.name.as_str()) + .collect(); + assert!( + names.contains(&"New folder") && names.contains(&"New folder (2)"), + "second quick create did not postfix the generic name: {names:?}" ); // A typed name keeps the old answer: back to the page, no edit mode. @@ -2981,7 +2973,6 @@ async fn drive_quick_create_names_and_edits() { ); folder_id(&app, &me, None, "typed").await; - // A typed duplicate is accepted too — folders share names now. let answer = app .post( "/api/folder/create", @@ -2995,13 +2986,14 @@ async fn drive_quick_create_names_and_edits() { answer.location ); let root = app.store.list_children(&me, None).await.unwrap(); - assert_eq!( - root.folders - .iter() - .filter(|folder| folder.name == "typed") - .count(), - 2, - "typed dupe did not land beside the first" + let names: Vec<&str> = root + .folders + .iter() + .map(|folder| folder.name.as_str()) + .collect(); + assert!( + names.contains(&"typed") && names.contains(&"typed (2)"), + "typed dupe did not land postfixed: {names:?}" ); } diff --git a/style/main.scss b/style/main.scss index 67d3d98..8f58800 100644 --- a/style/main.scss +++ b/style/main.scss @@ -4468,18 +4468,11 @@ input[type="radio"] { white-space: nowrap; } -// Upload progress rows under the filterbar: name, bar, percent. The track is +// Upload progress rows in the corner stack: name, bar, percent. The track is // the house upload-progress rule freed of its upload-box geometry (it was // absolutely positioned into a box the drive form never renders) — here it -// flexes beside the name it belongs to. -.upload-progress-list { - display: flex; - flex-direction: column; - gap: 8px; - margin-top: 10px; - - &:empty { display: none; } -} +// flexes beside the name it belongs to. The stack itself is the container, +// so there is no list wrapper to style or hide. .upload-progress-row { display: flex; @@ -4497,7 +4490,7 @@ input[type="radio"] { color: var(--muted); } -.upload-progress-list .upload-progress { +.in-status-stack .upload-progress { position: relative; flex: 1; left: auto; @@ -4599,3 +4592,157 @@ input[type="radio"] { &:hover { color: var(--danger); } } + +// -- viewer page polish (ViewerBuild) ------------------------------------------------ +// GET /view/{id} aligned with the house: a head row carries Back left and the +// .primary Download right (the iz detail-head arrangement), the title keeps +// the house .settings-title size, and the stage is a centered panel card — +// capped at the modal viewer's width so media never sprawls into a full-width +// slab at desktop sizes. Video/images shrink to fit the viewport (70vh, the +// same proportion as the modal's 78vh minus the page chrome); text and pdf +// fill the card in the same chrome. The native audio pill ignores the theme's +// shape language, so it sits in a sunken wrap at a readable width instead. +.viewer-head { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 12px; +} + +.viewer-title { overflow-wrap: anywhere; } + +.viewer-stage { + width: 100%; + max-width: min(100%, 960px); + margin: 16px auto; + padding: 20px 24px 24px; + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-lg); + align-items: center; +} + +.viewer-details { + width: 100%; + max-width: min(100%, 960px); + margin: 0 auto; +} + +.viewer-stage .viewer-media { + width: 100%; + height: auto; + max-width: 100%; + max-height: 70vh; + display: block; +} + +.viewer-stage .viewer-pdf, +.viewer-stage .viewer-text { + width: 100%; + height: 70vh; + max-height: 70vh; +} + +.viewer-audio-wrap { + width: min(560px, 100%); + display: flex; + justify-content: center; + padding: 12px 16px; + background: var(--surface-sunken); + border: 1px solid var(--border); + border-radius: var(--radius-md); +} + +.viewer-audio-wrap .viewer-audio { width: 100%; } + +// -- row polish (RowBuild) ------------------------------------------------------------ +// Single-line discipline for the drive/trash/shared rows, the anchored options +// menu, and progress rows inside the corner stack. One contiguous section; +// the house panel, chip, quiet and user-menu rules above do the rest. + +// A row never wraps: the name takes the slack as an ellipsis, every detail +// token and action holds its column. The name span in trash and public rows +// is `.member-name`, which carries no geometry of its own — inside a row it +// borrows the dep-title shape (flex, ellipsis, and the old-house `.dep-title` +// geometry it also wears in markup, so the ellipsis does not depend on this +// block alone); the shared page wraps its linked names in `.dep-title` +// directly. +.dep-row { flex-wrap: nowrap; } + +.dep-row > .member-name, +.dep-row > .dep-title { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +// Detail tokens never break mid-value ('6.1 KiB' stays whole): the name's +// ellipsis absorbs the pressure instead. +.dep-row > .field-note { + flex: none; + white-space: nowrap; +} + +// Chips, action forms and the options menu hold their width; only the name +// (or the spacer) yields. Action buttons and links never wrap their own +// label under pressure either ('Delete forever' stays one line). +.dep-row > .file-chip, +.dep-row > .pop-row-form, +.dep-row > .entry-options { flex: none; } + +.dep-row .quiet { flex: none; white-space: nowrap; } + +// The row's Options menu wears the house user-menu panel. The positioning +// context is pinned here rather than inherited, so the panel stays anchored +// to its trigger whatever the generic rule does. +.entry-options { position: relative; } + +// A
menu is a toggle, not a hover: while open, the panel stays — +// even where the pointer rests outside hover and focus. The Escape pin +// (`.user-menu-esc`) still wins on specificity, so Escape keeps closing it. +.entry-options[open] > .user-menu-panel { + visibility: visible; + opacity: 1; + pointer-events: auto; +} + +// Panels clip their corners with `overflow: hidden`, which would cut an open +// menu off at the panel's edge — most visibly on the bottom rows, whose menu +// opens past it. While a menu is open the clip lifts; closed panels keep +// their corners. Near the viewport bottom the menu still opens downward and +// the page (the scrolling stage) grows to take it, the house drive-add +// behaviour — no upward variant to learn. +.panel:has(.entry-options[open]) { overflow: visible; } + +// Progress rows stretch the stack's width so the bar has room to flex; the +// stack's own max-width still caps them. +.in-status-stack .upload-progress-row { width: 100%; } + +// -- settings quota table (SettingsBuild) --------------------------------------- +// +// The human-unit quota row added a unit