17 Commits
Author SHA1 Message Date
nils 6a04d29eed metadata 2025-10-27 00:17:15 +01:00
nils 10e28cc5e2 previewzoomoverlay 2025-10-27 00:14:10 +01:00
nils 970678986a sidebar shadow 2025-10-26 23:15:12 +01:00
nils 40e45f3a01 previewzoomoverlay 2025-10-26 21:01:48 +01:00
nils 518b79bec6 stuff 2025-10-26 20:29:43 +01:00
nils 01fb4e308a cleanup 2025-10-26 19:46:32 +01:00
nils b6300ffa30 panel actions 2025-10-26 19:14:35 +01:00
nils b163a07e84 lazy-thumbnails 2025-10-26 10:36:47 +01:00
nils 42a3a53314 panning 2025-10-26 02:52:26 +02:00
nils 4a06fa82eb cache warming 2025-10-26 02:19:19 +02:00
nils 80238bb7a1 zoom 2025-10-26 02:05:31 +02:00
nils dcbd46531e preview zoom 2025-10-26 01:45:37 +02:00
nils 0864b39336 panel actions 2025-10-26 01:04:21 +02:00
nils 2a0c96bb4c detail panel 2025-10-26 00:28:40 +02:00
nils c53213a357 cleanup 2025-10-25 23:49:51 +02:00
nils dc633783e0 frontend 2025-10-24 15:13:37 +02:00
nils e33ab71fac move to sidebar 2025-10-24 14:07:09 +02:00
33 changed files with 2845 additions and 3195 deletions
+25 -87
View File
@@ -67,7 +67,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -635,7 +635,6 @@ dependencies = [
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
"url", "url",
"utoipa",
"uuid", "uuid",
] ]
@@ -705,7 +704,7 @@ dependencies = [
"regex", "regex",
"rustc-hash", "rustc-hash",
"shlex", "shlex",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -990,7 +989,7 @@ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"strsim", "strsim",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -1001,7 +1000,7 @@ checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81"
dependencies = [ dependencies = [
"darling_core", "darling_core",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -1051,7 +1050,7 @@ dependencies = [
"dsl_auto_type", "dsl_auto_type",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -1071,7 +1070,7 @@ version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe2444076b48641147115697648dc743c2c00b61adade0f01ce67133c7babe8c" checksum = "fe2444076b48641147115697648dc743c2c00b61adade0f01ce67133c7babe8c"
dependencies = [ dependencies = [
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -1093,7 +1092,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -1119,7 +1118,7 @@ dependencies = [
"heck", "heck",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -1288,7 +1287,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -1813,8 +1812,6 @@ checksum = "4b0f83760fb341a774ed326568e19f5a863af4a952def8c39f9ab92fd95b88e5"
dependencies = [ dependencies = [
"equivalent", "equivalent",
"hashbrown 0.16.0", "hashbrown 0.16.0",
"serde",
"serde_core",
] ]
[[package]] [[package]]
@@ -2270,7 +2267,7 @@ checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -2362,31 +2359,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"syn 2.0.106", "syn",
]
[[package]]
name = "proc-macro-error"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn 1.0.109",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2",
"quote",
"version_check",
] ]
[[package]] [[package]]
@@ -2921,7 +2894,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -3109,16 +3082,6 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"unicode-ident",
]
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.106" version = "2.0.106"
@@ -3147,7 +3110,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -3189,7 +3152,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -3200,7 +3163,7 @@ checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -3296,7 +3259,7 @@ checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -3446,7 +3409,7 @@ checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -3551,31 +3514,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utoipa"
version = "4.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5afb1a60e207dca502682537fefcfd9921e71d0b83e9576060f09abc6efab23"
dependencies = [
"indexmap",
"serde",
"serde_json",
"utoipa-gen",
]
[[package]]
name = "utoipa-gen"
version = "4.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20c24e8ab68ff9ee746aad22d39b5535601e6416d1b0feeabf78be986a5c4392"
dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
"syn 2.0.106",
"uuid",
]
[[package]] [[package]]
name = "uuid" name = "uuid"
version = "1.18.1" version = "1.18.1"
@@ -3677,7 +3615,7 @@ dependencies = [
"log", "log",
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
@@ -3712,7 +3650,7 @@ checksum = "9f07d2f20d4da7b26400c9f4a0511e6e0345b040694e8a75bd41d578fa4421d7"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
"wasm-bindgen-backend", "wasm-bindgen-backend",
"wasm-bindgen-shared", "wasm-bindgen-shared",
] ]
@@ -3789,7 +3727,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -3800,7 +3738,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -4027,7 +3965,7 @@ checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
"synstructure", "synstructure",
] ]
@@ -4048,7 +3986,7 @@ checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
@@ -4068,7 +4006,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
"synstructure", "synstructure",
] ]
@@ -4108,7 +4046,7 @@ checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.106", "syn",
] ]
[[package]] [[package]]
-1
View File
@@ -45,7 +45,6 @@ quick-xml = "0.32"
futures-util = "0.3" futures-util = "0.3"
url = "2.5" url = "2.5"
once_cell = "1.19" once_cell = "1.19"
utoipa = { version = "4.2", default-features = false, features = ["chrono", "uuid", "preserve_order"] }
# Error handling # Error handling
thiserror = "1.0" thiserror = "1.0"
-8
View File
@@ -1,8 +0,0 @@
use backend::openapi::ApiDoc;
use utoipa::OpenApi;
fn main() {
let spec = ApiDoc::openapi();
let json = serde_json::to_string_pretty(&spec).expect("serialize openapi");
println!("{}", json);
}
-4
View File
@@ -133,12 +133,8 @@ impl AppConfig {
fn redact_database_url(raw: &str) -> String { fn redact_database_url(raw: &str) -> String {
match Url::parse(raw) { match Url::parse(raw) {
Ok(mut parsed) => { Ok(mut parsed) => {
if parsed.password().is_some() {
let _ = parsed.set_password(Some("*****")); let _ = parsed.set_password(Some("*****"));
parsed.to_string() parsed.to_string()
} else {
raw.to_string()
}
} }
Err(_) => "***".to_string(), Err(_) => "***".to_string(),
} }
-14
View File
@@ -12,7 +12,6 @@ pub type AppResult<T> = Result<T, AppError>;
pub struct AppError { pub struct AppError {
status: StatusCode, status: StatusCode,
message: String, message: String,
code: Option<String>,
} }
impl AppError { impl AppError {
@@ -20,7 +19,6 @@ impl AppError {
Self { Self {
status, status,
message: message.into(), message: message.into(),
code: None,
} }
} }
@@ -28,10 +26,6 @@ impl AppError {
Self::new(StatusCode::BAD_REQUEST, message) Self::new(StatusCode::BAD_REQUEST, message)
} }
pub fn conflict(message: impl Into<String>) -> Self {
Self::new(StatusCode::CONFLICT, message)
}
pub fn unauthorized() -> Self { pub fn unauthorized() -> Self {
Self::new(StatusCode::UNAUTHORIZED, "unauthorized") Self::new(StatusCode::UNAUTHORIZED, "unauthorized")
} }
@@ -43,11 +37,6 @@ impl AppError {
pub fn internal<E: Display>(error: E) -> Self { pub fn internal<E: Display>(error: E) -> Self {
Self::new(StatusCode::INTERNAL_SERVER_ERROR, error.to_string()) Self::new(StatusCode::INTERNAL_SERVER_ERROR, error.to_string())
} }
pub fn with_code(mut self, code: impl Into<String>) -> Self {
self.code = Some(code.into());
self
}
} }
impl IntoResponse for AppError { impl IntoResponse for AppError {
@@ -55,7 +44,6 @@ impl IntoResponse for AppError {
let status = self.status; let status = self.status;
let body = Json(ErrorResponse { let body = Json(ErrorResponse {
error: self.message, error: self.message,
code: self.code,
}); });
(status, body).into_response() (status, body).into_response()
} }
@@ -64,8 +52,6 @@ impl IntoResponse for AppError {
#[derive(Serialize)] #[derive(Serialize)]
struct ErrorResponse { struct ErrorResponse {
error: String, error: String,
#[serde(skip_serializing_if = "Option::is_none")]
code: Option<String>,
} }
impl From<diesel::result::Error> for AppError { impl From<diesel::result::Error> for AppError {
-1
View File
@@ -4,7 +4,6 @@ pub mod db;
pub mod error; pub mod error;
pub mod jobs; pub mod jobs;
pub mod models; pub mod models;
pub mod openapi;
pub mod routes; pub mod routes;
pub mod s3; pub mod s3;
pub mod schema; pub mod schema;
-951
View File
@@ -1,951 +0,0 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use utoipa::{IntoParams, OpenApi, ToSchema};
use uuid::Uuid;
#[derive(OpenApi)]
#[openapi(
paths(
doc::health_check,
doc::login,
doc::refresh,
doc::logout,
doc::me,
doc::select_tenant,
doc::list_documents,
doc::check_document,
doc::upload_document,
doc::get_document,
doc::update_document,
doc::delete_document,
doc::download_document,
doc::download_with_token,
doc::move_document,
doc::assign_tags,
doc::remove_tag,
doc::bulk_move_documents,
doc::bulk_update_tags,
doc::bulk_assign_correspondents,
doc::assign_correspondents,
doc::remove_correspondent,
doc::reanalyze_selected_documents,
doc::list_document_assets,
doc::request_document_assets,
doc::get_document_asset,
doc::create_folder,
doc::ensure_folder_path,
doc::get_folder,
doc::list_folder_contents,
doc::delete_folder,
doc::update_folder,
doc::list_tags,
doc::create_tag,
doc::update_tag,
doc::delete_tag,
doc::list_correspondents,
doc::create_correspondent,
doc::update_correspondent,
doc::delete_correspondent,
),
components(
schemas(
schemas::LoginRequest,
schemas::AccessTokenResponse,
schemas::TenantSummary,
schemas::TenantSelectionResponse,
schemas::TenantSelectionRequest,
schemas::LoginResponseVariants,
schemas::DocumentResponse,
schemas::DocumentDetailResponse,
schemas::DocumentVersion,
schemas::DocumentAssetSummary,
schemas::DocumentAssetDetail,
schemas::DocumentAssetObject,
schemas::DocumentCorrespondent,
schemas::DocumentTag,
schemas::DocumentDownloadResponse,
schemas::UpdateDocumentRequest,
schemas::BulkMoveDocumentsRequest,
schemas::BulkMoveDocumentsResponse,
schemas::AssignTagsRequest,
schemas::MoveDocumentRequest,
schemas::BulkTagRequest,
schemas::BulkTagResponse,
schemas::CorrespondentAssignment,
schemas::BulkTagAction,
schemas::BulkCorrespondentsRequest,
schemas::BulkCorrespondentsResponse,
schemas::BulkCorrespondentAction,
schemas::AssignCorrespondentsRequest,
schemas::RemoveCorrespondentParams,
schemas::ReanalyzeRequest,
schemas::ReanalyzeResponse,
schemas::DocumentAssetRequestParams,
schemas::AssetObjectsQuery,
schemas::DocumentCheckQuery,
schemas::DocumentCheckResponse,
schemas::UploadDocumentForm,
schemas::CreateFolderRequest,
schemas::EnsureFolderPathRequest,
schemas::FolderResponse,
schemas::FolderInfo,
schemas::FolderContentsResponse,
schemas::FolderDocumentSummary,
schemas::UpdateFolderRequest,
schemas::FolderContentsParams,
schemas::TagCatalogEntry,
schemas::CreateTagRequest,
schemas::UpdateTagRequest,
schemas::CorrespondentCatalogEntry,
schemas::CreateCorrespondentRequest,
schemas::UpdateCorrespondentRequest,
)
),
tags(
(name = "Health", description = "Service health"),
(name = "Auth", description = "Authentication"),
(name = "Documents", description = "Document management"),
(name = "Assets", description = "Document assets"),
(name = "Folders", description = "Folder management"),
(name = "Tags", description = "Tag catalog"),
(name = "Correspondents", description = "Correspondent catalog")
)
)]
pub struct ApiDoc;
#[allow(dead_code)]
mod doc {
use super::schemas::*;
use uuid::Uuid;
#[allow(dead_code)]
fn __keep_uuid_import() {
let _ = Uuid::nil();
}
#[utoipa::path(
get,
path = "/api/health",
responses((status = 200, description = "Service is healthy")),
tag = "Health"
)]
pub(super) fn health_check() {}
#[utoipa::path(
post,
path = "/api/auth/login",
request_body = LoginRequest,
responses(
(status = 200, description = "Login succeeded", body = LoginResponseVariants),
(status = 401, description = "Invalid credentials")
),
tag = "Auth"
)]
pub(super) fn login() {}
#[utoipa::path(
post,
path = "/api/auth/refresh",
responses(
(status = 200, description = "Refreshed access token", body = AccessTokenResponse),
(status = 401, description = "Missing or invalid refresh token")
),
tag = "Auth"
)]
pub(super) fn refresh() {}
#[utoipa::path(
post,
path = "/api/auth/logout",
responses((status = 204, description = "Session revoked")),
tag = "Auth"
)]
pub(super) fn logout() {}
#[utoipa::path(
get,
path = "/api/auth/me",
responses((status = 200, description = "Authenticated principal", body = AccessTokenResponse)),
tag = "Auth"
)]
pub(super) fn me() {}
#[utoipa::path(
post,
path = "/api/auth/select-tenant",
request_body = TenantSelectionRequest,
responses((status = 200, description = "Tenant selected", body = AccessTokenResponse)),
tag = "Auth"
)]
pub(super) fn select_tenant() {}
#[utoipa::path(
get,
path = "/api/documents",
params(DocumentListQuery),
responses((status = 200, description = "List documents", body = [DocumentResponse])),
tag = "Documents"
)]
pub(super) fn list_documents() {}
#[utoipa::path(
post,
path = "/api/documents",
request_body = UploadDocumentForm,
responses(
(status = 201, description = "Document created", body = DocumentDetailResponse),
(status = 200, description = "Existing document reused", body = DocumentDetailResponse),
(status = 204, description = "Upload skipped because the document already exists")
),
tag = "Documents"
)]
pub(super) fn upload_document() {}
#[utoipa::path(
get,
path = "/api/documents/check",
params(DocumentCheckQuery),
responses((status = 200, description = "Checksum lookup", body = DocumentCheckResponse)),
tag = "Documents"
)]
pub(super) fn check_document() {}
#[utoipa::path(
get,
path = "/api/documents/{id}",
params(("id" = Uuid, Path, description = "Document ID")),
responses((status = 200, description = "Document detail", body = DocumentDetailResponse)),
tag = "Documents"
)]
pub(super) fn get_document() {}
#[utoipa::path(
patch,
path = "/api/documents/{id}",
params(("id" = Uuid, Path, description = "Document ID")),
request_body = UpdateDocumentRequest,
responses((status = 200, description = "Updated document", body = DocumentDetailResponse)),
tag = "Documents"
)]
pub(super) fn update_document() {}
#[utoipa::path(
delete,
path = "/api/documents/{id}",
params(("id" = Uuid, Path, description = "Document ID")),
responses((status = 204, description = "Document deleted")),
tag = "Documents"
)]
pub(super) fn delete_document() {}
#[utoipa::path(
get,
path = "/api/documents/{id}/download",
params(("id" = Uuid, Path, description = "Document ID")),
responses((status = 200, description = "Download metadata", body = DocumentDownloadResponse)),
tag = "Documents"
)]
pub(super) fn download_document() {}
#[utoipa::path(
get,
path = "/download/{token}",
params(("token" = String, Path, description = "Download token")),
responses((status = 302, description = "Redirect to pre-signed URL")),
tag = "Documents"
)]
pub(super) fn download_with_token() {}
#[utoipa::path(
patch,
path = "/api/documents/{id}/folder",
params(("id" = Uuid, Path, description = "Document ID")),
request_body = MoveDocumentRequest,
responses((status = 204, description = "Document moved")),
tag = "Documents"
)]
pub(super) fn move_document() {}
#[utoipa::path(
post,
path = "/api/documents/{id}/tags",
params(("id" = Uuid, Path, description = "Document ID")),
request_body = AssignTagsRequest,
responses((status = 204, description = "Tags assigned")),
tag = "Documents"
)]
pub(super) fn assign_tags() {}
#[utoipa::path(
delete,
path = "/api/documents/{id}/tags/{tag_id}",
params(
("id" = Uuid, Path, description = "Document ID"),
("tag_id" = Uuid, Path, description = "Tag ID")
),
responses((status = 204, description = "Tag removed")),
tag = "Documents"
)]
pub(super) fn remove_tag() {}
#[utoipa::path(
post,
path = "/api/documents/bulk/move",
request_body = BulkMoveDocumentsRequest,
responses((status = 200, description = "Bulk move outcome", body = BulkMoveDocumentsResponse)),
tag = "Documents"
)]
pub(super) fn bulk_move_documents() {}
#[utoipa::path(
post,
path = "/api/documents/bulk/tags",
request_body = BulkTagRequest,
responses((status = 200, description = "Bulk tag outcome", body = BulkTagResponse)),
tag = "Documents"
)]
pub(super) fn bulk_update_tags() {}
#[utoipa::path(
post,
path = "/api/documents/bulk/correspondents",
request_body = BulkCorrespondentsRequest,
responses((status = 200, description = "Bulk correspondents outcome", body = BulkCorrespondentsResponse)),
tag = "Documents"
)]
pub(super) fn bulk_assign_correspondents() {}
#[utoipa::path(
post,
path = "/api/documents/{id}/correspondents",
params(("id" = Uuid, Path, description = "Document ID")),
request_body = AssignCorrespondentsRequest,
responses((status = 204, description = "Correspondents assigned")),
tag = "Documents"
)]
pub(super) fn assign_correspondents() {}
#[utoipa::path(
delete,
path = "/api/documents/{id}/correspondents/{correspondent_id}",
params(
("id" = Uuid, Path, description = "Document ID"),
("correspondent_id" = Uuid, Path, description = "Correspondent ID"),
RemoveCorrespondentParams
),
responses((status = 204, description = "Correspondent removed")),
tag = "Documents"
)]
pub(super) fn remove_correspondent() {}
#[utoipa::path(
post,
path = "/api/documents/bulk/reanalyze",
request_body = ReanalyzeRequest,
responses((status = 200, description = "Reanalyze queued", body = ReanalyzeResponse)),
tag = "Documents"
)]
pub(super) fn reanalyze_selected_documents() {}
#[utoipa::path(
get,
path = "/api/documents/{id}/assets",
params(("id" = Uuid, Path, description = "Document ID")),
responses((status = 200, description = "Document assets", body = [DocumentAssetSummary])),
tag = "Assets"
)]
pub(super) fn list_document_assets() {}
#[utoipa::path(
post,
path = "/api/documents/{id}/assets",
params(
("id" = Uuid, Path, description = "Document ID"),
DocumentAssetRequestParams
),
responses((status = 202, description = "Asset generation requested")),
tag = "Assets"
)]
pub(super) fn request_document_assets() {}
#[utoipa::path(
get,
path = "/api/assets/{asset_id}",
params(
("asset_id" = Uuid, Path, description = "Asset ID"),
AssetObjectsQuery
),
responses((status = 200, description = "Asset detail", body = DocumentAssetDetail)),
tag = "Assets"
)]
pub(super) fn get_document_asset() {}
#[utoipa::path(
post,
path = "/api/folders",
request_body = CreateFolderRequest,
responses((status = 200, description = "Folder created", body = FolderResponse)),
tag = "Folders"
)]
pub(super) fn create_folder() {}
#[utoipa::path(
post,
path = "/api/folders/path",
request_body = EnsureFolderPathRequest,
responses((status = 200, description = "Folder path ensured", body = FolderResponse)),
tag = "Folders"
)]
pub(super) fn ensure_folder_path() {}
#[utoipa::path(
get,
path = "/api/folders/{id}",
params(("id" = Uuid, Path, description = "Folder ID")),
responses((status = 200, description = "Folder detail", body = FolderResponse)),
tag = "Folders"
)]
pub(super) fn get_folder() {}
#[utoipa::path(
get,
path = "/api/folders/{id}/contents",
params(
("id" = Uuid, Path, description = "Folder ID"),
FolderContentsParams
),
responses((status = 200, description = "Folder contents", body = FolderContentsResponse)),
tag = "Folders"
)]
pub(super) fn list_folder_contents() {}
#[utoipa::path(
delete,
path = "/api/folders/{id}",
params(("id" = Uuid, Path, description = "Folder ID")),
responses((status = 204, description = "Folder deleted")),
tag = "Folders"
)]
pub(super) fn delete_folder() {}
#[utoipa::path(
patch,
path = "/api/folders/{id}",
params(("id" = Uuid, Path, description = "Folder ID")),
request_body = UpdateFolderRequest,
responses((status = 204, description = "Folder updated")),
tag = "Folders"
)]
pub(super) fn update_folder() {}
#[utoipa::path(
get,
path = "/api/tags",
responses((status = 200, description = "Tags", body = [TagCatalogEntry])),
tag = "Tags"
)]
pub(super) fn list_tags() {}
#[utoipa::path(
post,
path = "/api/tags",
request_body = CreateTagRequest,
responses((status = 200, description = "Tag created", body = TagCatalogEntry)),
tag = "Tags"
)]
pub(super) fn create_tag() {}
#[utoipa::path(
patch,
path = "/api/tags/{id}",
params(("id" = Uuid, Path, description = "Tag ID")),
request_body = UpdateTagRequest,
responses((status = 200, description = "Tag updated", body = TagCatalogEntry)),
tag = "Tags"
)]
pub(super) fn update_tag() {}
#[utoipa::path(
delete,
path = "/api/tags/{id}",
params(("id" = Uuid, Path, description = "Tag ID")),
responses((status = 204, description = "Tag deleted")),
tag = "Tags"
)]
pub(super) fn delete_tag() {}
#[utoipa::path(
get,
path = "/api/correspondents",
responses((status = 200, description = "Correspondents", body = [CorrespondentCatalogEntry])),
tag = "Correspondents"
)]
pub(super) fn list_correspondents() {}
#[utoipa::path(
post,
path = "/api/correspondents",
request_body = CreateCorrespondentRequest,
responses((status = 200, description = "Correspondent created", body = CorrespondentCatalogEntry)),
tag = "Correspondents"
)]
pub(super) fn create_correspondent() {}
#[utoipa::path(
patch,
path = "/api/correspondents/{id}",
params(("id" = Uuid, Path, description = "Correspondent ID")),
request_body = UpdateCorrespondentRequest,
responses((status = 200, description = "Correspondent updated", body = CorrespondentCatalogEntry)),
tag = "Correspondents"
)]
pub(super) fn update_correspondent() {}
#[utoipa::path(
delete,
path = "/api/correspondents/{id}",
params(("id" = Uuid, Path, description = "Correspondent ID")),
responses((status = 204, description = "Correspondent deleted")),
tag = "Correspondents"
)]
pub(super) fn delete_correspondent() {}
}
#[cfg(test)]
mod tests {
use super::ApiDoc;
use utoipa::OpenApi;
#[test]
fn openapi_serializes() {
let spec = ApiDoc::openapi();
let _ = serde_json::to_string(&spec).expect("serialize openapi");
}
}
pub mod schemas {
use super::*;
#[derive(Serialize, Deserialize, ToSchema)]
pub struct LoginRequest {
pub username: String,
pub password: String,
#[schema(nullable)]
pub preferred_tenant_slug: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct AccessTokenResponse {
pub access_token: String,
pub token_type: String,
pub expires_in: i64,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct TenantSummary {
pub tenant_id: Uuid,
pub slug: String,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct TenantSelectionResponse {
pub selection_token: String,
pub tenants: Vec<TenantSummary>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct TenantSelectionRequest {
pub tenant_id: Uuid,
}
#[derive(Serialize, Deserialize, ToSchema)]
#[serde(untagged)]
pub enum LoginResponseVariants {
Token(AccessTokenResponse),
Selection(TenantSelectionResponse),
}
#[derive(Serialize, Deserialize, IntoParams, ToSchema)]
#[into_params(parameter_in = Query)]
pub struct DocumentListQuery {
pub folder_id: Option<Uuid>,
pub include_deleted: Option<bool>,
pub include_descendants: Option<bool>,
pub query: Option<String>,
pub tags: Option<String>,
pub correspondents: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentTag {
pub id: Uuid,
pub label: String,
#[schema(nullable)]
pub color: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentAssetObject {
pub id: Uuid,
pub ordinal: i32,
pub metadata: Value,
#[schema(nullable)]
pub url: Option<String>,
#[schema(nullable)]
pub expires_at: Option<i64>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentAssetSummary {
pub id: Uuid,
pub asset_type: String,
pub mime_type: String,
pub metadata: Value,
#[schema(nullable)]
pub cardinality: Option<i32>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentAssetDetail {
pub id: Uuid,
pub asset_type: String,
pub mime_type: String,
pub metadata: Value,
pub created_at: String,
#[schema(nullable)]
pub cardinality: Option<i32>,
pub objects: Vec<DocumentAssetObject>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentVersion {
pub id: Uuid,
pub version_number: i32,
pub checksum: String,
pub size_bytes: i64,
pub created_at: String,
pub metadata: Value,
#[schema(nullable)]
pub operations_summary: Option<Value>,
#[schema(nullable)]
pub assets: Option<Vec<DocumentAssetSummary>>,
pub download_path: String,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentCorrespondent {
pub id: Uuid,
pub name: String,
pub role: String,
pub metadata: Value,
pub assigned_at: String,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentResponse {
pub id: Uuid,
pub filename: String,
pub title: String,
pub original_name: String,
#[schema(nullable)]
pub content_type: Option<String>,
#[schema(nullable)]
pub folder_id: Option<Uuid>,
pub uploaded_at: String,
pub updated_at: String,
#[schema(nullable)]
pub deleted_at: Option<String>,
#[schema(nullable)]
pub issued_at: Option<String>,
pub metadata: Value,
pub tags: Vec<DocumentTag>,
#[schema(nullable)]
pub correspondents: Option<Vec<DocumentCorrespondent>>,
#[schema(nullable)]
pub current_version: Option<DocumentVersion>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentDetailResponse {
pub document: DocumentResponse,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentDownloadResponse {
pub url: String,
pub expires_in: u64,
pub filename: String,
#[schema(nullable)]
pub content_type: Option<String>,
pub size_bytes: i64,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct UpdateDocumentRequest {
#[schema(nullable)]
pub title: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct BulkMoveDocumentsRequest {
pub document_ids: Vec<Uuid>,
#[schema(nullable)]
pub folder_id: Option<Uuid>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct BulkMoveDocumentsResponse {
pub updated: usize,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct AssignTagsRequest {
pub tag_ids: Vec<Uuid>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct MoveDocumentRequest {
#[schema(nullable)]
pub folder_id: Option<Uuid>,
}
#[derive(Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum BulkTagAction {
Add,
Remove,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct BulkTagRequest {
pub document_ids: Vec<Uuid>,
pub tag_ids: Vec<Uuid>,
pub action: BulkTagAction,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct BulkTagResponse {
pub added: usize,
pub removed: usize,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct CorrespondentAssignment {
pub correspondent_id: Uuid,
pub role: String,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct AssignCorrespondentsRequest {
pub assignments: Vec<CorrespondentAssignment>,
#[serde(default)]
pub replace: bool,
}
#[derive(Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "lowercase")]
pub enum BulkCorrespondentAction {
Add,
Remove,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct BulkCorrespondentsRequest {
pub document_ids: Vec<Uuid>,
pub assignments: Vec<CorrespondentAssignment>,
#[serde(default = "default_bulk_correspondent_action")]
pub action: BulkCorrespondentAction,
}
fn default_bulk_correspondent_action() -> BulkCorrespondentAction {
BulkCorrespondentAction::Add
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct BulkCorrespondentsResponse {
pub assigned: usize,
pub removed: usize,
}
#[derive(Serialize, Deserialize, IntoParams, ToSchema)]
#[into_params(parameter_in = Query)]
pub struct RemoveCorrespondentParams {
pub role: String,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct ReanalyzeRequest {
pub document_ids: Vec<Uuid>,
#[serde(default)]
pub force: bool,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct ReanalyzeResponse {
pub queued: usize,
}
#[derive(Serialize, Deserialize, IntoParams, ToSchema)]
#[into_params(parameter_in = Query)]
pub struct DocumentAssetRequestParams {
#[serde(default)]
pub force: Option<bool>,
}
#[derive(Serialize, Deserialize, IntoParams, ToSchema)]
#[into_params(parameter_in = Query)]
pub struct AssetObjectsQuery {
#[serde(default)]
pub start: Option<i32>,
#[serde(default)]
pub limit: Option<i32>,
}
#[derive(Serialize, Deserialize, IntoParams, ToSchema)]
#[into_params(parameter_in = Query)]
pub struct DocumentCheckQuery {
pub checksum: String,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct DocumentCheckResponse {
pub exists: bool,
#[schema(nullable)]
pub document_id: Option<Uuid>,
#[schema(nullable)]
pub title: Option<String>,
#[schema(nullable)]
pub filename: Option<String>,
#[schema(nullable)]
pub version_id: Option<Uuid>,
#[schema(nullable)]
pub version_number: Option<i32>,
#[schema(nullable)]
pub uploaded_at: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct UploadDocumentForm {
#[schema(value_type = String, format = Binary)]
pub file: String,
#[schema(nullable)]
pub folder_id: Option<Uuid>,
#[schema(nullable)]
pub metadata: Option<Value>,
#[schema(nullable)]
pub title: Option<String>,
#[schema(nullable, value_type = Vec<Uuid>)]
pub tag_ids: Option<Vec<Uuid>>,
#[schema(nullable, value_type = Vec<CorrespondentAssignment>)]
pub correspondents: Option<Vec<CorrespondentAssignment>>,
#[schema(nullable, example = "2024-01-01T00:00:00Z")]
pub issued_at: Option<String>,
#[schema(nullable)]
pub skip_existing: Option<bool>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct CreateFolderRequest {
pub name: String,
#[schema(nullable)]
pub parent_id: Option<Uuid>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct EnsureFolderPathRequest {
#[schema(nullable)]
pub parent_id: Option<Uuid>,
pub segments: Vec<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct FolderInfo {
pub id: Uuid,
pub name: String,
#[schema(nullable)]
pub parent_id: Option<Uuid>,
pub created_at: String,
pub updated_at: String,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct FolderResponse {
pub folder: FolderInfo,
}
#[derive(Serialize, Deserialize, IntoParams, ToSchema)]
#[into_params(parameter_in = Query)]
pub struct FolderContentsParams {
#[serde(default)]
pub include_documents: Option<bool>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct FolderDocumentSummary {
pub id: Uuid,
pub title: String,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct FolderContentsResponse {
#[schema(nullable)]
pub folder: Option<FolderInfo>,
pub subfolders: Vec<FolderInfo>,
pub documents: Vec<FolderDocumentSummary>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct UpdateFolderRequest {
#[schema(nullable)]
pub parent_id: Option<Option<Uuid>>,
#[schema(nullable)]
pub name: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct TagCatalogEntry {
pub id: Uuid,
pub label: String,
#[schema(nullable)]
pub color: Option<String>,
pub usage_count: i64,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct CreateTagRequest {
pub label: String,
#[schema(nullable)]
pub color: Option<String>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct UpdateTagRequest {
#[schema(nullable)]
pub label: Option<Option<String>>,
#[schema(nullable)]
pub color: Option<Option<String>>,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct CorrespondentCatalogEntry {
pub id: Uuid,
pub name: String,
pub metadata: Value,
pub role_counts: Value,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct CreateCorrespondentRequest {
pub name: String,
#[schema(default, value_type = Object)]
pub metadata: Value,
}
#[derive(Serialize, Deserialize, ToSchema)]
pub struct UpdateCorrespondentRequest {
#[schema(nullable)]
pub name: Option<String>,
#[schema(nullable)]
pub metadata: Option<Value>,
}
}
File diff suppressed because it is too large Load Diff
-120
View File
@@ -1,120 +0,0 @@
use std::path::Path as FsPath;
use uuid::Uuid;
use crate::error::{AppError, AppResult};
use crate::models::{Document, DocumentAsset, DocumentAssetObject, DocumentVersion};
use crate::state::AppState;
use crate::utils::time::to_iso;
use super::{
DocumentAssetDetailResponse, DocumentAssetObjectResponse, DocumentAssetResponse,
DocumentVersionResponse,
};
pub fn build_download_path(
state: &AppState,
document: &Document,
user_id: Uuid,
) -> AppResult<String> {
state
.jwt
.generate_download_token(document.id, user_id, document.tenant_id)
.map(|token| format!("/download/{token}"))
.map_err(|err| AppError::internal(format!("failed to generate download token: {err}")))
}
pub fn to_version_response(
version: DocumentVersion,
include_operations_summary: bool,
) -> DocumentVersionResponse {
DocumentVersionResponse {
id: version.id,
version_number: version.version_number,
s3_key: version.s3_key,
size_bytes: version.size_bytes,
checksum: version.checksum,
created_at: to_iso(version.created_at),
metadata: version.metadata,
operations_summary: if include_operations_summary {
Some(version.operations_summary)
} else {
None
},
}
}
pub fn to_asset_summary(asset: DocumentAsset) -> DocumentAssetResponse {
DocumentAssetResponse {
id: asset.id,
asset_type: asset.asset_type,
mime_type: asset.mime_type,
metadata: asset.metadata,
cardinality: asset.cardinality,
}
}
pub fn to_asset_detail_response(
asset: DocumentAsset,
objects: Vec<DocumentAssetObjectResponse>,
) -> DocumentAssetDetailResponse {
DocumentAssetDetailResponse {
id: asset.id,
asset_type: asset.asset_type,
mime_type: asset.mime_type,
metadata: asset.metadata,
created_at: to_iso(asset.created_at),
cardinality: asset.cardinality,
objects,
}
}
pub fn to_asset_object_response(
object: DocumentAssetObject,
url: Option<String>,
expires_at: Option<i64>,
) -> DocumentAssetObjectResponse {
DocumentAssetObjectResponse {
id: object.id,
ordinal: object.ordinal,
metadata: object.metadata,
url,
expires_at,
}
}
pub fn derive_document_title(original: &str) -> String {
let trimmed = original.trim();
if trimmed.is_empty() {
return "Document".to_string();
}
let stem = FsPath::new(trimmed)
.file_stem()
.and_then(|s| s.to_str())
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(|s| s.to_string());
stem.unwrap_or_else(|| trimmed.to_string())
}
pub fn filename_with_retained_extension(title: &str, current_filename: &str) -> String {
let extension = FsPath::new(current_filename)
.extension()
.and_then(|ext| ext.to_str());
if let Some(ext) = extension {
if title
.rsplit_once('.')
.map(|(_, existing_ext)| existing_ext.eq_ignore_ascii_case(ext))
.unwrap_or(false)
{
title.to_string()
} else {
format!("{title}.{ext}")
}
} else {
title.to_string()
}
}
@@ -1,61 +0,0 @@
use std::collections::HashSet;
use uuid::Uuid;
use crate::error::{AppError, AppResult};
use super::CorrespondentAssignmentInput;
pub const CORRESPONDENT_ROLES: &[&str] = &["sender", "receiver", "other"];
pub fn normalize_role(value: &str) -> String {
value.trim().to_lowercase()
}
pub fn is_valid_correspondent_role(role: &str) -> bool {
CORRESPONDENT_ROLES.iter().any(|allowed| *allowed == role)
}
pub fn normalize_correspondent_assignments(
assignments: &[CorrespondentAssignmentInput],
) -> AppResult<(Vec<(Uuid, String)>, Vec<Uuid>, Vec<String>)> {
let mut unique_pairs: HashSet<(Uuid, String)> = HashSet::new();
let mut normalized_pairs: Vec<(Uuid, String)> = Vec::new();
let mut role_set: HashSet<String> = HashSet::new();
let mut correspondent_ids: HashSet<Uuid> = HashSet::new();
for assignment in assignments {
let role = normalize_role(&assignment.role);
if role.is_empty() {
return Err(AppError::bad_request("role must not be empty"));
}
if !is_valid_correspondent_role(&role) {
return Err(AppError::bad_request(format!(
"invalid correspondent role '{role}'. Allowed roles: {}",
CORRESPONDENT_ROLES.join(", ")
)));
}
if !unique_pairs.insert((assignment.correspondent_id, role.clone())) {
continue;
}
normalized_pairs.push((assignment.correspondent_id, role.clone()));
role_set.insert(role);
correspondent_ids.insert(assignment.correspondent_id);
}
if normalized_pairs.is_empty() {
return Err(AppError::bad_request(
"assignments must contain at least one unique correspondent/role pair",
));
}
let mut correspondents_vec: Vec<Uuid> = correspondent_ids.into_iter().collect();
correspondents_vec.sort();
let mut roles_vec: Vec<String> = role_set.into_iter().collect();
roles_vec.sort();
Ok((normalized_pairs, correspondents_vec, roles_vec))
}
@@ -1,91 +0,0 @@
use serde_json::Value;
use uuid::Uuid;
pub fn build_quickwit_query(input: &str) -> Option<String> {
let tokens: Vec<String> = input
.split_whitespace()
.filter(|token| !token.is_empty())
.map(|token| {
let normalized = token.to_lowercase();
escape_quickwit_token(&normalized)
})
.collect();
if tokens.is_empty() {
return None;
}
let parts: Vec<String> = tokens
.into_iter()
.map(|token| format!("(title:{token} OR text:{token})"))
.collect();
Some(parts.join(" AND "))
}
pub fn escape_quickwit_token(token: &str) -> String {
let mut escaped = String::with_capacity(token.len());
for ch in token.chars() {
match ch {
'+' | '-' | '&' | '|' | '!' | '(' | ')' | '{' | '}' | '[' | ']' | '^' | '"' | '~'
| '*' | '?' | ':' | '\\' | '/' => {
escaped.push('\\');
escaped.push(ch);
}
_ => escaped.push(ch),
}
}
escaped
}
pub fn extract_document_id(hit: &Value) -> Option<Uuid> {
for key in ["_source", "source", "fields", "stored_fields"] {
if let Some(value) = hit.get(key) {
if let Some(uuid) = extract_uuid_from_value(value) {
return Some(uuid);
}
}
}
if let Some(value) = hit.get("document_id") {
if let Some(uuid) = extract_uuid_from_value(value) {
return Some(uuid);
}
}
None
}
pub fn extract_uuid_from_value(value: &Value) -> Option<Uuid> {
if let Some(obj) = value.as_object() {
if let Some(inner) = obj.get("document_id") {
return parse_uuid_value(inner);
}
}
if let Some(arr) = value.as_array() {
for item in arr {
if let Some(uuid) = extract_uuid_from_value(item) {
return Some(uuid);
}
}
}
parse_uuid_value(value)
}
pub fn parse_uuid_value(value: &Value) -> Option<Uuid> {
if let Some(s) = value.as_str() {
return Uuid::parse_str(s).ok();
}
if let Some(arr) = value.as_array() {
for item in arr {
if let Some(uuid) = parse_uuid_value(item) {
return Some(uuid);
}
}
}
None
}
+18 -59
View File
@@ -4,7 +4,6 @@ use axum::{
}; };
use diesel::{dsl::exists, prelude::*, PgConnection}; use diesel::{dsl::exists, prelude::*, PgConnection};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid; use uuid::Uuid;
use crate::models::{Document, Folder, NewFolder}; use crate::models::{Document, Folder, NewFolder};
@@ -19,10 +18,7 @@ use super::documents::{
load_correspondents_for_documents, load_primary_assets, load_tags_for_documents, load_correspondents_for_documents, load_primary_assets, load_tags_for_documents,
to_document_response, DocumentResponse, to_document_response, DocumentResponse,
}; };
use crate::utils::{ use crate::utils::time::to_iso;
json::{classify_nullable, NullableValue},
time::to_iso,
};
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct CreateFolderRequest { pub struct CreateFolderRequest {
@@ -36,6 +32,13 @@ pub struct EnsureFolderPathRequest {
pub segments: Vec<String>, pub segments: Vec<String>,
} }
#[derive(Deserialize)]
pub struct UpdateFolderRequest {
#[serde(default)]
pub parent_id: Option<Option<Uuid>>,
pub name: Option<String>,
}
#[derive(Serialize)] #[derive(Serialize)]
pub struct FolderResponse { pub struct FolderResponse {
pub folder: FolderInfo, pub folder: FolderInfo,
@@ -67,24 +70,6 @@ pub struct FolderInfo {
pub updated_at: String, pub updated_at: String,
} }
pub async fn get_folder(
Path(folder_id): Path<Uuid>,
TenantScopedConn {
mut conn,
tenant_id,
..
}: TenantScopedConn,
) -> AppResult<Json<FolderResponse>> {
let folder: Folder = folders::table
.find(folder_id)
.filter(folders::tenant_id.eq(tenant_id))
.first(&mut conn)?;
Ok(Json(FolderResponse {
folder: folder_to_info(folder),
}))
}
pub async fn ensure_folder_path( pub async fn ensure_folder_path(
TenantScopedConn { TenantScopedConn {
mut conn, mut conn,
@@ -337,15 +322,8 @@ pub async fn update_folder(
tenant_id, tenant_id,
.. ..
}: TenantScopedConn, }: TenantScopedConn,
Json(body): Json<Value>, Json(payload): Json<UpdateFolderRequest>,
) -> AppResult<StatusCode> { ) -> AppResult<StatusCode> {
if !body.is_object() {
return Err(AppError::bad_request("request body must be a JSON object"));
}
let parent_class = classify_nullable(body.get("parent_id")).map_err(AppError::bad_request)?;
let name_class = classify_nullable(body.get("name")).map_err(AppError::bad_request)?;
conn.transaction::<(), AppError, _>(|conn| { conn.transaction::<(), AppError, _>(|conn| {
let folder: Folder = folders::table let folder: Folder = folders::table
.find(folder_id) .find(folder_id)
@@ -354,53 +332,35 @@ pub async fn update_folder(
let mut next_parent = folder.parent_id; let mut next_parent = folder.parent_id;
let mut parent_changed = false; let mut parent_changed = false;
match parent_class {
NullableValue::Omitted => {} if let Some(parent_request) = payload.parent_id {
NullableValue::Null => { if parent_request == Some(folder_id) {
if folder.parent_id.is_some() {
parent_changed = true;
}
next_parent = None;
}
NullableValue::String(value) => {
let trimmed = value.trim();
if trimmed.is_empty() {
return Err(AppError::bad_request("parent_id must not be empty"));
}
let parent_id = Uuid::parse_str(trimmed)
.map_err(|_| AppError::bad_request("parent_id must be a valid UUID or null"))?;
if parent_id == folder_id {
return Err(AppError::bad_request("folder cannot be its own parent")); return Err(AppError::bad_request("folder cannot be its own parent"));
} }
if let Some(parent_id) = parent_request {
let _parent: Folder = folders::table let _parent: Folder = folders::table
.find(parent_id) .find(parent_id)
.filter(folders::tenant_id.eq(tenant_id)) .filter(folders::tenant_id.eq(tenant_id))
.first(conn)?; .first(conn)?;
if folder.parent_id != Some(parent_id) {
let descendant_ids = gather_descendant_folder_ids(conn, tenant_id, folder_id)?; let descendant_ids = gather_descendant_folder_ids(conn, tenant_id, folder_id)?;
if descendant_ids.contains(&parent_id) { if descendant_ids.contains(&parent_id) {
return Err(AppError::bad_request( return Err(AppError::bad_request(
"cannot move folder into itself or a descendant", "cannot move folder into itself or a descendant",
)); ));
} }
parent_changed = true;
} }
next_parent = Some(parent_id); parent_changed = parent_request != folder.parent_id;
} next_parent = parent_request;
} }
let mut new_name = folder.name.clone(); let mut new_name = folder.name.clone();
let mut name_changed = false; let mut name_changed = false;
match name_class {
NullableValue::Omitted => {} if let Some(name) = payload.name {
NullableValue::Null => { let trimmed = name.trim();
return Err(AppError::bad_request("name cannot be null"));
}
NullableValue::String(value) => {
let trimmed = value.trim();
if trimmed.is_empty() { if trimmed.is_empty() {
return Err(AppError::bad_request("name must not be empty")); return Err(AppError::bad_request("name must not be empty"));
} }
@@ -410,7 +370,6 @@ pub async fn update_folder(
name_changed = true; name_changed = true;
} }
} }
}
if !parent_changed && !name_changed { if !parent_changed && !name_changed {
return Ok(()); return Ok(());
+5 -21
View File
@@ -2,15 +2,12 @@ use axum::http::HeaderValue;
use axum::{ use axum::{
extract::DefaultBodyLimit, extract::DefaultBodyLimit,
middleware, middleware,
response::Json,
routing::{delete, get, patch, post}, routing::{delete, get, patch, post},
Router, Router,
}; };
use std::sync::Arc;
use tower_http::cors::{AllowOrigin, CorsLayer}; use tower_http::cors::{AllowOrigin, CorsLayer};
use utoipa::OpenApi;
use crate::{auth::AuthenticatedUser, openapi::ApiDoc, state::AppState}; use crate::{auth::AuthenticatedUser, state::AppState};
pub mod auth; pub mod auth;
pub mod correspondents; pub mod correspondents;
@@ -57,7 +54,6 @@ pub fn create_router(state: AppState) -> Router<()> {
.route("/me", get(auth::me)); .route("/me", get(auth::me));
let documents_routes = Router::new() let documents_routes = Router::new()
.route("/check", get(documents::check_document))
.route( .route(
"/", "/",
get(documents::list_documents).post(documents::upload_document), get(documents::list_documents).post(documents::upload_document),
@@ -101,9 +97,10 @@ pub fn create_router(state: AppState) -> Router<()> {
let folders_routes = Router::new() let folders_routes = Router::new()
.route("/", post(folders::create_folder)) .route("/", post(folders::create_folder))
.route("/path", post(folders::ensure_folder_path)) .route("/path", post(folders::ensure_folder_path))
.route("/:id", get(folders::get_folder)) .route(
.route("/:id", delete(folders::delete_folder)) "/:id",
.route("/:id", patch(folders::update_folder)) delete(folders::delete_folder).patch(folders::update_folder),
)
.route("/:id/contents", get(folders::list_folder_contents)); .route("/:id/contents", get(folders::list_folder_contents));
let tags_routes = Router::new() let tags_routes = Router::new()
@@ -132,22 +129,9 @@ pub fn create_router(state: AppState) -> Router<()> {
.nest("/api/assets", assets_routes) .nest("/api/assets", assets_routes)
.layer(middleware::from_extractor_with_state::<AuthenticatedUser, _>(protected_state)); .layer(middleware::from_extractor_with_state::<AuthenticatedUser, _>(protected_state));
let openapi_arc = Arc::new(ApiDoc::openapi());
let docs_route = Router::new().route(
"/api/docs/openapi.json",
get({
let spec = openapi_arc.clone();
move || {
let spec = spec.clone();
async move { Json((*spec).clone()) }
}
}),
);
Router::new() Router::new()
.merge(download_routes) .merge(download_routes)
.merge(protected_routes) .merge(protected_routes)
.merge(docs_route)
.nest("/api/auth", auth_routes) .nest("/api/auth", auth_routes)
.route("/api/health", get(health::health_check)) .route("/api/health", get(health::health_check))
.with_state(state) .with_state(state)
+8 -137
View File
@@ -11,13 +11,12 @@ use axum::Router;
use backend::auth::jwt::JwtService; use backend::auth::jwt::JwtService;
use backend::config::AppConfig; use backend::config::AppConfig;
use backend::db::{self, PgPool}; use backend::db::{self, PgPool};
use backend::models::{Job, NewUser, NewUserMembership, Tenant}; use backend::models::{Job, NewUser, NewUserMembership};
use backend::routes; use backend::routes;
use backend::state::AppState; use backend::state::AppState;
use backend::storage::ObjectStorage; use backend::storage::ObjectStorage;
use diesel::connection::SimpleConnection; use diesel::connection::SimpleConnection;
use diesel::prelude::*; use diesel::prelude::*;
use diesel::OptionalExtension;
use diesel::PgConnection; use diesel::PgConnection;
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use http_body_util::BodyExt; use http_body_util::BodyExt;
@@ -152,20 +151,16 @@ impl TestApp {
let state = AppState::new(pool.clone(), config, storage_for_state, jwt); let state = AppState::new(pool.clone(), config, storage_for_state, jwt);
let router = routes::create_router(state.clone()); let router = routes::create_router(state.clone());
let app = Self { Ok(Self {
state, state,
router, router,
storage, storage,
}; })
app.ensure_default_tenant().await?;
Ok(app)
} }
pub async fn cleanup(&self) -> Result<()> { pub async fn cleanup(&self) -> Result<()> {
let pool = self.state.pool.clone(); let pool = self.state.pool.clone();
let _ = tokio::task::spawn_blocking(move || -> Result<()> { tokio::task::spawn_blocking(move || -> Result<()> {
let mut conn = pool let mut conn = pool
.get() .get()
.map_err(|err| anyhow!("failed to get cleanup connection: {err}"))?; .map_err(|err| anyhow!("failed to get cleanup connection: {err}"))?;
@@ -173,10 +168,7 @@ impl TestApp {
Ok(()) Ok(())
}) })
.await .await
.context("cleanup task panicked")?; .context("cleanup task panicked")?
self.ensure_default_tenant().await?;
Ok(())
} }
#[allow(dead_code)] #[allow(dead_code)]
@@ -184,20 +176,6 @@ impl TestApp {
self.storage.clone() self.storage.clone()
} }
#[allow(dead_code)]
pub async fn storage_key_for(&self, key: &str) -> Result<String> {
let tenant = self
.state
.tenants
.get_by_slug(&self.state.config.default_tenant_slug)
.map_err(|err| anyhow!("default tenant not found: {:?}", err))?;
let root = tenant
.storage_root
.clone()
.ok_or_else(|| anyhow!("default tenant missing storage root"))?;
Ok(format!("{}{}", root, key))
}
pub async fn insert_user(&self, username: &str, password: &str, role: &str) -> Result<Uuid> { pub async fn insert_user(&self, username: &str, password: &str, role: &str) -> Result<Uuid> {
let username = username.to_string(); let username = username.to_string();
let password = password.to_string(); let password = password.to_string();
@@ -206,7 +184,7 @@ impl TestApp {
.state .state
.tenants .tenants
.tenant_id_for_slug(&self.state.config.default_tenant_slug) .tenant_id_for_slug(&self.state.config.default_tenant_slug)
.map_err(|err| anyhow!("default tenant not found: {:?}", err))?; .context("default tenant not found")?;
self.with_conn(move |conn| { self.with_conn(move |conn| {
let password_hash = hash_password(&password)?; let password_hash = hash_password(&password)?;
let user = NewUser { let user = NewUser {
@@ -235,60 +213,6 @@ impl TestApp {
.await .await
} }
async fn ensure_default_tenant(&self) -> Result<Uuid> {
let slug_value = self.state.config.default_tenant_slug.clone();
let quickwit_enabled = self.state.config.quickwit_endpoint.is_some();
self.with_conn(move |conn| {
use backend::schema::tenants::dsl as tenants_dsl;
let existing = tenants_dsl::tenants
.filter(tenants_dsl::slug.eq(&slug_value))
.first::<Tenant>(conn)
.optional()
.context("failed to load default tenant")?;
let tenant_id = if let Some(current) = existing {
let desired_root = current
.storage_root
.clone()
.filter(|root| root.ends_with('/'))
.unwrap_or_else(|| format!("test-tenants/{}/", current.id));
if current.storage_root.as_deref() != Some(desired_root.as_str()) {
diesel::update(tenants_dsl::tenants.filter(tenants_dsl::id.eq(current.id)))
.set(tenants_dsl::storage_root.eq(Some(desired_root)))
.execute(conn)
.context("failed to update default tenant storage root")?;
}
current.id
} else {
let new_id = Uuid::new_v4();
let root = format!("test-tenants/{}/", new_id);
let quickwit_value = if quickwit_enabled {
Some(format!("documents-{}", new_id))
} else {
None
};
diesel::insert_into(tenants_dsl::tenants)
.values((
tenants_dsl::id.eq(new_id),
tenants_dsl::slug.eq(&slug_value),
tenants_dsl::storage_root.eq(Some(root)),
tenants_dsl::quickwit_index.eq(quickwit_value),
))
.execute(conn)
.context("failed to insert default tenant")?;
new_id
};
Ok(tenant_id)
})
.await
}
pub async fn login_token(&self, username: &str, password: &str) -> Result<String> { pub async fn login_token(&self, username: &str, password: &str) -> Result<String> {
#[derive(Serialize)] #[derive(Serialize)]
struct LoginPayload<'a> { struct LoginPayload<'a> {
@@ -323,7 +247,7 @@ impl TestApp {
#[derive(Deserialize)] #[derive(Deserialize)]
struct TenantSummary { struct TenantSummary {
tenant_id: Uuid, tenant_id: Uuid,
_slug: String, slug: String,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -478,30 +402,6 @@ impl TestApp {
data: &[u8], data: &[u8],
folder_id: Option<Uuid>, folder_id: Option<Uuid>,
token: &str, token: &str,
) -> Result<hyper::Response<Body>> {
self.upload_document_with_options(
path,
filename,
content_type,
data,
folder_id,
None,
None,
token,
)
.await
}
pub async fn upload_document_with_options(
&self,
path: &str,
filename: &str,
content_type: &str,
data: &[u8],
folder_id: Option<Uuid>,
title: Option<&str>,
metadata_json: Option<&str>,
token: &str,
) -> Result<hyper::Response<Body>> { ) -> Result<hyper::Response<Body>> {
let boundary = format!("boundary-{}", Uuid::new_v4()); let boundary = format!("boundary-{}", Uuid::new_v4());
let mut body = Vec::new(); let mut body = Vec::new();
@@ -524,20 +424,6 @@ impl TestApp {
body.extend(b"\r\n"); body.extend(b"\r\n");
} }
if let Some(title_value) = title {
body.extend(format!("--{boundary}\r\n").as_bytes());
body.extend(b"Content-Disposition: form-data; name=\"title\"\r\n\r\n");
body.extend(title_value.as_bytes());
body.extend(b"\r\n");
}
if let Some(metadata_value) = metadata_json {
body.extend(format!("--{boundary}\r\n").as_bytes());
body.extend(b"Content-Disposition: form-data; name=\"metadata\"\r\n\r\n");
body.extend(metadata_value.as_bytes());
body.extend(b"\r\n");
}
body.extend(format!("--{boundary}--\r\n").as_bytes()); body.extend(format!("--{boundary}--\r\n").as_bytes());
let builder = Request::builder() let builder = Request::builder()
@@ -604,22 +490,7 @@ async fn prepare_database(pool: &PgPool) -> Result<()> {
fn truncate_all(conn: &mut PgConnection) -> Result<()> { fn truncate_all(conn: &mut PgConnection) -> Result<()> {
conn.batch_execute( conn.batch_execute(
"TRUNCATE TABLE \ "TRUNCATE TABLE document_tags, document_versions, documents, folders, tags, users RESTART IDENTITY CASCADE;",
document_asset_objects, \
document_assets, \
document_correspondents, \
correspondents, \
document_tags, \
document_versions, \
documents, \
folders, \
jobs, \
refresh_tokens, \
tags, \
user_memberships, \
users, \
tenants \
RESTART IDENTITY CASCADE;",
) )
.context("failed to truncate tables")?; .context("failed to truncate tables")?;
Ok(()) Ok(())
+4 -42
View File
@@ -15,7 +15,6 @@ struct DocumentDetail {
struct DocumentInfo { struct DocumentInfo {
id: Uuid, id: Uuid,
title: String, title: String,
filename: String,
original_name: String, original_name: String,
deleted_at: Option<String>, deleted_at: Option<String>,
issued_at: Option<String>, issued_at: Option<String>,
@@ -57,12 +56,12 @@ struct DocumentDownload {
filename: String, filename: String,
} }
#[derive(Deserialize)]
#[derive(Deserialize)] #[derive(Deserialize)]
struct BulkReanalyze { struct BulkReanalyze {
queued: usize, queued: usize,
} }
#[derive(Deserialize)]
struct BulkMoveResult { struct BulkMoveResult {
updated: usize, updated: usize,
} }
@@ -187,10 +186,9 @@ async fn upload_and_list_document() -> Result<()> {
assert_eq!(current_version.size_bytes, file_bytes.len() as i64); assert_eq!(current_version.size_bytes, file_bytes.len() as i64);
assert!(current_version.assets.is_empty()); assert!(current_version.assets.is_empty());
let storage_key = app.storage_key_for(&current_version.s3_key).await?;
let stored = app let stored = app
.storage() .storage()
.get(&storage_key) .get(&current_version.s3_key)
.await .await
.expect("object stored"); .expect("object stored");
assert_eq!(stored.bytes, file_bytes); assert_eq!(stored.bytes, file_bytes);
@@ -241,43 +239,6 @@ async fn upload_and_list_document() -> Result<()> {
Ok(()) Ok(())
} }
#[tokio::test]
async fn upload_document_with_custom_title_sets_filename() -> Result<()> {
let _lock = acquire_db_lock().await;
let app = TestApp::new().await?;
let password = "passw0rd";
app.insert_user("nora", password, "admin").await?;
let token = app.login_token("nora", password).await?;
let file_bytes = b"example contract body".to_vec();
let title = "Vendor Contract";
let original_filename = "scan.pdf";
let upload = app
.upload_document_with_options(
"/api/documents",
original_filename,
"application/pdf",
&file_bytes,
None,
Some(title),
None,
&token,
)
.await?;
assert_eq!(upload.status(), StatusCode::CREATED);
let body = body_to_vec(upload.into_body()).await?;
let detail: DocumentDetail = serde_json::from_slice(&body)?;
assert_eq!(detail.document.title, title);
assert_eq!(detail.document.filename, format!("{title}.pdf"));
assert_eq!(detail.document.original_name, original_filename);
app.cleanup().await?;
Ok(())
}
#[tokio::test] #[tokio::test]
async fn duplicate_and_restore_document() -> Result<()> { async fn duplicate_and_restore_document() -> Result<()> {
let _lock = acquire_db_lock().await; let _lock = acquire_db_lock().await;
@@ -357,6 +318,7 @@ async fn duplicate_and_restore_document() -> Result<()> {
Ok(()) Ok(())
} }
#[tokio::test] #[tokio::test]
async fn bulk_move_documents_to_folder() -> Result<()> { async fn bulk_move_documents_to_folder() -> Result<()> {
let _lock = acquire_db_lock().await; let _lock = acquire_db_lock().await;
+12 -75
View File
@@ -5,7 +5,6 @@ use axum::http::StatusCode;
use common::{acquire_db_lock, body_to_vec, TestApp}; use common::{acquire_db_lock, body_to_vec, TestApp};
use serde::Deserialize; use serde::Deserialize;
use serde::Serialize; use serde::Serialize;
use serde_json::json;
use uuid::Uuid; use uuid::Uuid;
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -17,7 +16,6 @@ struct FolderResponse {
struct FolderInfo { struct FolderInfo {
id: Uuid, id: Uuid,
name: String, name: String,
parent_id: Option<Uuid>,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -44,6 +42,14 @@ struct EnsureFolderPath<'a> {
segments: &'a [&'a str], segments: &'a [&'a str],
} }
#[derive(Serialize)]
struct UpdateFolderRequest {
#[serde(skip_serializing_if = "Option::is_none")]
parent_id: Option<Option<Uuid>>,
#[serde(skip_serializing_if = "Option::is_none")]
name: Option<String>,
}
#[derive(Serialize)] #[derive(Serialize)]
struct MoveDocumentRequest { struct MoveDocumentRequest {
folder_id: Option<Uuid>, folder_id: Option<Uuid>,
@@ -144,78 +150,6 @@ async fn folder_move_and_delete_flow() -> Result<()> {
Ok(()) Ok(())
} }
#[tokio::test]
async fn update_folder_parent_to_root() -> Result<()> {
let _lock = acquire_db_lock().await;
let app = TestApp::new().await?;
let password = "rootpass";
app.insert_user("root-admin", password, "admin").await?;
let token = app.login_token("root-admin", password).await?;
// Create a parent folder under root
let parent_resp = app
.post_json(
"/api/folders",
&CreateFolder {
name: "Parent",
parent_id: None,
},
Some(&token),
)
.await?;
assert_eq!(parent_resp.status(), StatusCode::OK);
let parent_body = body_to_vec(parent_resp.into_body()).await?;
let parent: FolderResponse = serde_json::from_slice(&parent_body)?;
// Create a child folder inside the parent
let child_resp = app
.post_json(
"/api/folders",
&CreateFolder {
name: "Child",
parent_id: Some(parent.folder.id),
},
Some(&token),
)
.await?;
assert_eq!(child_resp.status(), StatusCode::OK);
let child_body = body_to_vec(child_resp.into_body()).await?;
let child: FolderResponse = serde_json::from_slice(&child_body)?;
// Move the child back to the root by setting parent_id to null
let update_resp = app
.patch_json(
&format!("/api/folders/{}", child.folder.id),
&json!({ "parent_id": null }),
Some(&token),
)
.await?;
assert_eq!(update_resp.status(), StatusCode::NO_CONTENT);
// Fetch the child folder and ensure parent_id is now null
let updated_resp = app
.get(&format!("/api/folders/{}", child.folder.id), Some(&token))
.await?;
assert_eq!(updated_resp.status(), StatusCode::OK);
let updated_body = body_to_vec(updated_resp.into_body()).await?;
let updated_folder: FolderResponse = serde_json::from_slice(&updated_body)?;
assert!(updated_folder.folder.parent_id.is_none());
// Root contents should include the child folder by name
let root_contents = app.get("/api/folders/root/contents", Some(&token)).await?;
assert_eq!(root_contents.status(), StatusCode::OK);
let root_body = body_to_vec(root_contents.into_body()).await?;
let root: FolderContents = serde_json::from_slice(&root_body)?;
assert!(root
.subfolders
.iter()
.any(|folder| folder.id == child.folder.id));
app.cleanup().await?;
Ok(())
}
#[tokio::test] #[tokio::test]
async fn ensure_path_creates_nested_folders() -> Result<()> { async fn ensure_path_creates_nested_folders() -> Result<()> {
let _lock = acquire_db_lock().await; let _lock = acquire_db_lock().await;
@@ -333,7 +267,10 @@ async fn folder_rename_updates_name_and_child_paths() -> Result<()> {
let rename_resp = app let rename_resp = app
.patch_json( .patch_json(
&format!("/api/folders/{}", parent.folder.id), &format!("/api/folders/{}", parent.folder.id),
&json!({ "name": "Archive" }), &UpdateFolderRequest {
parent_id: None,
name: Some("Archive".to_string()),
},
Some(&token), Some(&token),
) )
.await?; .await?;
+1 -4
View File
@@ -17,8 +17,7 @@ Health
Documents Documents
--------- ---------
- GET /api/documents - List or search documents. Optional filters: `folder_id` (defaults to root when omitted), `include_deleted`, `include_descendants` (defaults to true when a `folder_id` is provided and no other override is supplied), `query` (Quickwit full-text), `tags` (comma-separated tag UUIDs), and `correspondents` (comma-separated correspondent UUIDs). Each entry includes tags, correspondent assignments, and current version info. - GET /api/documents - List or search documents. Optional filters: `folder_id` (defaults to root when omitted), `include_deleted`, `include_descendants` (defaults to true when a `folder_id` is provided and no other override is supplied), `query` (Quickwit full-text), `tags` (comma-separated tag UUIDs), and `correspondents` (comma-separated correspondent UUIDs). Each entry includes tags, correspondent assignments, and current version info.
- GET /api/documents/check?checksum=<sha256> - Lightweight checksum preflight. Returns `exists=false` when no document with the supplied SHA-256 checksum is present; otherwise returns `exists=true` plus the current document metadata. - POST /api/documents - Upload a document via multipart form-data (`file`, optional metadata/folder fields).
- POST /api/documents - Upload a document via multipart form-data. Required field: `file`. Optional fields: `title`, `folder_id`, JSON `metadata`, JSON array `tag_ids`, JSON array `correspondents` (each with `correspondent_id` and `role`), and `issued_at` (RFC3339). When `title` is supplied, the stored filename becomes `<title><original_extension>`. Include `skip_existing=true` to receive `204 No Content` instead of reusing a matching document.
- POST /api/documents/bulk/move - Move multiple documents to a target folder. - POST /api/documents/bulk/move - Move multiple documents to a target folder.
- POST /api/documents/bulk/tags - Add or remove tags across multiple documents. - POST /api/documents/bulk/tags - Add or remove tags across multiple documents.
- POST /api/documents/bulk/correspondents - Bulk correspondent actions. Default `action=add` replaces existing assignments for the provided roles before adding the supplied correspondents; `action=remove` drops the specified correspondent/role pairs. - POST /api/documents/bulk/correspondents - Bulk correspondent actions. Default `action=add` replaces existing assignments for the provided roles before adding the supplied correspondents; `action=remove` drops the specified correspondent/role pairs.
@@ -47,11 +46,9 @@ Folders
------- -------
- POST /api/folders - Create a folder (optionally under a parent). - POST /api/folders - Create a folder (optionally under a parent).
- POST /api/folders/path - Ensure a nested folder path exists, creating missing segments. - POST /api/folders/path - Ensure a nested folder path exists, creating missing segments.
- GET /api/folders/:id - Fetch folder metadata.
- GET /api/folders/:id/contents - List subfolders and documents inside a folder; use `root` for the workspace root. - GET /api/folders/:id/contents - List subfolders and documents inside a folder; use `root` for the workspace root.
- DELETE /api/folders/:id - Soft-delete a folder. - DELETE /api/folders/:id - Soft-delete a folder.
- PATCH /api/folders/:id - Update a folder's parent (`parent_id`) and/or rename it (`name`). - PATCH /api/folders/:id - Update a folder's parent (`parent_id`) and/or rename it (`name`).
- GET /api/docs/openapi.json - Generated OpenAPI specification (JSON).
Tags Tags
---- ----
+10
View File
@@ -8,6 +8,7 @@
"name": "papercrate-frontend", "name": "papercrate-frontend",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@fontsource/inter": "^5.2.8",
"@tabler/icons-react": "3.11.0", "@tabler/icons-react": "3.11.0",
"axios": "1.7.7", "axios": "1.7.7",
"react": "18.3.1", "react": "18.3.1",
@@ -1852,6 +1853,15 @@
"node": ">=10.0.0" "node": ">=10.0.0"
} }
}, },
"node_modules/@fontsource/inter": {
"version": "5.2.8",
"resolved": "https://registry.npmjs.org/@fontsource/inter/-/inter-5.2.8.tgz",
"integrity": "sha512-P6r5WnJoKiNVV+zvW2xM13gNdFhAEpQ9dQJHt3naLvfg+LkF2ldgSLiF4T41lf1SQCM9QmkqPTn4TH568IRagg==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@jridgewell/gen-mapping": { "node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13", "version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
+3 -2
View File
@@ -9,6 +9,7 @@
"lint": "echo \"No linting configured\"" "lint": "echo \"No linting configured\""
}, },
"dependencies": { "dependencies": {
"@fontsource/inter": "^5.2.8",
"@tabler/icons-react": "3.11.0", "@tabler/icons-react": "3.11.0",
"axios": "1.7.7", "axios": "1.7.7",
"react": "18.3.1", "react": "18.3.1",
@@ -19,6 +20,7 @@
"@babel/core": "7.26.0", "@babel/core": "7.26.0",
"@babel/preset-env": "7.26.0", "@babel/preset-env": "7.26.0",
"@babel/preset-react": "7.26.3", "@babel/preset-react": "7.26.3",
"@svgr/webpack": "8.1.0",
"babel-loader": "9.2.1", "babel-loader": "9.2.1",
"css-loader": "7.1.2", "css-loader": "7.1.2",
"dotenv": "16.4.5", "dotenv": "16.4.5",
@@ -26,7 +28,6 @@
"style-loader": "4.0.0", "style-loader": "4.0.0",
"webpack": "5.95.0", "webpack": "5.95.0",
"webpack-cli": "5.1.4", "webpack-cli": "5.1.4",
"webpack-dev-server": "5.1.0", "webpack-dev-server": "5.1.0"
"@svgr/webpack": "8.1.0"
} }
} }
@@ -118,11 +118,11 @@ function CorrespondentsPanel({
}, []); }, []);
return ( return (
<section className="correspondents-panel column"> <section className="correspondents-panel">
<div className="column-header"> <div className="panel-section__header">
<div className="column-header__titles"> <div className="panel-section__titles">
<h2>Correspondents</h2> <h2>Correspondents</h2>
<div className="column-subtitle">{correspondents.length} total</div> <div className="panel-section__subtitle">{correspondents.length} total</div>
</div> </div>
<div className="header-actions correspondents-actions"> <div className="header-actions correspondents-actions">
<form className="correspondents-actions__form" onSubmit={handleCreate}> <form className="correspondents-actions__form" onSubmit={handleCreate}>
@@ -147,7 +147,7 @@ function CorrespondentsPanel({
</button> </button>
</div> </div>
</div> </div>
<div className="column-body tags-panel__body"> <div className="panel-section__body tags-panel__body">
{correspondents.length === 0 ? ( {correspondents.length === 0 ? (
<div className="empty-state">No correspondents created yet.</div> <div className="empty-state">No correspondents created yet.</div>
) : ( ) : (
+319 -58
View File
@@ -1,11 +1,20 @@
import React, { useCallback, useEffect, useMemo, useState } from 'react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom'; import {
import { DownloadIcon, EditIcon, ArrowLeftIcon, ArrowRightIcon } from '../ui/icons'; DownloadIcon,
EditIcon,
ArrowLeftIcon,
ArrowRightIcon,
ChevronsRightIcon,
AnalyzeIcon,
WindowMaximizeIcon,
TextScanIcon,
} from '../ui/icons';
import { getTagColorStyle } from '../utils/colors'; import { getTagColorStyle } from '../utils/colors';
import { formatFileSize } from '../utils/format'; import { formatFileSize } from '../utils/format';
import { resolveDocumentAssetUrl, createAssetView } from '../asset_manager'; import { resolveDocumentAssetUrl, createAssetView } from '../asset_manager';
import { useAssetNavigator } from '../hooks/useAssetNavigator'; import { useAssetNavigator } from '../hooks/useAssetNavigator';
import { CORRESPONDENT_ROLES } from '../constants/correspondents'; import { CORRESPONDENT_ROLES } from '../constants/correspondents';
import PreviewZoomOverlay from './PreviewZoomOverlay';
const MAX_PREVIEW_STACK_ITEMS = 15; const MAX_PREVIEW_STACK_ITEMS = 15;
@@ -208,6 +217,7 @@ const PreviewStack = ({
emptyMessage = 'Preview unavailable', emptyMessage = 'Preview unavailable',
onItemActivate, onItemActivate,
onOpenPreview, onOpenPreview,
onZoomPreview,
activeItemId = null, activeItemId = null,
}) => { }) => {
if (!items.length) { if (!items.length) {
@@ -240,7 +250,11 @@ const PreviewStack = ({
zIndex: preparedItems.length - index, zIndex: preparedItems.length - index,
transform, transform,
}} }}
aria-hidden={hasMultiple && !onItemActivate && !onOpenPreview ? 'true' : undefined} aria-hidden={
hasMultiple && !onItemActivate && !onOpenPreview && !onZoomPreview
? 'true'
: undefined
}
> >
<img <img
src={entry.url} src={entry.url}
@@ -248,22 +262,34 @@ const PreviewStack = ({
className="preview-stack__image" className="preview-stack__image"
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
if (isFront && onOpenPreview) { if (isFront) {
if (onZoomPreview) {
onZoomPreview(entry);
} else if (onOpenPreview) {
onOpenPreview(entry.id); onOpenPreview(entry.id);
} else if (onItemActivate) { } else if (onItemActivate) {
onItemActivate(entry.id); onItemActivate(entry.id);
} }
} else if (onItemActivate) {
onItemActivate(entry.id);
}
}} }}
onKeyDown={(event) => { onKeyDown={(event) => {
if (!onItemActivate && !onOpenPreview) return; if (!onItemActivate && !onOpenPreview && !onZoomPreview) return;
if (event.key === 'Enter' || event.key === ' ') { if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault(); event.preventDefault();
event.stopPropagation(); event.stopPropagation();
if (isFront && onOpenPreview) { if (isFront) {
if (onZoomPreview) {
onZoomPreview(entry);
} else if (onOpenPreview) {
onOpenPreview(entry.id); onOpenPreview(entry.id);
} else { } else {
onItemActivate?.(entry.id); onItemActivate?.(entry.id);
} }
} else {
onItemActivate?.(entry.id);
}
} }
}} }}
/> />
@@ -297,9 +323,24 @@ const DetailPanel = ({
onCorrespondentAdd, onCorrespondentAdd,
onCorrespondentRemove, onCorrespondentRemove,
resolveApiPath, resolveApiPath,
onClose = () => {},
}) => { }) => {
const selectedCount = selectedDocuments.length; const selectedCount = selectedDocuments.length;
const singleDoc = selectedCount === 1 ? selectedDocuments[0] : null; const singleDoc = selectedCount === 1 ? selectedDocuments[0] : null;
const singleDocId = singleDoc?.id || null;
const selectionKey = useMemo(
() => selectedDocuments.map((doc) => doc?.id ?? '').join('|'),
[selectedDocuments],
);
const singleDownloadHref = useMemo(() => {
if (!singleDoc) return null;
const downloadPath = singleDoc.current_version?.download_path;
if (!downloadPath || !resolveApiPath) {
return null;
}
return resolveApiPath(downloadPath);
}, [singleDoc, resolveApiPath]);
const [titleEditDocId, setTitleEditDocId] = useState(null); const [titleEditDocId, setTitleEditDocId] = useState(null);
const [titleDraft, setTitleDraft] = useState(''); const [titleDraft, setTitleDraft] = useState('');
@@ -309,6 +350,7 @@ const DetailPanel = ({
const [ocrUrl, setOcrUrl] = useState(null); const [ocrUrl, setOcrUrl] = useState(null);
const [ocrLoading, setOcrLoading] = useState(false); const [ocrLoading, setOcrLoading] = useState(false);
const [ocrError, setOcrError] = useState(null); const [ocrError, setOcrError] = useState(null);
const [zoomedPreview, setZoomedPreview] = useState(null);
useEffect(() => { useEffect(() => {
if (!singleDoc) { if (!singleDoc) {
@@ -338,6 +380,10 @@ const DetailPanel = ({
setOcrUrl(null); setOcrUrl(null);
}, [singleDoc?.id]); }, [singleDoc?.id]);
useEffect(() => {
setZoomedPreview(null);
}, [selectionKey]);
const startTitleEdit = useCallback(() => { const startTitleEdit = useCallback(() => {
if (!singleDoc) return; if (!singleDoc) return;
setTitleEditDocId(singleDoc.id); setTitleEditDocId(singleDoc.id);
@@ -500,6 +546,7 @@ const DetailPanel = ({
}, [selectedDocuments]); }, [selectedDocuments]);
const stackTopDocument = stackDocuments[0] || null; const stackTopDocument = stackDocuments[0] || null;
const stackTopDocId = stackTopDocument?.id || null;
const stackPreviewNavigator = useAssetNavigator({ const stackPreviewNavigator = useAssetNavigator({
document: stackTopDocument, document: stackTopDocument,
assetType: 'preview', assetType: 'preview',
@@ -699,15 +746,178 @@ const DetailPanel = ({
[bulkCorrespondents, onBulkCorrespondentRemove, onCorrespondentRemove, selectedDocuments], [bulkCorrespondents, onBulkCorrespondentRemove, onCorrespondentRemove, selectedDocuments],
); );
const openZoomPreview = useCallback((config) => {
if (!config) return;
setZoomedPreview({
mode: config.mode,
docId: config.docId ?? null,
});
}, []);
const closeZoomPreview = useCallback(() => {
setZoomedPreview(null);
}, []);
const handleSingleZoom = useCallback(
(entry) => {
if (!singleHasPreview) return;
const targetId = entry?.id ?? singleDocId;
if (!targetId) return;
openZoomPreview({ mode: 'single', docId: targetId });
},
[openZoomPreview, singleHasPreview, singleDocId],
);
const handleStackZoom = useCallback(
(entry) => {
if (!stackTopDocId || entry?.id !== stackTopDocId) return;
if (!topHasPreview) return;
openZoomPreview({ mode: 'stack', docId: stackTopDocId });
},
[openZoomPreview, stackTopDocId, topHasPreview],
);
const zoomDisplay = useMemo(() => {
if (!zoomedPreview) {
return null;
}
if (
zoomedPreview.mode === 'single' &&
singleDocId &&
singleDoc &&
singleHasPreview &&
zoomedPreview.docId === singleDocId
) {
return {
url: singlePreviewNavigator.currentUrl,
alt: singleDoc.title || singleDoc.original_name || 'Document preview',
canGoPrev:
singleEffectiveCardinality > 1 && Boolean(singlePreviewNavigator.canGoPrev),
canGoNext:
singleEffectiveCardinality > 1 && Boolean(singlePreviewNavigator.canGoNext),
goPrev: singlePreviewNavigator.goPrev,
goNext: singlePreviewNavigator.goNext,
};
}
if (
zoomedPreview.mode === 'stack' &&
stackTopDocId &&
stackTopDocument &&
zoomedPreview.docId === stackTopDocId &&
topHasPreview
) {
return {
url: stackPreviewNavigator.currentUrl,
alt: stackTopDocument.title || stackTopDocument.original_name || 'Document preview',
canGoPrev:
topEffectiveCardinality > 1 && Boolean(stackPreviewNavigator.canGoPrev),
canGoNext:
topEffectiveCardinality > 1 && Boolean(stackPreviewNavigator.canGoNext),
goPrev: stackPreviewNavigator.goPrev,
goNext: stackPreviewNavigator.goNext,
};
}
return null;
}, [
zoomedPreview,
singleDoc,
singleDocId,
singleHasPreview,
singlePreviewNavigator.currentUrl,
singlePreviewNavigator.canGoPrev,
singlePreviewNavigator.canGoNext,
singlePreviewNavigator.goPrev,
singlePreviewNavigator.goNext,
singleEffectiveCardinality,
stackTopDocument,
stackTopDocId,
topHasPreview,
stackPreviewNavigator.currentUrl,
stackPreviewNavigator.canGoPrev,
stackPreviewNavigator.canGoNext,
stackPreviewNavigator.goPrev,
stackPreviewNavigator.goNext,
topEffectiveCardinality,
]);
useEffect(() => {
if (zoomedPreview && !zoomDisplay) {
setZoomedPreview(null);
}
}, [zoomedPreview, zoomDisplay]);
useEffect(() => {
if (typeof ensureAssetUrl !== 'function') {
return;
}
const warmNavigator = (navigator) => {
const {
documentId,
asset,
ordinal,
canGoPrev,
canGoNext,
cardinality,
} = navigator;
if (!documentId || !asset || !Number.isFinite(ordinal)) {
return;
}
const requests = [];
if (canGoPrev) {
const prevOrdinal = Math.max(1, ordinal - 1);
if (!cardinality || prevOrdinal <= cardinality) {
requests.push(
ensureAssetUrl(documentId, asset, {
start: prevOrdinal,
limit: 1,
objectOrdinal: prevOrdinal,
}),
);
}
}
if (canGoNext) {
const nextOrdinal = ordinal + 1;
if (!cardinality || nextOrdinal <= cardinality) {
requests.push(
ensureAssetUrl(documentId, asset, {
start: nextOrdinal,
limit: 1,
objectOrdinal: nextOrdinal,
}),
);
}
}
requests.forEach((promise) => promise?.catch?.(() => {}));
};
warmNavigator(singlePreviewNavigator);
warmNavigator(stackPreviewNavigator);
}, [
ensureAssetUrl,
singlePreviewNavigator.documentId,
singlePreviewNavigator.asset,
singlePreviewNavigator.ordinal,
singlePreviewNavigator.canGoPrev,
singlePreviewNavigator.canGoNext,
stackPreviewNavigator.documentId,
stackPreviewNavigator.asset,
stackPreviewNavigator.ordinal,
stackPreviewNavigator.canGoPrev,
stackPreviewNavigator.canGoNext,
]);
const renderSingle = () => { const renderSingle = () => {
if (!singleDoc) { if (!singleDoc) {
return <p className="meta">Select a document to view metadata, tags and actions.</p>; return <p className="meta">Select a document to view metadata, tags and actions.</p>;
} }
const displayName = singleDoc.title || singleDoc.original_name; const displayName = singleDoc.title || singleDoc.original_name;
const downloadHref = singleDoc.current_version?.download_path
? resolveApiPath?.(singleDoc.current_version.download_path)
: null;
const isEditingTitle = titleEditDocId === singleDoc.id; const isEditingTitle = titleEditDocId === singleDoc.id;
const sizeBytes = Number(singleDoc.current_version?.size_bytes) || 0; const sizeBytes = Number(singleDoc.current_version?.size_bytes) || 0;
const sizeLabel = sizeBytes > 0 ? formatFileSize(sizeBytes) : '—'; const sizeLabel = sizeBytes > 0 ? formatFileSize(sizeBytes) : '—';
@@ -743,6 +953,7 @@ const DetailPanel = ({
emptyMessage="Preview loading…" emptyMessage="Preview loading…"
onItemActivate={handlePreviewActivate} onItemActivate={handlePreviewActivate}
onOpenPreview={onOpenPreview} onOpenPreview={onOpenPreview}
onZoomPreview={handleSingleZoom}
activeItemId={activePreviewId} activeItemId={activePreviewId}
/> />
{hasPreviewImage && (effectiveCardinality > 1 || canGoPrev || canGoNext) ? ( {hasPreviewImage && (effectiveCardinality > 1 || canGoPrev || canGoNext) ? (
@@ -857,44 +1068,6 @@ const DetailPanel = ({
{singleDoc.original_name} {singleDoc.original_name}
</div> </div>
</div> </div>
<div className="detail-actions">
<a
className="button-link with-icon"
href={downloadHref || '#'}
target="_blank"
rel="noopener noreferrer"
aria-disabled={!downloadHref}
onClick={(event) => {
if (!downloadHref) {
event.preventDefault();
}
}}
>
<DownloadIcon className="icon-inline" />
<span>Download</span>
</a>
<button
type="button"
className="secondary"
onClick={() => onOpenPreview(singleDoc.id)}
>
Open preview
</button>
<button
type="button"
className="secondary"
onClick={() => onRegenerateThumbnails(singleDoc.id)}
>
Re-run analysis
</button>
</div>
{hasOcrAsset ? (
<div className="detail-ocr-trigger">
<button type="button" className="secondary" onClick={openOcrModal}>
View OCR text
</button>
</div>
) : null}
<TagSection <TagSection
title="Tags" title="Tags"
tags={tagsForDoc.map((tag) => ({ tags={tagsForDoc.map((tag) => ({
@@ -931,7 +1104,7 @@ const DetailPanel = ({
{metadata && ( {metadata && (
<div> <div>
<dt>Metadata</dt> <dt>Metadata</dt>
<pre>{JSON.stringify(metadata, null, 2)}</pre> <pre className="detail-metadata__block">{JSON.stringify(metadata, null, 2)}</pre>
</div> </div>
)} )}
{hasOcrAsset && ocrOpen {hasOcrAsset && ocrOpen
@@ -1002,6 +1175,7 @@ const DetailPanel = ({
emptyMessage="No previews available." emptyMessage="No previews available."
onItemActivate={handlePreviewActivate} onItemActivate={handlePreviewActivate}
onOpenPreview={onOpenPreview} onOpenPreview={onOpenPreview}
onZoomPreview={handleStackZoom}
activeItemId={activePreviewId} activeItemId={activePreviewId}
/> />
{topDocIdLocal && topHasPreview && (topCardinalityLocal > 1 || topCanGoPrev || topCanGoNext) ? ( {topDocIdLocal && topHasPreview && (topCardinalityLocal > 1 || topCanGoPrev || topCanGoNext) ? (
@@ -1074,23 +1248,110 @@ const DetailPanel = ({
showCount showCount
className="bulk-correspondents" className="bulk-correspondents"
/> />
<button
type="button"
className="secondary"
onClick={() => onBulkReanalyze?.()}
>
Re-analyze selection
</button>
</> </>
); );
}; };
const isBulkSelection = selectedCount > 1;
const showOcrAction = Boolean(singleDoc && hasOcrAsset);
return ( return (
<aside className="detail-panel column"> <>
<div className="column-body scrollable"> <aside className="detail-panel panel">
<div className="panel-header">
<div className="panel-actions">
<button
type="button"
className="icon-button ghost"
onClick={onClose}
aria-label="Close detail panel"
title="Close detail panel"
>
<ChevronsRightIcon />
</button>
<div className="spacer" />
{isBulkSelection && onBulkReanalyze ? (
<button
type="button"
className="icon-button ghost"
onClick={(event) => {
event.stopPropagation();
onBulkReanalyze();
}}
aria-label="Re-run analysis for selection"
title="Re-run analysis for selection"
>
<AnalyzeIcon />
</button>
) : null}
{singleDoc && singleDownloadHref ? (
<a
className="icon-button"
href={singleDownloadHref}
target="_blank"
rel="noopener noreferrer"
aria-label="Download document"
title="Download document"
onClick={(event) => event.stopPropagation()}
>
<DownloadIcon />
</a>
) : null}
{singleDoc ? (
<button
type="button"
className="icon-button ghost"
onClick={(event) => {
event.stopPropagation();
onOpenPreview(singleDoc.id);
}}
aria-label="Open preview"
title="Open preview"
disabled={!singleHasPreview}
>
<WindowMaximizeIcon />
</button>
) : null}
{showOcrAction ? (
<button
type="button"
className="icon-button ghost"
onClick={(event) => {
event.stopPropagation();
openOcrModal();
}}
aria-label="View OCR text"
title="View OCR text"
>
<TextScanIcon />
</button>
) : null}
{singleDoc ? (
<button
type="button"
className="icon-button ghost"
onClick={(event) => {
event.stopPropagation();
onRegenerateThumbnails(singleDoc.id);
}}
aria-label="Re-run analysis"
title="Re-run analysis"
>
<AnalyzeIcon />
</button>
) : null}
</div>
</div>
<div className="panel-body">
{selectedCount <= 1 ? renderSingle() : renderBulk()} {selectedCount <= 1 ? renderSingle() : renderBulk()}
</div> </div>
</aside> </aside>
<PreviewZoomOverlay
open={Boolean(zoomDisplay?.url)}
display={zoomDisplay}
onClose={closeZoomPreview}
/>
</>
); );
}; };
+262
View File
@@ -0,0 +1,262 @@
import React, { useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { ArrowLeftIcon, ArrowRightIcon } from '../ui/icons';
const noop = () => {};
const clamp = (value, min, max) => {
if (value < min) return min;
if (value > max) return max;
return value;
};
const ensureDocumentRoot = () => {
if (typeof document === 'undefined') {
return null;
}
return document.body;
};
const PreviewZoomOverlay = ({
open = false,
display = null,
onClose = noop,
}) => {
const portalTarget = ensureDocumentRoot();
const [isNativeScale, setIsNativeScale] = useState(false);
const [naturalSize, setNaturalSize] = useState({ width: null, height: null });
const scrollRef = useRef(null);
const imageRef = useRef(null);
const focusRef = useRef(null);
const previouslyFocusedRef = useRef(null);
useEffect(() => {
setIsNativeScale(false);
setNaturalSize({ width: null, height: null });
focusRef.current = null;
const scrollEl = scrollRef.current;
if (scrollEl) {
scrollEl.scrollLeft = 0;
scrollEl.scrollTop = 0;
}
}, [open]);
useEffect(() => {
if (!open || !isNativeScale) {
return;
}
const scrollEl = scrollRef.current;
const imageEl = imageRef.current;
if (!scrollEl || !imageEl) {
return;
}
const imageWidth = imageEl.naturalWidth || imageEl.clientWidth;
const imageHeight = imageEl.naturalHeight || imageEl.clientHeight;
if (!(imageWidth > 0 && imageHeight > 0)) {
return;
}
const target = focusRef.current || { xRatio: 0.5, yRatio: 0.5 };
const maxScrollLeft = Math.max(0, imageWidth - scrollEl.clientWidth);
const maxScrollTop = Math.max(0, imageHeight - scrollEl.clientHeight);
const desiredLeft = target.xRatio * imageWidth - scrollEl.clientWidth / 2;
const desiredTop = target.yRatio * imageHeight - scrollEl.clientHeight / 2;
scrollEl.scrollLeft = clamp(desiredLeft, 0, maxScrollLeft);
scrollEl.scrollTop = clamp(desiredTop, 0, maxScrollTop);
}, [open, isNativeScale, naturalSize.width, naturalSize.height]);
useEffect(() => {
if (!open) {
if (previouslyFocusedRef.current && typeof previouslyFocusedRef.current.focus === 'function') {
previouslyFocusedRef.current.focus();
}
previouslyFocusedRef.current = null;
return undefined;
}
if (typeof document !== 'undefined') {
const active = document.activeElement;
if (active && typeof active.focus === 'function') {
previouslyFocusedRef.current = active;
} else {
previouslyFocusedRef.current = null;
}
}
const scrollEl = scrollRef.current;
if (!scrollEl) {
return undefined;
}
const frame = requestAnimationFrame(() => {
scrollEl.focus();
});
return () => {
cancelAnimationFrame(frame);
if (previouslyFocusedRef.current && typeof previouslyFocusedRef.current.focus === 'function') {
previouslyFocusedRef.current.focus();
previouslyFocusedRef.current = null;
}
};
}, [open]);
const handleKeyDown = (event) => {
event.stopPropagation();
if (!open) {
return;
}
if (event.key === 'Escape') {
event.preventDefault();
onClose();
return;
}
if (event.key === 'ArrowLeft') {
if (display?.canGoPrev && display?.goPrev) {
event.preventDefault();
display.goPrev();
}
return;
}
if (event.key === 'ArrowRight') {
if (display?.canGoNext && display?.goNext) {
event.preventDefault();
display.goNext();
}
}
};
if (!open || !display?.url || !portalTarget) {
return null;
}
const navVisible = Boolean(display?.canGoPrev || display?.canGoNext);
const stageClassName = [
'preview-zoom__stage',
]
.filter(Boolean)
.join(' ');
const containerClassName = [
'preview-zoom__scroll',
isNativeScale ? 'preview-zoom__scroll--native' : '',
]
.filter(Boolean)
.join(' ');
const imageStyle = isNativeScale
? {
cursor: 'zoom-out',
width: naturalSize.width ? `${naturalSize.width}px` : 'auto',
height: naturalSize.height ? `${naturalSize.height}px` : 'auto',
maxWidth: 'none',
maxHeight: 'none',
}
: {
cursor: 'zoom-in',
maxWidth: '95vw',
maxHeight: '95vh',
};
return createPortal(
(
<div
className="preview-zoom-backdrop"
role="dialog"
aria-modal="true"
aria-label="Enlarged document preview"
onClick={onClose}
>
<div
className={stageClassName}
onClick={(event) => event.stopPropagation()}
onKeyDown={handleKeyDown}
>
<div
className={containerClassName}
ref={scrollRef}
tabIndex={-1}
>
<img
src={display.url}
alt={display.alt || 'Document preview'}
className="preview-zoom__image"
ref={imageRef}
draggable={false}
onLoad={(event) => {
setNaturalSize({
width: event.currentTarget.naturalWidth || null,
height: event.currentTarget.naturalHeight || null,
});
}}
onClick={(event) => {
event.stopPropagation();
if (!isNativeScale) {
const img = imageRef.current;
if (img) {
const rect = img.getBoundingClientRect();
const xRatio = rect.width > 0 ? (event.clientX - rect.left) / rect.width : 0.5;
const yRatio = rect.height > 0 ? (event.clientY - rect.top) / rect.height : 0.5;
focusRef.current = {
xRatio: clamp(xRatio, 0, 1),
yRatio: clamp(yRatio, 0, 1),
};
} else {
focusRef.current = null;
}
} else {
focusRef.current = null;
}
setIsNativeScale((current) => !current);
}}
style={imageStyle}
/>
</div>
{navVisible ? (
<div className="preview-zoom__nav">
<button
type="button"
className="preview-zoom__nav-button"
onClick={(event) => {
event.stopPropagation();
if (display?.canGoPrev && display?.goPrev) {
display.goPrev();
}
}}
aria-label="Previous preview"
disabled={!display?.canGoPrev}
>
<ArrowLeftIcon />
</button>
<button
type="button"
className="preview-zoom__nav-button"
onClick={(event) => {
event.stopPropagation();
if (display?.canGoNext && display?.goNext) {
display.goNext();
}
}}
aria-label="Next preview"
disabled={!display?.canGoNext}
>
<ArrowRightIcon />
</button>
</div>
) : null}
</div>
</div>
),
portalTarget,
);
};
export default PreviewZoomOverlay;
+147 -89
View File
@@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useMemo, useRef } from 'react'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { getAssetFromVersion, resolveDocumentAssetUrl, createAssetView } from '../asset_manager'; import { getAssetFromVersion, resolveDocumentAssetUrl, createAssetView } from '../asset_manager';
import { getTagColorStyle } from '../utils/colors'; import { getTagColorStyle } from '../utils/colors';
import { DownloadIcon, EditIcon, ViewListIcon, ViewGridIcon, FolderIcon } from '../ui/icons'; import { DownloadIcon, EditIcon, ViewListIcon, ViewGridIcon, FolderIcon, TrashIcon } from '../ui/icons';
const TAG_MIME_TYPES = ['application/x-papercrate-tag', 'text/papercrate-tag']; const TAG_MIME_TYPES = ['application/x-papercrate-tag', 'text/papercrate-tag'];
const DEFAULT_GRID_ICON_SIZE = 96; const DEFAULT_GRID_ICON_SIZE = 96;
@@ -13,13 +13,62 @@ const getPageCount = (doc) =>
? doc.current_version.metadata.page_count ? doc.current_version.metadata.page_count
: null; : null;
// Detects when an element becomes visible within a scroll container.
const useLazyVisibility = (rootRef, resetKey) => {
const targetRef = useRef(null);
const [isVisible, setIsVisible] = useState(false);
useEffect(() => {
setIsVisible(false);
}, [resetKey]);
const rootNode = rootRef?.current || null;
useEffect(() => {
if (isVisible) {
return undefined;
}
const element = targetRef.current;
if (!element) {
return undefined;
}
if (typeof window === 'undefined' || typeof IntersectionObserver === 'undefined') {
setIsVisible(true);
return undefined;
}
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setIsVisible(true);
observer.disconnect();
}
});
},
{
root: rootNode,
rootMargin: '200px 0px',
threshold: 0.01,
},
);
observer.observe(element);
return () => observer.disconnect();
}, [isVisible, rootNode, resetKey]);
return { ref: targetRef, isVisible };
};
const DocumentThumbnailImage = ({ const DocumentThumbnailImage = ({
document, document,
ensureAssetUrl, ensureAssetUrl,
getDocumentAsset, getDocumentAsset,
alt, alt,
maxSize = LIST_ICON_SIZE, maxSize = LIST_ICON_SIZE,
scrollRootRef = null,
}) => { }) => {
const { ref: visibilityRef, isVisible } = useLazyVisibility(scrollRootRef, document?.id);
const resolvedMaxSize = Math.max(1, Math.round(maxSize || 1)); const resolvedMaxSize = Math.max(1, Math.round(maxSize || 1));
const thumbnailAsset = useMemo( const thumbnailAsset = useMemo(
() => getAssetFromVersion(document?.current_version, 'thumbnail'), () => getAssetFromVersion(document?.current_version, 'thumbnail'),
@@ -45,14 +94,15 @@ const DocumentThumbnailImage = ({
() => ({ width: `${dimensions.width}px`, height: `${dimensions.height}px` }), () => ({ width: `${dimensions.width}px`, height: `${dimensions.height}px` }),
[dimensions.height, dimensions.width], [dimensions.height, dimensions.width],
); );
const url = useMemo( const url = useMemo(() => {
() => if (!isVisible) {
resolveDocumentAssetUrl(document, 'thumbnail', { return null;
}
return resolveDocumentAssetUrl(document, 'thumbnail', {
ensureAssetUrl, ensureAssetUrl,
getAsset: getDocumentAsset, getAsset: getDocumentAsset,
}), });
[document, ensureAssetUrl, getDocumentAsset], }, [document, ensureAssetUrl, getDocumentAsset, isVisible]);
);
const pageCount = getPageCount(document); const pageCount = getPageCount(document);
const showMultiPageBadge = Number.isFinite(pageCount) && pageCount > 1; const showMultiPageBadge = Number.isFinite(pageCount) && pageCount > 1;
@@ -62,13 +112,15 @@ const DocumentThumbnailImage = ({
} }
return ( return (
<div className="document-thumbnail-wrapper"> <div className="document-thumbnail-wrapper" ref={visibilityRef}>
<div className={innerClasses.join(' ')} style={innerStyle}> <div className={innerClasses.join(' ')} style={innerStyle}>
{url ? ( {url ? (
<img <img
src={url} src={url}
alt={alt || ''} alt={alt || ''}
className="document-thumbnail" className="document-thumbnail"
loading="lazy"
decoding="async"
draggable={false} draggable={false}
onDragStart={(event) => event.preventDefault()} onDragStart={(event) => event.preventDefault()}
/> />
@@ -125,6 +177,7 @@ const DocumentsTable = ({
viewMode = 'list', viewMode = 'list',
onViewModeChange, onViewModeChange,
onClearSelection, onClearSelection,
showHeader = true,
}) => { }) => {
const showingSearchResults = searchResults !== null; const showingSearchResults = searchResults !== null;
const rows = showingSearchResults ? searchResults : documents; const rows = showingSearchResults ? searchResults : documents;
@@ -142,6 +195,18 @@ const DocumentsTable = ({
[draggingDocumentIds], [draggingDocumentIds],
); );
const scrollRef = useRef(null); const scrollRef = useRef(null);
const [, forceVisibilityTick] = useState(0);
const lastScrollNodeRef = useRef(null);
const assignScrollRef = useCallback((node) => {
if (lastScrollNodeRef.current === node) {
return;
}
lastScrollNodeRef.current = node;
scrollRef.current = node;
if (node) {
forceVisibilityTick((value) => value + 1);
}
}, []);
const isGridView = viewMode === 'grid'; const isGridView = viewMode === 'grid';
const gridIconSize = DEFAULT_GRID_ICON_SIZE; const gridIconSize = DEFAULT_GRID_ICON_SIZE;
const handleSetViewMode = useCallback( const handleSetViewMode = useCallback(
@@ -156,6 +221,11 @@ const DocumentsTable = ({
}, },
[onViewModeChange], [onViewModeChange],
); );
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = 0;
}
}, [viewMode]);
const isTagDragEvent = useCallback((event) => { const isTagDragEvent = useCallback((event) => {
const types = Array.from(event.dataTransfer?.types || []); const types = Array.from(event.dataTransfer?.types || []);
return TAG_MIME_TYPES.some((type) => types.includes(type)); return TAG_MIME_TYPES.some((type) => types.includes(type));
@@ -263,16 +333,6 @@ const DocumentsTable = ({
[isTagDragEvent, onDocumentTagDrop], [isTagDragEvent, onDocumentTagDrop],
); );
const handleGridBackgroundClick = useCallback(
(event) => {
if (event.target !== event.currentTarget) {
return;
}
onClearSelection?.();
},
[onClearSelection],
);
const showDefaultEmptyState = !showingSearchResults && !subfolders.length && rows.length === 0; const showDefaultEmptyState = !showingSearchResults && !subfolders.length && rows.length === 0;
const showListSearchEmptyState = const showListSearchEmptyState =
showingSearchResults && rows.length === 0 && !isGridView && !isSearchLoading; showingSearchResults && rows.length === 0 && !isGridView && !isSearchLoading;
@@ -282,35 +342,14 @@ const DocumentsTable = ({
return ( return (
<section <section
className={`documents-panel column documents-panel--view-${isGridView ? 'grid' : 'list'}`} className={`documents-panel documents-panel--view-${isGridView ? 'grid' : 'list'}`}
> >
<div className="column-header"> {showHeader ? (
<div className="column-header__titles"> <div className="panel-section__header">
<nav className="breadcrumb" aria-label="Folder breadcrumbs"> <div className="panel-section__titles">
{breadcrumbs.map((crumb, index) => { <h2>{currentFolderName}</h2>
const isLast = index === breadcrumbs.length - 1;
return (
<span key={crumb.id} className="breadcrumb-item">
{isLast ? (
<span className="breadcrumb-current">{crumb.name}</span>
) : (
<a
href="#"
onClick={(event) => {
event.preventDefault();
onFolderSelect(crumb.id);
}}
>
{crumb.name}
</a>
)}
{!isLast && <span className="breadcrumb-separator"></span>}
</span>
);
})}
</nav>
{showingSearchResults && ( {showingSearchResults && (
<div className="column-subtitle">Search results</div> <div className="panel-section__subtitle">Search results</div>
)} )}
</div> </div>
<div className="header-actions"> <div className="header-actions">
@@ -349,6 +388,7 @@ const DocumentsTable = ({
</button> </button>
</div> </div>
</div> </div>
) : null}
{showDefaultEmptyState && ( {showDefaultEmptyState && (
<div className="empty-state"> <div className="empty-state">
Drop files anywhere or onto a folder to upload documents. Drop files anywhere or onto a folder to upload documents.
@@ -359,9 +399,9 @@ const DocumentsTable = ({
No documents match the current filters. No documents match the current filters.
</div> </div>
)} )}
<div className="column-body"> <div className="panel-section__body">
<div <div
ref={scrollRef} ref={assignScrollRef}
className="documents-scroll" className="documents-scroll"
onFocus={(event) => { onFocus={(event) => {
if (event.target === scrollRef.current) { if (event.target === scrollRef.current) {
@@ -376,13 +416,22 @@ const DocumentsTable = ({
onDocumentListKeyDown(event); onDocumentListKeyDown(event);
} }
}} }}
onClick={(event) => {
if (event.target === event.currentTarget) {
onClearSelection?.();
}
}}
aria-activedescendant={isGridView ? undefined : activeDescendantId} aria-activedescendant={isGridView ? undefined : activeDescendantId}
> >
{showDefaultEmptyState ? null : isGridView ? ( {showDefaultEmptyState ? null : isGridView ? (
<div <div
className="documents-grid" className="documents-grid"
role="list" role="list"
onClick={handleGridBackgroundClick} onClick={(event) => {
if (event.target === event.currentTarget) {
onClearSelection?.();
}
}}
style={{ '--documents-grid-icon-size': `${gridIconSize}px` }} style={{ '--documents-grid-icon-size': `${gridIconSize}px` }}
> >
{!showingSearchResults && {!showingSearchResults &&
@@ -477,6 +526,7 @@ const DocumentsTable = ({
getDocumentAsset={getDocumentAsset} getDocumentAsset={getDocumentAsset}
alt={`Thumbnail for ${doc.title || doc.original_name}`} alt={`Thumbnail for ${doc.title || doc.original_name}`}
maxSize={gridIconSize} maxSize={gridIconSize}
scrollRootRef={scrollRef}
/> />
<div className="document-card__meta"> <div className="document-card__meta">
<div <div
@@ -619,13 +669,20 @@ const DocumentsTable = ({
<td className="doc-list__name"> <td className="doc-list__name">
<div className="doc-list__name-content"> <div className="doc-list__name-content">
<span>{folder.name}</span> <span>{folder.name}</span>
{folder.id !== 'root' && ( </div>
</td>
<td>Folder</td>
<td></td>
<td className="actions">
<div className="action-buttons">
{folder.id !== 'root' && onFolderRename && (
<button <button
type="button" type="button"
className="icon-button ghost doc-list__icon-button" className="icon-button ghost"
title="Rename"
aria-label={`Rename folder ${folder.name}`}
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
if (!onFolderRename) return;
const nextName = window.prompt('Rename folder', folder.name || ''); const nextName = window.prompt('Rename folder', folder.name || '');
if (!nextName) { if (!nextName) {
return; return;
@@ -636,27 +693,23 @@ const DocumentsTable = ({
} }
onFolderRename(folder.id, trimmed); onFolderRename(folder.id, trimmed);
}} }}
title="Rename folder"
aria-label={`Rename folder ${folder.name}`}
> >
<EditIcon className="doc-list__icon" size={16} /> <EditIcon className="icon-inline" />
</button> </button>
)} )}
</div>
</td>
<td>Folder</td>
<td></td>
<td className="actions">
<button <button
type="button" type="button"
className="icon-button danger" className="icon-button danger"
title="Delete"
aria-label={`Delete folder ${folder.name}`}
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
onFolderDelete(folder.id); onFolderDelete(folder.id);
}} }}
> >
Delete <TrashIcon className="icon-inline" />
</button> </button>
</div>
</td> </td>
</tr> </tr>
); );
@@ -690,36 +743,13 @@ const DocumentsTable = ({
ensureAssetUrl={ensureAssetUrl} ensureAssetUrl={ensureAssetUrl}
getDocumentAsset={getDocumentAsset} getDocumentAsset={getDocumentAsset}
alt={`Thumbnail for ${doc.title || doc.original_name}`} alt={`Thumbnail for ${doc.title || doc.original_name}`}
scrollRootRef={scrollRef}
/> />
</td> </td>
<td className="doc-list__name"> <td className="doc-list__name">
<div className="doc-name"> <div className="doc-name">
<div className="doc-list__name-content"> <div className="doc-list__name-content">
<span className="doc-name__title">{doc.title || doc.original_name}</span> <span className="doc-name__title">{doc.title || doc.original_name}</span>
<button
type="button"
className="icon-button ghost doc-list__icon-button"
onClick={(event) => {
event.stopPropagation();
if (!onDocumentRename) return;
const nextName = window.prompt(
'Rename document',
doc.title || doc.original_name || '',
);
if (!nextName) {
return;
}
const trimmed = nextName.trim();
if (!trimmed || trimmed === (doc.title || doc.original_name)) {
return;
}
onDocumentRename(doc.id, trimmed);
}}
title="Rename document"
aria-label={`Rename document ${doc.title || doc.original_name}`}
>
<EditIcon className="doc-list__icon" size={16} />
</button>
</div> </div>
{(doc.tags || []).length > 0 && ( {(doc.tags || []).length > 0 && (
<div className="doc-name__tags"> <div className="doc-name__tags">
@@ -788,31 +818,59 @@ const DocumentsTable = ({
</td> </td>
<td className="actions"> <td className="actions">
<div className="action-buttons"> <div className="action-buttons">
{onDocumentRename && (
<button
type="button"
className="icon-button ghost"
title="Rename"
aria-label={`Rename document ${doc.title || doc.original_name}`}
onClick={(event) => {
event.stopPropagation();
const nextName = window.prompt(
'Rename document',
doc.title || doc.original_name || '',
);
if (!nextName) {
return;
}
const trimmed = nextName.trim();
if (!trimmed || trimmed === (doc.title || doc.original_name)) {
return;
}
onDocumentRename(doc.id, trimmed);
}}
>
<EditIcon className="icon-inline" />
</button>
)}
{downloadHref ? ( {downloadHref ? (
<a <a
className="button-link with-icon" className="icon-button"
href={downloadHref} href={downloadHref}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
title="Download"
aria-label="Download document"
onClick={(event) => event.stopPropagation()} onClick={(event) => event.stopPropagation()}
onAuxClick={(event) => event.stopPropagation()} onAuxClick={(event) => event.stopPropagation()}
onContextMenu={(event) => event.stopPropagation()} onContextMenu={(event) => event.stopPropagation()}
> >
<DownloadIcon className="icon-inline" /> <DownloadIcon className="icon-inline" />
<span>Download</span>
</a> </a>
) : ( ) : (
<span className="meta">No download</span> <span className="meta">No download</span>
)} )}
<button <button
type="button" type="button"
className="danger" className="icon-button danger"
title="Delete"
aria-label="Delete document"
onClick={(event) => { onClick={(event) => {
event.stopPropagation(); event.stopPropagation();
onDocumentDelete?.(doc.id); onDocumentDelete?.(doc.id);
}} }}
> >
Delete <TrashIcon className="icon-inline" />
</button> </button>
</div> </div>
</td> </td>
+356 -150
View File
@@ -1,3 +1,5 @@
import '@fontsource/inter/400.css';
import React, { import React, {
useCallback, useCallback,
useContext, useContext,
@@ -30,6 +32,16 @@ import CorrespondentsPanel from './correspondents/CorrespondentsPanel';
import { CORRESPONDENT_ROLES } from './constants/correspondents'; import { CORRESPONDENT_ROLES } from './constants/correspondents';
import TagManager from './tag_manager'; import TagManager from './tag_manager';
import Sidebar from './sidebar/Sidebar'; import Sidebar from './sidebar/Sidebar';
import {
ChevronsRightIcon,
ChevronsLeftIcon,
ViewListIcon,
ViewGridIcon,
FolderPlusIcon,
RefreshIcon,
ArrowUpIcon,
MinusVerticalIcon,
} from './ui/icons';
import DocumentsTable from './documents/DocumentsTable'; import DocumentsTable from './documents/DocumentsTable';
import { AppShellContext, useAppShell } from './appShellContext'; import { AppShellContext, useAppShell } from './appShellContext';
import DocumentViewerRoute from './routes/DocumentViewerRoute'; import DocumentViewerRoute from './routes/DocumentViewerRoute';
@@ -309,9 +321,9 @@ const LoginView = ({
const DocumentsLayout = ({ sidebarProps, children }) => ( const DocumentsLayout = ({ sidebarProps, children, sidebarCollapsed }) => (
<main className="documents-main"> <main className={`documents-main${sidebarCollapsed ? ' documents-main--sidebar-collapsed' : ''}`}>
<Sidebar {...sidebarProps} /> {!sidebarCollapsed ? <Sidebar {...sidebarProps} /> : null}
{children} {children}
</main> </main>
); );
@@ -335,6 +347,9 @@ const AppLayout = () => {
({ message, variant }) => setStatusMessage(message, variant), ({ message, variant }) => setStatusMessage(message, variant),
[setStatusMessage], [setStatusMessage],
); );
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const collapseSidebar = useCallback(() => setSidebarCollapsed(true), []);
const expandSidebar = useCallback(() => setSidebarCollapsed(false), []);
const reportApiError = useApiError({ const reportApiError = useApiError({
onReport: handleApiReport, onReport: handleApiReport,
}); });
@@ -345,6 +360,8 @@ const AppLayout = () => {
); );
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [isCreateFolderModalOpen, setCreateFolderModalOpen] = useState(false); const [isCreateFolderModalOpen, setCreateFolderModalOpen] = useState(false);
const [isTagsModalOpen, setTagsModalOpen] = useState(false);
const [isCorrespondentsModalOpen, setCorrespondentsModalOpen] = useState(false);
const [newFolderName, setNewFolderName] = useState(''); const [newFolderName, setNewFolderName] = useState('');
const [createFolderError, setCreateFolderError] = useState(''); const [createFolderError, setCreateFolderError] = useState('');
const [creatingFolder, setCreatingFolder] = useState(false); const [creatingFolder, setCreatingFolder] = useState(false);
@@ -366,15 +383,11 @@ const AppLayout = () => {
const stored = window.localStorage.getItem('papercrate_view_mode'); const stored = window.localStorage.getItem('papercrate_view_mode');
return stored === 'grid' ? 'grid' : 'list'; return stored === 'grid' ? 'grid' : 'list';
}); });
const initialRowSelection = routeDocumentId const initialRowSelection = [];
? [resolveDocumentRowKey(routeDocumentId)]
: [];
const [selectedRowKeys, setSelectedRowKeys] = useState(initialRowSelection); const [selectedRowKeys, setSelectedRowKeys] = useState(initialRowSelection);
const [selectionOrder, setSelectionOrder] = useState(initialRowSelection); const [selectionOrder, setSelectionOrder] = useState(initialRowSelection);
const [focusedDocumentId, setFocusedDocumentId] = useState(routeDocumentId); const [focusedDocumentId, setFocusedDocumentId] = useState(null);
const [focusedRowKey, setFocusedRowKey] = useState(() => const [focusedRowKey, setFocusedRowKey] = useState(null);
routeDocumentId ? resolveDocumentRowKey(routeDocumentId) : null,
);
const tokenRef = useRef(token); const tokenRef = useRef(token);
const refreshPromiseRef = useRef(null); const refreshPromiseRef = useRef(null);
const breadcrumbFetchRef = useRef(new Set()); const breadcrumbFetchRef = useRef(new Set());
@@ -423,13 +436,9 @@ const AppLayout = () => {
const documentsRouteMatch = useMatch('/documents'); const documentsRouteMatch = useMatch('/documents');
const documentsFolderRouteMatch = useMatch('/documents/folder/:folderId'); const documentsFolderRouteMatch = useMatch('/documents/folder/:folderId');
const documentsDetailRouteMatch = useMatch('/documents/:documentId'); const documentsDetailRouteMatch = useMatch('/documents/:documentId');
const tagsRouteMatch = useMatch('/tags');
const correspondentsRouteMatch = useMatch('/correspondents');
const isDocumentsRoute = Boolean( const isDocumentsRoute = Boolean(
documentsRouteMatch || documentsFolderRouteMatch || documentsDetailRouteMatch, documentsRouteMatch || documentsFolderRouteMatch || documentsDetailRouteMatch,
); );
const isTagsRoute = Boolean(tagsRouteMatch);
const isCorrespondentsRoute = Boolean(correspondentsRouteMatch);
const toggleTagFilter = useCallback((tagId) => { const toggleTagFilter = useCallback((tagId) => {
if (!tagId) return; if (!tagId) return;
setActiveTagFilters((previous) => setActiveTagFilters((previous) =>
@@ -455,6 +464,10 @@ const AppLayout = () => {
setSearchLoading(false); setSearchLoading(false);
}, []); }, []);
const handleSearchChange = useCallback((value) => {
setSearchQuery(value);
}, []);
const handleSearchSubmit = useCallback(() => { const handleSearchSubmit = useCallback(() => {
if (!navigate) return; if (!navigate) return;
const targetFolder = selectedFolder && selectedFolder !== 'root' ? selectedFolder : 'root'; const targetFolder = selectedFolder && selectedFolder !== 'root' ? selectedFolder : 'root';
@@ -814,14 +827,7 @@ const AppLayout = () => {
if (selectionInitializedRef.current) { if (selectionInitializedRef.current) {
nextDocKeys = previousDocKeys.filter((key) => availableDocKeySet.has(key)); nextDocKeys = previousDocKeys.filter((key) => availableDocKeySet.has(key));
} else { } else {
const filtered = previousDocKeys.filter((key) => availableDocKeySet.has(key)); nextDocKeys = previousDocKeys.filter((key) => availableDocKeySet.has(key));
if (filtered.length) {
nextDocKeys = filtered;
} else if (availableDocKeys.length) {
nextDocKeys = [availableDocKeys[0]];
} else {
nextDocKeys = [];
}
} }
mergedSelection = [...previousFolderKeys, ...nextDocKeys]; mergedSelection = [...previousFolderKeys, ...nextDocKeys];
@@ -3682,6 +3688,24 @@ const AppLayout = () => {
setCreateFolderError(''); setCreateFolderError('');
}, [creatingFolder]); }, [creatingFolder]);
const openTagsModal = useCallback(() => {
setCorrespondentsModalOpen(false);
setTagsModalOpen(true);
}, []);
const closeTagsModal = useCallback(() => {
setTagsModalOpen(false);
}, []);
const openCorrespondentsModal = useCallback(() => {
setTagsModalOpen(false);
setCorrespondentsModalOpen(true);
}, []);
const closeCorrespondentsModal = useCallback(() => {
setCorrespondentsModalOpen(false);
}, []);
const handleCreateFolderSubmit = useCallback( const handleCreateFolderSubmit = useCallback(
async (event) => { async (event) => {
event.preventDefault(); event.preventDefault();
@@ -3742,6 +3766,31 @@ const AppLayout = () => {
}; };
}, [isCreateFolderModalOpen, closeCreateFolderModal]); }, [isCreateFolderModalOpen, closeCreateFolderModal]);
useEffect(() => {
setTagsModalOpen(false);
setCorrespondentsModalOpen(false);
}, [location.pathname]);
useEffect(() => {
if (!isTagsModalOpen && !isCorrespondentsModalOpen) {
return;
}
const handleKeyDown = (event) => {
if (event.key === 'Escape') {
event.preventDefault();
if (isTagsModalOpen) {
closeTagsModal();
} else if (isCorrespondentsModalOpen) {
closeCorrespondentsModal();
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, [isTagsModalOpen, isCorrespondentsModalOpen, closeTagsModal, closeCorrespondentsModal]);
useEffect(() => { useEffect(() => {
if (!token) return undefined; if (!token) return undefined;
@@ -4442,6 +4491,17 @@ const AppLayout = () => {
correspondents, correspondents,
activeCorrespondentIds: activeCorrespondentFilters, activeCorrespondentIds: activeCorrespondentFilters,
onToggleCorrespondentFilter: toggleCorrespondentFilter, onToggleCorrespondentFilter: toggleCorrespondentFilter,
appStatus,
loading,
previewActive,
searchQuery,
onSearchChange: handleSearchChange,
onSearchSubmit: handleSearchSubmit,
onSearchClear: clearFilters,
isFilterActive,
onLogout: handleLogout,
status,
onCollapse: collapseSidebar,
}; };
const resolveThumbnailUrlForDoc = useCallback( const resolveThumbnailUrlForDoc = useCallback(
@@ -4538,6 +4598,7 @@ const AppLayout = () => {
onCorrespondentAdd: handleCorrespondentAdd, onCorrespondentAdd: handleCorrespondentAdd,
onCorrespondentRemove: handleCorrespondentRemove, onCorrespondentRemove: handleCorrespondentRemove,
resolveApiPath, resolveApiPath,
onClose: clearDocumentSelection,
}; };
const skeuoWorkspaceProps = useMemo( const skeuoWorkspaceProps = useMemo(
@@ -4585,7 +4646,6 @@ const AppLayout = () => {
tags, tags,
refreshTags, refreshTags,
handleTagUpdate, handleTagUpdate,
handleTagCreate,
handleTagDelete, handleTagDelete,
handleDocumentTagAttach, handleDocumentTagAttach,
correspondents, correspondents,
@@ -4610,6 +4670,8 @@ const AppLayout = () => {
ensurePreviewData, ensurePreviewData,
notifyApiError, notifyApiError,
resolveApiPath, resolveApiPath,
openTagsModal,
openCorrespondentsModal,
}), }),
[ [
token, token,
@@ -4622,7 +4684,6 @@ const AppLayout = () => {
tags, tags,
refreshTags, refreshTags,
handleTagUpdate, handleTagUpdate,
handleTagCreate,
handleTagDelete, handleTagDelete,
handleDocumentTagAttach, handleDocumentTagAttach,
correspondents, correspondents,
@@ -4647,15 +4708,22 @@ const AppLayout = () => {
ensurePreviewData, ensurePreviewData,
notifyApiError, notifyApiError,
resolveApiPath, resolveApiPath,
openTagsModal,
openCorrespondentsModal,
], ],
); );
if (['logged-out', 'authenticating', 'selecting-tenant'].includes(appStatus)) { if (['logged-out', 'authenticating', 'selecting-tenant'].includes(appStatus)) {
const shouldRememberLastLocation = appStatus !== 'logged-out';
return ( return (
<Navigate <Navigate
to="/account/login" to="/account/login"
replace replace
state={{ from: location.pathname + location.search }} state={
shouldRememberLastLocation
? { from: location.pathname + location.search }
: undefined
}
/> />
); );
} }
@@ -4667,81 +4735,6 @@ const AppLayout = () => {
active={dropOverlayState.active} active={dropOverlayState.active}
folderName={dropOverlayState.folderName} folderName={dropOverlayState.folderName}
/> />
<header className="app-bar">
<div className="app-bar__main">
<div className="app-bar__meta">
<h1>Papercrate</h1>
<span className="app-bar__hint">
{appStatus === 'bootstrapping' && loading
? 'Loading your library…'
: previewActive
? 'Viewing document preview. Press ← Back to return to the library.'
: 'Drag files here to upload.'}
</span>
</div>
<div className="app-bar__search">
<input
type="search"
value={searchQuery}
onChange={(event) => setSearchQuery(event.target.value)}
placeholder="Search documents"
aria-label="Search documents"
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleSearchSubmit();
}
}}
/>
{isFilterActive && (
<button
type="button"
className="app-bar__search-clear"
onClick={clearFilters}
>
Clear
</button>
)}
</div>
<div className="app-bar__right">
<div className="app-bar__links">
<button
type="button"
className={`app-bar__link${isDocumentsRoute ? ' active' : ''}`}
onClick={() => navigate('/documents')}
>
Documents
</button>
<button
type="button"
className={`app-bar__link${isTagsRoute ? ' active' : ''}`}
onClick={() => navigate('/tags')}
>
Tags
<span className="app-bar__link-count">{tags.length}</span>
</button>
<button
type="button"
className={`app-bar__link${isCorrespondentsRoute ? ' active' : ''}`}
onClick={() => navigate('/correspondents')}
>
Correspondents
<span className="app-bar__link-count">{correspondents.length}</span>
</button>
</div>
{status && (
<div className="app-bar__status">
<StatusBanner status={status} />
</div>
)}
<div className="app-bar__actions">
<button className="secondary" onClick={handleLogout}>
Log out
</button>
</div>
</div>
</div>
</header>
<Outlet /> <Outlet />
{isCreateFolderModalOpen && ( {isCreateFolderModalOpen && (
<div <div
@@ -4791,6 +4784,74 @@ const AppLayout = () => {
</div> </div>
</div> </div>
)} )}
{isTagsModalOpen && (
<div
className="modal-backdrop"
role="presentation"
onClick={closeTagsModal}
>
<div
className="modal modal--panel"
role="dialog"
aria-modal="true"
aria-labelledby="tags-modal-title"
onClick={(event) => event.stopPropagation()}
>
<div className="panel-modal__header">
<h3 id="tags-modal-title">Manage Tags</h3>
<button type="button" className="secondary" onClick={closeTagsModal}>
Close
</button>
</div>
<div className="panel-modal__body">
<TagsPanel
tags={tags}
onRefresh={refreshTags}
onCreateTag={handleTagCreate}
onUpdateTag={handleTagUpdate}
onDeleteTag={handleTagDelete}
onNotify={setStatusMessage}
/>
</div>
</div>
</div>
)}
{isCorrespondentsModalOpen && (
<div
className="modal-backdrop"
role="presentation"
onClick={closeCorrespondentsModal}
>
<div
className="modal modal--panel"
role="dialog"
aria-modal="true"
aria-labelledby="correspondents-modal-title"
onClick={(event) => event.stopPropagation()}
>
<div className="panel-modal__header">
<h3 id="correspondents-modal-title">Manage Correspondents</h3>
<button
type="button"
className="secondary"
onClick={closeCorrespondentsModal}
>
Close
</button>
</div>
<div className="panel-modal__body">
<CorrespondentsPanel
correspondents={correspondents}
onRefresh={refreshCorrespondents}
onCreate={handleCorrespondentCreate}
onUpdate={handleCorrespondentUpdate}
onDelete={handleCorrespondentDelete}
onNotify={setStatusMessage}
/>
</div>
</div>
</div>
)}
</div> </div>
</AppShellContext.Provider> </AppShellContext.Provider>
); );
@@ -4803,20 +4864,212 @@ const DocumentsRoute = () => {
detailPanelProps, detailPanelProps,
workspaceMode, workspaceMode,
skeuoWorkspaceProps, skeuoWorkspaceProps,
openTagsModal,
openCorrespondentsModal,
exitSkeuoWorkspace,
} = useAppShell(); } = useAppShell();
const navigate = useNavigate();
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const collapseSidebar = useCallback(() => setSidebarCollapsed(true), []);
const expandSidebar = useCallback(() => setSidebarCollapsed(false), []);
const sidebarPropsWithActions = useMemo(
() => ({
...sidebarProps,
onManageTags: openTagsModal,
onManageCorrespondents: openCorrespondentsModal,
onCollapse: collapseSidebar,
}),
[sidebarProps, openTagsModal, openCorrespondentsModal, collapseSidebar],
);
const {
currentFolderName,
viewMode,
onViewModeChange,
onRequestCreateFolder,
creatingFolder,
onRefresh,
onShowSkeuoWorkspace,
searchResults,
breadcrumbs,
} = documentsTableProps;
const isGridView = viewMode === 'grid';
const showingSearchResults = Array.isArray(searchResults);
const headerTitle = showingSearchResults ? 'Search results' : currentFolderName;
const headerSubtitle = showingSearchResults
? `${searchResults.length} matching document${searchResults.length === 1 ? '' : 's'}`
: null;
const parentBreadcrumb = breadcrumbs && breadcrumbs.length > 1 ? breadcrumbs[breadcrumbs.length - 2] : null;
const handleNavigateParent = parentBreadcrumb
? () => {
const target = parentBreadcrumb.id === 'root'
? '/documents'
: `/documents/folder/${parentBreadcrumb.id}`;
navigate(target);
}
: null;
const detailHasContent = detailPanelProps.selectedDocuments?.length > 0;
const toggleSidebar = sidebarCollapsed ? expandSidebar : collapseSidebar;
const ToggleIcon = sidebarCollapsed ? ChevronsRightIcon : ChevronsLeftIcon;
const toggleLabel = sidebarCollapsed ? 'Expand sidebar' : 'Collapse sidebar';
if (workspaceMode === 'skeuo') { if (workspaceMode === 'skeuo') {
return ( return (
<DocumentsLayout sidebarProps={sidebarProps}> <DocumentsLayout
sidebarProps={sidebarPropsWithActions}
sidebarCollapsed={sidebarCollapsed}
>
<div className="main-content">
<div className="panel-header main-content__header">
<div className="panel-actions main-content__actions">
{sidebarCollapsed ? (
<button
type="button"
className="icon-button ghost"
onClick={toggleSidebar}
aria-label={toggleLabel}
title={toggleLabel}
>
<ToggleIcon />
</button>
) : null}
{parentBreadcrumb ? (
<button
type="button"
className="icon-button ghost"
onClick={handleNavigateParent}
aria-label="Go to parent folder"
title="Go to parent folder"
>
<ArrowUpIcon />
</button>
) : null}
<h2 className="main-content__title">
{headerTitle}
{headerSubtitle ? (
<span className="main-content__subtitle">{headerSubtitle}</span>
) : null}
</h2>
<div className="spacer" />
<button
type="button"
className="icon-button ghost"
onClick={skeuoWorkspaceProps.onRefresh}
aria-label="Refresh"
title="Refresh"
>
<RefreshIcon />
</button>
<button type="button" className="secondary" onClick={exitSkeuoWorkspace}>
Back to List
</button>
</div>
</div>
<div className="main-content__body">
<SkeuomorphicWorkspace {...skeuoWorkspaceProps} /> <SkeuomorphicWorkspace {...skeuoWorkspaceProps} />
</div>
</div>
</DocumentsLayout> </DocumentsLayout>
); );
} }
return ( return (
<DocumentsLayout sidebarProps={sidebarProps}> <DocumentsLayout
<DocumentsTable {...documentsTableProps} /> sidebarProps={sidebarPropsWithActions}
sidebarCollapsed={sidebarCollapsed}
>
<div className={`main-content main-content--documents${detailHasContent ? ' main-content--has-detail' : ''}`}>
<div className="panel-header main-content__header">
<div className="panel-actions main-content__actions">
{sidebarCollapsed ? (
<button
type="button"
className="icon-button ghost"
onClick={toggleSidebar}
aria-label={toggleLabel}
title={toggleLabel}
>
<ToggleIcon />
</button>
) : null}
{parentBreadcrumb ? (
<button
type="button"
className="icon-button ghost"
onClick={handleNavigateParent}
aria-label="Go to parent folder"
title="Go to parent folder"
>
<ArrowUpIcon />
</button>
) : null}
<h2 className="main-content__title">
{headerTitle}
{headerSubtitle ? (
<span className="main-content__subtitle">{headerSubtitle}</span>
) : null}
</h2>
<div className="spacer" />
<div className="view-toggle" role="group" aria-label="Change view">
<button
type="button"
className={`view-toggle__button${isGridView ? '' : ' active'}`}
onClick={() => onViewModeChange?.('list')}
aria-pressed={!isGridView}
title="List view"
>
<ViewListIcon className="view-toggle__icon" size={18} />
</button>
<button
type="button"
className={`view-toggle__button${isGridView ? ' active' : ''}`}
onClick={() => onViewModeChange?.('grid')}
aria-pressed={isGridView}
title="Icons view"
>
<ViewGridIcon className="view-toggle__icon" size={18} />
</button>
</div>
<span className="main-content__actions-divider" aria-hidden="true">
<MinusVerticalIcon />
</span>
<button
type="button"
className="icon-button ghost"
onClick={onRequestCreateFolder}
disabled={creatingFolder}
aria-label={creatingFolder ? 'Creating folder…' : 'Create folder'}
title={creatingFolder ? 'Creating folder…' : 'Create folder'}
>
<FolderPlusIcon />
</button>
<button
type="button"
className="icon-button ghost"
onClick={onRefresh}
aria-label="Refresh"
title="Refresh"
>
<RefreshIcon />
</button>
<button className="secondary" type="button" onClick={onShowSkeuoWorkspace}>
Desk View
</button>
</div>
</div>
<div
className={`main-content__body main-content__body--documents${detailHasContent ? ' main-content__body--has-detail' : ''}`}
>
<DocumentsTable {...documentsTableProps} showHeader={false} />
</div>
{detailHasContent ? (
<DetailPanel {...detailPanelProps} /> <DetailPanel {...detailPanelProps} />
) : null}
</div>
</DocumentsLayout> </DocumentsLayout>
); );
}; };
@@ -4951,51 +5204,6 @@ const LoginRoute = () => {
); );
}; };
function TagsRoute() {
const {
tags,
refreshTags,
handleTagUpdate,
handleTagDelete,
setStatusMessage,
} = useAppShell();
return (
<main className="panels-main">
<TagsPanel
tags={tags}
onRefresh={refreshTags}
onUpdateTag={handleTagUpdate}
onDeleteTag={handleTagDelete}
onNotify={setStatusMessage}
/>
</main>
);
}
function CorrespondentsRoute() {
const {
correspondents,
refreshCorrespondents,
handleCorrespondentCreate,
handleCorrespondentUpdate,
handleCorrespondentDelete,
setStatusMessage,
} = useAppShell();
return (
<main className="panels-main">
<CorrespondentsPanel
correspondents={correspondents}
onRefresh={refreshCorrespondents}
onCreate={handleCorrespondentCreate}
onUpdate={handleCorrespondentUpdate}
onDelete={handleCorrespondentDelete}
onNotify={setStatusMessage}
/>
</main>
);
}
const AppRouter = () => ( const AppRouter = () => (
<Routes> <Routes>
<Route path="/account/login" element={<LoginRoute />} /> <Route path="/account/login" element={<LoginRoute />} />
@@ -5004,8 +5212,6 @@ const AppRouter = () => (
<Route path="/documents" element={<DocumentsRoute />} /> <Route path="/documents" element={<DocumentsRoute />} />
<Route path="/documents/folder/:folderId" element={<DocumentsRoute />} /> <Route path="/documents/folder/:folderId" element={<DocumentsRoute />} />
<Route path="/documents/:documentId" element={<DocumentViewerRoute />} /> <Route path="/documents/:documentId" element={<DocumentViewerRoute />} />
<Route path="/tags" element={<TagsRoute />} />
<Route path="/correspondents" element={<CorrespondentsRoute />} />
<Route path="*" element={<Navigate to="/documents" replace />} /> <Route path="*" element={<Navigate to="/documents" replace />} />
</Route> </Route>
</Routes> </Routes>
+103 -14
View File
@@ -1,5 +1,5 @@
import React, { useCallback, useMemo } from 'react'; import React, { useCallback, useMemo } from 'react';
import { ChevronIcon, TrashIcon, EditIcon, FolderIcon } from '../ui/icons'; import { ChevronIcon, TrashIcon, EditIcon, FolderIcon, ChevronsLeftIcon } from '../ui/icons';
import { getTagColorStyle } from '../utils/colors'; import { getTagColorStyle } from '../utils/colors';
@@ -136,6 +136,19 @@ const Sidebar = ({
correspondents = [], correspondents = [],
activeCorrespondentIds = [], activeCorrespondentIds = [],
onToggleCorrespondentFilter, onToggleCorrespondentFilter,
onManageTags,
onManageCorrespondents,
searchQuery = '',
onSearchChange,
onSearchSubmit,
onSearchClear,
isFilterActive,
appStatus,
loading,
previewActive,
onLogout,
status,
onCollapse,
}) => { }) => {
const sortedCorrespondents = useMemo( const sortedCorrespondents = useMemo(
() => () =>
@@ -150,6 +163,27 @@ const Sidebar = ({
); );
const handleToggleTag = onToggleTagFilter || (() => {}); const handleToggleTag = onToggleTagFilter || (() => {});
const activeTagSet = new Set(activeTagIds); const activeTagSet = new Set(activeTagIds);
const handleManageTags = onManageTags || (() => {});
const handleManageCorrespondents = onManageCorrespondents || (() => {});
const handleSearchInputChange = useCallback(
(event) => {
onSearchChange?.(event.target.value);
},
[onSearchChange],
);
const handleSearchFormSubmit = useCallback(
(event) => {
event.preventDefault();
onSearchSubmit?.();
},
[onSearchSubmit],
);
const handleSearchClear = useCallback(() => {
onSearchClear?.();
}, [onSearchClear]);
const handleLogoutClick = useCallback(() => {
onLogout?.();
}, [onLogout]);
const renderNodes = useCallback( const renderNodes = useCallback(
(ids, depth) => (ids, depth) =>
@@ -193,9 +227,54 @@ const Sidebar = ({
); );
const rootNode = folderNodes.get('root'); const rootNode = folderNodes.get('root');
const hintText = appStatus === 'bootstrapping' && loading
? 'Loading your library…'
: previewActive
? 'Viewing document preview. Press ← Back to return to the library.'
: 'Drag files here to upload.';
return ( return (
<aside className="sidebar column"> <aside className="sidebar">
<div className="panel-header sidebar__header">
<div className="panel-actions">
<h1 className="sidebar__title">Papercrate</h1>
<div className="spacer" />
{onCollapse ? (
<button
type="button"
className="icon-button ghost"
onClick={onCollapse}
aria-label="Collapse sidebar"
title="Collapse sidebar"
>
<ChevronsLeftIcon />
</button>
) : null}
</div>
</div>
<div className="panel-body sidebar__body">
<span className="sidebar__hint">{hintText}</span>
{status && (
<div className="sidebar__status">
<div className={`status-banner ${status.variant}`}>{status.message}</div>
</div>
)}
{onSearchChange && (
<form className="sidebar__search" onSubmit={handleSearchFormSubmit}>
<input
type="search"
value={searchQuery}
onChange={handleSearchInputChange}
placeholder="Search documents"
aria-label="Search documents"
/>
{isFilterActive && (
<button type="button" onClick={handleSearchClear}>
Clear
</button>
)}
</form>
)}
<div className="sidebar-section sidebar-section--folders"> <div className="sidebar-section sidebar-section--folders">
<div className="sidebar-section__header"> <div className="sidebar-section__header">
<h3>Folders</h3> <h3>Folders</h3>
@@ -206,8 +285,14 @@ const Sidebar = ({
</div> </div>
<div className="sidebar-section"> <div className="sidebar-section">
<div className="sidebar-section__header"> <div className="sidebar-section__header">
<button
type="button"
className="sidebar-section__title"
onClick={handleManageTags}
>
<h3>Tags</h3> <h3>Tags</h3>
<span className="meta">{tags.length}</span> <span className="meta">{tags.length}</span>
</button>
</div> </div>
<div <div
className={`sidebar-tag-cloud${ className={`sidebar-tag-cloud${
@@ -215,8 +300,7 @@ const Sidebar = ({
}`} }`}
role="list" role="list"
> >
{tags.length ? ( {tags.map((tag) => {
tags.map((tag) => {
const isActive = activeTagSet.has(tag.id); const isActive = activeTagSet.has(tag.id);
const style = getTagColorStyle(tag.color); const style = getTagColorStyle(tag.color);
const className = `sidebar-tag-pill${isActive ? ' active' : ''}`; const className = `sidebar-tag-pill${isActive ? ' active' : ''}`;
@@ -249,20 +333,22 @@ const Sidebar = ({
{tag.label} {tag.label}
</button> </button>
); );
}) })}
) : (
<span className="meta">No tags yet</span>
)}
</div> </div>
</div> </div>
<div className="sidebar-section"> <div className="sidebar-section">
<div className="sidebar-section__header"> <div className="sidebar-section__header">
<button
type="button"
className="sidebar-section__title"
onClick={handleManageCorrespondents}
>
<h3>Correspondents</h3> <h3>Correspondents</h3>
<span className="meta">{correspondents.length}</span> <span className="meta">{correspondents.length}</span>
</button>
</div> </div>
<ul className="sidebar-correspondent-list"> <ul className="sidebar-correspondent-list">
{sortedCorrespondents.length ? ( {sortedCorrespondents.map((correspondent) => {
sortedCorrespondents.map((correspondent) => {
const isActive = activeCorrespondentSet.has(correspondent.id); const isActive = activeCorrespondentSet.has(correspondent.id);
const className = `sidebar-correspondent-item${isActive ? ' active' : ''}`; const className = `sidebar-correspondent-item${isActive ? ' active' : ''}`;
const label = correspondent.name || 'Unnamed'; const label = correspondent.name || 'Unnamed';
@@ -287,12 +373,15 @@ const Sidebar = ({
</span> </span>
</li> </li>
); );
}) })}
) : (
<li className="meta">No correspondents yet</li>
)}
</ul> </ul>
</div> </div>
<div className="sidebar__footer">
<button className="secondary" type="button" onClick={handleLogoutClick}>
Log out
</button>
</div>
</div>
</aside> </aside>
); );
}; };
-55
View File
@@ -13,57 +13,6 @@
grid-column: 2 / -1; grid-column: 2 / -1;
min-height: 0; min-height: 0;
position: relative; position: relative;
background-color: var(--surface-subtle);
}
.skeuo-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 1rem;
padding: 0.75rem 1rem 0.5rem;
background-color: var(--surface-subtle);
}
.skeuo-header__meta {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.skeuo-header__meta h2 {
margin: 0;
font-size: 1.25rem;
font-weight: 600;
}
.skeuo-breadcrumbs {
display: flex;
flex-wrap: wrap;
gap: 0.35rem;
font-size: 0.85rem;
color: var(--muted);
}
.skeuo-crumb {
display: inline-flex;
align-items: center;
gap: 0.35rem;
}
.skeuo-crumb.is-current {
color: var(--fg);
font-weight: 600;
}
.skeuo-crumb-separator {
opacity: 0.4;
}
.skeuo-header__actions {
display: flex;
align-items: center;
gap: 0.5rem;
} }
.skeuo-canvas { .skeuo-canvas {
@@ -119,10 +68,6 @@
transition: none; transition: none;
} }
.skeuo-item.is-zoomed {
cursor: pointer;
}
.skeuo-item.is-tag-target .skeuo-item__card { .skeuo-item.is-tag-target .skeuo-item__card {
outline: 1em dashed var(--accent); outline: 1em dashed var(--accent);
outline-offset: 1.41em; outline-offset: 1.41em;
+172 -138
View File
@@ -9,6 +9,7 @@ import React, {
import { resolveDocumentAssetUrl, createAssetView } from './asset_manager'; import { resolveDocumentAssetUrl, createAssetView } from './asset_manager';
import { useAssetNavigator } from './hooks/useAssetNavigator'; import { useAssetNavigator } from './hooks/useAssetNavigator';
import { ArrowLeftIcon, ArrowRightIcon } from './ui/icons'; import { ArrowLeftIcon, ArrowRightIcon } from './ui/icons';
import PreviewZoomOverlay from './detail/PreviewZoomOverlay';
import { getReadableTextColor } from './utils/colors'; import { getReadableTextColor } from './utils/colors';
import './skeuomorphic_ws.css'; import './skeuomorphic_ws.css';
@@ -28,9 +29,6 @@ const resolveSizeKey = (doc) =>
const CARD_MIN = 240; const CARD_MIN = 240;
const CARD_MAX = 340; const CARD_MAX = 340;
const EMPTY_CARD_ASPECT = 1.4; const EMPTY_CARD_ASPECT = 1.4;
const ZOOM_FILL_RATIO = 0.99;
const ZOOM_MIN_SCALE = 1.05;
const ZOOM_MAX_SCALE = 5;
const TAG_REMOVE_DISTANCE = 160; const TAG_REMOVE_DISTANCE = 160;
const DEBUG_DRAG = false; const DEBUG_DRAG = false;
@@ -52,6 +50,7 @@ const SkeuoPreviewCard = ({
getDocumentAsset, getDocumentAsset,
navScale = 1, navScale = 1,
prefetch = 3, prefetch = 3,
onNavigatorSnapshot,
}) => { }) => {
const navigator = useAssetNavigator({ const navigator = useAssetNavigator({
document: doc, document: doc,
@@ -62,6 +61,32 @@ const SkeuoPreviewCard = ({
}); });
const { currentUrl, cardinality, canGoPrev, canGoNext } = navigator; const { currentUrl, cardinality, canGoPrev, canGoNext } = navigator;
const docId = doc?.id ?? null;
useEffect(() => {
if (!onNavigatorSnapshot || !docId) {
return undefined;
}
const snapshot = {
url: currentUrl || null,
alt: title,
canGoPrev,
canGoNext,
goPrev: navigator.goPrev,
goNext: navigator.goNext,
};
onNavigatorSnapshot(docId, snapshot);
return () => onNavigatorSnapshot(docId, null);
}, [
docId,
currentUrl,
title,
canGoPrev,
canGoNext,
navigator.goPrev,
navigator.goNext,
onNavigatorSnapshot,
]);
const hasPreview = Boolean(currentUrl); const hasPreview = Boolean(currentUrl);
const cardClasses = ['skeuo-item__card']; const cardClasses = ['skeuo-item__card'];
if (!hasPreview) cardClasses.push('skeuo-item__card--empty'); if (!hasPreview) cardClasses.push('skeuo-item__card--empty');
@@ -303,7 +328,7 @@ const useDocumentDrag = ({
setDraggingId, setDraggingId,
syncLayoutSnapshot, syncLayoutSnapshot,
canvasSize, canvasSize,
toggleZoom, openOverlayForDoc,
}) => { }) => {
const dragStateRef = useRef(null); const dragStateRef = useRef(null);
@@ -330,7 +355,7 @@ const useDocumentDrag = ({
); );
const handlePointerDown = useCallback( const handlePointerDown = useCallback(
(event, docId, { lockWhenZoomed = false } = {}) => { (event, docId) => {
if (DEBUG_DRAG) { if (DEBUG_DRAG) {
console.log( console.log(
'[skeuo] handlePointerDown fired for doc', '[skeuo] handlePointerDown fired for doc',
@@ -376,7 +401,7 @@ const useDocumentDrag = ({
startY: event.clientY, startY: event.clientY,
rotation: entry?.rotation ?? 0, rotation: entry?.rotation ?? 0,
moved: false, moved: false,
locked: Boolean(lockWhenZoomed), locked: false,
width: docWidth, width: docWidth,
height: docHeight, height: docHeight,
scale: baseScale, scale: baseScale,
@@ -475,13 +500,19 @@ const useDocumentDrag = ({
const docId = state.docId; const docId = state.docId;
finishDrag(event.pointerId); finishDrag(event.pointerId);
if (!moved) { if (!moved) {
toggleZoom(docId); const originInfo = {
rotation: state.rotation || 0,
scale: state.scale || 1,
width: state.width,
height: state.height,
};
openOverlayForDoc(docId, originInfo);
} }
return; return;
} }
finishDrag(event.pointerId); finishDrag(event.pointerId);
}, },
[finishDrag, toggleZoom], [finishDrag, openOverlayForDoc],
); );
const handlePointerCancel = useCallback( const handlePointerCancel = useCallback(
@@ -547,10 +578,6 @@ const getContrastingTextColor = (hex) => getReadableTextColor(hex, { light: '#1f
const SkeuomorphicWorkspace = ({ const SkeuomorphicWorkspace = ({
documents = [], documents = [],
searchResults = null, searchResults = null,
breadcrumbs = [],
currentFolderName = 'Folder',
onExit,
onRefresh,
onDocumentOpen, onDocumentOpen,
resolveThumbnailUrl, resolveThumbnailUrl,
onAssignTagToDocument = null, onAssignTagToDocument = null,
@@ -560,7 +587,6 @@ const SkeuomorphicWorkspace = ({
activeTagIds = [], activeTagIds = [],
}) => { }) => {
const items = useMemo(() => (searchResults ? searchResults : documents), [documents, searchResults]); const items = useMemo(() => (searchResults ? searchResults : documents), [documents, searchResults]);
const showingSearchResults = searchResults !== null;
const containerRef = useRef(null); const containerRef = useRef(null);
@@ -572,7 +598,10 @@ const SkeuomorphicWorkspace = ({
const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 }); const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 });
const [draggingId, setDraggingId] = useState(null); const [draggingId, setDraggingId] = useState(null);
const [zoomedId, setZoomedId] = useState(null); const [overlayDocId, setOverlayDocId] = useState(null);
const [overlayOriginRect, setOverlayOriginRect] = useState(null);
const [overlayOriginTransform, setOverlayOriginTransform] = useState(null);
const [previewSnapshots, setPreviewSnapshots] = useState(() => new Map());
const [tagDropTargetId, setTagDropTargetId] = useState(null); const [tagDropTargetId, setTagDropTargetId] = useState(null);
const [pendingTagDocId, setPendingTagDocId] = useState(null); const [pendingTagDocId, setPendingTagDocId] = useState(null);
const [pendingRemovalTag, setPendingRemovalTag] = useState(null); const [pendingRemovalTag, setPendingRemovalTag] = useState(null);
@@ -580,6 +609,36 @@ const SkeuomorphicWorkspace = ({
const pendingDocTagDragRef = useRef(null); const pendingDocTagDragRef = useRef(null);
const docSizeMapRef = useRef(new Map()); const docSizeMapRef = useRef(new Map());
const removalCursorActiveRef = useRef(false); const removalCursorActiveRef = useRef(false);
const handleNavigatorSnapshot = useCallback((docId, snapshot) => {
if (!docId) {
return;
}
setPreviewSnapshots((previous) => {
const prevSnapshot = previous.get(docId);
if (!snapshot) {
if (!previous.has(docId)) {
return previous;
}
const next = new Map(previous);
next.delete(docId);
return next;
}
const next = new Map(previous);
const sameSnapshot =
prevSnapshot &&
prevSnapshot.url === snapshot.url &&
prevSnapshot.alt === snapshot.alt &&
prevSnapshot.canGoPrev === snapshot.canGoPrev &&
prevSnapshot.canGoNext === snapshot.canGoNext &&
prevSnapshot.goPrev === snapshot.goPrev &&
prevSnapshot.goNext === snapshot.goNext;
if (sameSnapshot) {
return previous;
}
next.set(docId, snapshot);
return next;
});
}, []);
const activeTagSet = useMemo(() => { const activeTagSet = useMemo(() => {
if (!Array.isArray(activeTagIds) || activeTagIds.length === 0) { if (!Array.isArray(activeTagIds) || activeTagIds.length === 0) {
return new Set(); return new Set();
@@ -779,70 +838,39 @@ const SkeuomorphicWorkspace = ({
docSizeMapRef.current = new Map(); docSizeMapRef.current = new Map();
}, [items]); }, [items]);
const resolveZoomMetrics = useCallback( const overlayDisplay = useMemo(() => {
(doc, cardWidth, cardHeight) => { if (!overlayDocId) {
const canvasWidth = canvasSize.width || DEFAULT_CANVAS_WIDTH; return null;
const canvasHeight = canvasSize.height || DEFAULT_CANVAS_HEIGHT;
const safeCardWidth = cardWidth || CARD_MIN;
const safeCardHeight = cardHeight || CARD_MIN;
const usableWidth = Math.max(canvasWidth - CANVAS_PADDING * 2, safeCardWidth);
const usableHeight = Math.max(canvasHeight - CANVAS_PADDING * 2, safeCardHeight);
const viewportTargetWidth = usableWidth * ZOOM_FILL_RATIO;
const viewportTargetHeight = usableHeight * ZOOM_FILL_RATIO;
let zoomWidth = safeCardWidth;
let zoomHeight = safeCardHeight;
const previewDims = doc ? resolvePreviewDimensions(doc) : null;
if (previewDims?.width && previewDims?.height) {
const previewWidth = previewDims.width;
const previewHeight = previewDims.height;
const widthScaleLimit = previewWidth > 0 ? viewportTargetWidth / previewWidth : 1;
const heightScaleLimit = previewHeight > 0 ? viewportTargetHeight / previewHeight : 1;
const scaleToFit = Math.min(1, widthScaleLimit || 1, heightScaleLimit || 1);
zoomWidth = previewWidth * scaleToFit;
zoomHeight = previewHeight * scaleToFit;
} else {
const rawScale = Math.min(
viewportTargetWidth / safeCardWidth,
viewportTargetHeight / safeCardHeight,
);
const boundedScale =
rawScale >= 1
? clamp(Math.max(rawScale, ZOOM_MIN_SCALE), ZOOM_MIN_SCALE, ZOOM_MAX_SCALE)
: rawScale;
zoomWidth = safeCardWidth * boundedScale;
zoomHeight = safeCardHeight * boundedScale;
} }
const snapshot = previewSnapshots.get(overlayDocId);
if (!Number.isFinite(zoomWidth) || zoomWidth <= 0) { if (!snapshot || !snapshot.url) {
zoomWidth = safeCardWidth; return null;
} }
if (!Number.isFinite(zoomHeight) || zoomHeight <= 0) { const doc = documentLookup.get(overlayDocId);
zoomHeight = safeCardHeight; const alt = snapshot.alt || doc?.title || doc?.original_name || 'Document preview';
}
zoomWidth = Math.max(zoomWidth, safeCardWidth);
zoomHeight = Math.max(zoomHeight, safeCardHeight);
const zoomTargetX = (canvasWidth - zoomWidth) / 2;
const zoomTargetY = (canvasHeight - zoomHeight) / 2;
const maxX = Math.max(CANVAS_PADDING, canvasWidth - zoomWidth - CANVAS_PADDING);
const maxY = Math.max(CANVAS_PADDING, canvasHeight - zoomHeight - CANVAS_PADDING);
const clampedX = clamp(zoomTargetX, CANVAS_PADDING, maxX);
const clampedY = clamp(zoomTargetY, CANVAS_PADDING, maxY);
const zoomCenterX = clampedX + zoomWidth / 2;
const zoomCenterY = clampedY + zoomHeight / 2;
return { return {
zoomWidth, url: snapshot.url,
zoomHeight, alt,
zoomCenterX, canGoPrev: snapshot.canGoPrev,
zoomCenterY, canGoNext: snapshot.canGoNext,
goPrev: snapshot.goPrev,
goNext: snapshot.goNext,
}; };
}, }, [overlayDocId, previewSnapshots, documentLookup]);
[canvasSize.width, canvasSize.height, resolvePreviewDimensions],
); const closeOverlay = useCallback(() => {
setOverlayDocId(null);
setOverlayOriginRect(null);
setOverlayOriginTransform(null);
}, []);
useEffect(() => {
if (overlayDocId && !documentLookup.has(overlayDocId)) {
setOverlayDocId(null);
setOverlayOriginRect(null);
setOverlayOriginTransform(null);
}
}, [overlayDocId, documentLookup]);
const resolveBaseMetrics = useCallback( const resolveBaseMetrics = useCallback(
(doc, cardWidth, cardHeight) => { (doc, cardWidth, cardHeight) => {
@@ -1014,17 +1042,62 @@ const SkeuomorphicWorkspace = ({
[syncLayoutSnapshot], [syncLayoutSnapshot],
); );
const toggleZoom = useCallback( const openOverlayForDoc = useCallback(
(docId) => { (docId, originInfo = null) => {
setZoomedId((current) => { if (!docId) {
if (current === docId) { return;
return null; }
const snapshot = previewSnapshots.get(docId);
if (!snapshot || !snapshot.url) {
return;
}
const container = itemRefs.current.get(docId);
const imageNode = container?.querySelector?.('.skeuo-item__card img');
if (!container || !imageNode) {
return;
}
const rect = imageNode.getBoundingClientRect();
let originTransform = null;
if (originInfo) {
const { rotation = 0, scale = 1, width: originWidth, height: originHeight } = originInfo;
originTransform = {
rotation,
scaleX: scale,
scaleY: scale,
baseWidth: originWidth,
baseHeight: originHeight,
};
}
if (!originTransform) {
const entry = layoutRef.current.get(docId) || null;
const doc = documentLookup.get(docId) || null;
const { width: cardWidth, height: cardHeight } = ensureDocumentSize(doc);
const { baseWidth, baseHeight, baseScale } = resolveBaseMetrics(doc, cardWidth, cardHeight);
const effectiveWidth = baseWidth * baseScale;
const effectiveHeight = baseHeight * baseScale;
originTransform = {
rotation: entry?.rotation ?? 0,
scaleX: baseScale,
scaleY: baseScale,
baseWidth: Number.isFinite(effectiveWidth) && effectiveWidth > 0 ? effectiveWidth : cardWidth,
baseHeight: Number.isFinite(effectiveHeight) && effectiveHeight > 0 ? effectiveHeight : cardHeight,
};
} }
bringToFront(docId); bringToFront(docId);
return docId; setOverlayOriginRect(rect);
}); setOverlayOriginTransform(originTransform);
setOverlayDocId(docId);
}, },
[bringToFront], [
bringToFront,
previewSnapshots,
itemRefs,
setOverlayOriginTransform,
ensureDocumentSize,
resolveBaseMetrics,
documentLookup,
layoutRef,
],
); );
const { handlePointerDown, handlePointerMove, handlePointerUp, handlePointerCancel } = useDocumentDrag({ const { handlePointerDown, handlePointerMove, handlePointerUp, handlePointerCancel } = useDocumentDrag({
layoutRef, layoutRef,
@@ -1036,7 +1109,7 @@ const SkeuomorphicWorkspace = ({
setDraggingId, setDraggingId,
syncLayoutSnapshot, syncLayoutSnapshot,
canvasSize, canvasSize,
toggleZoom, openOverlayForDoc,
}); });
const handleTagDragEnterDoc = useCallback( const handleTagDragEnterDoc = useCallback(
@@ -1489,40 +1562,9 @@ const SkeuomorphicWorkspace = ({
[queueFocusCanvas, handleTagDragEnd, onRemoveTagFromDocument, updateRemovalCursor], [queueFocusCanvas, handleTagDragEnd, onRemoveTagFromDocument, updateRemovalCursor],
); );
const renderBreadcrumbs = () => {
if (!breadcrumbs.length) return null;
return (
<nav className="skeuo-breadcrumbs" aria-label="Folder breadcrumbs">
{breadcrumbs.map((crumb, index) => {
const isLast = index === breadcrumbs.length - 1;
return (
<span key={crumb.id} className={`skeuo-crumb${isLast ? ' is-current' : ''}`}>
{crumb.name}
{!isLast && <span className="skeuo-crumb-separator"></span>}
</span>
);
})}
</nav>
);
};
return ( return (
<>
<div className="skeuo-shell"> <div className="skeuo-shell">
<header className="skeuo-header">
<div className="skeuo-header__meta">
<h2>{currentFolderName}</h2>
{renderBreadcrumbs()}
{showingSearchResults && <span className="meta">Showing search results</span>}
</div>
<div className="skeuo-header__actions">
<button type="button" className="secondary" onClick={onRefresh}>
Refresh
</button>
<button type="button" onClick={onExit}>
Back to List
</button>
</div>
</header>
<div <div
className="skeuo-canvas" className="skeuo-canvas"
ref={containerRef} ref={containerRef}
@@ -1550,31 +1592,17 @@ const SkeuomorphicWorkspace = ({
typeof layout.centerX === 'number' ? layout.centerX : fallbackLayout.centerX; typeof layout.centerX === 'number' ? layout.centerX : fallbackLayout.centerX;
const layoutCenterY = const layoutCenterY =
typeof layout.centerY === 'number' ? layout.centerY : fallbackLayout.centerY; typeof layout.centerY === 'number' ? layout.centerY : fallbackLayout.centerY;
const isZoomed = zoomedId === doc.id; const rotation = layout.rotation || 0;
const { zoomWidth, zoomHeight, zoomCenterX, zoomCenterY } = resolveZoomMetrics( const zoomScale = baseScale;
doc,
cardWidth,
cardHeight,
);
const targetCenterX = isZoomed ? zoomCenterX : layoutCenterX;
const targetCenterY = isZoomed ? zoomCenterY : layoutCenterY;
const rotation = isZoomed ? 0 : layout.rotation || 0;
const zoomScale = isZoomed
? Math.min(
1,
Number.isFinite(zoomWidth / baseWidth) ? zoomWidth / baseWidth : 1,
Number.isFinite(zoomHeight / baseHeight) ? zoomHeight / baseHeight : 1,
)
: baseScale;
const transform = formatTransform( const transform = formatTransform(
Math.round(targetCenterX), Math.round(layoutCenterX),
Math.round(targetCenterY), Math.round(layoutCenterY),
rotation, rotation,
zoomScale, zoomScale,
); );
const style = { const style = {
transform, transform,
zIndex: isZoomed ? 9999 : layout.z ?? 1, zIndex: layout.z ?? 1,
}; };
const bodyStyle = { const bodyStyle = {
width: Math.round(baseWidth), width: Math.round(baseWidth),
@@ -1595,7 +1623,6 @@ const SkeuomorphicWorkspace = ({
const dropPending = pendingTagDocId === doc.id; const dropPending = pendingTagDocId === doc.id;
const itemClasses = ['skeuo-item']; const itemClasses = ['skeuo-item'];
if (dragging) itemClasses.push('is-dragging'); if (dragging) itemClasses.push('is-dragging');
if (isZoomed) itemClasses.push('is-zoomed');
if (dropActive) itemClasses.push('is-tag-target'); if (dropActive) itemClasses.push('is-tag-target');
if (dropPending) itemClasses.push('is-tag-pending'); if (dropPending) itemClasses.push('is-tag-pending');
if (!matchesFilter) itemClasses.push('is-filtered-out'); if (!matchesFilter) itemClasses.push('is-filtered-out');
@@ -1616,9 +1643,7 @@ const SkeuomorphicWorkspace = ({
itemRefs.current.delete(doc.id); itemRefs.current.delete(doc.id);
} }
}} }}
onPointerDown={(event) => onPointerDown={(event) => handlePointerDown(event, doc.id)}
handlePointerDown(event, doc.id, { lockWhenZoomed: isZoomed })
}
onPointerMove={handlePointerMove} onPointerMove={handlePointerMove}
onPointerUp={handlePointerUp} onPointerUp={handlePointerUp}
onPointerCancel={handlePointerCancel} onPointerCancel={handlePointerCancel}
@@ -1640,6 +1665,7 @@ const SkeuomorphicWorkspace = ({
ensureAssetUrl={ensureAssetUrl} ensureAssetUrl={ensureAssetUrl}
getDocumentAsset={getDocumentAsset} getDocumentAsset={getDocumentAsset}
navScale={inverseTagScale} navScale={inverseTagScale}
onNavigatorSnapshot={handleNavigatorSnapshot}
/> />
{tags.length > 0 && ( {tags.length > 0 && (
<div className="skeuo-item__tags" aria-hidden="true" style={tagsStyle}> <div className="skeuo-item__tags" aria-hidden="true" style={tagsStyle}>
@@ -1687,6 +1713,14 @@ const SkeuomorphicWorkspace = ({
)} )}
</div> </div>
</div> </div>
<PreviewZoomOverlay
open={Boolean(overlayDisplay?.url)}
display={overlayDisplay}
onClose={closeOverlay}
originRect={overlayOriginRect}
originTransform={overlayOriginTransform}
/>
</>
); );
}; };
+589 -363
View File
File diff suppressed because it is too large Load Diff
+86 -8
View File
@@ -1,12 +1,22 @@
import React, { useCallback, useMemo, useState } from 'react'; import React, { useCallback, useMemo, useState } from 'react';
import { getTagColorStyle, HEX_COLOR_PATTERN } from '../utils/colors'; import { getTagColorStyle, HEX_COLOR_PATTERN } from '../utils/colors';
function TagsPanel({ tags, onRefresh, onUpdateTag, onDeleteTag, onNotify }) { function TagsPanel({
tags,
onRefresh,
onCreateTag,
onUpdateTag,
onDeleteTag,
onNotify,
}) {
const [editingId, setEditingId] = useState(null); const [editingId, setEditingId] = useState(null);
const [draftLabel, setDraftLabel] = useState(''); const [draftLabel, setDraftLabel] = useState('');
const [draftColor, setDraftColor] = useState(''); const [draftColor, setDraftColor] = useState('');
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [deletingId, setDeletingId] = useState(null); const [deletingId, setDeletingId] = useState(null);
const [createLabel, setCreateLabel] = useState('');
const [createColor, setCreateColor] = useState('');
const [creating, setCreating] = useState(false);
const startEdit = useCallback((tag) => { const startEdit = useCallback((tag) => {
setEditingId(tag.id); setEditingId(tag.id);
@@ -98,25 +108,93 @@ function TagsPanel({ tags, onRefresh, onUpdateTag, onDeleteTag, onNotify }) {
[onDeleteTag, editingId, cancelEdit, onNotify], [onDeleteTag, editingId, cancelEdit, onNotify],
); );
const handleCreate = useCallback(
async (event) => {
event.preventDefault();
if (typeof onCreateTag !== 'function') {
return;
}
const trimmedLabel = createLabel.trim();
if (!trimmedLabel) {
onNotify?.('Tag label cannot be empty.', 'error');
return;
}
const trimmedColor = createColor.trim();
const colorPattern = /^#([0-9a-fA-F]{6})$/;
if (trimmedColor && !colorPattern.test(trimmedColor)) {
onNotify?.('Colors must use the #RRGGBB format.', 'error');
return;
}
setCreating(true);
try {
await onCreateTag({
label: trimmedLabel,
color: trimmedColor ? trimmedColor : null,
});
setCreateLabel('');
setCreateColor('');
} catch (createError) {
const message = createError?.message || 'Failed to create tag.';
onNotify?.(message, 'error');
} finally {
setCreating(false);
}
},
[createLabel, createColor, onCreateTag, onNotify],
);
return ( return (
<section className="tags-panel column"> <section className="tags-panel">
<div className="column-header"> <div className="panel-section__header">
<div className="column-header__titles"> <div className="panel-section__titles">
<h2>Tags</h2> <h2>Tags</h2>
<div className="column-subtitle">{tags.length} total</div> <div className="panel-section__subtitle">{tags.length} total</div>
</div> </div>
<div className="header-actions"> <div className="header-actions tags-actions">
<form className="tags-actions__form" onSubmit={handleCreate}>
<input
type="text"
placeholder="New tag label"
value={createLabel}
onChange={(event) => setCreateLabel(event.target.value)}
disabled={creating}
/>
<input
type="color"
className="tags-table__color-picker"
value={createColor || '#3366ff'}
onChange={(event) => setCreateColor(event.target.value)}
disabled={creating}
aria-label="Tag color (optional)"
/>
{createColor && (
<button
type="button"
className="secondary"
onClick={() => setCreateColor('')}
disabled={creating}
>
Clear
</button>
)}
<button type="submit" disabled={creating || !createLabel.trim()}>
{creating ? 'Creating…' : 'Create'}
</button>
</form>
<button <button
className="secondary" className="secondary"
type="button" type="button"
onClick={onRefresh} onClick={onRefresh}
disabled={saving || Boolean(deletingId)} disabled={saving || creating || Boolean(deletingId)}
> >
Refresh Refresh
</button> </button>
</div> </div>
</div> </div>
<div className="column-body tags-panel__body"> <div className="panel-section__body tags-panel__body">
{tags.length === 0 ? ( {tags.length === 0 ? (
<div className="empty-state">No tags created yet.</div> <div className="empty-state">No tags created yet.</div>
) : ( ) : (
+98
View File
@@ -9,6 +9,15 @@ import {
IconLayoutGrid, IconLayoutGrid,
IconArrowLeft, IconArrowLeft,
IconArrowRight, IconArrowRight,
IconArrowUp,
IconChevronsRight,
IconChevronsLeft,
IconAnalyze,
IconWindowMaximize,
IconTextScan2,
IconFolderPlus,
IconRefresh,
IconMinusVertical,
} from '@tabler/icons-react'; } from '@tabler/icons-react';
import FolderSvg from '../assets/folder.svg'; import FolderSvg from '../assets/folder.svg';
@@ -120,6 +129,78 @@ export const ArrowRightIcon = ({ className, size = '1em', stroke = 1.6, ...rest
/> />
); );
export const ChevronsLeftIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconChevronsLeft
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const ChevronsRightIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconChevronsRight
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const FolderPlusIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconFolderPlus
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const RefreshIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconRefresh
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const ArrowUpIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconArrowUp
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const MinusVerticalIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconMinusVertical
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const AnalyzeIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconAnalyze
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export const WindowMaximizeIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconWindowMaximize
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
export default { export default {
ChevronIcon, ChevronIcon,
TrashIcon, TrashIcon,
@@ -130,4 +211,21 @@ export default {
DownloadIcon, DownloadIcon,
ViewListIcon, ViewListIcon,
ViewGridIcon, ViewGridIcon,
ChevronsLeftIcon,
ChevronsRightIcon,
AnalyzeIcon,
WindowMaximizeIcon,
FolderPlusIcon,
RefreshIcon,
ArrowUpIcon,
MinusVerticalIcon,
}; };
export const TextScanIcon = ({ className, size = '1em', stroke = 1.6, ...rest }) => (
<IconTextScan2
className={composeClassName('icon', className)}
size={size}
stroke={stroke}
{...rest}
/>
);
@@ -0,0 +1,34 @@
{{- if and .Values.quickwit.enabled .Values.quickwit.indexJob.enabled .Values.quickwit.indexJob.indexConfig.create }}
{{- $cfg := .Values.quickwit.indexJob.indexConfig -}}
{{- $config := dict "value" "" -}}
{{- if $cfg.file }}
{{- with $.Files.Get $cfg.file -}}
{{- $_ := set $config "value" . -}}
{{- end -}}
{{- end -}}
{{- if and (not (index $config "value")) $cfg.contents }}
{{- $_ := set $config "value" $cfg.contents -}}
{{- end -}}
{{- if eq (trim (default "" (index $config "value"))) "" -}}
{{- fail "Quickwit index configuration requires either indexConfig.file or indexConfig.contents" -}}
{{- end }}
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "papercrate.fullname" . }}-quickwit-index
labels:
{{- include "papercrate.labels" . | nindent 4 }}
app.kubernetes.io/component: quickwit
app.kubernetes.io/part-of: quickwit-index
data:
{{ $cfg.key }}: |
{{ index $config "value" | indent 4 }}
{{- $ctx := dict "storageUri" (.Values.quickwit.env.storageUri | default "") -}}
{{- if and (eq (index $ctx "storageUri") "") .Values.global.s3.bucket -}}
{{- $_ := set $ctx "storageUri" (printf "s3://%s/quickwit" .Values.global.s3.bucket) -}}
{{- end -}}
{{- $storageUri := index $ctx "storageUri" -}}
{{- if $storageUri }}
{{ printf "index_uri: %s/documents" (trimSuffix "/" $storageUri) | indent 4 }}
{{- end }}
{{- end }}
@@ -0,0 +1,78 @@
{{- if and .Values.quickwit.enabled .Values.quickwit.indexJob.enabled }}
apiVersion: batch/v1
kind: Job
metadata:
name: {{ include "papercrate.fullname" . }}-quickwit-index
labels:
{{- include "papercrate.labels" . | nindent 4 }}
app.kubernetes.io/component: quickwit-index
annotations:
"helm.sh/hook": post-install,post-upgrade
"helm.sh/hook-delete-policy": before-hook-creation,hook-succeeded
spec:
backoffLimit: {{ .Values.quickwit.indexJob.backoffLimit }}
template:
metadata:
labels:
{{- include "papercrate.selectorLabels" . | nindent 8 }}
app.kubernetes.io/component: quickwit-index
spec:
restartPolicy: Never
{{- if or .Values.global.imagePullSecrets .Values.imagePullSecrets }}
imagePullSecrets:
{{- range .Values.global.imagePullSecrets }}
- name: {{ . }}
{{- end }}
{{- range .Values.imagePullSecrets }}
- name: {{ . }}
{{- end }}
{{- end }}
{{- $qw := dict "storageUri" .Values.quickwit.env.storageUri "metastoreUri" .Values.quickwit.env.metastoreUri -}}
{{- if and (not (index $qw "storageUri")) .Values.global.s3.bucket -}}
{{- $_ := set $qw "storageUri" (printf "s3://%s/quickwit" .Values.global.s3.bucket) -}}
{{- end -}}
{{- if not (index $qw "storageUri") -}}
{{- fail "quickwit.env.storageUri must be set, or provide global.s3.bucket" -}}
{{- end -}}
{{- if and (not (index $qw "metastoreUri")) .Values.postgres.enabled -}}
{{- $dbUser := required "postgres.auth.username is required when postgres.enabled" .Values.postgres.auth.username -}}
{{- $dbPass := required "postgres.auth.password is required when postgres.enabled" .Values.postgres.auth.password -}}
{{- $dbHost := printf "%s-postgres" (include "papercrate.fullname" .) -}}
{{- $_ := set $qw "metastoreUri" (printf "postgres://%s:%s@%s:5432/quickwit" $dbUser $dbPass $dbHost) -}}
{{- end -}}
{{- if not (index $qw "metastoreUri") -}}
{{- fail "quickwit.env.metastoreUri must be set when not using bundled Postgres" -}}
{{- end }}
containers:
- name: quickwit-index
image: {{ include "papercrate.quickwit.image" . }}:{{ include "papercrate.image.tag" (dict "image" .Values.quickwit.image "Chart" .Chart) }}
imagePullPolicy: {{ .Values.quickwit.image.pullPolicy }}
command:
- quickwit
- index
- create
args:
- --index-config=/config/{{ .Values.quickwit.indexJob.indexConfig.key }}
- --endpoint=http://{{ include "papercrate.fullname" . }}-quickwit:{{ .Values.quickwit.service.port }}
{{- if or .Values.quickwit.envFrom .Values.global.s3.credentialsSecret }}
envFrom:
{{- with .Values.global.s3.credentialsSecret }}
- secretRef:
name: {{ . }}
{{- end }}
{{- range .Values.quickwit.envFrom }}
- {{ toYaml . | nindent 12 | trim }}
{{- end }}
{{- end }}
{{- if or .Values.quickwit.indexJob.indexConfig.existingConfigMap .Values.quickwit.indexJob.indexConfig.create }}
volumeMounts:
- name: index-config
mountPath: /config
{{- end }}
{{- if or .Values.quickwit.indexJob.indexConfig.existingConfigMap .Values.quickwit.indexJob.indexConfig.create }}
volumes:
- name: index-config
configMap:
name: {{ if .Values.quickwit.indexJob.indexConfig.existingConfigMap }}{{ .Values.quickwit.indexJob.indexConfig.existingConfigMap }}{{ else }}{{ include "papercrate.fullname" . }}-quickwit-index{{ end }}
{{- end }}
{{- end }}
+10
View File
@@ -141,6 +141,16 @@ quickwit:
nodeSelector: {} nodeSelector: {}
tolerations: [] tolerations: []
affinity: {} affinity: {}
indexJob:
enabled: true
backoffLimit: 3
indexConfig:
existingConfigMap: ""
key: documents-index.yaml
create: true
file: files/quickwit/documents-index.yaml
contents: ""
imagePullSecrets: [] imagePullSecrets: []
nameOverride: "" nameOverride: ""
fullnameOverride: "" fullnameOverride: ""