forge
Explore
Log in

Don't you dare go Hollow

Auto-postfix names, aligned rows, human-unit limits, styled viewer

Browse files at this commit

4cd43f863a8d6f2c9931f44a0c7ccdf24214b298Ahmet Kaan GümüşParent: e806d74
  • feat
    • auto-postfix names, aligned rows, human-unit limits, styled viewer
Show full message
feat: auto-postfix names, aligned rows, human-unit limits, styled viewer

- 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.rsmodified+25 -17
@@ -35,9 +35,6 @@ pub use reconcile::{ReconcileOptions, reconcile};
35 /// leak the distinction exists to prevent.35 /// leak the distinction exists to prevent.
36 #[derive(Debug, thiserror::Error)]36 #[derive(Debug, thiserror::Error)]
37 pub enum StoreError {37 pub enum StoreError {
38- /// The name is already taken among the live siblings.
39- #[error("that name is already taken here")]
40- NameTaken,
41 /// The database refused the write or could not be read.38 /// The database refused the write or could not be read.
42 #[error("database: {0}")]39 #[error("database: {0}")]
43 Backend(String),40 Backend(String),
@@ -382,7 +379,9 @@ pub trait Store: 'static + Send + Sync {
382 // -- folders -----------------------------------------------------------379 // -- folders -----------------------------------------------------------
383 380
384 /// Creates a folder. A parent of another owner is [`StoreError::CrossOwner`],381 /// Creates a folder. A parent of another owner is [`StoreError::CrossOwner`],
385- /// not a refusal — the asker named a thing that is not theirs.382+ /// not a refusal — the asker named a thing that is not theirs. A live
383+ /// sibling wearing the name is no refusal either: the folder takes the
384+ /// first free `name (2)` postfix instead.
386 async fn create_folder(385 async fn create_folder(
387 &self,386 &self,
388 owner_id: &str,387 owner_id: &str,
@@ -394,12 +393,14 @@ pub trait Store: 'static + Send + Sync {
394 /// means for its screen.393 /// means for its screen.
395 async fn folder(&self, id: &str) -> Result<Option<Folder>>;394 async fn folder(&self, id: &str) -> Result<Option<Folder>>;
396 395
397- /// Renames a folder. Names are labels, never identities: a live sibling396+ /// Renames a folder. A live sibling wearing the name is no refusal: the
398- /// may already wear the name, and the rename still lands.397+ /// rename lands on the first free `name (2)` postfix instead.
399 async fn rename_folder(&self, id: &str, name: &str) -> Result<()>;398 async fn rename_folder(&self, id: &str, name: &str) -> Result<()>;
400 399
401 /// Moves a folder. Into its own descendant is [`StoreError::Cycle`];400 /// Moves a folder. Into its own descendant is [`StoreError::Cycle`];
402- /// across owners is [`StoreError::CrossOwner`].401+ /// across owners is [`StoreError::CrossOwner`]. A live child of the
402+ /// destination wearing the folder's name is no obstacle: the move lands
403+ /// on the first free `name (2)` postfix.
403 async fn move_folder(&self, id: &str, parent_id: Option<&str>) -> Result<()>;404 async fn move_folder(&self, id: &str, parent_id: Option<&str>) -> Result<()>;
404 405
405 /// Trashes a folder: the folder, every descendant folder and every file406 /// Trashes a folder: the folder, every descendant folder and every file
@@ -415,11 +416,11 @@ pub trait Store: 'static + Send + Sync {
415 parent_id: Option<&str>,416 parent_id: Option<&str>,
416 ) -> Result<Listing>;417 ) -> Result<Listing>;
417 418
418- // -- files -------------------------------------------------------------
419-
420 /// Stores small bytes straight through: sanitises the name, checks the419 /// Stores small bytes straight through: sanitises the name, checks the
421 /// quota, sniffs the mime (never trusting the uploader), writes the420 /// quota, sniffs the mime (never trusting the uploader), writes the
422- /// file, attempts a thumbnail for images and video, and recomputes usage. The421+ /// file, attempts a thumbnail for images and video, and recomputes usage. A
422+ /// live sibling wearing the name is no refusal: the file takes the first
423+ /// free `stem (2).ext` postfix instead. The
423 /// chunked upload's finish is the same pipeline over assembled chunks.424 /// chunked upload's finish is the same pipeline over assembled chunks.
424 async fn insert_file(425 async fn insert_file(
425 &self,426 &self,
@@ -432,10 +433,13 @@ pub trait Store: 'static + Send + Sync {
432 /// One file's row, still without its bytes.433 /// One file's row, still without its bytes.
433 async fn file(&self, id: &str) -> Result<Option<File>>;434 async fn file(&self, id: &str) -> Result<Option<File>>;
434 435
435- /// Renames a file. A name a live sibling wears is [`StoreError::NameTaken`].436+ /// Renames a file. A live sibling wearing the name is no refusal: the
437+ /// rename lands on the first free `stem (2).ext` postfix instead.
436 async fn rename_file(&self, id: &str, name: &str) -> Result<()>;438 async fn rename_file(&self, id: &str, name: &str) -> Result<()>;
437 439
438- /// Moves a file. Across owners is [`StoreError::CrossOwner`].440+ /// Moves a file. Across owners is [`StoreError::CrossOwner`]. A live
441+ /// child of the destination wearing the file's name is no obstacle: the
442+ /// move lands on the first free `stem (2).ext` postfix.
439 async fn move_file(&self, id: &str, folder_id: Option<&str>) -> Result<()>;443 async fn move_file(&self, id: &str, folder_id: Option<&str>) -> Result<()>;
440 444
441 /// Trashes a file. The bytes stay on disk — and counting toward quota —445 /// Trashes a file. The bytes stay on disk — and counting toward quota —
@@ -464,16 +468,18 @@ pub trait Store: 'static + Send + Sync {
464 async fn list_trash(&self, owner_id: &str) -> Result<Listing>;468 async fn list_trash(&self, owner_id: &str) -> Result<Listing>;
465 469
466 /// Restores a trashed file. Refused with [`StoreError::AncestorTrashed`]470 /// Restores a trashed file. Refused with [`StoreError::AncestorTrashed`]
467- /// while any ancestor folder is still trashed, and with471+ /// while any ancestor folder is still trashed. A live sibling wearing
468- /// [`StoreError::NameTaken`] while a live sibling wears its name.472+ /// the name is no refusal: the restore lands on the first free
473+ /// `stem (2).ext` postfix instead.
469 async fn restore_file(&self, id: &str) -> Result<()>;474 async fn restore_file(&self, id: &str) -> Result<()>;
470 475
471 /// Restores a trashed folder and everything under it that it took with476 /// Restores a trashed folder and everything under it that it took with
472 /// it — descendants wearing the folder's own trash timestamp. Anything477 /// it — descendants wearing the folder's own trash timestamp. Anything
473 /// trashed individually before the folder keeps its earlier moment and478 /// trashed individually before the folder keeps its earlier moment and
474 /// stays trashed. Refused with [`StoreError::AncestorTrashed`] while any479 /// stays trashed. Refused with [`StoreError::AncestorTrashed`] while any
475- /// ancestor folder is still trashed; a live sibling wearing the name is480+ /// ancestor folder is still trashed. A live sibling wearing the name is
476- /// no refusal — folder names may repeat.481+ /// no refusal: the restored folder takes the first free `name (2)`
482+ /// postfix instead.
477 async fn restore_folder(&self, id: &str) -> Result<()>;483 async fn restore_folder(&self, id: &str) -> Result<()>;
478 484
479 /// Purges one trashed file for good: the row goes and the bytes and485 /// Purges one trashed file for good: the row goes and the bytes and
@@ -612,7 +618,9 @@ pub trait Store: 'static + Send + Sync {
612 /// Assembles a session's chunks in order, rechecks the quota, sniffs the618 /// Assembles a session's chunks in order, rechecks the quota, sniffs the
613 /// mime (never trusting anything the uploader said), writes the file,619 /// mime (never trusting anything the uploader said), writes the file,
614 /// attempts a thumbnail for images and video, inserts the row and marks the session620 /// attempts a thumbnail for images and video, inserts the row and marks the session
615- /// done — and returns the file. A session whose chunks do not add up, or621+ /// done — and returns the file. A live sibling wearing the session's
622+ /// name is no refusal: the file takes the first free `stem (2).ext`
623+ /// postfix instead. A session whose chunks do not add up, or
616 /// whose owner filled their quota while it was arriving, is refused with624 /// whose owner filled their quota while it was arriving, is refused with
617 /// the chunks still staged for another attempt.625 /// the chunks still staged for another attempt.
618 async fn finish_upload(&self, id: &str) -> Result<File>;626 async fn finish_upload(&self, id: &str) -> Result<File>;
crates/in-core/src/store/turso_store.rsmodified+232 -63
@@ -459,6 +459,50 @@ pub(crate) fn label_of(name: &str) -> String {
459 trimmed459 trimmed
460 }460 }
461 }461 }
462+/// The longest name the store keeps whole: the drive forms carry
463+/// `maxlength="255"`, so a postfix (` (2)`, `.txt`) truncates the base to
464+/// fit rather than growing the name past what the UI accepts.
465+pub(crate) const MAX_NAME_CHARS: usize = 255;
466+
467+/// The first `max` characters of `s`, on a character boundary — never
468+/// splitting a multi-byte character the way a byte slice would.
469+fn truncate_chars(s: &str, max: usize) -> &str {
470+ if s.chars().count() <= max {
471+ return s;
472+ }
473+ match s.char_indices().nth(max) {
474+ Some((idx, _)) => &s[..idx],
475+ None => s,
476+ }
477+}
478+
479+/// Splits a file name at its LAST dot into stem and extension (dot kept on
480+/// the extension): `report.txt` is `("report", ".txt")`, `archive.tar.gz`
481+/// is `("archive.tar", ".gz")`. No dot, a leading dot only (`.gitignore`),
482+/// or a trailing dot (`foo.`) is no split — the whole name is the stem —
483+/// so the postfix never lands in front of a dotfile's only dot.
484+fn split_file_name(name: &str) -> (&str, &str) {
485+ match name.rfind('.') {
486+ Some(at) if at > 0 && at + 1 < name.len() => (&name[..at], &name[at..]),
487+ _ => (name, ""),
488+ }
489+}
490+
491+/// `report.txt` at 2 is `report (2).txt`; `name` at 2 is `name (2)`. The
492+/// stem is truncated so stem + postfix + extension fits [`MAX_NAME_CHARS`].
493+fn postfixed_file_name(want: &str, n: u32) -> String {
494+ let suffix = format!(" ({n})");
495+ let (stem, ext) = split_file_name(want);
496+ let keep = MAX_NAME_CHARS.saturating_sub(suffix.chars().count() + ext.chars().count());
497+ format!("{}{}{}", truncate_chars(stem, keep), suffix, ext)
498+}
499+
500+/// `Name` at 2 is `Name (2)`, truncated to fit [`MAX_NAME_CHARS`].
501+fn postfixed_folder_name(want: &str, n: u32) -> String {
502+ let suffix = format!(" ({n})");
503+ let keep = MAX_NAME_CHARS.saturating_sub(suffix.chars().count());
504+ format!("{}{}", truncate_chars(want, keep), suffix)
505+}
462 506
463 /// Addresses match case-insensitively: the provider may capitalise what507 /// Addresses match case-insensitively: the provider may capitalise what
464 /// the row stored, so both sides fold before comparing. Provisioning folds508 /// the row stored, so both sides fold before comparing. Provisioning folds
@@ -671,15 +715,6 @@ fn backend<E: std::fmt::Display>(e: E) -> StoreError {
671 StoreError::Backend(e.to_string())715 StoreError::Backend(e.to_string())
672 }716 }
673 717
674-/// Whether this engine error is a uniqueness refusal rather than a
675-/// malfunction. The store checks names before writing, so this is only ever
676-/// the backstop for a race two Immediate transactions could not serialise —
677-/// and it answers with the name the check would have used.
678-fn is_constraint_violation(e: &turso::Error) -> bool {
679- let text = e.to_string().to_lowercase();
680- text.contains("constraint") || text.contains("unique")
681-}
682-
683 fn now_text() -> Result<String> {718 fn now_text() -> Result<String> {
684 stamp(OffsetDateTime::now_utc())719 stamp(OffsetDateTime::now_utc())
685 }720 }
@@ -983,15 +1018,17 @@ impl Store for TursoStore {
983 name: &str,1018 name: &str,
984 ) -> Result<Folder> {1019 ) -> Result<Folder> {
985 let name = label_of(name);1020 let name = label_of(name);
986- // IMMEDIATE: the parent check and the insert are one write set, so a1021+ // IMMEDIATE: the parent check, the name search and the insert are
987- // parent trashed mid-create still refuses. Names are not checked:1022+ // one write set, so a parent trashed mid-create still refuses. A
988- // two folders may wear one name in one place.1023+ // live sibling wearing the name is no refusal: the folder takes the
1024+ // first free `name (2)` postfix instead.
989 let mut conn = self.tx_conn().await?;1025 let mut conn = self.tx_conn().await?;
990 let tx = conn1026 let tx = conn
991 .transaction_with_behavior(TransactionBehavior::Immediate)1027 .transaction_with_behavior(TransactionBehavior::Immediate)
992 .await1028 .await
993 .map_err(backend)?;1029 .map_err(backend)?;
994 check_live_parent(&tx, owner_id, parent_id).await?;1030 check_live_parent(&tx, owner_id, parent_id).await?;
1031+ let name = free_folder_name(&tx, owner_id, parent_id, &name, None).await?;
995 let id = Ulid::new().to_string();1032 let id = Ulid::new().to_string();
996 let now = now_text()?;1033 let now = now_text()?;
997 tx.execute(1034 tx.execute(
@@ -1000,7 +1037,7 @@ impl Store for TursoStore {
1000 params![id.clone(), owner_id, parent_id, name, now],1037 params![id.clone(), owner_id, parent_id, name, now],
1001 )1038 )
1002 .await1039 .await
1003- .map_err(|e| map_constraint(e, StoreError::NameTaken))?;1040+ .map_err(backend)?;
1004 let mut rows = tx1041 let mut rows = tx
1005 .query(1042 .query(
1006 &format!("SELECT {FOLDER_COLUMNS} FROM folder WHERE id = ?1"),1043 &format!("SELECT {FOLDER_COLUMNS} FROM folder WHERE id = ?1"),
@@ -1035,9 +1072,14 @@ impl Store for TursoStore {
1035 if folder.deleted_at.is_some() {1072 if folder.deleted_at.is_some() {
1036 return Err(StoreError::NotFound);1073 return Err(StoreError::NotFound);
1037 }1074 }
1075+ // A live sibling wearing the name is no refusal: the rename lands
1076+ // on the first free `name (2)` postfix instead.
1077+ let name =
1078+ free_folder_name(&tx, &folder.owner_id, folder.parent_id.as_deref(), &name, Some(id))
1079+ .await?;
1038 tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id])1080 tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id])
1039 .await1081 .await
1040- .map_err(|e| map_constraint(e, StoreError::NameTaken))?;1082+ .map_err(backend)?;
1041 refresh_usage(&tx, &folder.owner_id).await?;1083 refresh_usage(&tx, &folder.owner_id).await?;
1042 tx.commit().await.map_err(backend)?;1084 tx.commit().await.map_err(backend)?;
1043 self.announce([Topic::Library(folder.owner_id)]);1085 self.announce([Topic::Library(folder.owner_id)]);
@@ -1066,12 +1108,16 @@ impl Store for TursoStore {
1066 }1108 }
1067 cursor = parent_of(&tx, &current).await?;1109 cursor = parent_of(&tx, &current).await?;
1068 }1110 }
1111+ // A live child of the destination wearing the folder's name is no
1112+ // obstacle: the move lands on the first free `name (2)` postfix.
1113+ let name =
1114+ free_folder_name(&tx, &folder.owner_id, parent_id, &folder.name, Some(id)).await?;
1069 tx.execute(1115 tx.execute(
1070- "UPDATE folder SET parent_id = ?1 WHERE id = ?2",1116+ "UPDATE folder SET parent_id = ?1, name = ?2 WHERE id = ?3",
1071- params![parent_id, id],1117+ params![parent_id, name, id],
1072 )1118 )
1073 .await1119 .await
1074- .map_err(|e| map_constraint(e, StoreError::NameTaken))?;1120+ .map_err(backend)?;
1075 refresh_usage(&tx, &folder.owner_id).await?;1121 refresh_usage(&tx, &folder.owner_id).await?;
1076 tx.commit().await.map_err(backend)?;1122 tx.commit().await.map_err(backend)?;
1077 self.announce([Topic::Library(folder.owner_id)]);1123 self.announce([Topic::Library(folder.owner_id)]);
@@ -1219,9 +1265,9 @@ impl Store for TursoStore {
1219 check_live_parent(&tx, owner_id, folder_id).await?;1265 check_live_parent(&tx, owner_id, folder_id).await?;
1220 let (quota, used) = check_quota(&tx, owner_id).await?;1266 let (quota, used) = check_quota(&tx, owner_id).await?;
1221 fit_quota(quota, used, size)?;1267 fit_quota(quota, used, size)?;
1222- if file_name_taken(&tx, owner_id, folder_id, &name, None).await? {1268+ // A live sibling wearing the name is no refusal: the file takes the
1223- return Err(StoreError::NameTaken);1269+ // first free `stem (2).ext` postfix instead.
1224- }1270+ let name = free_file_name(&tx, owner_id, folder_id, &name, None).await?;
1225 let mime = sniff::sniff(bytes).to_string();1271 let mime = sniff::sniff(bytes).to_string();
1226 let (thumb_state, thumb_bytes) = thumb_for(&mime, size, Some(bytes));1272 let (thumb_state, thumb_bytes) = thumb_for(&mime, size, Some(bytes));
1227 // The bytes land first, temp-plus-rename, then the row says they are1273 // The bytes land first, temp-plus-rename, then the row says they are
@@ -1269,7 +1315,7 @@ impl Store for TursoStore {
1269 // a name nothing points at.1315 // a name nothing points at.
1270 let _ = std::fs::remove_file(&path);1316 let _ = std::fs::remove_file(&path);
1271 let _ = std::fs::remove_file(thumb_path(&self.storage, &id));1317 let _ = std::fs::remove_file(thumb_path(&self.storage, &id));
1272- return Err(map_constraint(e, StoreError::NameTaken));1318+ return Err(backend(e));
1273 }1319 }
1274 refresh_usage(&tx, owner_id).await?;1320 refresh_usage(&tx, owner_id).await?;
1275 let mut rows = tx1321 let mut rows = tx
@@ -1306,17 +1352,17 @@ impl Store for TursoStore {
1306 if file.deleted_at.is_some() {1352 if file.deleted_at.is_some() {
1307 return Err(StoreError::NotFound);1353 return Err(StoreError::NotFound);
1308 }1354 }
1309- if file_name_taken(&tx, &file.owner_id, file.folder_id.as_deref(), &name, Some(id)).await?1355+ // A live sibling wearing the name is no refusal: the rename lands
1310- {1356+ // on the first free `stem (2).ext` postfix instead.
1311- return Err(StoreError::NameTaken);1357+ let name =
1312- }1358+ free_file_name(&tx, &file.owner_id, file.folder_id.as_deref(), &name, Some(id)).await?;
1313 let now = now_text()?;1359 let now = now_text()?;
1314 tx.execute(1360 tx.execute(
1315 "UPDATE file SET name = ?1, updated_at = ?2 WHERE id = ?3",1361 "UPDATE file SET name = ?1, updated_at = ?2 WHERE id = ?3",
1316 params![name, now, id],1362 params![name, now, id],
1317 )1363 )
1318 .await1364 .await
1319- .map_err(|e| map_constraint(e, StoreError::NameTaken))?;1365+ .map_err(backend)?;
1320 refresh_usage(&tx, &file.owner_id).await?;1366 refresh_usage(&tx, &file.owner_id).await?;
1321 tx.commit().await.map_err(backend)?;1367 tx.commit().await.map_err(backend)?;
1322 self.announce([Topic::Library(file.owner_id)]);1368 self.announce([Topic::Library(file.owner_id)]);
@@ -1334,16 +1380,16 @@ impl Store for TursoStore {
1334 return Err(StoreError::NotFound);1380 return Err(StoreError::NotFound);
1335 }1381 }
1336 check_live_parent(&tx, &file.owner_id, folder_id).await?;1382 check_live_parent(&tx, &file.owner_id, folder_id).await?;
1337- if file_name_taken(&tx, &file.owner_id, folder_id, &file.name, Some(id)).await? {1383+ // A live child of the destination wearing the file's name is no
1338- return Err(StoreError::NameTaken);1384+ // obstacle: the move lands on the first free `stem (2).ext` postfix.
1339- }1385+ let name = free_file_name(&tx, &file.owner_id, folder_id, &file.name, Some(id)).await?;
1340 let now = now_text()?;1386 let now = now_text()?;
1341 tx.execute(1387 tx.execute(
1342- "UPDATE file SET folder_id = ?1, updated_at = ?2 WHERE id = ?3",1388+ "UPDATE file SET folder_id = ?1, name = ?2, updated_at = ?3 WHERE id = ?4",
1343- params![folder_id, now, id],1389+ params![folder_id, name, now, id],
1344 )1390 )
1345 .await1391 .await
1346- .map_err(|e| map_constraint(e, StoreError::NameTaken))?;1392+ .map_err(backend)?;
1347 refresh_usage(&tx, &file.owner_id).await?;1393 refresh_usage(&tx, &file.owner_id).await?;
1348 tx.commit().await.map_err(backend)?;1394 tx.commit().await.map_err(backend)?;
1349 self.announce([Topic::Library(file.owner_id)]);1395 self.announce([Topic::Library(file.owner_id)]);
@@ -1509,24 +1555,23 @@ impl Store for TursoStore {
1509 if let Some(folder_id) = file.folder_id.as_deref() {1555 if let Some(folder_id) = file.folder_id.as_deref() {
1510 ancestor_trashed(&tx, folder_id).await?;1556 ancestor_trashed(&tx, folder_id).await?;
1511 }1557 }
1512- if file_name_taken(1558+ // A live sibling wearing the name is no refusal: the restore lands
1559+ // on the first free `stem (2).ext` postfix instead.
1560+ let name = free_file_name(
1513 &tx,1561 &tx,
1514 &file.owner_id,1562 &file.owner_id,
1515 file.folder_id.as_deref(),1563 file.folder_id.as_deref(),
1516 &file.name,1564 &file.name,
1517 Some(id),1565 Some(id),
1518 )1566 )
1519- .await?1567+ .await?;
1520- {
1521- return Err(StoreError::NameTaken);
1522- }
1523 let now = now_text()?;1568 let now = now_text()?;
1524 tx.execute(1569 tx.execute(
1525- "UPDATE file SET deleted_at = NULL, updated_at = ?1 WHERE id = ?2",1570+ "UPDATE file SET name = ?1, deleted_at = NULL, updated_at = ?2 WHERE id = ?3",
1526- params![now, id],1571+ params![name, now, id],
1527 )1572 )
1528 .await1573 .await
1529- .map_err(|e| map_constraint(e, StoreError::NameTaken))?;1574+ .map_err(backend)?;
1530 refresh_usage(&tx, &file.owner_id).await?;1575 refresh_usage(&tx, &file.owner_id).await?;
1531 tx.commit().await.map_err(backend)?;1576 tx.commit().await.map_err(backend)?;
1532 self.announce([1577 self.announce([
@@ -1582,6 +1627,21 @@ impl Store for TursoStore {
1582 )1627 )
1583 .await1628 .await
1584 .map_err(backend)?;1629 .map_err(backend)?;
1630+ // A live sibling wearing the folder's name is no refusal: the
1631+ // restored folder takes the first free `name (2)` postfix. The
1632+ // cascade below needs no fix-up — no live row can sit under a
1633+ // trashed folder, so only this top folder can collide.
1634+ let name = free_folder_name(
1635+ &tx,
1636+ &folder.owner_id,
1637+ folder.parent_id.as_deref(),
1638+ &folder.name,
1639+ Some(id),
1640+ )
1641+ .await?;
1642+ tx.execute("UPDATE folder SET name = ?1 WHERE id = ?2", params![name, id])
1643+ .await
1644+ .map_err(backend)?;
1585 refresh_usage(&tx, &folder.owner_id).await?;1645 refresh_usage(&tx, &folder.owner_id).await?;
1586 tx.commit().await.map_err(backend)?;1646 tx.commit().await.map_err(backend)?;
1587 self.announce([1647 self.announce([
@@ -2304,28 +2364,29 @@ impl Store for TursoStore {
2304 .transaction_with_behavior(TransactionBehavior::Immediate)2364 .transaction_with_behavior(TransactionBehavior::Immediate)
2305 .await2365 .await
2306 .map_err(backend)?;2366 .map_err(backend)?;
2307- let vetted: Result<()> = async {2367+ let vetted: Result<String> = async {
2308 check_live_parent(&tx, &session.owner_id, session.folder_id.as_deref()).await?;2368 check_live_parent(&tx, &session.owner_id, session.folder_id.as_deref()).await?;
2309 let (quota, used) = check_quota(&tx, &session.owner_id).await?;2369 let (quota, used) = check_quota(&tx, &session.owner_id).await?;
2310 fit_quota(quota, used, session.size_bytes)?;2370 fit_quota(quota, used, session.size_bytes)?;
2311- if file_name_taken(2371+ // A live sibling wearing the session's name is no refusal: the
2372+ // finished file takes the first free `stem (2).ext` postfix.
2373+ free_file_name(
2312 &tx,2374 &tx,
2313 &session.owner_id,2375 &session.owner_id,
2314 session.folder_id.as_deref(),2376 session.folder_id.as_deref(),
2315 &session.name,2377 &session.name,
2316 None,2378 None,
2317 )2379 )
2318- .await?2380+ .await
2319- {
2320- return Err(StoreError::NameTaken);
2321- }
2322- Ok(())
2323 }2381 }
2324 .await;2382 .await;
2325- if let Err(e) = vetted {2383+ let name = match vetted {
2326- let _ = std::fs::remove_file(&tmp);2384+ Ok(name) => name,
2327- return Err(e);2385+ Err(e) => {
2328- }2386+ let _ = std::fs::remove_file(&tmp);
2387+ return Err(e);
2388+ }
2389+ };
2329 if std::fs::rename(&tmp, &dest).is_err() {2390 if std::fs::rename(&tmp, &dest).is_err() {
2330 let _ = std::fs::remove_file(&tmp);2391 let _ = std::fs::remove_file(&tmp);
2331 return Err(StoreError::Backend("could not place the assembled file".into()));2392 return Err(StoreError::Backend("could not place the assembled file".into()));
@@ -2353,7 +2414,7 @@ impl Store for TursoStore {
2353 file_id.clone(),2414 file_id.clone(),
2354 session.owner_id.as_str(),2415 session.owner_id.as_str(),
2355 session.folder_id.as_deref(),2416 session.folder_id.as_deref(),
2356- session.name.as_str(),2417+ name.as_str(),
2357 mime,2418 mime,
2358 session.size_bytes as i64,2419 session.size_bytes as i64,
2359 stored_thumb.as_str(),2420 stored_thumb.as_str(),
@@ -2367,7 +2428,7 @@ impl Store for TursoStore {
2367 // is what failed.2428 // is what failed.
2368 let _ = std::fs::remove_file(&dest);2429 let _ = std::fs::remove_file(&dest);
2369 let _ = std::fs::remove_file(thumb_path(&self.storage, &file_id));2430 let _ = std::fs::remove_file(thumb_path(&self.storage, &file_id));
2370- return Err(map_constraint(e, StoreError::NameTaken));2431+ return Err(backend(e));
2371 }2432 }
2372 tx.execute(2433 tx.execute(
2373 "UPDATE upload_session SET state = 'done', received_bytes = ?1 WHERE id = ?2",2434 "UPDATE upload_session SET state = 'done', received_bytes = ?1 WHERE id = ?2",
@@ -2590,6 +2651,95 @@ async fn file_name_taken(
2590 Ok(rows.next().await.map_err(backend)?.is_some())2651 Ok(rows.next().await.map_err(backend)?.is_some())
2591 }2652 }
2592 2653
2654+/// Whether a live sibling folder already wears `name` — the folder half of
2655+/// [`file_name_taken`], over `parent_id` (NULL is the root) instead of
2656+/// `folder_id`. Same rules: trash does not count, `exclude` skips the row
2657+/// being renamed, moved or restored.
2658+async fn folder_name_taken(
2659+ conn: &Connection,
2660+ owner_id: &str,
2661+ parent_id: Option<&str>,
2662+ name: &str,
2663+ exclude: Option<&str>,
2664+) -> Result<bool> {
2665+ let exclude = exclude.unwrap_or("");
2666+ let mut rows = match parent_id {
2667+ Some(parent) => {
2668+ conn.query(
2669+ "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id = ?2 \
2670+ AND name = ?3 AND deleted_at IS NULL AND id <> ?4",
2671+ params![owner_id, parent, name, exclude],
2672+ )
2673+ .await
2674+ .map_err(backend)?
2675+ }
2676+ None => {
2677+ conn.query(
2678+ "SELECT 1 FROM folder WHERE owner_id = ?1 AND parent_id IS NULL \
2679+ AND name = ?2 AND deleted_at IS NULL AND id <> ?3",
2680+ params![owner_id, name, exclude],
2681+ )
2682+ .await
2683+ .map_err(backend)?
2684+ }
2685+ };
2686+ Ok(rows.next().await.map_err(backend)?.is_some())
2687+}
2688+
2689+/// The name a new or renamed file actually takes: `want` when no live
2690+/// sibling wears it, else the first free `stem (2).ext` postfix — `(3)`,
2691+/// `(4)`, … when `(2)` is taken too. Runs inside the caller's write
2692+/// transaction, so the check and the write are one write set.
2693+async fn free_file_name(
2694+ conn: &Connection,
2695+ owner_id: &str,
2696+ folder_id: Option<&str>,
2697+ want: &str,
2698+ exclude: Option<&str>,
2699+) -> Result<String> {
2700+ if !file_name_taken(conn, owner_id, folder_id, want, exclude).await? {
2701+ return Ok(want.to_string());
2702+ }
2703+ let mut n = 2u32;
2704+ loop {
2705+ let candidate = postfixed_file_name(want, n);
2706+ if !file_name_taken(conn, owner_id, folder_id, &candidate, exclude).await? {
2707+ return Ok(candidate);
2708+ }
2709+ // Unreachable in practice — four billion live siblings — but the
2710+ // loop must be total, so exhaustion is a backend error, never a
2711+ // name refusal.
2712+ n = n
2713+ .checked_add(1)
2714+ .ok_or_else(|| StoreError::Backend("too many siblings".into()))?;
2715+ }
2716+}
2717+
2718+/// The folder half of [`free_file_name`]: `want` when free, else the first
2719+/// free `want (2)` postfix.
2720+async fn free_folder_name(
2721+ conn: &Connection,
2722+ owner_id: &str,
2723+ parent_id: Option<&str>,
2724+ want: &str,
2725+ exclude: Option<&str>,
2726+) -> Result<String> {
2727+ if !folder_name_taken(conn, owner_id, parent_id, want, exclude).await? {
2728+ return Ok(want.to_string());
2729+ }
2730+ let mut n = 2u32;
2731+ loop {
2732+ let candidate = postfixed_folder_name(want, n);
2733+ if !folder_name_taken(conn, owner_id, parent_id, &candidate, exclude).await? {
2734+ return Ok(candidate);
2735+ }
2736+ // Unreachable in practice — see `free_file_name` — but total.
2737+ n = n
2738+ .checked_add(1)
2739+ .ok_or_else(|| StoreError::Backend("too many siblings".into()))?;
2740+ }
2741+}
2742+
2593 /// Refuses with [`StoreError::AncestorTrashed`] while any folder at or above2743 /// Refuses with [`StoreError::AncestorTrashed`] while any folder at or above
2594 /// `folder_id` wears trash. The walk starts at the folder itself, so callers2744 /// `folder_id` wears trash. The walk starts at the folder itself, so callers
2595 /// pass the parent chain's head and get the whole ancestry vetted.2745 /// 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
2848 }2998 }
2849 }2999 }
2850 3000
2851-/// A uniqueness refusal is the name check's answer, not a malfunction: the
2852-/// backstop for a race two Immediate transactions could not serialise.
2853-fn map_constraint(e: turso::Error, taken: StoreError) -> StoreError {
2854- if is_constraint_violation(&e) {
2855- taken
2856- } else {
2857- backend(e)
2858- }
2859-}
2860-
2861 #[cfg(test)]3001 #[cfg(test)]
2862 mod tests {3002 mod tests {
2863 use super::*;3003 use super::*;
@@ -2904,4 +3044,33 @@ mod tests {
2904 assert_eq!(like_pattern("100%"), "%100\\%%");3044 assert_eq!(like_pattern("100%"), "%100\\%%");
2905 assert_eq!(like_pattern("a_b\\c"), "%a\\_b\\\\c%");3045 assert_eq!(like_pattern("a_b\\c"), "%a\\_b\\\\c%");
2906 }3046 }
3047+
3048+ #[test]
3049+ fn postfixes_split_at_the_last_dot() {
3050+ assert_eq!(postfixed_file_name("report.txt", 2), "report (2).txt");
3051+ assert_eq!(postfixed_file_name("archive.tar.gz", 2), "archive.tar (2).gz");
3052+ assert_eq!(postfixed_file_name("name", 2), "name (2)");
3053+ assert_eq!(postfixed_file_name("name", 3), "name (3)");
3054+ // A leading dot is the whole stem, not an extension: dotfiles keep
3055+ // their name whole and wear the postfix at the end.
3056+ assert_eq!(postfixed_file_name(".gitignore", 2), ".gitignore (2)");
3057+ assert_eq!(postfixed_folder_name("New folder", 2), "New folder (2)");
3058+ }
3059+
3060+ #[test]
3061+ fn postfixes_fit_the_name_cap() {
3062+ let long = "a".repeat(300);
3063+ let file = postfixed_file_name(&format!("{long}.txt"), 2);
3064+ assert_eq!(file.chars().count(), MAX_NAME_CHARS);
3065+ assert!(file.ends_with(" (2).txt"));
3066+ let folder = postfixed_folder_name(&long, 2);
3067+ assert_eq!(folder.chars().count(), MAX_NAME_CHARS);
3068+ assert!(folder.ends_with(" (2)"));
3069+ // Multi-byte stems truncate on a character boundary, never mid-rune.
3070+ let wide = "é".repeat(300);
3071+ let cut = postfixed_folder_name(&wide, 2);
3072+ assert_eq!(cut.chars().count(), MAX_NAME_CHARS);
3073+ assert!(cut.ends_with(" (2)"));
3074+ assert!(cut.starts_with("é"));
3075+ }
2907 }3076 }
\ No newline at end of file\ No newline at end of file
crates/in-core/tests/store.rsmodified+106 -31
@@ -169,7 +169,7 @@ async fn quota_and_disablement_round_trip() {
169 }169 }
170 170
171 #[tokio::test]171 #[tokio::test]
172-async fn folders_allow_duplicate_names_among_live_siblings() {172+async fn folders_postfix_onto_live_sibling_names() {
173 let scratch = Scratch::open().await;173 let scratch = Scratch::open().await;
174 let user = alice(&scratch.store).await;174 let user = alice(&scratch.store).await;
175 let root = scratch175 let root = scratch
@@ -184,18 +184,23 @@ async fn folders_allow_duplicate_names_among_live_siblings() {
184 .unwrap();184 .unwrap();
185 assert_eq!(kid.parent_id.as_deref(), Some(root.id.as_str()));185 assert_eq!(kid.parent_id.as_deref(), Some(root.id.as_str()));
186 186
187- // A live sibling wearing the name is no refusal: folders share names.187+ // A live sibling wearing the name is no refusal: the second folder
188+ // takes the first free postfix, the next one the one after.
188 let twin = scratch.store.create_folder(&user.id, None, "root").await.unwrap();189 let twin = scratch.store.create_folder(&user.id, None, "root").await.unwrap();
189 assert_ne!(twin.id, root.id);190 assert_ne!(twin.id, root.id);
191+ assert_eq!(twin.name, "root (2)");
192+ let third = scratch.store.create_folder(&user.id, None, "root").await.unwrap();
193+ assert_eq!(third.name, "root (3)");
190 // Same name in a different directory is a different name, as before.194 // Same name in a different directory is a different name, as before.
191- scratch195+ let away = scratch
192 .store196 .store
193 .create_folder(&user.id, Some(&root.id), "root")197 .create_folder(&user.id, Some(&root.id), "root")
194 .await198 .await
195 .unwrap();199 .unwrap();
200+ assert_eq!(away.name, "root");
196 201
197 let listing = scratch.store.list_children(&user.id, None).await.unwrap();202 let listing = scratch.store.list_children(&user.id, None).await.unwrap();
198- assert_eq!(listing.folders.len(), 2);203+ assert_eq!(listing.folders.len(), 3);
199 let listing = scratch204 let listing = scratch
200 .store205 .store
201 .list_children(&user.id, Some(&root.id))206 .list_children(&user.id, Some(&root.id))
@@ -512,13 +517,16 @@ async fn a_trashed_folder_name_restores_beside_a_live_twin() {
512 let user = alice(&scratch.store).await;517 let user = alice(&scratch.store).await;
513 let first = scratch.store.create_folder(&user.id, None, "x").await.unwrap();518 let first = scratch.store.create_folder(&user.id, None, "x").await.unwrap();
514 scratch.store.delete_folder(&first.id).await.unwrap();519 scratch.store.delete_folder(&first.id).await.unwrap();
515- // Deleting frees the name, and restoring beside the squatter is fine:520+ // Deleting frees the name, and restoring beside the squatter postfixes
516- // folder names may repeat.521+ // instead of refusing or duplicating.
517 scratch.store.create_folder(&user.id, None, "x").await.unwrap();522 scratch.store.create_folder(&user.id, None, "x").await.unwrap();
518 scratch.store.restore_folder(&first.id).await.unwrap();523 scratch.store.restore_folder(&first.id).await.unwrap();
519 let listing = scratch.store.list_children(&user.id, None).await.unwrap();524 let listing = scratch.store.list_children(&user.id, None).await.unwrap();
520- assert_eq!(listing.folders.iter().filter(|folder| folder.name == "x").count(), 2);525+ assert_eq!(listing.folders.len(), 2);
526+ assert!(listing.folders.iter().any(|folder| folder.name == "x"));
527+ assert!(listing.folders.iter().any(|folder| folder.name == "x (2)"));
521 }528 }
529+
522 #[tokio::test]530 #[tokio::test]
523 async fn used_bytes_counts_trash_and_purge_frees_it() {531 async fn used_bytes_counts_trash_and_purge_frees_it() {
524 let scratch = Scratch::open().await;532 let scratch = Scratch::open().await;
@@ -1215,19 +1223,19 @@ async fn a_second_migration_database_gains_the_preference_columns_on_open() {
1215 }1223 }
1216 1224
1217 #[tokio::test]1225 #[tokio::test]
1218-async fn renaming_or_moving_a_folder_onto_a_live_sibling_name_succeeds() {1226+async fn renaming_or_moving_a_folder_onto_a_live_sibling_name_postfixes() {
1219 let scratch = Scratch::open().await;1227 let scratch = Scratch::open().await;
1220 let user = alice(&scratch.store).await;1228 let user = alice(&scratch.store).await;
1221 let parent = scratch.store.create_folder(&user.id, None, "parent").await.unwrap();1229 let parent = scratch.store.create_folder(&user.id, None, "parent").await.unwrap();
1222 let other = scratch.store.create_folder(&user.id, None, "other").await.unwrap();1230 let other = scratch.store.create_folder(&user.id, None, "other").await.unwrap();
1223 1231
1224- // Renaming onto a live sibling's name lands.1232+ // Renaming onto a live sibling's name lands on the first free postfix.
1225 scratch.store.rename_folder(&other.id, "parent").await.unwrap();1233 scratch.store.rename_folder(&other.id, "parent").await.unwrap();
1226 let back: Folder = scratch.store.folder(&other.id).await.unwrap().unwrap();1234 let back: Folder = scratch.store.folder(&other.id).await.unwrap().unwrap();
1227- assert_eq!(back.name, "parent");1235+ assert_eq!(back.name, "parent (2)");
1228 1236
1229 // Moving under a parent is refused for strangers and the trashed, but1237 // Moving under a parent is refused for strangers and the trashed, but
1230- // never for a name: a live child wearing the name is no obstacle.1238+ // never for a name: a live child wearing the name is postfixed.
1231 let kid = scratch1239 let kid = scratch
1232 .store1240 .store
1233 .create_folder(&user.id, Some(&parent.id), "kid")1241 .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() {
1237 scratch.store.move_folder(&kid.id, None).await.unwrap();1245 scratch.store.move_folder(&kid.id, None).await.unwrap();
1238 let back: Folder = scratch.store.folder(&kid.id).await.unwrap().unwrap();1246 let back: Folder = scratch.store.folder(&kid.id).await.unwrap().unwrap();
1239 assert_eq!(back.parent_id, None);1247 assert_eq!(back.parent_id, None);
1248+ assert_eq!(back.name, "kid (2)");
1240 let listing = scratch.store.list_children(&user.id, None).await.unwrap();1249 let listing = scratch.store.list_children(&user.id, None).await.unwrap();
1241- assert_eq!(listing.folders.iter().filter(|folder| folder.name == "kid").count(), 2);1250+ assert_eq!(listing.folders.len(), 4);
1251+ assert!(listing.folders.iter().any(|folder| folder.name == "kid"));
1252+ assert!(listing.folders.iter().any(|folder| folder.name == "kid (2)"));
1242 }1253 }
1243 1254
1244 #[tokio::test]1255 #[tokio::test]
1245-async fn file_names_stay_unique_among_live_siblings() {1256+async fn file_upload_collisions_postfix_at_the_last_dot() {
1246 let scratch = Scratch::open().await;1257 let scratch = Scratch::open().await;
1247 let user = alice(&scratch.store).await;1258 let user = alice(&scratch.store).await;
1248- let first = scratch.store.insert_file(&user.id, None, "note", b"one").await.unwrap();1259+ let first = scratch.store.insert_file(&user.id, None, "report.txt", b"one").await.unwrap();
1249- // A live sibling wearing the name still refuses: files, unlike folders,1260+ assert_eq!(first.name, "report.txt");
1250- // keep one name per directory.1261+ // A live sibling wearing the name is no refusal: the postfix splits at
1251- assert!(matches!(1262+ // the last dot, and the (2) slot occupied steps on to (3).
1252- scratch.store.insert_file(&user.id, None, "note", b"two").await,1263+ let second = scratch.store.insert_file(&user.id, None, "report.txt", b"two").await.unwrap();
1253- Err(StoreError::NameTaken)1264+ assert_eq!(second.name, "report (2).txt");
1254- ));1265+ let third = scratch.store.insert_file(&user.id, None, "report.txt", b"three").await.unwrap();
1255- let other = scratch.store.insert_file(&user.id, None, "other", b"two").await.unwrap();1266+ assert_eq!(third.name, "report (3).txt");
1256- assert!(matches!(1267+}
1257- scratch.store.rename_file(&other.id, "note").await,1268+
1258- Err(StoreError::NameTaken)1269+#[tokio::test]
1259- ));1270+async fn extension_less_file_collisions_postfix_at_the_end() {
1260- // Trashing frees the name; restoring onto a squatter still refuses.1271+ let scratch = Scratch::open().await;
1272+ let user = alice(&scratch.store).await;
1273+ scratch.store.insert_file(&user.id, None, "note", b"one").await.unwrap();
1274+ let second = scratch.store.insert_file(&user.id, None, "note", b"two").await.unwrap();
1275+ assert_eq!(second.name, "note (2)");
1276+}
1277+
1278+#[tokio::test]
1279+async fn file_rename_onto_a_sibling_name_postfixes() {
1280+ let scratch = Scratch::open().await;
1281+ let user = alice(&scratch.store).await;
1282+ scratch.store.insert_file(&user.id, None, "report.txt", b"one").await.unwrap();
1283+ scratch.store.insert_file(&user.id, None, "report (2).txt", b"two").await.unwrap();
1284+ let other = scratch.store.insert_file(&user.id, None, "other.txt", b"three").await.unwrap();
1285+ // Both the plain name and (2) are taken: the rename steps on to (3).
1286+ scratch.store.rename_file(&other.id, "report.txt").await.unwrap();
1287+ let back = scratch.store.file(&other.id).await.unwrap().unwrap();
1288+ assert_eq!(back.name, "report (3).txt");
1289+ // Renaming onto a free name keeps it whole.
1290+ scratch.store.rename_file(&other.id, "fresh.txt").await.unwrap();
1291+ let back = scratch.store.file(&other.id).await.unwrap().unwrap();
1292+ assert_eq!(back.name, "fresh.txt");
1293+}
1294+
1295+#[tokio::test]
1296+async fn file_move_into_a_folder_with_a_name_twin_postfixes() {
1297+ let scratch = Scratch::open().await;
1298+ let user = alice(&scratch.store).await;
1299+ let folder = scratch.store.create_folder(&user.id, None, "docs").await.unwrap();
1300+ scratch.store.insert_file(&user.id, Some(&folder.id), "report.txt", b"inside").await.unwrap();
1301+ let loose = scratch.store.insert_file(&user.id, None, "report.txt", b"loose").await.unwrap();
1302+ // Same name in a different directory is fine; moving it next to its
1303+ // twin postfixes instead of refusing.
1304+ scratch.store.move_file(&loose.id, Some(&folder.id)).await.unwrap();
1305+ let back = scratch.store.file(&loose.id).await.unwrap().unwrap();
1306+ assert_eq!(back.folder_id.as_deref(), Some(folder.id.as_str()));
1307+ assert_eq!(back.name, "report (2).txt");
1308+}
1309+
1310+#[tokio::test]
1311+async fn file_restore_onto_a_squatter_postfixes() {
1312+ let scratch = Scratch::open().await;
1313+ let user = alice(&scratch.store).await;
1314+ let first = scratch.store.insert_file(&user.id, None, "note.txt", b"one").await.unwrap();
1315+ // Trashing frees the name: the next upload takes it plain.
1261 scratch.store.delete_file(&first.id).await.unwrap();1316 scratch.store.delete_file(&first.id).await.unwrap();
1262- scratch.store.insert_file(&user.id, None, "note", b"three").await.unwrap();1317+ let squatter = scratch.store.insert_file(&user.id, None, "note.txt", b"squatter").await.unwrap();
1263- assert!(matches!(1318+ assert_eq!(squatter.name, "note.txt");
1264- scratch.store.restore_file(&first.id).await,1319+ // Restoring onto the squatter postfixes instead of refusing.
1265- Err(StoreError::NameTaken)1320+ scratch.store.restore_file(&first.id).await.unwrap();
1266- ));1321+ let back = scratch.store.file(&first.id).await.unwrap().unwrap();
1322+ assert_eq!(back.name, "note (2).txt");
1323+}
1324+
1325+#[tokio::test]
1326+async fn finish_upload_onto_a_taken_name_postfixes() {
1327+ let scratch = Scratch::open().await;
1328+ let user = alice(&scratch.store).await;
1329+ scratch.store.insert_file(&user.id, None, "clip.txt", b"taken").await.unwrap();
1330+ let bytes = b"arriving";
1331+ let session = scratch
1332+ .store
1333+ .create_upload_session(&user.id, None, "clip.txt", bytes.len() as u64)
1334+ .await
1335+ .unwrap();
1336+ scratch.store.record_chunk(&session.id, 0, bytes).await.unwrap();
1337+ // The session keeps the user's literal name; the finished file wears
1338+ // the first free postfix.
1339+ let file = scratch.store.finish_upload(&session.id).await.unwrap();
1340+ assert_eq!(file.name, "clip (2).txt");
1341+ assert_eq!(scratch.store.file_bytes(&file.id).await.unwrap().unwrap(), bytes);
1267 }1342 }
1268 1343
1269 #[tokio::test]1344 #[tokio::test]
crates/in-web/src/drive.rsmodified+106 -138
@@ -32,7 +32,6 @@ use crate::server::{Refusal, app, back_to, refusal_of, require_user};
32 /// the leak the distinction exists to prevent.32 /// the leak the distinction exists to prevent.
33 fn store_refusal(error: StoreError) -> Refusal {33 fn store_refusal(error: StoreError) -> Refusal {
34 match error {34 match error {
35- StoreError::NameTaken => Refusal::NameTaken,
36 StoreError::QuotaExceeded => Refusal::QuotaExceeded,35 StoreError::QuotaExceeded => Refusal::QuotaExceeded,
37 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,36 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
38 // A move nesting a folder inside its own descendant.37 // A move nesting a folder inside its own descendant.
@@ -426,7 +425,7 @@ async fn drive(cx: &Cx) -> Result {
426 view! {425 view! {
427 cx =>426 cx =>
428 (topbar(cx, NavPage::Drive, &user, language).await?)427 (topbar(cx, NavPage::Drive, &user, language).await?)
429- <main class="settings-stage">428+ <main class="settings-stage stage-wide">
430 <div class="filterbar">429 <div class="filterbar">
431 if let Some(query) = asked.as_deref() {430 if let Some(query) = asked.as_deref() {
432 <p class="detail-quiet">(t(language, Key::SearchResults)) (format!(" “{query}”"))</p>431 <p class="detail-quiet">(t(language, Key::SearchResults)) (format!(" “{query}”"))</p>
@@ -515,16 +514,6 @@ async fn drive(cx: &Cx) -> Result {
515 </div>514 </div>
516 </details>515 </details>
517 </div>516 </div>
518- // The persistent notice stack: client-side upload errors and
519- // completions render here and stay until dismissed. The region
520- // itself is server HTML, but every card is client-made
521- // (`__inAdded`) and mirrored in `window.__inNotices`, which the
522- // status script re-renders on every `in:wire` — so the cards
523- // survive both swap paths (the live morph keeps client-made
524- // nodes; the full replace rebuilds them from the array, which
525- // lives on `window` and outlives the body).
526- <div id="in-status" class="in-status-stack" aria-live="polite"
527- data-dismiss-label=(t(language, Key::Dismiss))></div>
528 if let Some(refusal) = refusal {517 if let Some(refusal) = refusal {
529 <p class="field-error">(refusal.message_in(language))</p>518 <p class="field-error">(refusal.message_in(language))</p>
530 }519 }
@@ -540,8 +529,9 @@ async fn drive(cx: &Cx) -> Result {
540 // The upload control sits outside the list so the + menu's529 // The upload control sits outside the list so the + menu's
541 // "Upload files" label and the page-wide drop handler find it on530 // "Upload files" label and the page-wide drop handler find it on
542 // every drive view, folder or search. The input stays hidden via531 // every drive view, folder or search. The input stays hidden via
543- // the file-upload-input rule; the progress list below it carries532+ // the file-upload-input rule; live progress rows go to the
544- // the per-upload bars the script builds.533+ // document shell's `#in-status` corner stack, which every page
534+ // carries, so they stay visible across soft navigations.
545 <form id="upload-form" class="file-upload" method="post" action="/files"535 <form id="upload-form" class="file-upload" method="post" action="/files"
546 enctype="multipart/form-data" data-hard=""536 enctype="multipart/form-data" data-hard=""
547 data-failed-label=(t(language, Key::UploadFailed))537 data-failed-label=(t(language, Key::UploadFailed))
@@ -549,7 +539,6 @@ async fn drive(cx: &Cx) -> Result {
549 <input type="hidden" name="folder_id" value=(current_id.clone())>539 <input type="hidden" name="folder_id" value=(current_id.clone())>
550 <input id="drive-upload-input" class="file-upload-input" type="file" name="file" multiple="">540 <input id="drive-upload-input" class="file-upload-input" type="file" name="file" multiple="">
551 </form>541 </form>
552- <div id="upload-progress-list" class="upload-progress-list" aria-live="polite"></div>
553 // The full-page drop affordance: hidden until a file drag is542 // The full-page drop affordance: hidden until a file drag is
554 // over the window, pointer-transparent so it never blocks the543 // over the window, pointer-transparent so it never blocks the
555 // drop itself.544 // drop itself.
@@ -680,7 +669,6 @@ async fn drive(cx: &Cx) -> Result {
680 </main>669 </main>
681 (crate::dropdown::dropdown_script(cx).await?)670 (crate::dropdown::dropdown_script(cx).await?)
682 (upload_script(cx).await?)671 (upload_script(cx).await?)
683- (status_script(cx).await?)
684 }672 }
685 }673 }
686 674
@@ -715,7 +703,8 @@ fn query_value(query: &str, key: &str) -> Option<String> {
715 /// The upload control's client half: files under 8 MiB ride one multipart703 /// The upload control's client half: files under 8 MiB ride one multipart
716 /// post, files at or over it are split into the chunked protocol's calls —704 /// post, files at or over it are split into the chunked protocol's calls —
717 /// and every upload, small or big, draws the same live progress row (name,705 /// and every upload, small or big, draws the same live progress row (name,
718-/// bar, percent) into `#upload-progress-list`.706+/// bar, percent) into the persistent `#in-status` corner stack, which the
707+/// document shell renders on every page.
719 ///708 ///
720 /// The form wears `data-hard` so the soft-nav's multipart replay leaves it709 /// The form wears `data-hard` so the soft-nav's multipart replay leaves it
721 /// alone — two uploaders racing the same bytes would double-insert, and the710 /// alone — two uploaders racing the same bytes would double-insert, and the
@@ -723,9 +712,10 @@ fn query_value(query: &str, key: &str) -> Option<String> {
723 /// form posts plainly and the 303 lands back on the folder.712 /// form posts plainly and the 303 lands back on the folder.
724 ///713 ///
725 /// Failures never append inline notes anymore: they go through714 /// Failures never append inline notes anymore: they go through
726-/// `window.__inNotify` into the persistent stack ([`status_script`]), which715+/// `window.__inNotify` into the persistent stack
727-/// survives the swaps that used to wipe them. Completions announce there716+/// ([`crate::layout::status_script`]), which survives the swaps that used to
728-/// too, then the page navigates to the landing the post answered.717+/// wipe them. Completions announce there too, then the page navigates to the
718+/// landing the post answered.
729 ///719 ///
730 /// The same block carries the `?edit=` row's focus: the rename input the720 /// The same block carries the `?edit=` row's focus: the rename input the
731 /// server renders open gets focused with its name selected on arrival, so a721 /// server renders open gets focused with its name selected on arrival, so a
@@ -748,37 +738,92 @@ async fn upload_script(cx: &Cx) -> Result {
748 if (window.__inUpload) { return; } \738 if (window.__inUpload) { return; } \
749 window.__inUpload = true; \739 window.__inUpload = true; \
750 var LIMIT = 8388608; \740 var LIMIT = 8388608; \
751- function progressList() { return document.getElementById('upload-progress-list'); } \741+ function upBox() { return document.getElementById('in-status'); } \
742+ function upSeq() { window.__inUpSeq = (window.__inUpSeq || 0) + 1; return window.__inUpSeq; } \
743+ /* Rows are found by walking `[data-upload]` and comparing the \
744+ attribute in script: a selector with an interpolated value would \
745+ need double quotes inside this Rust string, so it is avoided. */ \
746+ function findRow(box, id) { \
747+ var rows = box.querySelectorAll('[data-upload]'); \
748+ for (var i = 0; i < rows.length; i++) { \
749+ if (rows[i].getAttribute('data-upload') == String(id)) { return rows[i]; } \
750+ } \
751+ return null; \
752+ } \
753+ /* The in-flight mirror: progress rows are client-made (`__inAdded`, \
754+ so the live morph keeps them) and mirrored here, so the full-replace \
755+ path — which rebuilds the body on every soft navigation — re-renders \
756+ them from this array on `in:wire` instead of losing sight of the \
757+ upload. Progress ticks only ever write the mirror, then paint the \
758+ live row if it is still connected; a tick landing mid-swap paints \
759+ on the next wire. Full page loads cannot preserve an in-flight bar \
760+ — the completion card still announces on landing. */ \
761+ function renderUploads() { \
762+ var box = upBox(); \
763+ if (!box) { return; } \
764+ if (!window.__inUploads) { window.__inUploads = []; } \
765+ var seen = {}; \
766+ window.__inUploads.forEach(function (u) { \
767+ seen[u.id] = true; \
768+ var row = findRow(box, u.id); \
769+ if (!row) { \
770+ row = document.createElement('div'); \
771+ row.className = 'upload-progress-row'; \
772+ row.setAttribute('data-upload', String(u.id)); \
773+ if (u.name) { row.setAttribute('aria-label', u.name); } \
774+ var name = document.createElement('span'); \
775+ name.className = 'upload-progress-name'; \
776+ name.textContent = u.name || ''; \
777+ var track = document.createElement('div'); \
778+ track.className = 'upload-progress'; \
779+ var fill = document.createElement('div'); \
780+ fill.className = 'upload-progress-fill'; \
781+ track.appendChild(fill); \
782+ var pct = document.createElement('span'); \
783+ pct.className = 'upload-progress-pct'; \
784+ row.appendChild(name); \
785+ row.appendChild(track); \
786+ row.appendChild(pct); \
787+ box.appendChild(window.__inAdded(row)); \
788+ } \
789+ var text = Math.min(100, Math.round(u.frac * 100)) + '%'; \
790+ var fillNow = row.querySelector('.upload-progress-fill'); \
791+ var pctNow = row.querySelector('.upload-progress-pct'); \
792+ if (fillNow) { fillNow.style.width = text; } \
793+ if (pctNow) { pctNow.textContent = text; } \
794+ }); \
795+ box.querySelectorAll('[data-upload]').forEach(function (row) { \
796+ if (!seen[row.getAttribute('data-upload')]) { row.remove(); } \
797+ }); \
798+ } \
752 function bar(label) { \799 function bar(label) { \
753- var row = document.createElement('div'); \800+ if (!window.__inUploads) { window.__inUploads = []; } \
754- row.className = 'upload-progress-row'; \801+ var u = { id: upSeq(), name: label || '', frac: 0 }; \
755- var name = document.createElement('span'); \802+ window.__inUploads.push(u); \
756- name.className = 'upload-progress-name'; \803+ renderUploads(); \
757- name.textContent = label || ''; \804+ return u; \
758- var track = document.createElement('div'); \
759- track.className = 'upload-progress'; \
760- var fill = document.createElement('div'); \
761- fill.className = 'upload-progress-fill'; \
762- track.appendChild(fill); \
763- var pct = document.createElement('span'); \
764- pct.className = 'upload-progress-pct'; \
765- pct.textContent = '0%'; \
766- row.appendChild(name); \
767- row.appendChild(track); \
768- row.appendChild(pct); \
769- if (label) { row.setAttribute('aria-label', label); } \
770- var list = progressList(); \
771- if (list) { list.appendChild(window.__inAdded(row)); } \
772- return { row: row, fill: fill, pct: pct }; \
773 } \805 } \
774- function setProgress(ui, frac) { \806+ function setProgress(u, frac) { \
807+ u.frac = frac; \
808+ var box = upBox(); \
809+ var row = box && findRow(box, u.id); \
810+ if (!row) { renderUploads(); return; } \
775 var text = Math.min(100, Math.round(frac * 100)) + '%'; \811 var text = Math.min(100, Math.round(frac * 100)) + '%'; \
776- ui.fill.style.width = text; \812+ var fill = row.querySelector('.upload-progress-fill'); \
777- ui.pct.textContent = text; \813+ var pct = row.querySelector('.upload-progress-pct'); \
814+ if (fill) { fill.style.width = text; } \
815+ if (pct) { pct.textContent = text; } \
778 } \816 } \
779- function dropRow(ui) { \817+ function dropRow(u) { \
780- if (ui.row.parentNode) { ui.row.parentNode.removeChild(ui.row); } \818+ if (window.__inUploads) { \
819+ window.__inUploads = window.__inUploads.filter(function (x) { return x.id !== u.id; }); \
820+ } \
821+ var box = upBox(); \
822+ var row = box && findRow(box, u.id); \
823+ if (row) { row.remove(); } \
781 } \824 } \
825+ document.addEventListener('in:wire', renderUploads); \
826+ renderUploads(); \
782 function notify(kind, message) { \827 function notify(kind, message) { \
783 if (window.__inNotify) { window.__inNotify(kind, message); } \828 if (window.__inNotify) { window.__inNotify(kind, message); } \
784 } \829 } \
@@ -937,73 +982,6 @@ async fn upload_script(cx: &Cx) -> Result {
937 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }982 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
938 }983 }
939 984
940-/// The persistent notice stack's client half: upload errors and completions
941-/// that must stay until dismissed.
942-///
943-/// How the cards survive the swaps: every card is registered through
944-/// `__inAdded`, so the live path's morph — which pairs only server-rendered
945-/// nodes and leaves client-made ones alone — keeps them where they are. The
946-/// full-replace path (navigations, form posts) rebuilds the body and would
947-/// drop them, so every notice is also mirrored in `window.__inNotices`,
948-/// which lives on the document's `window` and outlives any one body; the
949-/// `in:wire` pass `swap()` runs after every paint re-renders the stack from
950-/// that array. Dismissing (the ✕, labelled from the stack's
951-/// `data-dismiss-label`) drops the notice from both. Nothing here
952-/// auto-times out.
953-///
954-/// The server-rendered `?refusal` banner needs no such route: it rides the
955-/// redirect URL the swap just painted, so both paths re-render it from the
956-/// server's own bytes.
957-async fn status_script(cx: &Cx) -> Result {
958- use topcoat::view::Unescaped;
959- const JS: &str = "\
960- (function () { \
961- if (window.__inStatus) { return; } \
962- window.__inStatus = true; \
963- if (!window.__inNotices) { window.__inNotices = []; } \
964- var seq = 0; \
965- window.__inNotices.forEach(function (n) { if (n.id > seq) { seq = n.id; } }); \
966- function box() { return document.getElementById('in-status'); } \
967- function dismissLabel() { \
968- var b = box(); \
969- return (b && b.getAttribute('data-dismiss-label')) || 'dismiss'; \
970- } \
971- window.__inNotify = function (kind, text) { \
972- seq++; \
973- window.__inNotices.push({ id: seq, kind: kind, text: text }); \
974- render(); \
975- }; \
976- function render() { \
977- var target = box(); \
978- if (!target) { return; } \
979- target.querySelectorAll('[data-notice]').forEach(function (old) { old.remove(); }); \
980- window.__inNotices.forEach(function (n) { \
981- var card = document.createElement('div'); \
982- card.className = 'in-status-card in-status-' + n.kind; \
983- card.setAttribute('data-notice', String(n.id)); \
984- var text = document.createElement('span'); \
985- text.className = 'in-status-text'; \
986- text.textContent = n.text; \
987- var shut = document.createElement('button'); \
988- shut.type = 'button'; \
989- shut.className = 'in-status-dismiss'; \
990- shut.textContent = '✕'; \
991- shut.setAttribute('aria-label', dismissLabel()); \
992- shut.addEventListener('click', function () { \
993- window.__inNotices = window.__inNotices.filter(function (x) { return x.id !== n.id; }); \
994- card.remove(); \
995- }); \
996- card.appendChild(text); \
997- card.appendChild(shut); \
998- target.appendChild(window.__inAdded(card)); \
999- }); \
1000- } \
1001- document.addEventListener('in:wire', render); \
1002- render(); \
1003- })();";
1004- view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
1005-}
1006-
1007 #[derive(serde::Deserialize)]985 #[derive(serde::Deserialize)]
1008 struct CreateFolderForm {986 struct CreateFolderForm {
1009 #[serde(default)]987 #[serde(default)]
@@ -1047,10 +1025,9 @@ async fn create_folder(cx: &Cx, Form(input): Form<CreateFolderForm>) -> Redirect
1047 }1025 }
1048 }1026 }
1049 1027
1050-/// The + menu's quick create: the first free generic name, then a 303 to the1028+/// The + menu's quick create: a generic name, then a 303 to the folder view
1051-/// folder view with that row in its rename form. The loop is the1029+/// with that row in its rename form. The store postfixes a colliding name
1052-/// collision-suffixing (`New folder 2`, …), bounded so a pathological tree1030+/// itself, so one attempt always answers.
1053-/// answers unavailable instead of spinning.
1054 async fn quick_folder(1031 async fn quick_folder(
1055 cx: &Cx,1032 cx: &Cx,
1056 store: &std::sync::Arc<dyn Store>,1033 store: &std::sync::Arc<dyn Store>,
@@ -1058,29 +1035,20 @@ async fn quick_folder(
1058 parent: Option<&str>,1035 parent: Option<&str>,
1059 ) -> Redirect {1036 ) -> Redirect {
1060 let base = t(lang(cx).await, Key::NewFolder).to_string();1037 let base = t(lang(cx).await, Key::NewFolder).to_string();
1061- for attempt in 0..64u32 {1038+ match store.create_folder(owner_id, parent, &base).await {
1062- let name = if attempt == 0 {1039+ Ok(folder) => {
1063- base.clone()1040+ let location = match parent {
1064- } else {1041+ Some(parent) => format!("/drive?folder={parent}&edit={}", folder.id),
1065- format!("{} {}", base, attempt + 1)1042+ None => format!("/drive?edit={}", folder.id),
1066- };1043+ };
1067- match store.create_folder(owner_id, parent, &name).await {1044+ Ok((
1068- Ok(folder) => {1045+ StatusCode::SEE_OTHER,
1069- let location = match parent {1046+ [(header::LOCATION, location)],
1070- Some(parent) => format!("/drive?folder={parent}&edit={}", folder.id),1047+ Json(None),
1071- None => format!("/drive?edit={}", folder.id),1048+ ))
1072- };
1073- return Ok((
1074- StatusCode::SEE_OTHER,
1075- [(header::LOCATION, location)],
1076- Json(None),
1077- ));
1078- }
1079- Err(StoreError::NameTaken) => {}
1080- Err(error) => return redirect(cx, Some(store_refusal(error))),
1081 }1049 }
1050+ Err(error) => redirect(cx, Some(store_refusal(error))),
1082 }1051 }
1083- redirect(cx, Some(Refusal::Unavailable))
1084 }1052 }
1085 1053
1086 #[derive(serde::Deserialize)]1054 #[derive(serde::Deserialize)]
crates/in-web/src/files.rsmodified+11 -9
@@ -35,7 +35,6 @@ path_param!(id);
35 /// [`Refusal::NotFound`], same as a missing id.35 /// [`Refusal::NotFound`], same as a missing id.
36 fn store_refusal(error: StoreError) -> Refusal {36 fn store_refusal(error: StoreError) -> Refusal {
37 match error {37 match error {
38- StoreError::NameTaken => Refusal::NameTaken,
39 StoreError::QuotaExceeded => Refusal::QuotaExceeded,38 StoreError::QuotaExceeded => Refusal::QuotaExceeded,
40 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,39 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
41 StoreError::UploadExpired => Refusal::UploadExpired,40 StoreError::UploadExpired => Refusal::UploadExpired,
@@ -472,16 +471,22 @@ async fn view_file(cx: &Cx) -> Result {
472 view! {471 view! {
473 cx =>472 cx =>
474 (topbar(cx, NavPage::Drive, &user, language).await?)473 (topbar(cx, NavPage::Drive, &user, language).await?)
475- <main class="settings-stage">474+ <main class="settings-stage stage-wide">
476- <p><a class="quiet" href="/drive">(t(language, Key::BackToDrive))</a></p>475+ <div class="viewer-head">
477- <h1 class="settings-title">(entry_chip(cx, &file).await?) (file.name.clone())</h1>476+ <a class="quiet" href="/drive">(t(language, Key::BackToDrive))</a>
477+ <div class="spacer"></div>
478+ if may_download {
479+ <a class="primary" href=(download_href)>(t(language, Key::Download))</a>
480+ }
481+ </div>
482+ <h1 class="settings-title viewer-title">(entry_chip(cx, &file).await?) (file.name.clone())</h1>
478 <p class="field-note">(meta)</p>483 <p class="field-note">(meta)</p>
479 <div class="viewer-stage">484 <div class="viewer-stage">
480 if may_download {485 if may_download {
481 match viewer_kind(&file.mime) {486 match viewer_kind(&file.mime) {
482 Some(ViewerKind::Image) => <img class="viewer-media" src=(src.clone()) alt=(file.name.clone())>,487 Some(ViewerKind::Image) => <img class="viewer-media" src=(src.clone()) alt=(file.name.clone())>,
483 Some(ViewerKind::Video) => <video class="viewer-media" src=(src.clone()) controls="" preload="metadata"></video>,488 Some(ViewerKind::Video) => <video class="viewer-media" src=(src.clone()) controls="" preload="metadata"></video>,
484- Some(ViewerKind::Audio) => <audio class="viewer-audio" src=(src.clone()) controls="" preload="metadata"></audio>,489+ Some(ViewerKind::Audio) => <div class="viewer-audio-wrap"><audio class="viewer-audio" src=(src.clone()) controls="" preload="metadata"></audio></div>,
485 Some(ViewerKind::Pdf) => <object class="viewer-media viewer-pdf" data=(src.clone()) type="application/pdf">490 Some(ViewerKind::Pdf) => <object class="viewer-media viewer-pdf" data=(src.clone()) type="application/pdf">
486 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>491 <p class="field-note">(t(language, Key::PreviewUnavailable))</p>
487 </object>,492 </object>,
@@ -499,10 +504,7 @@ async fn view_file(cx: &Cx) -> Result {
499 </div>504 </div>
500 }505 }
501 </div>506 </div>
502- if may_download {507+ <section class="panel viewer-details">
503- <p><a class="primary" href=(download_href)>(t(language, Key::Download))</a></p>
504- }
505- <section class="panel">
506 <div class="panel-head">508 <div class="panel-head">
507 <h2 class="panel-title">(t(language, Key::FileDetails))</h2>509 <h2 class="panel-title">(t(language, Key::FileDetails))</h2>
508 </div>510 </div>
crates/in-web/src/i18n.rsmodified+10 -7
@@ -198,9 +198,10 @@ pub enum Key {
198 KindAll,198 KindAll,
199 KindFolders,199 KindFolders,
200 KindFiles,200 KindFiles,
201- // Wave-2 trash/share extras (TrashShareBuild owns this block).
202 SortDeleted,201 SortDeleted,
203 SortOwner,202 SortOwner,
203+ // Settings limits redesign (SettingsBuild owns this block).
204+ UploadLimitHelp,
204 }205 }
205 206
206 pub fn t(lang: Lang, key: Key) -> &'static str {207 pub fn t(lang: Lang, key: Key) -> &'static str {
@@ -289,7 +290,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
289 AdminPanel => "Everyone",290 AdminPanel => "Everyone",
290 AllUsers => "Everyone",291 AllUsers => "Everyone",
291 SetQuota => "Set the quota",292 SetQuota => "Set the quota",
292- QuotaBytes => "Quota in bytes",293+ QuotaBytes => "Storage quota",
293 DisableUser => "Disable",294 DisableUser => "Disable",
294 EnableUser => "Enable",295 EnableUser => "Enable",
295 DisabledBadge => "disabled",296 DisabledBadge => "disabled",
@@ -308,9 +309,9 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
308 Saved => "Saved.",309 Saved => "Saved.",
309 UploadedLabel => "Uploaded",310 UploadedLabel => "Uploaded",
310 DownloadsLabel => "Downloads",311 DownloadsLabel => "Downloads",
311- UploadLimits => "Upload limits",312+ UploadLimits => "Upload limit",
312 CurrentUploadLimit => "Current limit",313 CurrentUploadLimit => "Current limit",
313- MaxUploadBytes => "Limit in bytes",314+ MaxUploadBytes => "Upload limit",
314 Options => "Options",315 Options => "Options",
315 DropFilesToUpload => "Drop files to upload",316 DropFilesToUpload => "Drop files to upload",
316 Dismiss => "Dismiss",317 Dismiss => "Dismiss",
@@ -325,6 +326,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
325 KindFiles => "Files",326 KindFiles => "Files",
326 SortDeleted => "Deleted",327 SortDeleted => "Deleted",
327 SortOwner => "Owner",328 SortOwner => "Owner",
329+ UploadLimitHelp => "The most one uploaded file may be. Applies to everyone.",
328 },330 },
329 Lang::Tr => match key {331 Lang::Tr => match key {
330 Cancel => "Vazgeç",332 Cancel => "Vazgeç",
@@ -409,7 +411,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
409 AdminPanel => "Herkes",411 AdminPanel => "Herkes",
410 AllUsers => "Herkes",412 AllUsers => "Herkes",
411 SetQuota => "Kotayı ayarla",413 SetQuota => "Kotayı ayarla",
412- QuotaBytes => "Bayt olarak kota",414+ QuotaBytes => "Depolama kotası",
413 DisableUser => "Devre dışı bırak",415 DisableUser => "Devre dışı bırak",
414 EnableUser => "Etkinleştir",416 EnableUser => "Etkinleştir",
415 DisabledBadge => "devre dışı",417 DisabledBadge => "devre dışı",
@@ -428,9 +430,9 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
428 Saved => "Kaydedildi.",430 Saved => "Kaydedildi.",
429 UploadedLabel => "Yüklendi",431 UploadedLabel => "Yüklendi",
430 DownloadsLabel => "İndirme",432 DownloadsLabel => "İndirme",
431- UploadLimits => "Yükleme sınırları",433+ UploadLimits => "Yükleme sınırı",
432 CurrentUploadLimit => "Geçerli sınır",434 CurrentUploadLimit => "Geçerli sınır",
433- MaxUploadBytes => "Bayt olarak sınır",435+ MaxUploadBytes => "Yükleme sınırı",
434 Options => "Seçenekler",436 Options => "Seçenekler",
435 DropFilesToUpload => "Yüklemek için dosyaları bırakın",437 DropFilesToUpload => "Yüklemek için dosyaları bırakın",
436 Dismiss => "Kapat",438 Dismiss => "Kapat",
@@ -445,6 +447,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str {
445 KindFiles => "Dosyalar",447 KindFiles => "Dosyalar",
446 SortDeleted => "Silindi",448 SortDeleted => "Silindi",
447 SortOwner => "Sahibi",449 SortOwner => "Sahibi",
450+ UploadLimitHelp => "Tek bir dosyanın alabileceği en büyük boyut. Herkes için geçerlidir.",
448 },451 },
449 }452 }
450 }453 }
crates/in-web/src/layout.rsmodified+74 -0
@@ -868,6 +868,73 @@ pub async fn escape_script(cx: &Cx) -> Result {
868 })();";868 })();";
869 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }869 view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
870 }870 }
871+/// The persistent notice stack's client half: upload errors and completions
872+/// that must stay until dismissed. Emitted from the document shell so every
873+/// page carries the stack — an upload started on the drive keeps its home
874+/// when the reader soft-navigates to the trash mid-flight.
875+///
876+/// How the cards survive the swaps: every card is registered through
877+/// `__inAdded`, so the live path's morph — which pairs only server-rendered
878+/// nodes and leaves client-made ones alone — keeps them where they are. The
879+/// full-replace path (navigations, form posts) rebuilds the body and would
880+/// drop them, so every notice is also mirrored in `window.__inNotices`,
881+/// which lives on the document's `window` and outlives any one body; the
882+/// `in:wire` pass `swap()` runs after every paint re-renders the stack from
883+/// that array. Dismissing (the ✕, labelled from the stack's
884+/// `data-dismiss-label`) drops the notice from both. Nothing here
885+/// auto-times out.
886+///
887+/// The server-rendered `?refusal` banner needs no such route: it rides the
888+/// redirect URL the swap just painted, so both paths re-render it from the
889+/// server's own bytes.
890+pub async fn status_script(cx: &Cx) -> Result {
891+ const JS: &str = "\
892+ (function () { \
893+ if (window.__inStatus) { return; } \
894+ window.__inStatus = true; \
895+ if (!window.__inNotices) { window.__inNotices = []; } \
896+ var seq = 0; \
897+ window.__inNotices.forEach(function (n) { if (n.id > seq) { seq = n.id; } }); \
898+ function box() { return document.getElementById('in-status'); } \
899+ function dismissLabel() { \
900+ var b = box(); \
901+ return (b && b.getAttribute('data-dismiss-label')) || 'dismiss'; \
902+ } \
903+ window.__inNotify = function (kind, text) { \
904+ seq++; \
905+ window.__inNotices.push({ id: seq, kind: kind, text: text }); \
906+ render(); \
907+ }; \
908+ function render() { \
909+ var target = box(); \
910+ if (!target) { return; } \
911+ target.querySelectorAll('[data-notice]').forEach(function (old) { old.remove(); }); \
912+ window.__inNotices.forEach(function (n) { \
913+ var card = document.createElement('div'); \
914+ card.className = 'in-status-card in-status-' + n.kind; \
915+ card.setAttribute('data-notice', String(n.id)); \
916+ var text = document.createElement('span'); \
917+ text.className = 'in-status-text'; \
918+ text.textContent = n.text; \
919+ var shut = document.createElement('button'); \
920+ shut.type = 'button'; \
921+ shut.className = 'in-status-dismiss'; \
922+ shut.textContent = '✕'; \
923+ shut.setAttribute('aria-label', dismissLabel()); \
924+ shut.addEventListener('click', function () { \
925+ window.__inNotices = window.__inNotices.filter(function (x) { return x.id !== n.id; }); \
926+ card.remove(); \
927+ }); \
928+ card.appendChild(text); \
929+ card.appendChild(shut); \
930+ target.appendChild(window.__inAdded(card)); \
931+ }); \
932+ } \
933+ document.addEventListener('in:wire', render); \
934+ render(); \
935+ })();";
936+ view! { cx => <script>(Unescaped::new_unchecked(JS))</script> }
937+}
871 938
872 /// Every path that matches no page raises a `NotFoundError`, so it renders939 /// Every path that matches no page raises a `NotFoundError`, so it renders
873 /// through `root_layout`'s catch below rather than the router's bare default.940 /// 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 {
939 // would just reconnect against that refusal forever.1006 // would just reconnect against that refusal forever.
940 if asking { (live_script(cx).await?) }1007 if asking { (live_script(cx).await?) }
941 (content)1008 (content)
1009+ // The persistent corner stack: client-made upload progress
1010+ // rows and notice cards live here, marked `__inAdded` and
1011+ // mirrored on `window`, so both swap paths keep them while
1012+ // the reader moves between pages mid-upload.
1013+ <div id="in-status" class="in-status-stack" aria-live="polite"
1014+ data-dismiss-label=(t(lang, Key::Dismiss))></div>
1015+ (status_script(cx).await?)
942 </body>1016 </body>
943 </html>1017 </html>
944 }1018 }
crates/in-web/src/server.rsmodified+0 -6
@@ -194,8 +194,6 @@ pub enum Refusal {
194 NotFound,194 NotFound,
195 /// The bytes would not fit the remaining quota.195 /// The bytes would not fit the remaining quota.
196 QuotaExceeded,196 QuotaExceeded,
197- /// A sibling already carries that name.
198- NameTaken,
199 /// A folder with children stays until it is emptied.197 /// A folder with children stays until it is emptied.
200 FolderNotEmpty,198 FolderNotEmpty,
201 /// The target belongs to somebody else. Answered like [`Refusal::NotFound`]199 /// The target belongs to somebody else. Answered like [`Refusal::NotFound`]
@@ -233,7 +231,6 @@ impl Refusal {
233 Refusal::Forbidden => "Not permitted.".to_string(),231 Refusal::Forbidden => "Not permitted.".to_string(),
234 Refusal::NotFound => "No such file or folder.".to_string(),232 Refusal::NotFound => "No such file or folder.".to_string(),
235 Refusal::QuotaExceeded => "Over quota.".to_string(),233 Refusal::QuotaExceeded => "Over quota.".to_string(),
236- Refusal::NameTaken => "That name is already taken here.".to_string(),
237 Refusal::FolderNotEmpty => "That folder still has files in it.".to_string(),234 Refusal::FolderNotEmpty => "That folder still has files in it.".to_string(),
238 // Same sentence as NotFound: a cross-owner probe must not learn235 // Same sentence as NotFound: a cross-owner probe must not learn
239 // the target exists.236 // the target exists.
@@ -262,7 +259,6 @@ impl Refusal {
262 Refusal::Forbidden => "İzin verilmiyor.".to_string(),259 Refusal::Forbidden => "İzin verilmiyor.".to_string(),
263 Refusal::NotFound => "Böyle bir dosya ya da klasör yok.".to_string(),260 Refusal::NotFound => "Böyle bir dosya ya da klasör yok.".to_string(),
264 Refusal::QuotaExceeded => "Kota doldu.".to_string(),261 Refusal::QuotaExceeded => "Kota doldu.".to_string(),
265- Refusal::NameTaken => "Bu ad burada zaten var.".to_string(),
266 Refusal::FolderNotEmpty => "Bu klasörde hâlâ dosyalar var.".to_string(),262 Refusal::FolderNotEmpty => "Bu klasörde hâlâ dosyalar var.".to_string(),
267 Refusal::CrossOwner => "Böyle bir dosya ya da klasör yok.".to_string(),263 Refusal::CrossOwner => "Böyle bir dosya ya da klasör yok.".to_string(),
268 Refusal::ShareRevoked => "Bu bağlantı artık çalışmıyor.".to_string(),264 Refusal::ShareRevoked => "Bu bağlantı artık çalışmıyor.".to_string(),
@@ -287,7 +283,6 @@ impl Refusal {
287 "forbidden" => Refusal::Forbidden,283 "forbidden" => Refusal::Forbidden,
288 "not-found" => Refusal::NotFound,284 "not-found" => Refusal::NotFound,
289 "quota-exceeded" => Refusal::QuotaExceeded,285 "quota-exceeded" => Refusal::QuotaExceeded,
290- "name-taken" => Refusal::NameTaken,
291 "folder-not-empty" => Refusal::FolderNotEmpty,286 "folder-not-empty" => Refusal::FolderNotEmpty,
292 "cross-owner" => Refusal::CrossOwner,287 "cross-owner" => Refusal::CrossOwner,
293 "share-revoked" => Refusal::ShareRevoked,288 "share-revoked" => Refusal::ShareRevoked,
@@ -316,7 +311,6 @@ impl Refusal {
316 Refusal::Forbidden => "forbidden",311 Refusal::Forbidden => "forbidden",
317 Refusal::NotFound => "not-found",312 Refusal::NotFound => "not-found",
318 Refusal::QuotaExceeded => "quota-exceeded",313 Refusal::QuotaExceeded => "quota-exceeded",
319- Refusal::NameTaken => "name-taken",
320 Refusal::FolderNotEmpty => "folder-not-empty",314 Refusal::FolderNotEmpty => "folder-not-empty",
321 Refusal::CrossOwner => "cross-owner",315 Refusal::CrossOwner => "cross-owner",
322 Refusal::ShareRevoked => "share-revoked",316 Refusal::ShareRevoked => "share-revoked",
crates/in-web/src/settings.rsmodified+94 -31
@@ -49,6 +49,49 @@ fn quota_percent(user: &User) -> u8 {
49 (user.used_bytes.saturating_mul(100) / user.quota_bytes).min(100) as u849 (user.used_bytes.saturating_mul(100) / user.quota_bytes).min(100) as u8
50 }50 }
51 51
52+/// One mebibyte / gibibyte in bytes: the only two units the limit forms speak.
53+/// Raw bytes never reach the browser — the panel shows `human_bytes` and the
54+/// forms post a decimal amount plus one of these units, converted back here.
55+const MIB_BYTES: f64 = 1_048_576.0;
56+const GIB_BYTES: f64 = 1_073_741_824.0;
57+
58+/// The `(amount, unit)` pair a human-unit form field defaults to: gibibytes
59+/// once the value reaches one, mebiBytes below it, so `2 GiB` edits as `2`
60+/// GiB rather than `2048` MiB, while a small `512 MiB` cap stays addressable.
61+fn bytes_as_unit(bytes: u64) -> (String, &'static str) {
62+ if bytes >= GIB_BYTES as u64 {
63+ (trim_amount(bytes as f64 / GIB_BYTES), "GiB")
64+ } else {
65+ (trim_amount(bytes as f64 / MIB_BYTES), "MiB")
66+ }
67+}
68+
69+/// A form amount for a number input: two decimals at most, trailing zeros
70+/// (and a bare point) trimmed, so the field reads `2` and `2.5`, never
71+/// `2.00` or `2.5000000001`.
72+fn trim_amount(value: f64) -> String {
73+ let rounded = (value * 100.0).round() / 100.0;
74+ let text = format!("{rounded:.2}");
75+ text.trim_end_matches('0').trim_end_matches('.').to_string()
76+}
77+
78+/// The bytes an `(amount, unit)` pair names, or `None` when the pair is not
79+/// a usable limit: an unknown unit, or an amount that is not a finite
80+/// positive number. Callers decide whether zero passes (quota) or not
81+/// (upload limit).
82+fn unit_bytes(amount: &str, unit: &str) -> Option<u64> {
83+ let per = match unit {
84+ "MiB" => MIB_BYTES,
85+ "GiB" => GIB_BYTES,
86+ _ => return None,
87+ };
88+ let value: f64 = amount.trim().parse().ok()?;
89+ if !value.is_finite() || value < 0.0 {
90+ return None;
91+ }
92+ Some((value * per).round() as u64)
93+}
94+
52 type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;95 type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>;
53 96
54 /// Back to settings, the refusal (if any) on the query — or `saved=<call>`97 /// Back to settings, the refusal (if any) on the query — or `saved=<call>`
@@ -67,51 +110,62 @@ fn redirect_back(cx: &Cx, call: &str, refusal: Option<Refusal>) -> Redirect {
67 #[derive(Deserialize)]110 #[derive(Deserialize)]
68 struct QuotaForm {111 struct QuotaForm {
69 user_id: String,112 user_id: String,
70- quota_bytes: u64,113+ #[serde(default)]
114+ quota: String,
115+ #[serde(default)]
116+ quota_unit: String,
71 }117 }
72 118
73-/// Sets one account's byte ceiling. The bytes it already holds are untouched —119+/// Sets one account's byte ceiling from a human-unit pair (`quota` amount in
74-/// a quota lowered under current usage refuses new uploads until the person120+/// `quota_unit` MiB/GiB), converted to bytes for the store. The bytes already
75-/// frees space, rather than deleting anything.121+/// held are untouched — a quota lowered under current usage refuses new
122+/// uploads until the person frees space, rather than deleting anything.
76 #[route(POST "/api/settings/quota")]123 #[route(POST "/api/settings/quota")]
77 async fn set_quota(cx: &Cx, Form(input): Form<QuotaForm>) -> Redirect {124 async fn set_quota(cx: &Cx, Form(input): Form<QuotaForm>) -> Redirect {
78 if let Err(refusal) = require_admin(cx).await {125 if let Err(refusal) = require_admin(cx).await {
79 return redirect_back(cx, "quota", Some(refusal));126 return redirect_back(cx, "quota", Some(refusal));
80 }127 }
81- match app(cx).store.set_user_quota(&input.user_id, input.quota_bytes).await {128+ match unit_bytes(&input.quota, &input.quota_unit) {
82- Ok(()) => redirect_back(cx, "quota", None),129+ Some(quota_bytes) => match app(cx).store.set_user_quota(&input.user_id, quota_bytes).await {
83- Err(error) => redirect_back(cx, "quota", Some(refusal_of(error))),130+ Ok(()) => redirect_back(cx, "quota", None),
131+ Err(error) => redirect_back(cx, "quota", Some(refusal_of(error))),
132+ },
133+ None => redirect_back(cx, "quota", Some(Refusal::BadLimit)),
84 }134 }
85 }135 }
86 136
87 #[derive(Deserialize)]137 #[derive(Deserialize)]
88 struct UploadLimitForm {138 struct UploadLimitForm {
89- max_upload_bytes: u64,139+ #[serde(default)]
140+ max_upload: String,
141+ #[serde(default)]
142+ max_upload_unit: String,
90 }143 }
91-144+/// Sets the instance-wide per-file upload ceiling from a human-unit pair
92-/// Sets the instance-wide per-file upload ceiling, in bytes — the same unit145+/// (`max_upload` amount in `max_upload_unit` MiB/GiB), converted to bytes
93-/// the `max_upload_bytes` instance setting stores, so the round trip is146+/// for the `max_upload_bytes` instance setting — so `2 GiB` stores
94-/// exact: what the panel shows is what a save writes back. The bytes already147+/// `2147483648` and the panel reads it back as `2.0 GiB`. The fallback chain
95-/// held are untouched — a ceiling lowered under an existing file refuses new148+/// in [`crate::server::effective_upload_limit`] is untouched, and zero (or
96-/// uploads past it, rather than deleting anything.149+/// anything unparseable) is refused with `BadLimit`: an install must always
150+/// have a positive per-file ceiling.
97 #[route(POST "/api/settings/upload-limit")]151 #[route(POST "/api/settings/upload-limit")]
98 async fn set_upload_limit(cx: &Cx, Form(input): Form<UploadLimitForm>) -> Redirect {152 async fn set_upload_limit(cx: &Cx, Form(input): Form<UploadLimitForm>) -> Redirect {
99 if let Err(refusal) = require_admin(cx).await {153 if let Err(refusal) = require_admin(cx).await {
100 return redirect_back(cx, "upload-limit", Some(refusal));154 return redirect_back(cx, "upload-limit", Some(refusal));
101 }155 }
102- if input.max_upload_bytes == 0 {156+ match unit_bytes(&input.max_upload, &input.max_upload_unit) {
103- return redirect_back(cx, "upload-limit", Some(Refusal::BadLimit));157+ Some(bytes) if bytes > 0 => match app(cx)
104- }158+ .store
105- match app(cx)159+ .set_setting(
106- .store160+ crate::server::MAX_UPLOAD_SETTING,
107- .set_setting(161+ &bytes.to_string(),
108- crate::server::MAX_UPLOAD_SETTING,162+ )
109- &input.max_upload_bytes.to_string(),163+ .await
110- )164+ {
111- .await165+ Ok(()) => redirect_back(cx, "upload-limit", None),
112- {166+ Err(error) => redirect_back(cx, "upload-limit", Some(refusal_of(error))),
113- Ok(()) => redirect_back(cx, "upload-limit", None),167+ },
114- Err(error) => redirect_back(cx, "upload-limit", Some(refusal_of(error))),168+ _ => redirect_back(cx, "upload-limit", Some(Refusal::BadLimit)),
115 }169 }
116 }170 }
117 171
@@ -244,7 +298,7 @@ async fn settings(cx: &Cx) -> Result {
244 cx =>298 cx =>
245 (topbar(cx, NavPage::Settings, &fresh, language).await?)299 (topbar(cx, NavPage::Settings, &fresh, language).await?)
246 <div class="settings-shell">300 <div class="settings-shell">
247- <main class="settings-stage">301+ <main class="settings-stage stage-wide">
248 <h1 class="settings-title">(t(language, Key::Settings))</h1>302 <h1 class="settings-title">(t(language, Key::Settings))</h1>
249 (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "upload-limit"]).await?)303 (refusal_banner(cx, language, &["create", "revoke", "add", "remove", "quota", "disable", "preferences", "upload-limit"]).await?)
250 if let Some(token) = created {304 if let Some(token) = created {
@@ -334,9 +388,14 @@ async fn settings(cx: &Cx) -> Result {
334 <h2 class="panel-title">(t(language, Key::UploadLimits))</h2>388 <h2 class="panel-title">(t(language, Key::UploadLimits))</h2>
335 </div>389 </div>
336 <div class="panel-body">390 <div class="panel-body">
337- <p class="field-note">(format!("{}: {}", t(language, Key::CurrentUploadLimit), human_bytes(limit)))</p>391+ <p class="field-note">(t(language, Key::UploadLimitHelp))</p>
338 <form class="pop-row-form" method="post" action="/api/settings/upload-limit">392 <form class="pop-row-form" method="post" action="/api/settings/upload-limit">
339- <input class="field-input" type="number" name="max_upload_bytes" min="1" value=(limit.to_string()) aria-label=(t(language, Key::MaxUploadBytes))>393+ <span class="field-note">(format!("{}: {}", t(language, Key::CurrentUploadLimit), human_bytes(limit)))</span>
394+ <input class="field-input" type="number" name="max_upload" min="0" step="any" value=(bytes_as_unit(limit).0) aria-label=(t(language, Key::MaxUploadBytes))>
395+ <select class="field-input" name="max_upload_unit" aria-label=(t(language, Key::MaxUploadBytes))>
396+ <option value="MiB" selected=(bytes_as_unit(limit).1 == "MiB")>"MiB"</option>
397+ <option value="GiB" selected=(bytes_as_unit(limit).1 == "GiB")>"GiB"</option>
398+ </select>
340 <button class="quiet" type="submit">(t(language, Key::Save))</button>399 <button class="quiet" type="submit">(t(language, Key::Save))</button>
341 </form>400 </form>
342 </div>401 </div>
@@ -376,7 +435,11 @@ async fn settings(cx: &Cx) -> Result {
376 <td class="member-col-role">435 <td class="member-col-role">
377 <form class="pop-row-form member-quota" method="post" action="/api/settings/quota">436 <form class="pop-row-form member-quota" method="post" action="/api/settings/quota">
378 <input type="hidden" name="user_id" value=(listed.id.clone())>437 <input type="hidden" name="user_id" value=(listed.id.clone())>
379- <input class="field-input" type="number" name="quota_bytes" min="0" value=(listed.quota_bytes.to_string()) aria-label=(t(language, Key::QuotaBytes))>438+ <input class="field-input" type="number" name="quota" min="0" step="any" value=(bytes_as_unit(listed.quota_bytes).0) aria-label=(t(language, Key::QuotaBytes))>
439+ <select class="field-input" name="quota_unit" aria-label=(t(language, Key::QuotaBytes))>
440+ <option value="MiB" selected=(bytes_as_unit(listed.quota_bytes).1 == "MiB")>"MiB"</option>
441+ <option value="GiB" selected=(bytes_as_unit(listed.quota_bytes).1 == "GiB")>"GiB"</option>
442+ </select>
380 <button class="quiet" type="submit">(t(language, Key::SetQuota))</button>443 <button class="quiet" type="submit">(t(language, Key::SetQuota))</button>
381 </form>444 </form>
382 if listed.id != fresh.id {445 if listed.id != fresh.id {
crates/in-web/src/share.rsmodified+6 -7
@@ -87,7 +87,6 @@ fn redirect_back(cx: &Cx, nowhere: &str, call: &str, refusal: Option<Refusal>) -
87 pub(crate) fn refusal_of(error: StoreError) -> Refusal {87 pub(crate) fn refusal_of(error: StoreError) -> Refusal {
88 match error {88 match error {
89 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,89 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
90- StoreError::NameTaken => Refusal::NameTaken,
91 StoreError::QuotaExceeded => Refusal::QuotaExceeded,90 StoreError::QuotaExceeded => Refusal::QuotaExceeded,
92 StoreError::AncestorTrashed => Refusal::AncestorTrashed,91 StoreError::AncestorTrashed => Refusal::AncestorTrashed,
93 _ => Refusal::Unavailable,92 _ => Refusal::Unavailable,
@@ -726,7 +725,7 @@ async fn folder_card(
726 view! {725 view! {
727 cx =>726 cx =>
728 (wordmark(cx).await?)727 (wordmark(cx).await?)
729- <main class="settings-stage">728+ <main class="settings-stage stage-wide">
730 <h1 class="settings-title">(here.name.clone())</h1>729 <h1 class="settings-title">(here.name.clone())</h1>
731 <section class="panel">730 <section class="panel">
732 <div class="panel-body">731 <div class="panel-body">
@@ -737,11 +736,11 @@ async fn folder_card(
737 match row {736 match row {
738 PublicEntry::Folder(folder) => <div class="dep-row">737 PublicEntry::Folder(folder) => <div class="dep-row">
739 <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>738 <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>
740- <a class="dep-link" href=(format!("{base}?folder={}", folder.id))>(folder.name.clone())</a>739+ <a class="dep-link" href=(format!("{base}?folder={}", folder.id))><span class="dep-title">(folder.name.clone())</span></a>
741 </div>,740 </div>,
742 PublicEntry::File(file) => <div class="dep-row">741 PublicEntry::File(file) => <div class="dep-row">
743 (public_chip(cx, &format!("{base}?folder={at}&file={}&thumb=1", file.id), file).await?)742 (public_chip(cx, &format!("{base}?folder={at}&file={}&thumb=1", file.id), file).await?)
744- <span class="member-name">(file.name.clone())</span>743+ <span class="member-name dep-title">(file.name.clone())</span>
745 <span class="field-note">(crate::settings::human_bytes(file.size_bytes))</span>744 <span class="field-note">(crate::settings::human_bytes(file.size_bytes))</span>
746 <div class="spacer"></div>745 <div class="spacer"></div>
747 if link.can_download {746 if link.can_download {
@@ -961,7 +960,7 @@ async fn shared(cx: &Cx) -> Result {
961 view! {960 view! {
962 cx =>961 cx =>
963 (topbar(cx, NavPage::Shared, &user, language).await?)962 (topbar(cx, NavPage::Shared, &user, language).await?)
964- <main class="settings-stage">963+ <main class="settings-stage stage-wide">
965 <h1 class="settings-title">(t(language, Key::SharedWithMe))</h1>964 <h1 class="settings-title">(t(language, Key::SharedWithMe))</h1>
966 <div class="filterbar">965 <div class="filterbar">
967 <form class="field-box field-box-sort" method="get" action="/shared">966 <form class="field-box field-box-sort" method="get" action="/shared">
@@ -1016,13 +1015,13 @@ async fn shared(cx: &Cx) -> Result {
1016 <div class="dep-row">1015 <div class="dep-row">
1017 if row.item.kind == ShareKind::Folder {1016 if row.item.kind == ShareKind::Folder {
1018 <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>1017 <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>
1019- <a class="dep-link" href=(format!("/drive?folder={}", row.item.target_id))>(row.item.name.clone())</a>1018+ <a class="dep-link" href=(format!("/drive?folder={}", row.item.target_id))><span class="dep-title">(row.item.name.clone())</span></a>
1020 } else {1019 } else {
1021 match &row.file {1020 match &row.file {
1022 Some(file) => (shared_chip(cx, file).await?),1021 Some(file) => (shared_chip(cx, file).await?),
1023 None => <span class="file-chip file-chip-generic" aria-hidden="true">"▦"</span>,1022 None => <span class="file-chip file-chip-generic" aria-hidden="true">"▦"</span>,
1024 }1023 }
1025- <a class="dep-link" href=(format!("/view/{}", row.item.target_id))>(row.item.name.clone())</a>1024+ <a class="dep-link" href=(format!("/view/{}", row.item.target_id))><span class="dep-title">(row.item.name.clone())</span></a>
1026 }1025 }
1027 <div class="spacer"></div>1026 <div class="spacer"></div>
1028 <span class="field-note">(shared_details(language, row))</span>1027 <span class="field-note">(shared_details(language, row))</span>
crates/in-web/src/trash.rsmodified+4 -4
@@ -307,7 +307,7 @@ async fn trash(cx: &Cx) -> Result {
307 view! {307 view! {
308 cx =>308 cx =>
309 (topbar(cx, NavPage::Trash, &user, language).await?)309 (topbar(cx, NavPage::Trash, &user, language).await?)
310- <main class="settings-stage">310+ <main class="settings-stage stage-wide">
311 <h1 class="settings-title">(t(language, Key::Trash))</h1>311 <h1 class="settings-title">(t(language, Key::Trash))</h1>
312 <div class="filterbar">312 <div class="filterbar">
313 <form class="field-box field-box-sort" method="get" action="/trash">313 <form class="field-box field-box-sort" method="get" action="/trash">
@@ -348,7 +348,7 @@ async fn trash(cx: &Cx) -> Result {
348 (refusal_banner(cx, language, &["restore", "purge", "empty"]).await?)348 (refusal_banner(cx, language, &["restore", "purge", "empty"]).await?)
349 if !nothing_trashed {349 if !nothing_trashed {
350 <form method="post" action="/api/trash/empty">350 <form method="post" action="/api/trash/empty">
351- <button class="quiet-danger" type="submit">(t(language, Key::EmptyTrash))</button>351+ <button class="quiet quiet-danger" type="submit">(t(language, Key::EmptyTrash))</button>
352 </form>352 </form>
353 }353 }
354 <section class="panel">354 <section class="panel">
@@ -368,7 +368,7 @@ async fn trash(cx: &Cx) -> Result {
368 match row {368 match row {
369 TrashEntry::Folder(folder) => <div class="dep-row">369 TrashEntry::Folder(folder) => <div class="dep-row">
370 <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>370 <span class="file-chip file-chip-folder" aria-hidden="true">"▤"</span>
371- <span class="member-name">(folder.name.clone())</span>371+ <span class="member-name dep-title">(folder.name.clone())</span>
372 <span class="field-note">(trash_details(language, row))</span>372 <span class="field-note">(trash_details(language, row))</span>
373 <div class="spacer"></div>373 <div class="spacer"></div>
374 <form class="pop-row-form" method="post" action="/api/trash/restore">374 <form class="pop-row-form" method="post" action="/api/trash/restore">
@@ -384,7 +384,7 @@ async fn trash(cx: &Cx) -> Result {
384 </div>,384 </div>,
385 TrashEntry::File(file) => <div class="dep-row">385 TrashEntry::File(file) => <div class="dep-row">
386 (trash_chip(cx, file).await?)386 (trash_chip(cx, file).await?)
387- <span class="member-name">(file.name.clone())</span>387+ <span class="member-name dep-title">(file.name.clone())</span>
388 <span class="field-note">(trash_details(language, row))</span>388 <span class="field-note">(trash_details(language, row))</span>
389 <div class="spacer"></div>389 <div class="spacer"></div>
390 <form class="pop-row-form" method="post" action="/api/trash/restore">390 <form class="pop-row-form" method="post" action="/api/trash/restore">
crates/in-web/src/upload.rsmodified+0 -1
@@ -60,7 +60,6 @@ fn store_refusal(error: StoreError) -> Refusal {
60 StoreError::UploadExpired => Refusal::UploadExpired,60 StoreError::UploadExpired => Refusal::UploadExpired,
61 StoreError::BadChunk => Refusal::BadChunk,61 StoreError::BadChunk => Refusal::BadChunk,
62 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,62 StoreError::NotFound | StoreError::CrossOwner => Refusal::NotFound,
63- StoreError::NameTaken => Refusal::NameTaken,
64 _ => Refusal::Unavailable,63 _ => Refusal::Unavailable,
65 }64 }
66 }65 }
crates/in-web/tests/http.rsmodified+45 -53
@@ -1848,18 +1848,18 @@ async fn settings_quota_and_disable_guards() {
1848 assert_eq!(page.status, StatusCode::OK, "{}", page.text());1848 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
1849 assert!(page.text().contains("ada@in.test"), "{}", page.text());1849 assert!(page.text().contains("ada@in.test"), "{}", page.text());
1850 1850
1851- // Admin sets Bob's quota.1851+ // Admin sets Bob's quota in human units: 2 GiB lands as 2147483648 bytes.
1852 let answer = app1852 let answer = app
1853 .post(1853 .post(
1854 "/api/settings/quota",1854 "/api/settings/quota",
1855 Some(&admin),1855 Some(&admin),
1856- &[("user_id", &bob_id), ("quota_bytes", "123456")],1856+ &[("user_id", &bob_id), ("quota", "2"), ("quota_unit", "GiB")],
1857 )1857 )
1858 .await;1858 .await;
1859 assert!(answer.accepted(), "quota refused: {:?}", answer.location);1859 assert!(answer.accepted(), "quota refused: {:?}", answer.location);
1860 assert_eq!(1860 assert_eq!(
1861 app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes,1861 app.store.user(&bob_id).await.unwrap().unwrap().quota_bytes,
1862- 1234561862+ 2147483648
1863 );1863 );
1864 1864
1865 // A non-admin is refused the same call.1865 // A non-admin is refused the same call.
@@ -1867,7 +1867,11 @@ async fn settings_quota_and_disable_guards() {
1867 .post(1867 .post(
1868 "/api/settings/quota",1868 "/api/settings/quota",
1869 Some(&bob),1869 Some(&bob),
1870- &[("user_id", &bob_id), ("quota_bytes", "999")],1870+ &[
1871+ ("user_id", &bob_id),
1872+ ("quota", "999"),
1873+ ("quota_unit", "MiB"),
1874+ ],
1871 )1875 )
1872 .await;1876 .await;
1873 assert!(1877 assert!(
@@ -1931,7 +1935,7 @@ async fn signed_out_mutations_ask_to_sign_in() {
1931 (1935 (
1932 "/api/settings/quota",1936 "/api/settings/quota",
1933 "quota",1937 "quota",
1934- &[("user_id", "x"), ("quota_bytes", "1")][..],1938+ &[("user_id", "x"), ("quota", "1"), ("quota_unit", "GiB")][..],
1935 ),1939 ),
1936 ] {1940 ] {
1937 let answer = app.post(path, None, form).await;1941 let answer = app.post(path, None, form).await;
@@ -2258,42 +2262,29 @@ async fn view_only_public_thumb_serves_webp() {
2258 }2262 }
2259 2263
2260 #[tokio::test]2264 #[tokio::test]
2261-async fn a_refused_upload_carries_a_well_formed_query() {2265+async fn a_name_collision_upload_lands_postfixed() {
2262 let app = TestApp::build().await;2266 let app = TestApp::build().await;
2263 let cookie = app.sign_in("sub-dupe", "dupe@in.test", "Dupe").await;2267 let cookie = app.sign_in("sub-dupe", "dupe@in.test", "Dupe").await;
2264 2268
2265- // One file in, then the same name again: the refusal redirect must join2269+ // Three uploads under one name: none is refused — the later ones land
2266- // the feedback pairs with `?`, not `&` — a `/drive&refusal=...` Location2270+ // with a postfix before the extension instead of wasting the upload.
2267- // is a different path entirely and 404s (observed live).2271+ for body in [b"first" as &[u8], b"second", b"third"] {
2268- for _ in 0..2 {2272+ let answer = app
2269- app.post_multipart(2273+ .post_multipart(
2270- "/files",2274+ "/files",
2271- Some(&cookie),2275+ Some(&cookie),
2272- &[("folder_id", "")],2276+ &[("folder_id", "")],
2273- &[("same.txt", "text/plain", b"first or second")],2277+ &[("same.txt", "text/plain", body)],
2274- )2278+ )
2275- .await;2279+ .await;
2280+ assert!(answer.accepted(), "upload refused: {:?}", answer.location);
2276 }2281 }
2277- let answer = app
2278- .post_multipart(
2279- "/files",
2280- Some(&cookie),
2281- &[("folder_id", "")],
2282- &[("same.txt", "text/plain", b"third")],
2283- )
2284- .await;
2285- let location = answer.location.expect("no Location on the refusal");
2286- assert_eq!(answer.status, StatusCode::SEE_OTHER);
2287- assert!(
2288- location.starts_with("/drive?"),
2289- "refusal Location was: {location}"
2290- );
2291- assert!(location.contains("refusal=name-taken"), "{location}");
2292 2282
2293- // And the browser that follows it lands on the drive page, not the 404.2283+ let page = app.get("/drive", Some(&cookie)).await;
2294- let page = app.get(&location, Some(&cookie)).await;
2295 assert_eq!(page.status, StatusCode::OK, "{}", page.text());2284 assert_eq!(page.status, StatusCode::OK, "{}", page.text());
2296- assert!(page.text().contains("already taken"), "{}", page.text());2285+ assert!(page.text().contains("same.txt"), "{}", page.text());
2286+ assert!(page.text().contains("same (2).txt"), "{}", page.text());
2287+ assert!(page.text().contains("same (3).txt"), "{}", page.text());
2297 }2288 }
2298 2289
2299 // -- settings preferences ------------------------------------------------------2290 // -- settings preferences ------------------------------------------------------
@@ -2549,7 +2540,7 @@ fn assert_stage_nests(body: &str, markers: &[&str]) {
2549 "content still sits in the shell: {body}"2540 "content still sits in the shell: {body}"
2550 );2541 );
2551 let stage = body2542 let stage = body
2552- .find("<main class=\"settings-stage\">")2543+ .find("<main class=\"settings-stage")
2553 .expect("no settings-stage");2544 .expect("no settings-stage");
2554 let close = body.find("</main>").expect("no main close");2545 let close = body.find("</main>").expect("no main close");
2555 assert!(stage < close, "unclosed stage");2546 assert!(stage < close, "unclosed stage");
@@ -2931,8 +2922,8 @@ async fn drive_quick_create_names_and_edits() {
2931 .unwrap();2922 .unwrap();
2932 assert_eq!(folder_id(&app, &me, None, "New folder").await, edit);2923 assert_eq!(folder_id(&app, &me, None, "New folder").await, edit);
2933 2924
2934- // Duplicate folder names are allowed: a second quick create takes the2925+ // A second quick create never refuses: the store postfixes the generic
2935- // same generic name on a new row instead of suffixing.2926+ // name instead of duplicating it.
2936 let answer = app2927 let answer = app
2937 .post("/api/folder/create", Some(&cookie), &[("parent_id", "")])2928 .post("/api/folder/create", Some(&cookie), &[("parent_id", "")])
2938 .await;2929 .await;
@@ -2949,13 +2940,14 @@ async fn drive_quick_create_names_and_edits() {
2949 .unwrap();2940 .unwrap();
2950 assert_ne!(edit, edit2, "second quick create reused the row");2941 assert_ne!(edit, edit2, "second quick create reused the row");
2951 let root = app.store.list_children(&me, None).await.unwrap();2942 let root = app.store.list_children(&me, None).await.unwrap();
2952- assert_eq!(2943+ let names: Vec<&str> = root
2953- root.folders2944+ .folders
2954- .iter()2945+ .iter()
2955- .filter(|folder| folder.name == "New folder")2946+ .map(|folder| folder.name.as_str())
2956- .count(),2947+ .collect();
2957- 2,2948+ assert!(
2958- "second quick create did not repeat the generic name"2949+ names.contains(&"New folder") && names.contains(&"New folder (2)"),
2950+ "second quick create did not postfix the generic name: {names:?}"
2959 );2951 );
2960 2952
2961 // A typed name keeps the old answer: back to the page, no edit mode.2953 // 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() {
2981 );2973 );
2982 folder_id(&app, &me, None, "typed").await;2974 folder_id(&app, &me, None, "typed").await;
2983 2975
2984- // A typed duplicate is accepted too — folders share names now.
2985 let answer = app2976 let answer = app
2986 .post(2977 .post(
2987 "/api/folder/create",2978 "/api/folder/create",
@@ -2995,13 +2986,14 @@ async fn drive_quick_create_names_and_edits() {
2995 answer.location2986 answer.location
2996 );2987 );
2997 let root = app.store.list_children(&me, None).await.unwrap();2988 let root = app.store.list_children(&me, None).await.unwrap();
2998- assert_eq!(2989+ let names: Vec<&str> = root
2999- root.folders2990+ .folders
3000- .iter()2991+ .iter()
3001- .filter(|folder| folder.name == "typed")2992+ .map(|folder| folder.name.as_str())
3002- .count(),2993+ .collect();
3003- 2,2994+ assert!(
3004- "typed dupe did not land beside the first"2995+ names.contains(&"typed") && names.contains(&"typed (2)"),
2996+ "typed dupe did not land postfixed: {names:?}"
3005 );2997 );
3006 }2998 }
3007 2999
style/main.scssmodified+158 -11
@@ -4468,18 +4468,11 @@ input[type="radio"] {
4468 white-space: nowrap;4468 white-space: nowrap;
4469 }4469 }
4470 4470
4471-// Upload progress rows under the filterbar: name, bar, percent. The track is4471+// Upload progress rows in the corner stack: name, bar, percent. The track is
4472 // the house upload-progress rule freed of its upload-box geometry (it was4472 // the house upload-progress rule freed of its upload-box geometry (it was
4473 // absolutely positioned into a box the drive form never renders) — here it4473 // absolutely positioned into a box the drive form never renders) — here it
4474-// flexes beside the name it belongs to.4474+// flexes beside the name it belongs to. The stack itself is the container,
4475-.upload-progress-list {4475+// so there is no list wrapper to style or hide.
4476- display: flex;
4477- flex-direction: column;
4478- gap: 8px;
4479- margin-top: 10px;
4480-
4481- &:empty { display: none; }
4482-}
4483 4476
4484 .upload-progress-row {4477 .upload-progress-row {
4485 display: flex;4478 display: flex;
@@ -4497,7 +4490,7 @@ input[type="radio"] {
4497 color: var(--muted);4490 color: var(--muted);
4498 }4491 }
4499 4492
4500-.upload-progress-list .upload-progress {4493+.in-status-stack .upload-progress {
4501 position: relative;4494 position: relative;
4502 flex: 1;4495 flex: 1;
4503 left: auto;4496 left: auto;
@@ -4599,3 +4592,157 @@ input[type="radio"] {
4599 4592
4600 &:hover { color: var(--danger); }4593 &:hover { color: var(--danger); }
4601 }4594 }
4595+
4596+// -- viewer page polish (ViewerBuild) ------------------------------------------------
4597+// GET /view/{id} aligned with the house: a head row carries Back left and the
4598+// .primary Download right (the iz detail-head arrangement), the title keeps
4599+// the house .settings-title size, and the stage is a centered panel card —
4600+// capped at the modal viewer's width so media never sprawls into a full-width
4601+// slab at desktop sizes. Video/images shrink to fit the viewport (70vh, the
4602+// same proportion as the modal's 78vh minus the page chrome); text and pdf
4603+// fill the card in the same chrome. The native audio pill ignores the theme's
4604+// shape language, so it sits in a sunken wrap at a readable width instead.
4605+.viewer-head {
4606+ display: flex;
4607+ align-items: center;
4608+ gap: 10px;
4609+ margin-bottom: 12px;
4610+}
4611+
4612+.viewer-title { overflow-wrap: anywhere; }
4613+
4614+.viewer-stage {
4615+ width: 100%;
4616+ max-width: min(100%, 960px);
4617+ margin: 16px auto;
4618+ padding: 20px 24px 24px;
4619+ background: var(--surface);
4620+ border: 1px solid var(--border);
4621+ border-radius: var(--radius-lg);
4622+ align-items: center;
4623+}
4624+
4625+.viewer-details {
4626+ width: 100%;
4627+ max-width: min(100%, 960px);
4628+ margin: 0 auto;
4629+}
4630+
4631+.viewer-stage .viewer-media {
4632+ width: 100%;
4633+ height: auto;
4634+ max-width: 100%;
4635+ max-height: 70vh;
4636+ display: block;
4637+}
4638+
4639+.viewer-stage .viewer-pdf,
4640+.viewer-stage .viewer-text {
4641+ width: 100%;
4642+ height: 70vh;
4643+ max-height: 70vh;
4644+}
4645+
4646+.viewer-audio-wrap {
4647+ width: min(560px, 100%);
4648+ display: flex;
4649+ justify-content: center;
4650+ padding: 12px 16px;
4651+ background: var(--surface-sunken);
4652+ border: 1px solid var(--border);
4653+ border-radius: var(--radius-md);
4654+}
4655+
4656+.viewer-audio-wrap .viewer-audio { width: 100%; }
4657+
4658+// -- row polish (RowBuild) ------------------------------------------------------------
4659+// Single-line discipline for the drive/trash/shared rows, the anchored options
4660+// menu, and progress rows inside the corner stack. One contiguous section;
4661+// the house panel, chip, quiet and user-menu rules above do the rest.
4662+
4663+// A row never wraps: the name takes the slack as an ellipsis, every detail
4664+// token and action holds its column. The name span in trash and public rows
4665+// is `.member-name`, which carries no geometry of its own — inside a row it
4666+// borrows the dep-title shape (flex, ellipsis, and the old-house `.dep-title`
4667+// geometry it also wears in markup, so the ellipsis does not depend on this
4668+// block alone); the shared page wraps its linked names in `.dep-title`
4669+// directly.
4670+.dep-row { flex-wrap: nowrap; }
4671+
4672+.dep-row > .member-name,
4673+.dep-row > .dep-title {
4674+ flex: 1;
4675+ min-width: 0;
4676+ overflow: hidden;
4677+ text-overflow: ellipsis;
4678+ white-space: nowrap;
4679+}
4680+
4681+// Detail tokens never break mid-value ('6.1 KiB' stays whole): the name's
4682+// ellipsis absorbs the pressure instead.
4683+.dep-row > .field-note {
4684+ flex: none;
4685+ white-space: nowrap;
4686+}
4687+
4688+// Chips, action forms and the options menu hold their width; only the name
4689+// (or the spacer) yields. Action buttons and links never wrap their own
4690+// label under pressure either ('Delete forever' stays one line).
4691+.dep-row > .file-chip,
4692+.dep-row > .pop-row-form,
4693+.dep-row > .entry-options { flex: none; }
4694+
4695+.dep-row .quiet { flex: none; white-space: nowrap; }
4696+
4697+// The row's Options menu wears the house user-menu panel. The positioning
4698+// context is pinned here rather than inherited, so the panel stays anchored
4699+// to its trigger whatever the generic rule does.
4700+.entry-options { position: relative; }
4701+
4702+// A <details> menu is a toggle, not a hover: while open, the panel stays —
4703+// even where the pointer rests outside hover and focus. The Escape pin
4704+// (`.user-menu-esc`) still wins on specificity, so Escape keeps closing it.
4705+.entry-options[open] > .user-menu-panel {
4706+ visibility: visible;
4707+ opacity: 1;
4708+ pointer-events: auto;
4709+}
4710+
4711+// Panels clip their corners with `overflow: hidden`, which would cut an open
4712+// menu off at the panel's edge — most visibly on the bottom rows, whose menu
4713+// opens past it. While a menu is open the clip lifts; closed panels keep
4714+// their corners. Near the viewport bottom the menu still opens downward and
4715+// the page (the scrolling stage) grows to take it, the house drive-add
4716+// behaviour — no upward variant to learn.
4717+.panel:has(.entry-options[open]) { overflow: visible; }
4718+
4719+// Progress rows stretch the stack's width so the bar has room to flex; the
4720+// stack's own max-width still caps them.
4721+.in-status-stack .upload-progress-row { width: 100%; }
4722+
4723+// -- settings quota table (SettingsBuild) ---------------------------------------
4724+//
4725+// The human-unit quota row added a unit <select> beside the amount input, and
4726+// the old `.member-quota .field-input { width: 140px }` sized BOTH of them —
4727+// the role cell's intrinsic width grew ~140px and auto layout billed the
4728+// elastic address column, which `overflow-wrap: anywhere` then stacked one
4729+// character per line. Size each control for what it holds instead, and put a
4730+// floor under the address so no future control can squeeze it vertical again.
4731+// The auto-layout geometry above is untouched: the address still absorbs the
4732+// slack and wraps (never clips) under real pressure.
4733+.member-quota input.field-input {
4734+ width: 96px;
4735+ flex: none;
4736+}
4737+.member-quota select.field-input {
4738+ width: auto;
4739+ flex: none;
4740+}
4741+.member-table .member-col-address {
4742+ min-width: 26ch;
4743+}
4744+// Outside the narrow-viewport query the register has no pan: if minimums ever
4745+// exceed the panel again, scroll the register rather than stacking a column.
4746+.table-pan {
4747+ overflow-x: auto;
4748+}