From da9eb91af3067e9fdc9730be1df492bb000997f1 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 17:26:16 +0300 Subject: [PATCH] feat: share page, upload cancel, drop-up menus, single-border toolbar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - share: new /share/{kind}/{id} page (public link create/revoke with copy-once banner, im-user grants by email with download/view-only), linked from every row's Options menu; link rows name the target instead of its id; can_download checkboxes honest — unchecked no longer grants downloads (parse_flag absent=false, regression test) - upload: every in-flight progress row has a cancel control — XHR abort or loop stop + /api/upload/{id}/abort, works across soft navigations, 'Upload canceled.' card in the corner stack - options menu: measure against the nearest scrollport, not the viewport — the stage's content-height scroll area trapped the menu as unpainted scrollable overflow; opens upward when downward is trapped, no page movement when it fits - toolbar: dd triggers and arrow submits no longer wear a second border inside the field box; search label shortened to 'Search' so the placeholder stops clipping - settings: upload limit moved into the Everyone panel with a label and single 'applies to everyone' note --- crates/in-core/src/store/mod.rs | 11 ++ crates/in-core/src/store/turso_store.rs | 40 ++++- crates/in-core/tests/store.rs | 34 ++++ crates/in-web/src/drive.rs | 167 ++++++++++++++++-- crates/in-web/src/i18n.rs | 23 ++- crates/in-web/src/settings.rs | 65 ++++--- crates/in-web/src/share.rs | 216 +++++++++++++++++++++++- crates/in-web/tests/http.rs | 65 ++++++- style/main.scss | 106 +++++++++++- 9 files changed, 665 insertions(+), 62 deletions(-) diff --git a/crates/in-core/src/store/mod.rs b/crates/in-core/src/store/mod.rs index 333e673..b9500bf 100644 --- a/crates/in-core/src/store/mod.rs +++ b/crates/in-core/src/store/mod.rs @@ -560,6 +560,17 @@ pub trait Store: 'static + Send + Sync { user_id: &str, ) -> Result<()>; + /// Every grant on one target, newest first — the target's share page. The + /// caller must own the live target: another owner's target is + /// [`StoreError::CrossOwner`], a missing or trashed one + /// [`StoreError::NotFound`], the same rule as [`Store::add_share_user`]. + async fn shares_for_target( + &self, + caller_id: &str, + kind: ShareKind, + target_id: &str, + ) -> Result>; + /// Everything shared with the person that is still live: untrashed /// targets, newest grant first. The person's own library never appears /// here. diff --git a/crates/in-core/src/store/turso_store.rs b/crates/in-core/src/store/turso_store.rs index 2f141c2..f377c1d 100644 --- a/crates/in-core/src/store/turso_store.rs +++ b/crates/in-core/src/store/turso_store.rs @@ -15,8 +15,8 @@ use ulid::Ulid; use super::secret; use super::{ - CHUNK_SIZE, CreatedLink, File, Folder, Listing, Result, ShareKind, ShareLink, SharedItem, - Store, StoreError, ThumbState, UPLOAD_TTL_HOURS, UploadSession, UploadState, User, + CHUNK_SIZE, CreatedLink, File, Folder, Listing, Result, ShareKind, ShareLink, ShareUser, + SharedItem, Store, StoreError, ThumbState, UPLOAD_TTL_HOURS, UploadSession, UploadState, User, }; use super::{ReconcileOptions, reconcile, schema, sniff}; use crate::live::{Change, Topic}; @@ -2064,6 +2064,42 @@ impl Store for TursoStore { Ok(()) } + async fn shares_for_target( + &self, + caller_id: &str, + kind: ShareKind, + target_id: &str, + ) -> Result> { + // The caller must own a live target — the same rule as the sibling + // share writes: a stranger's target is cross-owner, a missing or + // trashed one not-found. + match target_owner(&self.conn, kind, target_id).await? { + Some(owner) if owner == caller_id => {} + Some(_) => return Err(StoreError::CrossOwner), + None => return Err(StoreError::NotFound), + } + let conn = self.conn.lock().await; + let mut rows = conn + .query( + "SELECT kind, target_id, user_id, can_download, created_at FROM share_user \ + WHERE kind = ?1 AND target_id = ?2 ORDER BY created_at DESC, user_id", + params![kind.as_str(), target_id], + ) + .await + .map_err(backend)?; + let mut out = Vec::new(); + while let Some(row) = rows.next().await.map_err(backend)? { + out.push(ShareUser { + kind: ShareKind::parse(&text(&row, 0)?)?, + target_id: text(&row, 1)?, + user_id: text(&row, 2)?, + can_download: row.get::(3).map_err(backend)? != 0, + created_at: parse_stamp(&text(&row, 4)?)?, + }); + } + Ok(out) + } + async fn shares_for_user(&self, user_id: &str) -> Result> { let conn = self.conn.lock().await; let mut rows = conn diff --git a/crates/in-core/tests/store.rs b/crates/in-core/tests/store.rs index 2a290b6..8d6b4c5 100644 --- a/crates/in-core/tests/store.rs +++ b/crates/in-core/tests/store.rs @@ -1127,6 +1127,40 @@ async fn add_share_user_needs_the_owner() { assert!(scratch.store.can_see(ShareKind::File, &file.id, &stranger.id).await.unwrap()); } +#[tokio::test] +async fn shares_for_target_lists_grants_for_the_owner() { + let scratch = Scratch::open().await; + let user = alice(&scratch.store).await; + let friend = bob(&scratch.store).await; + let stranger = scratch.store.provision_user("sub-caro", "caro@example.com", "Caro", 1024).await.unwrap(); + let file = scratch.store.insert_file(&user.id, None, "mine", b"data").await.unwrap(); + // No grants yet. + assert!(scratch.store.shares_for_target(&user.id, ShareKind::File, &file.id).await.unwrap().is_empty()); + // A stranger may not list another owner's grants; a missing target is + // not-found, like the sibling share writes answer. + assert!(matches!( + scratch.store.shares_for_target(&stranger.id, ShareKind::File, &file.id).await, + Err(StoreError::CrossOwner) + )); + assert!(matches!( + scratch.store.shares_for_target(&user.id, ShareKind::File, "missing").await, + Err(StoreError::NotFound) + )); + scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &friend.id, true).await.unwrap(); + scratch.store.add_share_user(&user.id, ShareKind::File, &file.id, &stranger.id, false).await.unwrap(); + let grants = scratch.store.shares_for_target(&user.id, ShareKind::File, &file.id).await.unwrap(); + assert_eq!(grants.len(), 2); + let flag_of = |id: &str| grants.iter().find(|grant| grant.user_id == id).map(|grant| grant.can_download); + assert_eq!(flag_of(&friend.id), Some(true)); + assert_eq!(flag_of(&stranger.id), Some(false)); + // A trashed target lists as not-found, like the sibling share writes. + scratch.store.delete_file(&file.id).await.unwrap(); + assert!(matches!( + scratch.store.shares_for_target(&user.id, ShareKind::File, &file.id).await, + Err(StoreError::NotFound) + )); +} + #[tokio::test] async fn a_provisioned_user_wears_the_default_preferences() { let scratch = Scratch::open().await; diff --git a/crates/in-web/src/drive.rs b/crates/in-web/src/drive.rs index d6316f3..01a4028 100644 --- a/crates/in-web/src/drive.rs +++ b/crates/in-web/src/drive.rs @@ -441,7 +441,7 @@ async fn drive(cx: &Cx) -> Result { } } @@ -593,6 +595,8 @@ async fn drive(cx: &Cx) -> Result {
(t(language, Key::Rename)) + (t(language, Key::Share))
@@ -642,6 +646,8 @@ async fn drive(cx: &Cx) -> Result {
(t(language, Key::Rename)) + (t(language, Key::Share))
@@ -669,6 +675,7 @@ async fn drive(cx: &Cx) -> Result { (crate::dropdown::dropdown_script(cx).await?) (upload_script(cx).await?) + (options_menu_script(cx).await?) } } @@ -703,8 +710,12 @@ fn query_value(query: &str, key: &str) -> Option { /// The upload control's client half: files under 8 MiB ride one multipart /// post, files at or over it are split into the chunked protocol's calls — /// and every upload, small or big, draws the same live progress row (name, -/// bar, percent) into the persistent `#in-status` corner stack, which the -/// document shell renders on every page. +/// bar, percent, cancel) into the persistent `#in-status` corner stack, +/// which the document shell renders on every page. Cancel aborts the small +/// path's XHR, or stops the chunked loop and posts the session's abort +/// endpoint — the abort handle rides the `window.__inUploads` mirror entry, +/// so the row's ✕ keeps working across soft navigations — then the row +/// drops and the canceled card announces through `window.__inNotify`. /// /// The form wears `data-hard` so the soft-nav's multipart replay leaves it /// alone — two uploaders racing the same bytes would double-insert, and the @@ -781,9 +792,19 @@ async fn upload_script(cx: &Cx) -> Result { track.appendChild(fill); \ var pct = document.createElement('span'); \ pct.className = 'upload-progress-pct'; \ + var shut = document.createElement('button'); \ + shut.type = 'button'; \ + shut.className = 'upload-progress-cancel'; \ + shut.textContent = '✕'; \ + if (u.cancelLabel) { shut.setAttribute('aria-label', u.cancelLabel); } \ + shut.addEventListener('click', function () { \ + shut.disabled = true; \ + if (u.cancel) { u.cancel(); } \ + }); \ row.appendChild(name); \ row.appendChild(track); \ row.appendChild(pct); \ + row.appendChild(shut); \ box.appendChild(window.__inAdded(row)); \ } \ var text = Math.min(100, Math.round(u.frac * 100)) + '%'; \ @@ -798,7 +819,14 @@ async fn upload_script(cx: &Cx) -> Result { } \ function bar(label) { \ if (!window.__inUploads) { window.__inUploads = []; } \ - var u = { id: upSeq(), name: label || '', frac: 0 }; \ + var form = document.getElementById('upload-form'); \ + var cancelLabel = (form && form.getAttribute('data-cancel-label')) || ''; \ + var u = { id: upSeq(), name: label || '', frac: 0, cancelLabel: cancelLabel }; \ + /* A cancel landing before the transport arms itself (the \ + start round-trip) still counts: the flag below stops the \ + loop at the next boundary, and sendBig aborts a session \ + minted after the click. */ \ + u.cancel = function () { u.cancelled = true; }; \ window.__inUploads.push(u); \ renderUploads(); \ return u; \ @@ -827,6 +855,10 @@ async fn upload_script(cx: &Cx) -> Result { function notify(kind, message) { \ if (window.__inNotify) { window.__inNotify(kind, message); } \ } \ + /* Cancel is not a failure: the rejection below carries a flag the \ + submit handler reads, so a deliberate cancel announces the \ + canceled card instead of the failed one. */ \ + function canceledErr() { var e = new Error('canceled'); e.canceled = true; return e; } \ async function startChunked(folder, name, size) { \ var r = await fetch('/api/upload/start', { \ method: 'POST', \ @@ -837,31 +869,68 @@ async fn upload_script(cx: &Cx) -> Result { if (!answer.ok) { throw new Error(answer.err || 'start'); } \ return answer.ok; \ } \ - async function sendBig(file, folder, onProgress) { \ + async function sendBig(file, folder, onProgress, u) { \ var session = await startChunked(folder, file.name, file.size); \ + /* The session id lives on the mirror entry, so the row's \ + cancel control still reaches the abort endpoint after a \ + soft navigation rebuilt the page around it. A cancel that \ + landed during the start flight aborts the fresh session \ + straight away instead of leaking it. */ \ + if (u) { \ + if (u.cancelled) { \ + fetch('/api/upload/' + session.id + '/abort', { method: 'POST' }); \ + throw canceledErr(); \ + } \ + u.sessionId = session.id; \ + u.cancel = function () { \ + u.cancelled = true; \ + try { u.abortChunk(); } catch (err) {} \ + fetch('/api/upload/' + session.id + '/abort', { method: 'POST' }); \ + }; \ + } \ var total = Math.max(1, file.size); \ var index = 0; \ + var flight = null; \ + if (u) { \ + u.abortChunk = function () { if (flight) { try { flight.abort(); } catch (err) {} } }; \ + } \ for (var off = 0; off < file.size; off += LIMIT, index++) { \ + if (u && u.cancelled) { throw canceledErr(); } \ var piece = file.slice(off, Math.min(file.size, off + LIMIT)); \ - var r = await fetch('/api/upload/' + session.id + '/' + index, { \ - method: 'PUT', \ - headers: { 'content-type': 'application/octet-stream' }, \ - body: piece \ - }); \ + flight = new AbortController(); \ + var r; \ + try { \ + r = await fetch('/api/upload/' + session.id + '/' + index, { \ + method: 'PUT', \ + headers: { 'content-type': 'application/octet-stream' }, \ + body: piece, \ + signal: flight.signal \ + }); \ + } catch (err) { \ + if (u && u.cancelled) { throw canceledErr(); } \ + throw err; \ + } \ if (!r.ok) { throw new Error('chunk'); } \ onProgress((off + piece.size) / total); \ } \ + if (u && u.cancelled) { throw canceledErr(); } \ var done = await fetch('/api/upload/' + session.id + '/finish', { method: 'POST' }); \ var fin = await done.json(); \ if (!fin.ok) { throw new Error((fin.err) || 'finish'); } \ onProgress(1); \ } \ - function sendSmall(action, folder, files, onProgress) { \ + function sendSmall(action, folder, files, onProgress, u) { \ return new Promise(function (resolve, reject) { \ var data = new FormData(); \ data.append('folder_id', folder); \ files.forEach(function (f) { data.append('file', f, f.name); }); \ var x = new XMLHttpRequest(); \ + if (u) { \ + u.cancel = function () { \ + u.cancelled = true; \ + try { x.abort(); } catch (err) {} \ + }; \ + } \ x.open('POST', action); \ x.setRequestHeader('accept', 'text/html'); \ x.upload.onprogress = function (ev) { \ @@ -873,6 +942,7 @@ async fn upload_script(cx: &Cx) -> Result { else { reject(new Error('small')); } \ }; \ x.onerror = function () { reject(new Error('small')); }; \ + x.onabort = function () { reject(canceledErr()); }; \ x.send(data); \ }); \ } \ @@ -891,6 +961,7 @@ async fn upload_script(cx: &Cx) -> Result { var big = files.filter(function (f) { return f.size >= LIMIT; }); \ var failLabel = form.getAttribute('data-failed-label') || 'upload failed'; \ var doneLabel = form.getAttribute('data-complete-label') || ''; \ + var canceledLabel = form.getAttribute('data-canceled-label') || ''; \ var landing = window.location.href; \ function settle() { \ input.value = ''; \ @@ -904,24 +975,27 @@ async fn upload_script(cx: &Cx) -> Result { var title = small.length === 1 ? small[0].name : (small.length + ' files'); \ var ui = bar(title); \ rows.push(ui); \ - var url = await sendSmall(form.getAttribute('action'), folder, small, function (frac) { setProgress(ui, frac); }); \ + var url = await sendSmall(form.getAttribute('action'), folder, small, function (frac) { setProgress(ui, frac); }, ui); \ if (url) { landing = url; } \ } \ for (var i = 0; i < big.length; i++) { \ await (function (file) { \ var ui2 = bar(file.name); \ rows.push(ui2); \ - return sendBig(file, folder, function (frac) { setProgress(ui2, frac); }); \ + return sendBig(file, folder, function (frac) { setProgress(ui2, frac); }, ui2); \ })(big[i]); \ } \ } catch (err) { \ rows.forEach(dropRow); \ - var why = err && err.message ? err.message : String(err); \ - notify('error', failLabel + ' (' + why + ')'); \ + if (err && err.canceled) { \ + if (canceledLabel) { notify('ok', canceledLabel); } \ + } else { \ + var why = err && err.message ? err.message : String(err); \ + notify('error', failLabel + ' (' + why + ')'); \ + } \ settle(); \ return; \ } \ - rows.forEach(dropRow); \ /* A refused upload answers 303 into a refusal banner page, which the XHR follows to a 200: the banner carries the message, so only trumpet success when no refusal rode the redirect. */ \ if (doneLabel && !/[?&]refusal=/.test(landing)) { notify('ok', doneLabel); } \ settle(); \ @@ -982,6 +1056,65 @@ async fn upload_script(cx: &Cx) -> Result { view! { cx => } } +/// The row Options menus' client half: a `
` +/// panel opens downward by house CSS, which runs a single bottom row's menu +/// past the viewport so Delete hides below the fold. On toggle open the +/// panel is measured one frame later — the toggle fires before the open +/// layout settles, so a synchronous read scrolls menus that fit — and only +/// lifted via the `menu-up` variant class when it spills past the viewport +/// bottom *and* fits better above (the same drop-up idea as `dropdown.rs`'s +/// `place`; `iz` has no details-menu variant to port, only that panel one). +/// The scroll fallback fires only when the menu spills in both directions; +/// a menu that fits as-is never moves the page. Trash rows carry plain +/// restore/purge forms, no menus — nothing to mirror there. +/// +/// The Rust `\`-continuations strip newlines, so the emitted script is one +/// long line: only `/* */` comments survive inside it. +async fn options_menu_script(cx: &Cx) -> Result { + use topcoat::view::Unescaped; + const JS: &str = "\ + (function () { \ + if (window.__inEntryOptions) { return; } \ + window.__inEntryOptions = true; \ + /* `toggle` does not bubble, but a capture listener still sees it \ + on the way down; per-details listeners would need rewiring \ + after every soft swap, this one survives them. */ \ + document.addEventListener('toggle', function (e) { \ + var details = e.target; \ + if (!details || !details.classList || !details.classList.contains('entry-options')) { return; } \ + if (!details.hasAttribute('open')) { details.classList.remove('menu-up'); return; } \ + var panel = details.querySelector('.user-menu-panel'); \ + if (!panel) { return; } \ + /* The toggle fires before the open layout settles (panel \ + transition, the `:has` overflow lift), so a synchronously \ + read rect is stale and the scroll fallback fired on menus \ + that fit — measure one frame later, post-layout. */ \ + window.requestAnimationFrame(function () { \ + if (!details.hasAttribute('open')) { return; } \ + details.classList.remove('menu-up'); \ + /* The clipper is the nearest scrollport (the stage is a \ + scroll container whose height is content-height on a \ + tall window), not the viewport: an abs-positioned panel \ + past the scrollport's visible bottom is trapped as \ + scrollable overflow — unreadable without scrolling. */ \ + var sc = details.closest('.settings-stage'); \ + var roomBottom = sc ? sc.getBoundingClientRect().bottom : window.innerHeight; \ + var roomTop = sc ? sc.getBoundingClientRect().top : 0; \ + var down = panel.getBoundingClientRect(); \ + if (down.bottom <= roomBottom - 8) { return; } \ + var trigger = details.querySelector('summary'); \ + var anchor = trigger ? trigger.getBoundingClientRect() : details.getBoundingClientRect(); \ + var above = anchor.top - roomTop - 4; \ + var below = roomBottom - anchor.bottom - 4; \ + if (above >= down.height || above > below) { details.classList.add('menu-up'); } \ + var r = panel.getBoundingClientRect(); \ + if (r.top < roomTop && r.bottom > roomBottom) { panel.scrollIntoView({ block: 'nearest' }); } \ + }); \ + }, true); \ + })();"; + view! { cx => } +} + #[derive(serde::Deserialize)] struct CreateFolderForm { #[serde(default)] diff --git a/crates/in-web/src/i18n.rs b/crates/in-web/src/i18n.rs index 9a941df..83be804 100644 --- a/crates/in-web/src/i18n.rs +++ b/crates/in-web/src/i18n.rs @@ -119,6 +119,7 @@ pub enum Key { Uploading, UploadComplete, UploadFailed, + UploadCanceled, CancelUpload, RetryUpload, // File view. @@ -202,6 +203,12 @@ pub enum Key { SortOwner, // Settings limits redesign (SettingsBuild owns this block). UploadLimitHelp, + EveryoneSubtitle, + UploadLimitSection, + // Per-entry share page (ShareBuild owns this block). + CreateLink, + ExpiresInDays, + NoShares, } pub fn t(lang: Lang, key: Key) -> &'static str { @@ -254,6 +261,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { Uploading => "Uploading…", UploadComplete => "Upload complete.", UploadFailed => "The upload failed.", + UploadCanceled => "Upload canceled.", CancelUpload => "Cancel the upload", RetryUpload => "Try again", FileDetails => "File", @@ -326,7 +334,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { KindFiles => "Files", SortDeleted => "Deleted", SortOwner => "Owner", - UploadLimitHelp => "The most one uploaded file may be. Applies to everyone.", + UploadLimitHelp => "The most one uploaded file may be.", + EveryoneSubtitle => "Per-person storage quotas below; the single-file upload limit follows.", + UploadLimitSection => "Upload limit — applies to everyone.", + CreateLink => "Create link", + ExpiresInDays => "Expires in days", + NoShares => "Not shared with anyone yet.", }, Lang::Tr => match key { Cancel => "Vazgeç", @@ -375,6 +388,7 @@ pub fn t(lang: Lang, key: Key) -> &'static str { Uploading => "Yükleniyor…", UploadComplete => "Yükleme tamamlandı.", UploadFailed => "Yükleme başarısız oldu.", + UploadCanceled => "Yükleme iptal edildi.", CancelUpload => "Yüklemeyi iptal et", RetryUpload => "Yeniden dene", FileDetails => "Dosya", @@ -447,7 +461,12 @@ pub fn t(lang: Lang, key: Key) -> &'static str { KindFiles => "Dosyalar", SortDeleted => "Silindi", SortOwner => "Sahibi", - UploadLimitHelp => "Tek bir dosyanın alabileceği en büyük boyut. Herkes için geçerlidir.", + UploadLimitHelp => "Tek bir dosyanın alabileceği en büyük boyut.", + EveryoneSubtitle => "Aşağıda kişi başına depolama kotaları; ardından herkes için geçerli tek dosyalık yükleme sınırı.", + UploadLimitSection => "Yükleme sınırı — herkes için geçerlidir.", + CreateLink => "Bağlantı oluştur", + ExpiresInDays => "Bitiş (gün)", + NoShares => "Henüz kimseyle paylaşılmadı.", }, } } diff --git a/crates/in-web/src/settings.rs b/crates/in-web/src/settings.rs index d3fe6d9..b4f771a 100644 --- a/crates/in-web/src/settings.rs +++ b/crates/in-web/src/settings.rs @@ -4,13 +4,15 @@ //! quota usage bar beside it, and the reader's own live share links with //! their revoke buttons — including the copy-once banner after a creation //! (`?created=` on the query, rendered once and never stored). -//! Admins additionally see every account with its quota and disabled flag. -//! `POST /api/settings/quota|disable` are admin-only: the first sets a -//! user's byte quota, the second disables or re-enables them (a disabled +//! Admins additionally see every account with its quota and disabled flag, +//! plus the instance-wide per-file upload limit in the same Everyone panel. +//! `POST /api/settings/quota|disable|upload-limit` are admin-only: the first +//! sets a user's byte quota, the second disables or re-enables them (a disabled //! account reads as signed-out everywhere, the im session untouched, and -//! disabling yourself is refused). +//! disabling yourself is refused), and the third sets the per-file ceiling +//! for the whole install. -use in_core::store::User; +use in_core::store::{ShareKind, User}; use serde::Deserialize; use topcoat::Result; use topcoat::context::Cx; @@ -280,12 +282,26 @@ async fn settings(cx: &Cx) -> Result { .iter() .filter(|link| link.revoked_at.is_none()) .collect(); + // The display name per live link's target: the row carries only the id. + // A missing or trashed target keeps its id — the grant row outlives the + // trash, and the panel still revokes it. Enrichment never fails the + // page: an unreadable target reads as its id, the way the shared list + // degrades per row. + let mut link_names: Vec<(&in_core::store::ShareLink, String)> = Vec::new(); + for link in &live_links { + let name = match link.kind { + ShareKind::File => store.file(&link.target_id).await.ok().flatten().map(|file| file.name), + ShareKind::Folder => store.folder(&link.target_id).await.ok().flatten().map(|folder| folder.name), + } + .unwrap_or_else(|| link.target_id.clone()); + link_names.push((*link, name)); + } let users = if fresh.admin { store.users().await? } else { Vec::new() }; - // The live per-file ceiling, read once for the admin panel below. Only + // The live per-file ceiling, read once for the Everyone panel below. Only // admins see it, so only they pay the extra setting read. let upload_limit = if fresh.admin { Some(crate::server::effective_upload_limit(cx).await) @@ -368,9 +384,9 @@ async fn settings(cx: &Cx) -> Result { if live_links.is_empty() {

(t(language, Key::NoLinks))

} - for link in live_links { + for (link, target_name) in &link_names {
- (format!("{} · {}", link.kind.as_str(), link.target_id.clone())) + (format!("{} · {}", link.kind.as_str(), target_name.clone())) (expiry_line(language, link.expires_at)) (if link.can_download { t(language, Key::CanDownload) } else { t(language, Key::ViewOnly) }) @@ -382,30 +398,12 @@ async fn settings(cx: &Cx) -> Result {
if fresh.admin { - if let Some(limit) = upload_limit { -
-
-

(t(language, Key::UploadLimits))

-
-
-

(t(language, Key::UploadLimitHelp))

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

(t(language, Key::AdminPanel))

+

(t(language, Key::EveryoneSubtitle))

@@ -460,6 +458,19 @@ async fn settings(cx: &Cx) -> Result {
+ if let Some(limit) = upload_limit { +

(t(language, Key::UploadLimitSection))

+

(t(language, Key::UploadLimitHelp))

+
+ (format!("{}: {}", t(language, Key::CurrentUploadLimit), human_bytes(limit))) + + + +
+ }
} diff --git a/crates/in-web/src/share.rs b/crates/in-web/src/share.rs index ccc993f..ddb5d5f 100644 --- a/crates/in-web/src/share.rs +++ b/crates/in-web/src/share.rs @@ -17,15 +17,16 @@ //! render the copy-once banner off that pair. use in_core::hash_share_token; -use in_core::store::{ShareKind, Store, StoreError, ThumbState, User}; +use in_core::store::{File, ShareKind, Store, StoreError, ThumbState, User}; use serde::Deserialize; use time::OffsetDateTime; use topcoat::Result; use topcoat::context::Cx; +use topcoat::router::error::not_found as page_not_found; use topcoat::router::content::Form; use topcoat::router::request::{headers as request_headers, uri}; use topcoat::router::response::IntoResponse; -use topcoat::router::{HeaderName, StatusCode, header, page, path_param, query_params, route}; +use topcoat::router::{HeaderName, HeaderValue, StatusCode, header, page, path_param, query_params, route}; use topcoat::view::view; use crate::i18n::{Key, Lang, lang, t}; @@ -34,6 +35,8 @@ use crate::layout::{NavPage, topbar, wordmark}; use crate::server::{Refusal, app, back_to, require_user}; path_param!(token); +path_param!(kind); +path_param!(id); /// A refusal surfaced as a banner: the `?refusal=&on=` pair the /// mutation redirects carry, rendered only when `on` names one of `calls` — @@ -214,7 +217,9 @@ async fn create_link(cx: &Cx, Form(input): Form) -> Redirect { &user.id, kind, &input.target_id, - parse_flag(input.can_download.as_deref(), true), + // Absent means the checkbox came unchecked: view-only. A checked + // box posts `1`; nothing posted must never mint a download. + parse_flag(input.can_download.as_deref(), false), expires_at, ) .await; @@ -322,7 +327,9 @@ async fn add_share(cx: &Cx, Form(input): Form) -> Redirect { kind, &input.target_id, &grantee.id, - parse_flag(input.can_download.as_deref(), true), + // Absent means the checkbox came unchecked: view-only, like the + // sibling link creator above. + parse_flag(input.can_download.as_deref(), false), ) .await { @@ -1041,3 +1048,204 @@ fn access_chip(language: Lang, can_download: bool) -> &'static str { t(language, Key::ViewOnly) } } + +/// `GET /share/{kind}/{id}`: one entry's share surface — the page the drive +/// row's Share item links to. Owner only: a signed-out reader goes back to +/// the landing, and anyone else — a stranger, or a missing or trashed target +/// — answers not-found, the way the other owner surfaces do. +/// +/// The public-link panel twins the settings page's shape: the live links for +/// this target with their expiry line, access chip and revoke form — or, when +/// none is live, the create form. The token's copy-once banner renders off +/// the create redirect's `?created=` pair, which lands back here through the +/// posting form's `Referer`, so no handler change was needed. The people +/// panel lists this target's grants with remove forms, plus the add form. +#[page("/share/{kind}/{id}")] +async fn share_entry(cx: &Cx) -> Result { + let kind_raw: &str = path_param::(cx); + let target_id: &str = path_param::(cx); + let Some(kind) = parse_kind(kind_raw) else { + return Err(page_not_found().into()); + }; + let user = match require_user(cx).await { + Ok(user) => user, + Err(_) => { + let location = (header::LOCATION, HeaderValue::from_static("/")); + return view! { + cx => + (StatusCode::SEE_OTHER) + (location) + }; + } + }; + let language = lang(cx).await; + let store = app(cx).store.clone(); + // The owned, live target: present, untrashed, and theirs. Anything else + // is not-found — a stranger learns nothing about whose it is. + let (name, file): (String, Option) = match kind { + ShareKind::File => { + let Some(file) = store.file(target_id).await? else { + return Err(page_not_found().into()); + }; + if file.owner_id != user.id || file.deleted_at.is_some() { + return Err(page_not_found().into()); + } + (file.name.clone(), Some(file)) + } + ShareKind::Folder => { + let Some(folder) = store.folder(target_id).await? else { + return Err(page_not_found().into()); + }; + if folder.owner_id != user.id || folder.deleted_at.is_some() { + return Err(page_not_found().into()); + } + (folder.name.clone(), None) + } + }; + // The live links for this target alone, newest first — the settings page + // lists every link; this page owns just its entry's. + let links = store.share_links(&user.id).await?; + let live: Vec<_> = links + .iter() + .filter(|link| link.kind == kind && link.target_id == target_id && link.revoked_at.is_none()) + .collect(); + // The grants on this target. The ownership read above already vetted the + // caller, so a refusal here is only ever the target going missing + // mid-page — still not-found, never a leak. + let grants = match store.shares_for_target(&user.id, kind, target_id).await { + Ok(grants) => grants, + Err(StoreError::NotFound) | Err(StoreError::CrossOwner) => { + return Err(page_not_found().into()); + } + Err(error) => return Err(error.into()), + }; + let mut people: Vec<(String, String, bool)> = Vec::new(); + for grant in &grants { + if let Some(grantee) = store.user(&grant.user_id).await? { + people.push((grantee.display_name, grantee.email, grant.can_download)); + } + } + let created = created_token(uri(cx).query().unwrap_or("")); + let origin = app(cx).config.listen_url(); + view! { + cx => + (topbar(cx, NavPage::Drive, &user, language).await?) +
+ +

+ if kind == ShareKind::Folder { + + } + if let Some(file) = file.as_ref() { + (entry_chip(cx, file).await?) + } + (name.clone()) +

+

(kind.as_str())

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

(t(language, Key::LinkCreated))

+
+
+

(t(language, Key::CopyLinkOnce))

+ +
+
+ } +
+
+

(t(language, Key::ShareLink))

+
+
+ if live.is_empty() { +
+ + + + + +
+ } + for link in live { +
+ (format!("{} · {}", link.kind.as_str(), name.clone())) + (expiry_line(language, link.expires_at)) + (access_chip(language, link.can_download)) +
+ + +
+
+ } +
+
+
+
+

(t(language, Key::SharedWith))

+
+
+ if people.is_empty() { +

(t(language, Key::NoShares))

+ } + for person in &people { +
+ (person.0.clone()) + (person.1.clone()) + (access_chip(language, person.2)) +
+ + + + +
+
+ } +
+ + + + + +
+
+
+
+ } +} + +/// The just-minted token off the redirect's `?created=` pair, if present. +/// Twins the drive and settings pages' helper; all three render the same +/// copy-once banner off the same pair. +fn created_token(query: &str) -> Option { + query.split('&').find_map(|pair| { + let (name, value) = pair.split_once('=')?; + (name == "created" && !value.is_empty()).then(|| value.to_string()) + }) +} + +/// When the link stops opening, or never on its own. Twins the settings +/// page's helper; the share page renders the same expiry line. +fn expiry_line(language: Lang, expires_at: Option) -> String { + match expires_at { + Some(at) => format!( + "{} {}", + t(language, Key::ExpiresLabel), + at.format(&time::format_description::well_known::Rfc3339) + .unwrap_or_else(|_| "?".to_string()) + ), + None => t(language, Key::NeverExpires).to_string(), + } +} diff --git a/crates/in-web/tests/http.rs b/crates/in-web/tests/http.rs index 2551d19..bdec50a 100644 --- a/crates/in-web/tests/http.rs +++ b/crates/in-web/tests/http.rs @@ -1365,6 +1365,69 @@ async fn view_only_link_download_is_dead_card() { ); } +/// An unchecked `can_download` box posts nothing at all, and nothing posted +/// must never mint a download: the absent flag reads view-only, the way an +/// explicitly refused one does — while the checked box still opens the bytes. +#[tokio::test] +async fn link_create_without_the_flag_is_view_only() { + let app = TestApp::build().await; + let admin = app.sign_in("sub-admin", "ada@in.test", "Ada").await; + let owner = owner_of(&app, "sub-admin").await; + let file = file_id(&app, &owner, "plain.txt", b"plain bytes").await; + // No can_download pair — what an unchecked checkbox posts. + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[("kind", "file"), ("target_id", &file)], + ) + .await; + assert!(answer.accepted(), "create refused: {:?}", answer.location); + let token = created_token(answer.location.as_deref().unwrap()); + let page = app.get(&format!("/s/{token}"), None).await; + assert_eq!(page.status, StatusCode::OK, "{}", page.text()); + assert!(page.text().contains("plain.txt"), "{}", page.text()); + let blocked = app.get(&format!("/s/{token}?dl=1"), None).await; + assert_eq!(blocked.status, StatusCode::OK, "{}", blocked.text()); + assert!( + blocked.text().contains("no longer works"), + "absent-flag download showed: {}", + blocked.text() + ); + // Both share surfaces print the target's name, never its raw id. + let named = app.get(&format!("/share/file/{file}"), Some(&admin)).await; + assert_eq!(named.status, StatusCode::OK, "{}", named.text()); + assert!( + named.text().contains("file · plain.txt"), + "share page showed no name: {}", + named.text() + ); + let settings = app.get("/settings", Some(&admin)).await; + assert_eq!(settings.status, StatusCode::OK, "{}", settings.text()); + assert!( + settings.text().contains("file · plain.txt"), + "settings panel showed no name: {}", + settings.text() + ); + // The checked box still opens the bytes. + let answer = app + .post( + "/api/share/link/create", + Some(&admin), + &[ + ("kind", "file"), + ("target_id", &file), + ("can_download", "1"), + ], + ) + .await; + assert!(answer.accepted(), "create refused: {:?}", answer.location); + let token = created_token(answer.location.as_deref().unwrap()); + let bytes = app.get(&format!("/s/{token}?dl=1"), None).await; + assert_eq!(bytes.status, StatusCode::OK); + assert_eq!(bytes.bytes, b"plain bytes"); +} + #[tokio::test] async fn folder_link_lists_and_serves_children() { let app = TestApp::build().await; @@ -2520,7 +2583,7 @@ async fn settings_panels_nest_inside_the_stage() { assert_eq!(page.status, StatusCode::OK, "{}", page.text()); let body = page.text(); let stage = body - .find("
") + .find("
").expect("no main close"); for marker in ["panel-head", "member-table", "name=\"ui\""] { diff --git a/style/main.scss b/style/main.scss index 8f58800..19f3168 100644 --- a/style/main.scss +++ b/style/main.scss @@ -4661,22 +4661,19 @@ input[type="radio"] { // the house panel, chip, quiet and user-menu rules above do the rest. // A row never wraps: the name takes the slack as an ellipsis, every detail -// token and action holds its column. The name span in trash and public rows -// is `.member-name`, which carries no geometry of its own — inside a row it -// borrows the dep-title shape (flex, ellipsis, and the old-house `.dep-title` -// geometry it also wears in markup, so the ellipsis does not depend on this -// block alone); the shared page wraps its linked names in `.dep-title` -// directly. -.dep-row { flex-wrap: nowrap; } - +// token and action holds its column. Trash and public names wear +// `.member-name dep-title`; shared and drive names nest `.dep-title` inside +// the link — the descendant selector covers both shapes, and the old-house +// `.dep-title` geometry in markup holds the ellipsis even on its own. .dep-row > .member-name, -.dep-row > .dep-title { +.dep-row .dep-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.dep-row { flex-wrap: nowrap; } // Detail tokens never break mid-value ('6.1 KiB' stays whole): the name's // ellipsis absorbs the pressure instead. @@ -4746,3 +4743,94 @@ input[type="radio"] { .table-pan { overflow-x: auto; } + +// -- drive round-3: single-border toolbar, menu drop-up, upload cancel ----- +// +// The Sort/Kind/dir filterbar forms nest their controls inside the bordered +// `.field-box`: the dd-enhanced trigger, the native select beside it, and +// the →/↑ submit buttons. Each nested box of its own reads as a doubled or +// overlapping control, so nested chrome is stripped and the box stays the +// one border. Shared rules, so /trash and /shared (the identical +// `.field-box-sort` pattern) inherit the fix with no per-page markup. +// +// A nested submit never draws its own box: borderless, transparent, and +// stretched to the box height so its label sits where the box's text sits. +.field-box .quiet { + border: none; + background: transparent; + height: auto; + align-self: stretch; + padding: 0 2px; +} +// A search submit keeps its label whole: exempt from the collapsed nested +// padding above, never shrunk, never wrapped — the box stays its only +// border, the button only its text width back. +.field-box-search .quiet { + flex: none; + padding: 0 10px; + white-space: nowrap; +} + +// The enhanced trigger is already chromeless through the class it clones +// off its select (`.status-select` carries no border or background); this +// pins that for any skin that buttons up a bare trigger, so the trigger +// sits flush inside the field box instead of framing itself twice. +.field-box .dd-trigger { + border: none; + background: transparent; +} + +// The native select behind an enhanced trigger never takes space: the +// element-qualified selector outranks any skin's bare `select` chrome +// without resorting to `!important`. +select.dd-native { display: none; } + +// A row Options menu near the viewport bottom opens upward instead of +// spilling past it: the toggle-time script in `drive.rs` adds `menu-up` +// when the downward panel would overflow, and this bottom-anchors the +// house panel to its trigger. The qualified open selector outranks the +// downward `[open]` rule above by specificity, not source order. +.entry-options.menu-up[open] > .user-menu-panel { + top: auto; + bottom: 100%; + margin-bottom: 4px; +} + +// The in-flight upload row's cancel control: the corner stack's dismiss +// voice (24px ✕, danger on hover) as a row-local class, so progress rows +// need no notice-card markup to borrow it. +.upload-progress-cancel { + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: none; + border-radius: var(--radius-sm); + background: transparent; + color: var(--muted-soft); + cursor: pointer; + + &:hover { color: var(--danger); } +} + +// -- share rows (ShareBuild) ------------------------------------------------------------ +// The share/people rows are `div.member-row` outside any table — the only +// `.member-row` rule in the house lives under `.member-table` (the Everyone +// register's own row borders), so these rows rendered as bare inline spans +// and the name, address, expiry and access chip ran together ('NeverMay +// download'). They get the row treatment without the card chrome: flex with +// the house gap, wrapping under narrow pressure. `div` qualified so the +// table's `tr.member-row` rows never match. +div.member-row { + display: flex; + align-items: center; + gap: 4px 10px; + flex-wrap: wrap; + padding: 8px 0; +} +div.member-row + div.member-row { + border-top: 1px solid var(--border); +}