From 5cc7c91b0c1921e4872b1e2364bb7304f9cf494c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 5 Sep 2026 22:25:21 +0300 Subject: [PATCH] feat(ui): move picker modal, Download in the Options menu, previews don't count MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Options menus' inline destination select becomes a Move item that opens the house modal: the drive root and every live folder as one row each, a folder's own subtree never listed. back_to and __inCloseModal strip the one-shot move= pair, so a posted move closes the picker on success and refusal alike. The destination tree fetch goes lazy with the select gone. File rows gain a Download item — /file/?dl=1 with the download attribute, so the soft-nav handler leaves the click to the browser. /file/ counted every byte serve, the viewer's inline loads and media range probes included; looking is not downloading, so only ?dl=1 serves count now (a resumed download still counts once, on its first chunk). The public-link path already counted downloads only. Regression test: previews_do_not_count_as_downloads. --- crates/in-core/src/store/mod.rs | 51 +++------- crates/in-web/src/drive.rs | 173 +++++++++++++++++++++++++++----- crates/in-web/src/files.rs | 14 ++- crates/in-web/src/i18n.rs | 6 -- crates/in-web/src/layout.rs | 2 +- crates/in-web/src/server.rs | 5 +- crates/in-web/tests/http.rs | 100 +++++++++++++++++- style/main.scss | 59 ++++++----- 8 files changed, 309 insertions(+), 101 deletions(-) diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index b9500bf..860a4d2 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -23,10 +23,10 @@ pub mod sniff; #[cfg(feature = "server")] pub mod turso_store; -#[cfg(feature = "server")] -pub use turso_store::{TursoStore, hash_share_token}; #[cfg(feature = "server")] pub use reconcile::{ReconcileOptions, reconcile}; +#[cfg(feature = "server")] +pub use turso_store::{TursoStore, hash_share_token}; /// What the store can fail with. A caller that needs to distinguish "no such /// row" from "someone else's row" gets [`StoreError::NotFound`] for the @@ -131,9 +131,10 @@ pub struct File { /// What the server decided the bytes are, never what the upload claimed. pub mime: String, pub size_bytes: u64, - /// How many times the bytes went to a reader: the download route and the - /// public-link bytes bump it through [`Store::record_download`], and - /// nothing internal — thumbnails, sniffing, the boot sweep — ever does. + /// How many times the bytes went to a downloader: the download route's + /// `?dl=1` serves and the public-link bytes bump it through + /// [`Store::record_download`], and nothing internal — previews, + /// thumbnails, sniffing, the boot sweep — ever does. pub download_count: u64, pub thumb_state: ThumbState, pub created_at: OffsetDateTime, @@ -410,11 +411,7 @@ pub trait Store: 'static + Send + Sync { /// One directory's live contents: the folders and files whose parent is /// `parent_id` (`None` is the root) and whose trash timestamp is empty. - async fn list_children( - &self, - owner_id: &str, - parent_id: Option<&str>, - ) -> Result; + async fn list_children(&self, owner_id: &str, parent_id: Option<&str>) -> Result; /// Stores small bytes straight through: sanitises the name, checks the /// quota, sniffs the mime (never trusting the uploader), writes the @@ -454,11 +451,11 @@ pub trait Store: 'static + Send + Sync { /// when no thumbnail was made, or its file went missing. async fn thumb_bytes(&self, id: &str) -> Result>>; - /// Counts one user-facing serve of a file's bytes. Byte routes call this - /// once per download they complete — not per range chunk, not per - /// thumbnail, never from internal reads (sniffing, the boot sweep). - /// [`Store::file_bytes`] is a pure read and does not call it. Unknown - /// ids are [`StoreError::NotFound`]. + /// Counts one user-facing download of a file's bytes. Byte routes call + /// this once per download they complete — on `?dl=1` serves, not per + /// range chunk, never for inline previews, thumbnails, or internal reads + /// (sniffing, the boot sweep). [`Store::file_bytes`] is a pure read and + /// does not call it. Unknown ids are [`StoreError::NotFound`]. async fn record_download(&self, id: &str) -> Result<()>; // -- trash ------------------------------------------------------------- @@ -581,8 +578,7 @@ pub trait Store: 'static + Send + Sync { /// it — may. A grant on a folder covers everything under it. Nobody else /// may — and the answer never says which of "no such target" and "not /// shared" it was. - async fn can_see(&self, kind: ShareKind, target_id: &str, user_id: &str) - -> Result; + async fn can_see(&self, kind: ShareKind, target_id: &str, user_id: &str) -> Result; /// Whether `user_id` may download the target: its owner always may, and /// anyone may who sees it through a grant whose `can_download` is set — @@ -590,12 +586,7 @@ pub trait Store: 'static + Send + Sync { /// permissive grant on the chain wins: a download grant above the target /// opens the bytes even under a view-only grant on the target itself. /// A view-only grant alone opens the page but not the bytes. - async fn can_download( - &self, - kind: ShareKind, - target_id: &str, - user_id: &str, - ) -> Result; + async fn can_download(&self, kind: ShareKind, target_id: &str, user_id: &str) -> Result; // -- chunked uploads --------------------------------------------------- @@ -619,12 +610,7 @@ pub trait Store: 'static + Send + Sync { /// re-sending an index replaces its bytes rather than counting them /// twice. Anything past the declared total, or on a session that is not /// active and unexpired, is refused. - async fn record_chunk( - &self, - id: &str, - index: u64, - bytes: &[u8], - ) -> Result; + async fn record_chunk(&self, id: &str, index: u64, bytes: &[u8]) -> Result; /// Assembles a session's chunks in order, rechecks the quota, sniffs the /// mime (never trusting anything the uploader said), writes the file, @@ -658,10 +644,5 @@ pub trait Store: 'static + Send + Sync { /// Owner-scoped substring search over live file and folder names, files /// and folders in their own lists. At most `limit` of each. - async fn search( - &self, - owner_id: &str, - query: &str, - limit: u32, - ) -> Result; + async fn search(&self, owner_id: &str, query: &str, limit: u32) -> Result; } diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs index f42e493..07b346c 100644 --- a/crates/in-web/src/drive.rs +++ b/crates/in-web/src/drive.rs @@ -63,6 +63,7 @@ struct DriveQuery { sort: Option, share: Option, kind: Option, + r#move: Option, } /// The folder the query names, if it names one this account may open: owned, @@ -137,6 +138,124 @@ async fn folder_tree(store: &dyn Store, user_id: &str) -> Vec<(String, String)> out } +/// The move picker's modal: `?move=kind:id` renders the drive root and every +/// live folder as one clickable row each over the page — the file-manager +/// idiom, replacing the select that used to sit inside the Options menu. +/// A folder's own subtree is left out: a move into itself or a descendant is +/// the store's refusal, and a row that can never be picked is noise. Sibling +/// names cannot collide (the store postfixes them), so the display path +/// identifies a subtree exactly. A pair naming nothing owned and live opens +/// nothing. +async fn move_modal( + cx: &Cx, + kind_raw: &str, + target_id: &str, + close_href: &str, + destinations: &[(String, String)], +) -> Result> { + let user = match require_user(cx).await { + Ok(user) => user, + Err(_) => return Ok(None), + }; + let language = lang(cx).await; + let store = app(cx).store.clone(); + // The owned, live target, the endpoint its rows post to, and — for a + // folder — the path prefix that marks its own subtree off the list. + let (name, file, action, field, own_path): ( + String, + Option, + &str, + &str, + Option, + ) = match kind_raw { + "file" => { + let Some(file) = store.file(target_id).await? else { + return Ok(None); + }; + if file.owner_id != user.id || file.deleted_at.is_some() { + return Ok(None); + } + ( + file.name.clone(), + Some(file), + "/api/file/move", + "folder_id", + None, + ) + } + "folder" => { + let Some(folder) = store.folder(target_id).await? else { + return Ok(None); + }; + if folder.owner_id != user.id || folder.deleted_at.is_some() { + return Ok(None); + } + let own = destinations + .iter() + .find(|dest| dest.0 == target_id) + .map(|dest| dest.1.clone()); + ( + folder.name.clone(), + None, + "/api/folder/move", + "parent_id", + own, + ) + } + _ => return Ok(None), + }; + let subtree = own_path.map(|path| format!("{path} / ")); + let rows: Vec<&(String, String)> = destinations + .iter() + .filter(|dest| match &subtree { + Some(prefix) => { + !dest.1.starts_with(prefix.as_str()) && dest.1 != prefix.trim_end_matches(" / ") + } + None => true, + }) + .collect(); + Ok(Some(view! { + cx => + + }?)) +} + fn human_size(bytes: u64) -> String { const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; let mut size = bytes as f64; @@ -366,7 +485,13 @@ async fn drive(cx: &Cx) -> Result { KindFilter::Files => found.folders.clear(), } } - let destinations = folder_tree(store.as_ref(), &user.id).await; + // The destination tree only pays when the move picker is open. + let move_pair = params.as_ref().and_then(|query| query.r#move.as_deref()); + let destinations = if move_pair.is_some() { + folder_tree(store.as_ref(), &user.id).await + } else { + Vec::new() + }; let refusal = page_refusal(cx); // Which folder row (if any) renders as its rename form: iz's `?edit=` // idiom — a server-side row swap, no client state to hold. @@ -422,6 +547,14 @@ async fn drive(cx: &Cx) -> Result { } None => None, }; + // The move picker: `?move=kind:id` renders the destination modal over + // the page — one shot, unlike the share dialog: a posted move comes back + // through `back_to`, which strips the pair, so the modal closes on both + // success and refusal (the refusal then wears the page banner). + let move_dialog = match move_pair.and_then(|pair| pair.split_once(':')) { + Some((move_kind, id)) => move_modal(cx, move_kind, id, &here, &destinations).await?, + None => None, + }; // The copy-once banner belongs to the modal when it is open. let created_panel = if share_pair.is_some() { None @@ -593,20 +726,8 @@ async fn drive(cx: &Cx) -> Result { href=(format!("{here}{edit_sep}edit={}", folder.id))>(t(language, Key::Rename)) (t(language, Key::Share)) -
- -
- - -
-
+ (t(language, Key::Move))
@@ -644,18 +765,13 @@ async fn drive(cx: &Cx) -> Result { href=(format!("{here}{edit_sep}edit={}", file.id))>(t(language, Key::Rename)) (t(language, Key::Share)) - - -
- - -
-
+ // The `download` attribute keeps the + // soft-nav handler off the click, so the + // bytes land as a file, not a page swap. + (t(language, Key::Download)) + (t(language, Key::Move))
@@ -669,6 +785,9 @@ async fn drive(cx: &Cx) -> Result { } + if let Some(dialog) = move_dialog { + (dialog) + } if let Some(dialog) = share_dialog { (dialog) } diff --git a/crates/in-web/src/files.rs b/crates/in-web/src/files.rs index 863dcd6..acf5de3 100644 --- a/crates/in-web/src/files.rs +++ b/crates/in-web/src/files.rs @@ -201,7 +201,8 @@ async fn visible_file( /// Serves one file's bytes, or the same not-found a stranger would see for /// a file that does not exist — never a `403`, which would confirm the id -/// belongs to somebody else's drive. +/// belongs to somebody else's drive. Only `?dl=1` counts a download: the +/// viewer reads the same bytes inline, and looking is not downloading. #[route(GET "/file/{id}")] async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> { let id: &str = path_param::(cx); @@ -267,9 +268,10 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> .and_then(|value| value.to_str().ok()); match range.and_then(|range| parse_range(range, total)) { Some(Ok((start, end))) => { - // A play counts once, on its first chunk; later seeks are the - // same view going on, not a new one. - if start == 0 { + // Only a real download counts — `?dl=1` — never the viewer's + // inline bytes. A resumed download counts once, on its first + // chunk; later chunks are the same download going on. + if forced && start == 0 { let _ = store.record_download(id).await; } let slice = bytes[start as usize..=end as usize].to_vec(); @@ -287,7 +289,9 @@ async fn download(cx: &Cx) -> topcoat::Result<(StatusCode, HeaderMap, Vec)> Ok((StatusCode::RANGE_NOT_SATISFIABLE, headers, Vec::new())) } None => { - let _ = store.record_download(id).await; + if forced { + let _ = store.record_download(id).await; + } Ok((StatusCode::OK, headers, bytes)) } } diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index 416a87b..957a687 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -102,7 +102,6 @@ pub enum Key { FolderName, CreateFolder, RenameFolder, - MoveFolder, DeleteFolder, EmptyFolder, FoldersHeading, @@ -126,7 +125,6 @@ pub enum Key { FileDetails, PreviewUnavailable, RenameFile, - MoveFile, DeleteFile, // Share. Share, @@ -255,7 +253,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { FolderName => "Folder name", CreateFolder => "Create folder", RenameFolder => "Rename folder", - MoveFolder => "Move folder", DeleteFolder => "Delete folder", EmptyFolder => { "This folder is empty. Press + to create or upload, or drop files on this page." @@ -279,7 +276,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { FileDetails => "File", PreviewUnavailable => "No preview for this kind of file.", RenameFile => "Rename file", - MoveFile => "Move file", DeleteFile => "Delete file", Share => "Share", ShareLink => "Share link", @@ -394,7 +390,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { FolderName => "Klasör adı", CreateFolder => "Klasörü oluştur", RenameFolder => "Klasörü yeniden adlandır", - MoveFolder => "Klasörü taşı", DeleteFolder => "Klasörü sil", EmptyFolder => { "Bu klasör boş. + ile oluştur ya da yükle, ya da dosyaları bu sayfaya bırak." @@ -418,7 +413,6 @@ pub fn t(lang: Lang, key: Key) -> &'static str { FileDetails => "Dosya", PreviewUnavailable => "Bu tür dosyanın önizlemesi yok.", RenameFile => "Dosyayı yeniden adlandır", - MoveFile => "Dosyayı taşı", DeleteFile => "Dosyayı sil", Share => "Paylaş", ShareLink => "Paylaşım bağlantısı", diff --git a/crates/in-web/src/layout.rs b/crates/in-web/src/layout.rs index 3f6cb42..acaa8f6 100644 --- a/crates/in-web/src/layout.rs +++ b/crates/in-web/src/layout.rs @@ -535,7 +535,7 @@ pub async fn soft_nav_script(cx: &Cx) -> Result { scrims.forEach(function (el) { el.remove(); }); \ sweepPanels(); \ var u = new URL(window.location.href); \ - ['task', 'file', 'confirm', 'new', 'refusal', 'on', 'share', 'created'].forEach(function (k) { u.searchParams.delete(k); }); \ + ['task', 'file', 'confirm', 'new', 'refusal', 'on', 'share', 'created', 'move'].forEach(function (k) { u.searchParams.delete(k); }); \ var q = u.searchParams.toString(); \ history.replaceState(null, '', u.pathname + (q ? '?' + q : '')); \ return true; \ diff --git a/crates/in-web/src/server.rs b/crates/in-web/src/server.rs index 5507b4b..fb14808 100644 --- a/crates/in-web/src/server.rs +++ b/crates/in-web/src/server.rs @@ -396,7 +396,8 @@ pub fn refusal_of(cx: &Cx, call: &str) -> Option { /// came with the request. /// /// The feedback pairs — `refusal=`, `on=`, `why=`, `saved=` — are how a page -/// renders what the last post did. Sending the browser back with them still +/// renders what the last post did, and `move=` opens the drive's one-shot +/// destination picker, which no post should return to. Sending the browser /// on the query re-renders that old answer under the new post's own: a change /// that succeeded right after one that was refused announces the refusal /// again, and reads as having failed. The answer this redirect carries — the @@ -413,7 +414,7 @@ pub fn back_to(cx: &Cx, nowhere: &str) -> String { .split('&') .filter(|pair| { !pair.is_empty() - && !["refusal", "on", "why", "saved"].iter().any(|key| { + && !["refusal", "on", "why", "saved", "move"].iter().any(|key| { pair.strip_prefix(*key) .is_some_and(|rest| rest.starts_with('=')) }) diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index 8ddd41f..f88c398 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -1262,6 +1262,74 @@ async fn forced_download_is_attachment() { assert_eq!(forced.bytes, b"read me"); } +/// Looking is not downloading: the viewer's inline serves — the plain GET +/// and a media element's range probe from byte 0 — never move the counter; +/// only the `?dl=1` disposition does, once per download. +#[tokio::test] +async fn previews_do_not_count_as_downloads() { + let app = TestApp::build().await; + let cookie = app.sign_in("sub-prev", "prev@in.test", "Prev").await; + let user = app + .store + .user_by_oidc_sub("sub-prev") + .await + .unwrap() + .unwrap(); + + app.post_multipart( + "/files", + Some(&cookie), + &[("folder_id", "")], + &[("clip.txt", "text/plain", b"counted only when taken")], + ) + .await; + let file = app + .store + .list_children(&user.id, None) + .await + .unwrap() + .files + .into_iter() + .next() + .unwrap(); + let count = || async { + app.store + .file(&file.id) + .await + .unwrap() + .unwrap() + .download_count + }; + + let inline = app.get(&format!("/file/{}", file.id), Some(&cookie)).await; + assert_eq!(inline.status, StatusCode::OK); + let probe = app + .get_with_range(&format!("/file/{}", file.id), Some(&cookie), "bytes=0-3") + .await; + assert_eq!(probe.status, StatusCode::PARTIAL_CONTENT); + assert_eq!( + count().await, + 0, + "previews counted: inline and range serves" + ); + + let taken = app + .get(&format!("/file/{}?dl=1", file.id), Some(&cookie)) + .await; + assert_eq!(taken.status, StatusCode::OK); + assert_eq!(count().await, 1, "a forced download did not count"); + // A mid-file chunk of a download is the same download going on. + let resumed = app + .get_with_range( + &format!("/file/{}?dl=1", file.id), + Some(&cookie), + "bytes=4-", + ) + .await; + assert_eq!(resumed.status, StatusCode::PARTIAL_CONTENT); + assert_eq!(count().await, 1, "a resumed chunk counted again"); +} + // -- public links (merged from http_d2.rs; one binary per crate) ------------ #[tokio::test] @@ -3152,7 +3220,37 @@ async fn drive_lists_folders_before_files_in_one_panel() { let folder_at = body.find("mmm folder").expect("no folder row"); let file_at = body.find("aaa file.txt").expect("no file row"); assert!(folder_at < file_at, "file row precedes folder row: {body}"); - assert!(body.contains("action=\"/api/folder/move\""), "{body}"); + // Move is a picker modal now: the row's menu links to it, and the modal + // carries the destination rows that post the move. + let folder_id = { + let at = body.find("/drive?folder=").expect("no folder link"); + let rest = &body[at + "/drive?folder=".len()..]; + let end = rest.find('"').expect("unterminated folder link"); + rest[..end].to_string() + }; + assert!( + body.contains(&format!("move=folder:{folder_id}")), + "folder row has no move entry: {body}" + ); + assert!( + body.contains(&format!("move=file:{file_id}")), + "file row has no move entry: {body}" + ); + let picker = app + .get(&format!("/drive?move=folder:{folder_id}"), Some(&cookie)) + .await; + let picker_body = picker.text(); + assert!( + picker_body.contains("action=\"/api/folder/move\""), + "{picker_body}" + ); + // A folder never offers its own subtree as a destination: with only the + // target folder in the tree, the drive root is the one row left. + assert_eq!( + picker_body.matches("class=\"move-pick\"").count(), + 1, + "{picker_body}" + ); // File rename follows the folder pattern: an edit link on the plain // view, the form only on the edit view. assert!( diff --git a/style/main.scss b/style/main.scss index a864a2d..03e4178 100644 --- a/style/main.scss +++ b/style/main.scss @@ -4432,19 +4432,6 @@ input[type="radio"] { &::marker, &::-webkit-details-marker { display: none; } } -// The move form inside the menu: picker and submit side by side, padded like -// the link items around them. -.user-menu-item-move { - display: flex; - align-items: center; - gap: 8px; - padding: 4px 14px; - - .field-input { - flex: 1; - min-width: 0; - } -} // The rename row: the form itself fills the row so the input takes the // middle and Rename/Cancel sit at the right edge, exactly where the Options @@ -4851,9 +4838,8 @@ div.member-row + div.member-row { // -- entry Options menu: flat rows, no boxed buttons ------------------------- // // Inside the menu, `.quiet`'s border box reads as a second frame (his round-4 -// screenshot): the Delete and Move submits become flat menu rows like the -// Rename/Share links — Delete keeps only its danger ink, Move only the -// accent. The Move row's select trigger keeps the house chevron. +// screenshot): the Delete submit becomes a flat menu row like the +// Rename/Share/Move links around it, keeping only its danger ink. .entry-options .user-menu-panel .quiet { border: none; background: none; @@ -4872,15 +4858,40 @@ div.member-row + div.member-row { &:hover { background: var(--row-hover); color: var(--danger); border: none; } } -// The Move submit sits beside its select, not under it: compact, accent-ink, -// no full-width row there. -.entry-options .user-menu-panel .user-menu-item-move .quiet { - width: auto; - flex: none; - padding: 0 2px; - color: var(--accent); +// -- the move destination picker --------------------------------------------- +// +// The explorer-style list the Options menu's Move item opens: one full-width +// row per destination, padded and hovered like the menu items it replaced. +.move-modal { + width: 480px; + padding: 18px 20px 20px; +} +.move-modal .viewer-head { + margin: 0 0 12px; +} +.move-list { + max-height: calc(100vh - 280px); + overflow-y: auto; +} +.move-dest { display: block; } +.move-dest + .move-dest { margin-top: 2px; } +.move-pick { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + height: 34px; + padding: 0 10px; + border: none; + border-radius: var(--radius); + background: none; + font-family: inherit; + font-size: 13px; + color: var(--ink-soft); + text-align: left; + cursor: pointer; - &:hover { background: none; color: var(--accent-ink); } + &:hover { background: var(--row-hover); color: var(--ink); } } // -- the share modal ---------------------------------------------------------