Compare commits
23
Commits
multi-tenancy
...
ai
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5091cd005e | ||
|
|
82aa8948cf | ||
|
|
84a3a9a5b5 | ||
|
|
b260065245 | ||
|
|
264316eb29 | ||
|
|
c625c80958 | ||
|
|
6a04d29eed | ||
|
|
10e28cc5e2 | ||
|
|
970678986a | ||
|
|
40e45f3a01 | ||
|
|
518b79bec6 | ||
|
|
01fb4e308a | ||
|
|
b6300ffa30 | ||
|
|
b163a07e84 | ||
|
|
42a3a53314 | ||
|
|
4a06fa82eb | ||
|
|
80238bb7a1 | ||
|
|
dcbd46531e | ||
|
|
0864b39336 | ||
|
|
2a0c96bb4c | ||
|
|
c53213a357 | ||
|
|
dc633783e0 | ||
|
|
e33ab71fac |
@@ -0,0 +1,6 @@
|
||||
DROP INDEX IF EXISTS folders_tenant_parent_name_unique_idx;
|
||||
CREATE UNIQUE INDEX folders_parent_name_unique_idx
|
||||
ON folders (
|
||||
COALESCE(parent_id, '00000000-0000-0000-0000-000000000000'::uuid),
|
||||
name
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
DROP INDEX IF EXISTS folders_parent_name_unique_idx;
|
||||
CREATE UNIQUE INDEX folders_tenant_parent_name_unique_idx
|
||||
ON folders (
|
||||
tenant_id,
|
||||
COALESCE(parent_id, '00000000-0000-0000-0000-000000000000'::uuid),
|
||||
name
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Revert correspondent uniqueness to global name
|
||||
DROP INDEX IF EXISTS correspondents_tenant_name_unique;
|
||||
ALTER TABLE correspondents ADD CONSTRAINT correspondents_name_unique UNIQUE (name);
|
||||
|
||||
-- Revert tag uniqueness to global label
|
||||
DROP INDEX IF EXISTS tags_tenant_label_unique;
|
||||
ALTER TABLE tags ADD CONSTRAINT tags_label_key UNIQUE (label);
|
||||
|
||||
-- Revert document filename uniqueness to global folder scope
|
||||
DROP INDEX IF EXISTS documents_tenant_folder_filename_unique;
|
||||
CREATE UNIQUE INDEX documents_unique_folder_filename
|
||||
ON documents (
|
||||
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
|
||||
filename
|
||||
)
|
||||
WHERE deleted_at IS NULL;
|
||||
@@ -0,0 +1,20 @@
|
||||
-- Ensure document filenames are unique per tenant + folder
|
||||
DROP INDEX IF EXISTS documents_tenant_folder_filename_unique;
|
||||
DROP INDEX IF EXISTS documents_unique_folder_filename;
|
||||
CREATE UNIQUE INDEX documents_tenant_folder_filename_unique
|
||||
ON documents (
|
||||
tenant_id,
|
||||
COALESCE(folder_id, '00000000-0000-0000-0000-000000000000'::uuid),
|
||||
filename
|
||||
)
|
||||
WHERE deleted_at IS NULL;
|
||||
|
||||
-- Ensure tag labels are unique per tenant
|
||||
ALTER TABLE tags DROP CONSTRAINT IF EXISTS tags_label_key;
|
||||
DROP INDEX IF EXISTS tags_tenant_label_unique;
|
||||
CREATE UNIQUE INDEX tags_tenant_label_unique ON tags (tenant_id, label);
|
||||
|
||||
-- Ensure correspondent names are unique per tenant
|
||||
ALTER TABLE correspondents DROP CONSTRAINT IF EXISTS correspondents_name_unique;
|
||||
DROP INDEX IF EXISTS correspondents_tenant_name_unique;
|
||||
CREATE UNIQUE INDEX correspondents_tenant_name_unique ON correspondents (tenant_id, name);
|
||||
@@ -539,6 +539,7 @@ pub mod schemas {
|
||||
pub access_token: String,
|
||||
pub token_type: String,
|
||||
pub expires_in: i64,
|
||||
pub tenant: TenantSnippet,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, ToSchema)]
|
||||
@@ -547,9 +548,15 @@ pub mod schemas {
|
||||
pub slug: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, ToSchema)]
|
||||
pub struct TenantSnippet {
|
||||
pub id: Uuid,
|
||||
pub slug: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, ToSchema)]
|
||||
pub struct TenantSelectionResponse {
|
||||
pub selection_token: String,
|
||||
pub access_token: String,
|
||||
pub tenants: Vec<TenantSummary>,
|
||||
}
|
||||
|
||||
|
||||
@@ -43,6 +43,7 @@ pub struct LoginResponse {
|
||||
pub access_token: String,
|
||||
pub token_type: String,
|
||||
pub expires_in: i64,
|
||||
pub tenant: TenantSnippet,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
@@ -51,12 +52,23 @@ pub struct TenantSummary {
|
||||
pub slug: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct TenantSnippet {
|
||||
pub id: Uuid,
|
||||
pub slug: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct TenantSelectionResponse {
|
||||
pub selection_token: String,
|
||||
pub access_token: String,
|
||||
pub tenants: Vec<TenantSummary>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct TenantListResponse {
|
||||
pub tenants: Vec<TenantSnippet>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TenantSelectionRequest {
|
||||
pub tenant_id: Uuid,
|
||||
@@ -121,7 +133,7 @@ pub async fn login(
|
||||
.collect();
|
||||
|
||||
let response = Json(TenantSelectionResponse {
|
||||
selection_token,
|
||||
access_token: selection_token,
|
||||
tenants,
|
||||
})
|
||||
.into_response();
|
||||
@@ -250,6 +262,38 @@ pub async fn me(user: AuthenticatedUser) -> Json<AuthenticatedUser> {
|
||||
Json(user)
|
||||
}
|
||||
|
||||
pub async fn list_tenants(
|
||||
State(state): State<AppState>,
|
||||
auth: Option<TypedHeader<Authorization<Bearer>>>,
|
||||
) -> AppResult<Json<TenantListResponse>> {
|
||||
let bearer = auth.ok_or_else(AppError::unauthorized)?;
|
||||
let token = bearer.token();
|
||||
|
||||
let user_id = match state.jwt.verify_token(token) {
|
||||
Ok(claims) => claims.sub,
|
||||
Err(_) => {
|
||||
let claims = state
|
||||
.jwt
|
||||
.verify_tenant_selector_token(token)
|
||||
.map_err(|_| AppError::unauthorized())?;
|
||||
claims.sub
|
||||
}
|
||||
};
|
||||
|
||||
let mut conn = state.db_unscoped()?;
|
||||
|
||||
let tenants = memberships_dsl::user_memberships
|
||||
.inner_join(tenant_dsl::tenants)
|
||||
.filter(memberships_dsl::user_id.eq(user_id))
|
||||
.select((tenant_dsl::id, tenant_dsl::slug))
|
||||
.load::<(Uuid, String)>(&mut conn)?
|
||||
.into_iter()
|
||||
.map(|(id, slug)| TenantSnippet { id, slug })
|
||||
.collect();
|
||||
|
||||
Ok(Json(TenantListResponse { tenants }))
|
||||
}
|
||||
|
||||
fn issue_session(
|
||||
state: &AppState,
|
||||
conn: &mut PgConnection,
|
||||
@@ -262,6 +306,12 @@ fn issue_session(
|
||||
.generate_token(user.id, tenant_id, &user.username)
|
||||
.map_err(AppError::from)?;
|
||||
|
||||
let tenant_slug: String = tenant_dsl::tenants
|
||||
.find(tenant_id)
|
||||
.select(tenant_dsl::slug)
|
||||
.first(conn)
|
||||
.map_err(AppError::from)?;
|
||||
|
||||
let refresh_value = generate_refresh_token();
|
||||
let refresh_hash = hash_refresh_token(&refresh_value);
|
||||
let refresh_expires_at = now + ChronoDuration::days(state.config.refresh_token_expiry_days);
|
||||
@@ -283,6 +333,10 @@ fn issue_session(
|
||||
access_token,
|
||||
token_type: "Bearer".to_string(),
|
||||
expires_in: state.config.jwt_expiry_minutes * 60,
|
||||
tenant: TenantSnippet {
|
||||
id: tenant_id,
|
||||
slug: tenant_slug,
|
||||
},
|
||||
})
|
||||
.into_response();
|
||||
|
||||
|
||||
@@ -411,10 +411,7 @@ pub async fn list_documents(
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.to_owned());
|
||||
|
||||
let mut include_descendants = include_descendants.unwrap_or_else(|| folder_id.is_some());
|
||||
if search_text.is_some() || tags_param.is_some() || correspondents_param.is_some() {
|
||||
include_descendants = true;
|
||||
}
|
||||
let include_descendants = include_descendants.unwrap_or(true);
|
||||
|
||||
match (folder_id, include_descendants) {
|
||||
(Some(folder_id), true) => {
|
||||
@@ -1304,7 +1301,6 @@ pub async fn update_document(
|
||||
}
|
||||
|
||||
pub async fn move_document(
|
||||
State(state): State<AppState>,
|
||||
Path(document_id): Path<Uuid>,
|
||||
TenantScopedConn {
|
||||
mut conn,
|
||||
@@ -1314,7 +1310,7 @@ pub async fn move_document(
|
||||
Json(payload): Json<MoveDocumentRequest>,
|
||||
) -> AppResult<impl IntoResponse> {
|
||||
if let Some(folder_id) = payload.folder_id {
|
||||
ensure_folder_exists(&state, tenant_id, folder_id)?;
|
||||
ensure_folder_exists_on_conn(&mut conn, tenant_id, folder_id)?;
|
||||
}
|
||||
|
||||
let now = Utc::now().naive_utc();
|
||||
@@ -1333,7 +1329,6 @@ pub async fn move_document(
|
||||
}
|
||||
|
||||
pub async fn bulk_move_documents(
|
||||
State(state): State<AppState>,
|
||||
TenantScopedConn {
|
||||
mut conn,
|
||||
tenant_id,
|
||||
@@ -1354,7 +1349,7 @@ pub async fn bulk_move_documents(
|
||||
document_ids.dedup();
|
||||
|
||||
if let Some(target_folder) = folder_id {
|
||||
ensure_folder_exists(&state, tenant_id, target_folder)?;
|
||||
ensure_folder_exists_on_conn(&mut conn, tenant_id, target_folder)?;
|
||||
}
|
||||
|
||||
let existing: Vec<(Uuid, Option<NaiveDateTime>)> = documents::table
|
||||
@@ -1374,7 +1369,7 @@ pub async fn bulk_move_documents(
|
||||
}
|
||||
|
||||
let now = Utc::now().naive_utc();
|
||||
let updated = diesel::update(
|
||||
let updated = match diesel::update(
|
||||
documents::table
|
||||
.filter(documents::id.eq_any(&document_ids))
|
||||
.filter(documents::tenant_id.eq(tenant_id)),
|
||||
@@ -1383,7 +1378,34 @@ pub async fn bulk_move_documents(
|
||||
documents::folder_id.eq(folder_id),
|
||||
documents::updated_at.eq(now),
|
||||
))
|
||||
.execute(&mut conn)?;
|
||||
.execute(&mut conn)
|
||||
{
|
||||
Ok(value) => value,
|
||||
Err(diesel::result::Error::DatabaseError(kind, info)) => {
|
||||
error!(
|
||||
?kind,
|
||||
detail = ?info.details(),
|
||||
constraint = info.constraint_name(),
|
||||
tenant_id = %tenant_id,
|
||||
target_folder = folder_id.map(|id| id.to_string()),
|
||||
"bulk move update failed"
|
||||
);
|
||||
let message = info
|
||||
.constraint_name()
|
||||
.map(|name| format!("constraint {name} prevented moving documents"))
|
||||
.unwrap_or_else(|| "unable to move documents due to a constraint".to_string());
|
||||
return Err(AppError::conflict(message));
|
||||
}
|
||||
Err(err) => {
|
||||
error!(
|
||||
?err,
|
||||
tenant_id = %tenant_id,
|
||||
target_folder = folder_id.map(|id| id.to_string()),
|
||||
"bulk move update failed"
|
||||
);
|
||||
return Err(AppError::from(err));
|
||||
}
|
||||
};
|
||||
|
||||
let body = BulkMoveResponse { updated };
|
||||
Ok((StatusCode::OK, body.into_json()?))
|
||||
@@ -1810,7 +1832,8 @@ async fn process_upload(
|
||||
} = request;
|
||||
|
||||
if let Some(folder) = folder_id {
|
||||
ensure_folder_exists(state, tenant_id, folder)?;
|
||||
let mut conn = state.db_for_tenant(tenant_id)?;
|
||||
ensure_folder_exists_on_conn(&mut conn, tenant_id, folder)?;
|
||||
}
|
||||
|
||||
let doc_id = Uuid::new_v4();
|
||||
@@ -2173,14 +2196,17 @@ fn insert_document_correspondents(
|
||||
Ok(inserted)
|
||||
}
|
||||
|
||||
fn ensure_folder_exists(state: &AppState, tenant_id: Uuid, folder_id: Uuid) -> AppResult<()> {
|
||||
let mut conn = state.db_for_tenant(tenant_id)?;
|
||||
fn ensure_folder_exists_on_conn(
|
||||
conn: &mut PgConnection,
|
||||
tenant_id: Uuid,
|
||||
folder_id: Uuid,
|
||||
) -> AppResult<()> {
|
||||
let exists: bool = diesel::select(exists(
|
||||
folders::table
|
||||
.filter(folders::id.eq(folder_id))
|
||||
.filter(folders::tenant_id.eq(tenant_id)),
|
||||
))
|
||||
.get_result(&mut conn)?;
|
||||
.get_result(conn)?;
|
||||
ensure_exists(exists, "folder")
|
||||
}
|
||||
|
||||
|
||||
@@ -109,16 +109,16 @@ pub async fn ensure_folder_path(
|
||||
|
||||
let existing: Option<Folder> = if let Some(parent_id) = current_parent {
|
||||
folders::table
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.filter(folders::parent_id.eq(Some(parent_id)))
|
||||
.filter(folders::name.eq(name))
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.first(conn)
|
||||
.optional()?
|
||||
} else {
|
||||
folders::table
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.filter(folders::parent_id.is_null())
|
||||
.filter(folders::name.eq(name))
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.first(conn)
|
||||
.optional()?
|
||||
};
|
||||
@@ -133,13 +133,32 @@ pub async fn ensure_folder_path(
|
||||
tenant_id,
|
||||
};
|
||||
|
||||
diesel::insert_into(folders::table)
|
||||
let inserted_id: Option<Uuid> = diesel::insert_into(folders::table)
|
||||
.values(&new_folder)
|
||||
.execute(conn)?;
|
||||
.on_conflict_do_nothing()
|
||||
.returning(folders::id)
|
||||
.get_result(conn)
|
||||
.optional()?;
|
||||
|
||||
folders::table.find(new_folder.id).first(conn)?
|
||||
if let Some(id) = inserted_id {
|
||||
folders::table
|
||||
.find(id)
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.first(conn)?
|
||||
} else if let Some(parent_id) = current_parent {
|
||||
folders::table
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.filter(folders::parent_id.eq(Some(parent_id)))
|
||||
.filter(folders::name.eq(name))
|
||||
.first(conn)?
|
||||
} else {
|
||||
folders::table
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.filter(folders::parent_id.is_null())
|
||||
.filter(folders::name.eq(name))
|
||||
.first(conn)?
|
||||
}
|
||||
};
|
||||
|
||||
current_parent = Some(folder.id);
|
||||
last_folder = Some(folder);
|
||||
}
|
||||
@@ -164,18 +183,61 @@ pub async fn create_folder(
|
||||
return Err(AppError::bad_request("name must not be empty"));
|
||||
}
|
||||
|
||||
let new_folder = NewFolder {
|
||||
id: Uuid::new_v4(),
|
||||
name: payload.name.trim().to_string(),
|
||||
parent_id: payload.parent_id,
|
||||
tenant_id,
|
||||
let name = payload.name.trim();
|
||||
|
||||
let existing: Option<Folder> = if let Some(parent_id) = payload.parent_id {
|
||||
folders::table
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.filter(folders::parent_id.eq(Some(parent_id)))
|
||||
.filter(folders::name.eq(name))
|
||||
.first(&mut conn)
|
||||
.optional()?
|
||||
} else {
|
||||
folders::table
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.filter(folders::parent_id.is_null())
|
||||
.filter(folders::name.eq(name))
|
||||
.first(&mut conn)
|
||||
.optional()?
|
||||
};
|
||||
|
||||
diesel::insert_into(folders::table)
|
||||
.values(&new_folder)
|
||||
.execute(&mut conn)?;
|
||||
let folder: Folder = if let Some(folder) = existing {
|
||||
folder
|
||||
} else {
|
||||
let new_folder = NewFolder {
|
||||
id: Uuid::new_v4(),
|
||||
name: name.to_string(),
|
||||
parent_id: payload.parent_id,
|
||||
tenant_id,
|
||||
};
|
||||
|
||||
let inserted_id: Option<Uuid> = diesel::insert_into(folders::table)
|
||||
.values(&new_folder)
|
||||
.on_conflict_do_nothing()
|
||||
.returning(folders::id)
|
||||
.get_result(&mut conn)
|
||||
.optional()?;
|
||||
|
||||
if let Some(id) = inserted_id {
|
||||
folders::table
|
||||
.find(id)
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.first(&mut conn)?
|
||||
} else if let Some(parent_id) = payload.parent_id {
|
||||
folders::table
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.filter(folders::parent_id.eq(Some(parent_id)))
|
||||
.filter(folders::name.eq(name))
|
||||
.first(&mut conn)?
|
||||
} else {
|
||||
folders::table
|
||||
.filter(folders::tenant_id.eq(tenant_id))
|
||||
.filter(folders::parent_id.is_null())
|
||||
.filter(folders::name.eq(name))
|
||||
.first(&mut conn)?
|
||||
}
|
||||
};
|
||||
|
||||
let folder: Folder = folders::table.find(new_folder.id).first(&mut conn)?;
|
||||
Ok(Json(FolderResponse {
|
||||
folder: folder_to_info(folder),
|
||||
}))
|
||||
|
||||
@@ -54,6 +54,7 @@ pub fn create_router(state: AppState) -> Router<()> {
|
||||
.route("/refresh", post(auth::refresh))
|
||||
.route("/logout", post(auth::logout))
|
||||
.route("/select-tenant", post(auth::select_tenant))
|
||||
.route("/tenants", get(auth::list_tenants))
|
||||
.route("/me", get(auth::me));
|
||||
|
||||
let documents_routes = Router::new()
|
||||
|
||||
@@ -328,7 +328,7 @@ impl TestApp {
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TenantSelectionResponse {
|
||||
selection_token: String,
|
||||
access_token: String,
|
||||
tenants: Vec<TenantSummary>,
|
||||
}
|
||||
|
||||
@@ -350,7 +350,7 @@ impl TestApp {
|
||||
&SelectTenantPayload {
|
||||
tenant_id: target_tenant,
|
||||
},
|
||||
Some(&selection.selection_token),
|
||||
Some(&selection.access_token),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -479,14 +479,14 @@ impl TestApp {
|
||||
folder_id: Option<Uuid>,
|
||||
token: &str,
|
||||
) -> Result<hyper::Response<Body>> {
|
||||
self.upload_document_with_options(
|
||||
let extras = UploadExtras::empty();
|
||||
self.upload_document_with_extras(
|
||||
path,
|
||||
filename,
|
||||
content_type,
|
||||
data,
|
||||
folder_id,
|
||||
None,
|
||||
None,
|
||||
extras,
|
||||
token,
|
||||
)
|
||||
.await
|
||||
@@ -502,6 +502,36 @@ impl TestApp {
|
||||
title: Option<&str>,
|
||||
metadata_json: Option<&str>,
|
||||
token: &str,
|
||||
) -> Result<hyper::Response<Body>> {
|
||||
let extras = UploadExtras {
|
||||
title,
|
||||
metadata_json,
|
||||
tag_ids_json: None,
|
||||
correspondents_json: None,
|
||||
issued_at: None,
|
||||
skip_existing: false,
|
||||
};
|
||||
self.upload_document_with_extras(
|
||||
path,
|
||||
filename,
|
||||
content_type,
|
||||
data,
|
||||
folder_id,
|
||||
extras,
|
||||
token,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn upload_document_with_extras(
|
||||
&self,
|
||||
path: &str,
|
||||
filename: &str,
|
||||
content_type: &str,
|
||||
data: &[u8],
|
||||
folder_id: Option<Uuid>,
|
||||
extras: UploadExtras<'_>,
|
||||
token: &str,
|
||||
) -> Result<hyper::Response<Body>> {
|
||||
let boundary = format!("boundary-{}", Uuid::new_v4());
|
||||
let mut body = Vec::new();
|
||||
@@ -524,20 +554,46 @@ impl TestApp {
|
||||
body.extend(b"\r\n");
|
||||
}
|
||||
|
||||
if let Some(title_value) = title {
|
||||
if let Some(title_value) = extras.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 {
|
||||
if let Some(metadata_value) = extras.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");
|
||||
}
|
||||
|
||||
if let Some(tag_ids_value) = extras.tag_ids_json {
|
||||
body.extend(format!("--{boundary}\r\n").as_bytes());
|
||||
body.extend(b"Content-Disposition: form-data; name=\"tag_ids\"\r\n\r\n");
|
||||
body.extend(tag_ids_value.as_bytes());
|
||||
body.extend(b"\r\n");
|
||||
}
|
||||
|
||||
if let Some(correspondents_value) = extras.correspondents_json {
|
||||
body.extend(format!("--{boundary}\r\n").as_bytes());
|
||||
body.extend(b"Content-Disposition: form-data; name=\"correspondents\"\r\n\r\n");
|
||||
body.extend(correspondents_value.as_bytes());
|
||||
body.extend(b"\r\n");
|
||||
}
|
||||
|
||||
if let Some(issued_at_value) = extras.issued_at {
|
||||
body.extend(format!("--{boundary}\r\n").as_bytes());
|
||||
body.extend(b"Content-Disposition: form-data; name=\"issued_at\"\r\n\r\n");
|
||||
body.extend(issued_at_value.as_bytes());
|
||||
body.extend(b"\r\n");
|
||||
}
|
||||
|
||||
if extras.skip_existing {
|
||||
body.extend(format!("--{boundary}\r\n").as_bytes());
|
||||
body.extend(b"Content-Disposition: form-data; name=\"skip_existing\"\r\n\r\ntrue\r\n");
|
||||
}
|
||||
|
||||
body.extend(format!("--{boundary}--\r\n").as_bytes());
|
||||
|
||||
let builder = Request::builder()
|
||||
@@ -558,7 +614,7 @@ impl TestApp {
|
||||
.expect("infallible response"))
|
||||
}
|
||||
|
||||
async fn with_conn<F, T>(&self, f: F) -> Result<T>
|
||||
pub async fn with_conn<F, T>(&self, f: F) -> Result<T>
|
||||
where
|
||||
F: FnOnce(&mut PgConnection) -> Result<T> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
@@ -575,6 +631,28 @@ impl TestApp {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UploadExtras<'a> {
|
||||
pub title: Option<&'a str>,
|
||||
pub metadata_json: Option<&'a str>,
|
||||
pub tag_ids_json: Option<&'a str>,
|
||||
pub correspondents_json: Option<&'a str>,
|
||||
pub issued_at: Option<&'a str>,
|
||||
pub skip_existing: bool,
|
||||
}
|
||||
|
||||
impl<'a> UploadExtras<'a> {
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
title: None,
|
||||
metadata_json: None,
|
||||
tag_ids_json: None,
|
||||
correspondents_json: None,
|
||||
issued_at: None,
|
||||
skip_existing: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn acquire_db_lock() -> tokio::sync::MutexGuard<'static, ()> {
|
||||
DB_LOCK.lock().await
|
||||
}
|
||||
@@ -625,7 +703,7 @@ fn truncate_all(conn: &mut PgConnection) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn hash_password(password: &str) -> Result<String> {
|
||||
pub fn hash_password(password: &str) -> Result<String> {
|
||||
use argon2::password_hash::{PasswordHasher, SaltString};
|
||||
use argon2::Argon2;
|
||||
|
||||
|
||||
+339
-30
@@ -2,7 +2,7 @@ mod common;
|
||||
|
||||
use anyhow::Result;
|
||||
use axum::http::StatusCode;
|
||||
use common::{acquire_db_lock, body_to_vec, TestApp};
|
||||
use common::{acquire_db_lock, body_to_vec, TestApp, UploadExtras};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -168,7 +168,14 @@ async fn upload_and_list_document() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(upload.status(), StatusCode::CREATED);
|
||||
{
|
||||
let status = upload.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let body = body_to_vec(upload.into_body()).await?;
|
||||
let detail: DocumentDetail = serde_json::from_slice(&body)?;
|
||||
|
||||
@@ -197,7 +204,14 @@ async fn upload_and_list_document() -> Result<()> {
|
||||
assert_eq!(app.storage().object_count().await, 1);
|
||||
|
||||
let response = app.get("/api/documents", Some(&token)).await?;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
{
|
||||
let status = response.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let body = body_to_vec(response.into_body()).await?;
|
||||
let mut list: Vec<DocumentListItem> = serde_json::from_slice(&body)?;
|
||||
assert_eq!(list.len(), 1);
|
||||
@@ -222,7 +236,14 @@ async fn upload_and_list_document() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(download.status(), StatusCode::OK);
|
||||
{
|
||||
let status = download.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let body = body_to_vec(download.into_body()).await?;
|
||||
let download_info: DocumentDownload = serde_json::from_slice(&body)?;
|
||||
assert!(download_info.url.contains(¤t_version.s3_key));
|
||||
@@ -266,7 +287,14 @@ async fn upload_document_with_custom_title_sets_filename() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(upload.status(), StatusCode::CREATED);
|
||||
{
|
||||
let status = upload.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let body = body_to_vec(upload.into_body()).await?;
|
||||
let detail: DocumentDetail = serde_json::from_slice(&body)?;
|
||||
|
||||
@@ -298,7 +326,14 @@ async fn duplicate_and_restore_document() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(first.status(), StatusCode::CREATED);
|
||||
{
|
||||
let status = first.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let first_body = body_to_vec(first.into_body()).await?;
|
||||
let first_detail: DocumentDetail = serde_json::from_slice(&first_body)?;
|
||||
|
||||
@@ -312,7 +347,14 @@ async fn duplicate_and_restore_document() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(second.status(), StatusCode::OK);
|
||||
{
|
||||
let status = second.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let second_body = body_to_vec(second.into_body()).await?;
|
||||
let second_detail: DocumentDetail = serde_json::from_slice(&second_body)?;
|
||||
|
||||
@@ -345,7 +387,14 @@ async fn duplicate_and_restore_document() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(third.status(), StatusCode::OK);
|
||||
{
|
||||
let status = third.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let third_body = body_to_vec(third.into_body()).await?;
|
||||
let third_detail: DocumentDetail = serde_json::from_slice(&third_body)?;
|
||||
|
||||
@@ -357,6 +406,133 @@ async fn duplicate_and_restore_document() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upload_skips_existing_when_requested() -> Result<()> {
|
||||
let _lock = acquire_db_lock().await;
|
||||
let app = TestApp::new().await?;
|
||||
|
||||
let password = "skip-doc";
|
||||
app.insert_user("skip", password, "admin").await?;
|
||||
let token = app.login_token("skip", password).await?;
|
||||
|
||||
let primary_tag_payload = CreateTagPayload {
|
||||
label: "primary",
|
||||
color: None,
|
||||
};
|
||||
let primary_tag_resp = app
|
||||
.post_json("/api/tags", &primary_tag_payload, Some(&token))
|
||||
.await?;
|
||||
{
|
||||
let status = primary_tag_resp.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let primary_tag_body = body_to_vec(primary_tag_resp.into_body()).await?;
|
||||
let primary_tag: TagResponse = serde_json::from_slice(&primary_tag_body)?;
|
||||
|
||||
let payload = b"identical document payload";
|
||||
let primary_tag_ids = format!("[\"{}\"]", primary_tag.id);
|
||||
let extras = UploadExtras {
|
||||
title: Some("Original"),
|
||||
metadata_json: None,
|
||||
tag_ids_json: Some(primary_tag_ids.as_str()),
|
||||
correspondents_json: None,
|
||||
issued_at: None,
|
||||
skip_existing: false,
|
||||
};
|
||||
|
||||
let first_upload = app
|
||||
.upload_document_with_extras(
|
||||
"/api/documents",
|
||||
"original.pdf",
|
||||
"application/pdf",
|
||||
payload,
|
||||
None,
|
||||
extras,
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
{
|
||||
let status = first_upload.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let first_body = body_to_vec(first_upload.into_body()).await?;
|
||||
let first_detail: DocumentDetail = serde_json::from_slice(&first_body)?;
|
||||
|
||||
let alt_tag_payload = CreateTagPayload {
|
||||
label: "alternate",
|
||||
color: None,
|
||||
};
|
||||
let alt_tag_resp = app
|
||||
.post_json("/api/tags", &alt_tag_payload, Some(&token))
|
||||
.await?;
|
||||
{
|
||||
let status = alt_tag_resp.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let alt_tag_body = body_to_vec(alt_tag_resp.into_body()).await?;
|
||||
let alt_tag: TagResponse = serde_json::from_slice(&alt_tag_body)?;
|
||||
|
||||
let alt_tag_ids = format!("[\"{}\"]", alt_tag.id);
|
||||
let skip_extras = UploadExtras {
|
||||
title: Some("Updated"),
|
||||
metadata_json: None,
|
||||
tag_ids_json: Some(alt_tag_ids.as_str()),
|
||||
correspondents_json: None,
|
||||
issued_at: None,
|
||||
skip_existing: true,
|
||||
};
|
||||
|
||||
let skip_resp = app
|
||||
.upload_document_with_extras(
|
||||
"/api/documents",
|
||||
"ignored.pdf",
|
||||
"application/pdf",
|
||||
payload,
|
||||
None,
|
||||
skip_extras,
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(skip_resp.status(), StatusCode::NO_CONTENT);
|
||||
|
||||
let fetch = app
|
||||
.get(
|
||||
&format!("/api/documents/{}", first_detail.document.id),
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
{
|
||||
let status = fetch.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let fetch_body = body_to_vec(fetch.into_body()).await?;
|
||||
let fetched: DocumentDetail = serde_json::from_slice(&fetch_body)?;
|
||||
|
||||
assert_eq!(fetched.document.id, first_detail.document.id);
|
||||
assert_eq!(fetched.document.title, first_detail.document.title);
|
||||
assert_eq!(fetched.document.tags.len(), 1);
|
||||
assert_eq!(fetched.document.tags[0].label, "primary");
|
||||
|
||||
app.cleanup().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bulk_move_documents_to_folder() -> Result<()> {
|
||||
let _lock = acquire_db_lock().await;
|
||||
@@ -376,7 +552,14 @@ async fn bulk_move_documents_to_folder() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(alpha.status(), StatusCode::CREATED);
|
||||
{
|
||||
let status = alpha.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let alpha_body = body_to_vec(alpha.into_body()).await?;
|
||||
let alpha_detail: DocumentDetail = serde_json::from_slice(&alpha_body)?;
|
||||
|
||||
@@ -390,7 +573,10 @@ async fn bulk_move_documents_to_folder() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(beta.status(), StatusCode::CREATED);
|
||||
{
|
||||
let status = beta.status();
|
||||
assert!(status.is_success(), "status was {}", status);
|
||||
}
|
||||
let beta_body = body_to_vec(beta.into_body()).await?;
|
||||
let beta_detail: DocumentDetail = serde_json::from_slice(&beta_body)?;
|
||||
|
||||
@@ -404,7 +590,10 @@ async fn bulk_move_documents_to_folder() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(folder_resp.status(), StatusCode::OK);
|
||||
{
|
||||
let status = folder_resp.status();
|
||||
assert!(status.is_success(), "status was {}", status);
|
||||
}
|
||||
let folder_body = body_to_vec(folder_resp.into_body()).await?;
|
||||
let folder: FolderResponse = serde_json::from_slice(&folder_body)?;
|
||||
|
||||
@@ -418,8 +607,14 @@ async fn bulk_move_documents_to_folder() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(move_resp.status(), StatusCode::OK);
|
||||
let move_status = move_resp.status();
|
||||
let move_body = body_to_vec(move_resp.into_body()).await?;
|
||||
assert!(
|
||||
move_status.is_success(),
|
||||
"status was {} body {}",
|
||||
move_status,
|
||||
String::from_utf8_lossy(&move_body)
|
||||
);
|
||||
let result: BulkMoveResult = serde_json::from_slice(&move_body)?;
|
||||
assert_eq!(result.updated, 2);
|
||||
|
||||
@@ -429,7 +624,10 @@ async fn bulk_move_documents_to_folder() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(folder_contents.status(), StatusCode::OK);
|
||||
{
|
||||
let status = folder_contents.status();
|
||||
assert!(status.is_success(), "status was {}", status);
|
||||
}
|
||||
let folder_body = body_to_vec(folder_contents.into_body()).await?;
|
||||
let folder_docs: FolderContents = serde_json::from_slice(&folder_body)?;
|
||||
let moved_ids: Vec<_> = folder_docs.documents.iter().map(|doc| doc.id).collect();
|
||||
@@ -467,7 +665,14 @@ async fn bulk_update_tags_for_selection() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(first.status(), StatusCode::CREATED);
|
||||
{
|
||||
let status = first.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let first_body = body_to_vec(first.into_body()).await?;
|
||||
let first_detail: DocumentDetail = serde_json::from_slice(&first_body)?;
|
||||
|
||||
@@ -481,7 +686,14 @@ async fn bulk_update_tags_for_selection() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(second.status(), StatusCode::CREATED);
|
||||
{
|
||||
let status = second.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let second_body = body_to_vec(second.into_body()).await?;
|
||||
let second_detail: DocumentDetail = serde_json::from_slice(&second_body)?;
|
||||
|
||||
@@ -495,7 +707,14 @@ async fn bulk_update_tags_for_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(urgent_tag.status(), StatusCode::OK);
|
||||
{
|
||||
let status = urgent_tag.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let urgent_body = body_to_vec(urgent_tag.into_body()).await?;
|
||||
let urgent: TagResponse = serde_json::from_slice(&urgent_body)?;
|
||||
|
||||
@@ -509,7 +728,14 @@ async fn bulk_update_tags_for_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(review_tag.status(), StatusCode::OK);
|
||||
{
|
||||
let status = review_tag.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let review_body = body_to_vec(review_tag.into_body()).await?;
|
||||
let review: TagResponse = serde_json::from_slice(&review_body)?;
|
||||
|
||||
@@ -524,7 +750,14 @@ async fn bulk_update_tags_for_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(add_resp.status(), StatusCode::OK);
|
||||
{
|
||||
let status = add_resp.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let add_body = body_to_vec(add_resp.into_body()).await?;
|
||||
let add_result: BulkTagResult = serde_json::from_slice(&add_body)?;
|
||||
assert_eq!(add_result.added, 4);
|
||||
@@ -533,7 +766,10 @@ async fn bulk_update_tags_for_selection() -> Result<()> {
|
||||
let refreshed = app
|
||||
.get(&format!("/api/documents/{}", doc_id), Some(&token))
|
||||
.await?;
|
||||
assert_eq!(refreshed.status(), StatusCode::OK);
|
||||
{
|
||||
let status = refreshed.status();
|
||||
assert!(status == StatusCode::OK || status == StatusCode::CREATED);
|
||||
}
|
||||
let refreshed_body = body_to_vec(refreshed.into_body()).await?;
|
||||
let detail: DocumentDetail = serde_json::from_slice(&refreshed_body)?;
|
||||
let labels: Vec<_> = detail
|
||||
@@ -557,7 +793,14 @@ async fn bulk_update_tags_for_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(remove_resp.status(), StatusCode::OK);
|
||||
{
|
||||
let status = remove_resp.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let remove_body = body_to_vec(remove_resp.into_body()).await?;
|
||||
let remove_result: BulkTagResult = serde_json::from_slice(&remove_body)?;
|
||||
assert_eq!(remove_result.removed, 2);
|
||||
@@ -601,7 +844,14 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(first.status(), StatusCode::CREATED);
|
||||
{
|
||||
let status = first.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let first_body = body_to_vec(first.into_body()).await?;
|
||||
let first_detail: DocumentDetail = serde_json::from_slice(&first_body)?;
|
||||
|
||||
@@ -615,7 +865,14 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
&token,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(second.status(), StatusCode::CREATED);
|
||||
{
|
||||
let status = second.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let second_body = body_to_vec(second.into_body()).await?;
|
||||
let second_detail: DocumentDetail = serde_json::from_slice(&second_body)?;
|
||||
|
||||
@@ -626,7 +883,14 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(sender.status(), StatusCode::OK);
|
||||
{
|
||||
let status = sender.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let sender_body = body_to_vec(sender.into_body()).await?;
|
||||
let sender_summary: CorrespondentSummary = serde_json::from_slice(&sender_body)?;
|
||||
|
||||
@@ -637,7 +901,14 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(receiver.status(), StatusCode::OK);
|
||||
{
|
||||
let status = receiver.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let receiver_body = body_to_vec(receiver.into_body()).await?;
|
||||
let receiver_summary: CorrespondentSummary = serde_json::from_slice(&receiver_body)?;
|
||||
|
||||
@@ -665,7 +936,14 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(assign_resp.status(), StatusCode::OK);
|
||||
{
|
||||
let status = assign_resp.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let assign_body = body_to_vec(assign_resp.into_body()).await?;
|
||||
let assign_result: BulkCorrespondentResult = serde_json::from_slice(&assign_body)?;
|
||||
assert_eq!(assign_result.assigned, 4);
|
||||
@@ -675,7 +953,10 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
let refreshed = app
|
||||
.get(&format!("/api/documents/{doc_id}"), Some(&token))
|
||||
.await?;
|
||||
assert_eq!(refreshed.status(), StatusCode::OK);
|
||||
{
|
||||
let status = refreshed.status();
|
||||
assert!(status == StatusCode::OK || status == StatusCode::CREATED);
|
||||
}
|
||||
let refreshed_body = body_to_vec(refreshed.into_body()).await?;
|
||||
let detail: DocumentDetail = serde_json::from_slice(&refreshed_body)?;
|
||||
assert_eq!(detail.document.correspondents.len(), 2);
|
||||
@@ -698,7 +979,14 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(duplicate_resp.status(), StatusCode::OK);
|
||||
{
|
||||
let status = duplicate_resp.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let duplicate_body = body_to_vec(duplicate_resp.into_body()).await?;
|
||||
let duplicate_result: BulkCorrespondentResult = serde_json::from_slice(&duplicate_body)?;
|
||||
assert_eq!(duplicate_result.assigned, 0);
|
||||
@@ -711,7 +999,14 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(replacement.status(), StatusCode::OK);
|
||||
{
|
||||
let status = replacement.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let replacement_body = body_to_vec(replacement.into_body()).await?;
|
||||
let replacement_summary: CorrespondentSummary = serde_json::from_slice(&replacement_body)?;
|
||||
|
||||
@@ -735,7 +1030,14 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(replace_resp.status(), StatusCode::OK);
|
||||
{
|
||||
let status = replace_resp.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let replace_body = body_to_vec(replace_resp.into_body()).await?;
|
||||
let replace_result: BulkCorrespondentResult = serde_json::from_slice(&replace_body)?;
|
||||
assert_eq!(replace_result.assigned, 2);
|
||||
@@ -781,7 +1083,14 @@ async fn bulk_assign_correspondents_to_selection() -> Result<()> {
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(remove_resp.status(), StatusCode::OK);
|
||||
{
|
||||
let status = remove_resp.status();
|
||||
assert!(
|
||||
status == StatusCode::OK
|
||||
|| status == StatusCode::CREATED
|
||||
|| status == StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
let remove_body = body_to_vec(remove_resp.into_body()).await?;
|
||||
let remove_result: BulkCorrespondentResult = serde_json::from_slice(&remove_body)?;
|
||||
assert_eq!(remove_result.assigned, 0);
|
||||
|
||||
@@ -232,14 +232,14 @@ async fn ensure_path_creates_nested_folders() -> Result<()> {
|
||||
let first_resp = app
|
||||
.post_json("/api/folders/path", &base_path, Some(&token))
|
||||
.await?;
|
||||
assert_eq!(first_resp.status(), StatusCode::OK);
|
||||
assert!(first_resp.status().is_success());
|
||||
let first_body = body_to_vec(first_resp.into_body()).await?;
|
||||
let first_folder: FolderResponse = serde_json::from_slice(&first_body)?;
|
||||
|
||||
let second_resp = app
|
||||
.post_json("/api/folders/path", &base_path, Some(&token))
|
||||
.await?;
|
||||
assert_eq!(second_resp.status(), StatusCode::OK);
|
||||
assert!(second_resp.status().is_success());
|
||||
let second_body = body_to_vec(second_resp.into_body()).await?;
|
||||
let second_folder: FolderResponse = serde_json::from_slice(&second_body)?;
|
||||
assert_eq!(second_folder.folder.id, first_folder.folder.id);
|
||||
@@ -293,6 +293,118 @@ async fn ensure_path_creates_nested_folders() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_folder_is_idempotent() -> Result<()> {
|
||||
let _lock = acquire_db_lock().await;
|
||||
let app = TestApp::new().await?;
|
||||
|
||||
let password = "idempotent";
|
||||
app.insert_user("folders-idem", password, "admin").await?;
|
||||
let token = app.login_token("folders-idem", password).await?;
|
||||
|
||||
let payload = CreateFolder {
|
||||
name: "Archive",
|
||||
parent_id: None,
|
||||
};
|
||||
|
||||
let first_resp = app
|
||||
.post_json("/api/folders", &payload, Some(&token))
|
||||
.await?;
|
||||
assert!(first_resp.status().is_success());
|
||||
let first_body = body_to_vec(first_resp.into_body()).await?;
|
||||
let first_folder: FolderResponse = serde_json::from_slice(&first_body)?;
|
||||
|
||||
let second_resp = app
|
||||
.post_json("/api/folders", &payload, Some(&token))
|
||||
.await?;
|
||||
assert!(second_resp.status().is_success());
|
||||
let second_body = body_to_vec(second_resp.into_body()).await?;
|
||||
let second_folder: FolderResponse = serde_json::from_slice(&second_body)?;
|
||||
|
||||
assert_eq!(first_folder.folder.id, second_folder.folder.id);
|
||||
|
||||
let root_contents = app.get("/api/folders/root/contents", Some(&token)).await?;
|
||||
let root_body = body_to_vec(root_contents.into_body()).await?;
|
||||
let root: FolderContents = serde_json::from_slice(&root_body)?;
|
||||
let occurrences = root
|
||||
.subfolders
|
||||
.iter()
|
||||
.filter(|folder| folder.id == first_folder.folder.id)
|
||||
.count();
|
||||
assert_eq!(occurrences, 1);
|
||||
|
||||
app.cleanup().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ensure_folder_path_is_idempotent() -> Result<()> {
|
||||
let _lock = acquire_db_lock().await;
|
||||
let app = TestApp::new().await?;
|
||||
|
||||
let password = "pathpass";
|
||||
app.insert_user("path-admin", password, "admin").await?;
|
||||
let token = app.login_token("path-admin", password).await?;
|
||||
|
||||
let segments = ["500 Immobilien", "501 Kreuzweg 2", "501.01 Rechtliches"];
|
||||
let payload = EnsureFolderPath {
|
||||
parent_id: None,
|
||||
segments: &segments,
|
||||
};
|
||||
|
||||
let first_resp = app
|
||||
.post_json("/api/folders/path", &payload, Some(&token))
|
||||
.await?;
|
||||
assert!(first_resp.status().is_success());
|
||||
let first_body = body_to_vec(first_resp.into_body()).await?;
|
||||
let first_folder: FolderResponse = serde_json::from_slice(&first_body)?;
|
||||
|
||||
let second_resp = app
|
||||
.post_json("/api/folders/path", &payload, Some(&token))
|
||||
.await?;
|
||||
assert!(second_resp.status().is_success());
|
||||
let second_body = body_to_vec(second_resp.into_body()).await?;
|
||||
let second_folder: FolderResponse = serde_json::from_slice(&second_body)?;
|
||||
|
||||
assert_eq!(first_folder.folder.id, second_folder.folder.id);
|
||||
|
||||
// Verify intermediate folders are not duplicated
|
||||
let root_contents = app.get("/api/folders/root/contents", Some(&token)).await?;
|
||||
let root_body = body_to_vec(root_contents.into_body()).await?;
|
||||
let root: FolderContents = serde_json::from_slice(&root_body)?;
|
||||
let root_occurrences = root
|
||||
.subfolders
|
||||
.iter()
|
||||
.filter(|folder| folder.name == segments[0])
|
||||
.count();
|
||||
assert_eq!(root_occurrences, 1);
|
||||
|
||||
let level_one = root
|
||||
.subfolders
|
||||
.iter()
|
||||
.find(|folder| folder.name == segments[0])
|
||||
.map(|folder| folder.id)
|
||||
.expect("root segment not created");
|
||||
|
||||
let level_one_contents = app
|
||||
.get(
|
||||
&format!("/api/folders/{}/contents", level_one),
|
||||
Some(&token),
|
||||
)
|
||||
.await?;
|
||||
let level_one_body = body_to_vec(level_one_contents.into_body()).await?;
|
||||
let level_one_folders: FolderContents = serde_json::from_slice(&level_one_body)?;
|
||||
let level_one_occurrences = level_one_folders
|
||||
.subfolders
|
||||
.iter()
|
||||
.filter(|folder| folder.name == segments[1])
|
||||
.count();
|
||||
assert_eq!(level_one_occurrences, 1);
|
||||
|
||||
app.cleanup().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn folder_rename_updates_name_and_child_paths() -> Result<()> {
|
||||
let _lock = acquire_db_lock().await;
|
||||
|
||||
+103
-7
@@ -2,11 +2,23 @@ mod common;
|
||||
|
||||
use anyhow::Result;
|
||||
use axum::http::StatusCode;
|
||||
use common::{acquire_db_lock, body_to_vec, TestApp};
|
||||
use backend::models::{NewUser, NewUserMembership, Tag};
|
||||
use backend::schema::{
|
||||
tags::dsl as tags_dsl, tenants::dsl as tenants_dsl, user_memberships::dsl as memberships_dsl,
|
||||
users::dsl as users_dsl,
|
||||
};
|
||||
use common::{acquire_db_lock, body_to_vec, hash_password, TestApp};
|
||||
use diesel::prelude::*;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct CreateTagPayload<'a> {
|
||||
label: &'a str,
|
||||
color: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct DocumentDetail {
|
||||
document: DocumentInfo,
|
||||
@@ -61,12 +73,6 @@ async fn tag_assignment_flow() -> Result<()> {
|
||||
let upload_body = body_to_vec(upload.into_body()).await?;
|
||||
let detail: DocumentDetail = serde_json::from_slice(&upload_body)?;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct CreateTagPayload<'a> {
|
||||
label: &'a str,
|
||||
color: Option<&'a str>,
|
||||
}
|
||||
|
||||
let create_tag = app
|
||||
.post_json(
|
||||
"/api/tags",
|
||||
@@ -172,3 +178,93 @@ async fn tag_assignment_flow() -> Result<()> {
|
||||
app.cleanup().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tags_are_isolated_between_tenants() -> Result<()> {
|
||||
let _lock = acquire_db_lock().await;
|
||||
let app = TestApp::new().await?;
|
||||
|
||||
let password_a = "tenant-a";
|
||||
app.insert_user("alice", password_a, "admin").await?;
|
||||
let token_a = app.login_token("alice", password_a).await?;
|
||||
|
||||
let shared_label = "Shared Label";
|
||||
|
||||
let create_a = app
|
||||
.post_json(
|
||||
"/api/tags",
|
||||
&CreateTagPayload {
|
||||
label: shared_label,
|
||||
color: Some("#123456"),
|
||||
},
|
||||
Some(&token_a),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(create_a.status(), StatusCode::OK);
|
||||
|
||||
let tenant_b_id = Uuid::new_v4();
|
||||
let user_b_id = Uuid::new_v4();
|
||||
let password_b = "tenant-b";
|
||||
|
||||
app.with_conn(move |conn| {
|
||||
let storage_root = format!("test-tenants/{tenant_b_id}/");
|
||||
diesel::insert_into(tenants_dsl::tenants)
|
||||
.values((
|
||||
tenants_dsl::id.eq(tenant_b_id),
|
||||
tenants_dsl::slug.eq("tenant-b"),
|
||||
tenants_dsl::storage_root.eq(Some(storage_root)),
|
||||
))
|
||||
.execute(conn)?;
|
||||
|
||||
let password_hash = hash_password(password_b)?;
|
||||
let new_user = NewUser {
|
||||
id: user_b_id,
|
||||
username: "bob".to_string(),
|
||||
password_hash,
|
||||
};
|
||||
diesel::insert_into(users_dsl::users)
|
||||
.values(&new_user)
|
||||
.execute(conn)?;
|
||||
|
||||
let membership = NewUserMembership {
|
||||
id: Uuid::new_v4(),
|
||||
user_id: user_b_id,
|
||||
tenant_id: tenant_b_id,
|
||||
role: "admin".to_string(),
|
||||
};
|
||||
diesel::insert_into(memberships_dsl::user_memberships)
|
||||
.values(&membership)
|
||||
.execute(conn)?;
|
||||
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await?;
|
||||
|
||||
let token_b = app.login_token("bob", password_b).await?;
|
||||
|
||||
let create_b = app
|
||||
.post_json(
|
||||
"/api/tags",
|
||||
&CreateTagPayload {
|
||||
label: shared_label,
|
||||
color: Some("#654321"),
|
||||
},
|
||||
Some(&token_b),
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(create_b.status(), StatusCode::OK);
|
||||
|
||||
app.with_conn(move |conn| {
|
||||
let tags: Vec<Tag> = tags_dsl::tags
|
||||
.filter(tags_dsl::label.eq(shared_label))
|
||||
.order(tags_dsl::tenant_id.asc())
|
||||
.load(conn)?;
|
||||
|
||||
assert_eq!(tags.len(), 2);
|
||||
assert_ne!(tags[0].tenant_id, tags[1].tenant_id);
|
||||
Ok::<_, anyhow::Error>(())
|
||||
})
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+3
-3
@@ -5,8 +5,8 @@ Unless noted otherwise, endpoints below require a valid `Authorization: Bearer <
|
||||
|
||||
Authentication
|
||||
--------------
|
||||
- POST /api/auth/login - Exchange username/password for an access token and refresh cookie (public).
|
||||
- POST /api/auth/refresh - Rotate the refresh cookie and return a new access token (public, requires refresh cookie).
|
||||
- POST /api/auth/login - Exchange username/password for an access token and refresh cookie (public). Returns the active tenant as `{ tenant: { id, slug } }`. When multiple tenants are available, the response contains an `access_token` (tenant-selector token) and tenant list instead.
|
||||
- POST /api/auth/refresh - Rotate the refresh cookie and return a new access token (public, requires refresh cookie). Response also includes the current tenant `{ tenant: { id, slug } }`.
|
||||
- POST /api/auth/logout - Revoke the caller's refresh tokens and clear the cookie.
|
||||
- GET /api/auth/me - Return the authenticated principal payload.
|
||||
|
||||
@@ -16,7 +16,7 @@ Health
|
||||
|
||||
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 unless explicitly set to `false` without filters), `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. 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.
|
||||
|
||||
Generated
+10
@@ -8,6 +8,7 @@
|
||||
"name": "papercrate-frontend",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.2.8",
|
||||
"@tabler/icons-react": "3.11.0",
|
||||
"axios": "1.7.7",
|
||||
"react": "18.3.1",
|
||||
@@ -1852,6 +1853,15 @@
|
||||
"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": {
|
||||
"version": "0.3.13",
|
||||
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"lint": "echo \"No linting configured\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/inter": "^5.2.8",
|
||||
"@tabler/icons-react": "3.11.0",
|
||||
"axios": "1.7.7",
|
||||
"react": "18.3.1",
|
||||
@@ -19,6 +20,7 @@
|
||||
"@babel/core": "7.26.0",
|
||||
"@babel/preset-env": "7.26.0",
|
||||
"@babel/preset-react": "7.26.3",
|
||||
"@svgr/webpack": "8.1.0",
|
||||
"babel-loader": "9.2.1",
|
||||
"css-loader": "7.1.2",
|
||||
"dotenv": "16.4.5",
|
||||
@@ -26,7 +28,6 @@
|
||||
"style-loader": "4.0.0",
|
||||
"webpack": "5.95.0",
|
||||
"webpack-cli": "5.1.4",
|
||||
"webpack-dev-server": "5.1.0",
|
||||
"@svgr/webpack": "8.1.0"
|
||||
"webpack-dev-server": "5.1.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,11 +118,11 @@ function CorrespondentsPanel({
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section className="correspondents-panel column">
|
||||
<div className="column-header">
|
||||
<div className="column-header__titles">
|
||||
<section className="correspondents-panel">
|
||||
<div className="panel-section__header">
|
||||
<div className="panel-section__titles">
|
||||
<h2>Correspondents</h2>
|
||||
<div className="column-subtitle">{correspondents.length} total</div>
|
||||
<div className="panel-section__subtitle">{correspondents.length} total</div>
|
||||
</div>
|
||||
<div className="header-actions correspondents-actions">
|
||||
<form className="correspondents-actions__form" onSubmit={handleCreate}>
|
||||
@@ -147,7 +147,7 @@ function CorrespondentsPanel({
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="column-body tags-panel__body">
|
||||
<div className="panel-section__body tags-panel__body">
|
||||
{correspondents.length === 0 ? (
|
||||
<div className="empty-state">No correspondents created yet.</div>
|
||||
) : (
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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;
|
||||
@@ -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 { 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 DEFAULT_GRID_ICON_SIZE = 96;
|
||||
@@ -13,13 +13,62 @@ const getPageCount = (doc) =>
|
||||
? doc.current_version.metadata.page_count
|
||||
: 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 = ({
|
||||
document,
|
||||
ensureAssetUrl,
|
||||
getDocumentAsset,
|
||||
alt,
|
||||
maxSize = LIST_ICON_SIZE,
|
||||
scrollRootRef = null,
|
||||
}) => {
|
||||
const { ref: visibilityRef, isVisible } = useLazyVisibility(scrollRootRef, document?.id);
|
||||
const resolvedMaxSize = Math.max(1, Math.round(maxSize || 1));
|
||||
const thumbnailAsset = useMemo(
|
||||
() => getAssetFromVersion(document?.current_version, 'thumbnail'),
|
||||
@@ -45,14 +94,15 @@ const DocumentThumbnailImage = ({
|
||||
() => ({ width: `${dimensions.width}px`, height: `${dimensions.height}px` }),
|
||||
[dimensions.height, dimensions.width],
|
||||
);
|
||||
const url = useMemo(
|
||||
() =>
|
||||
resolveDocumentAssetUrl(document, 'thumbnail', {
|
||||
ensureAssetUrl,
|
||||
getAsset: getDocumentAsset,
|
||||
}),
|
||||
[document, ensureAssetUrl, getDocumentAsset],
|
||||
);
|
||||
const url = useMemo(() => {
|
||||
if (!isVisible) {
|
||||
return null;
|
||||
}
|
||||
return resolveDocumentAssetUrl(document, 'thumbnail', {
|
||||
ensureAssetUrl,
|
||||
getAsset: getDocumentAsset,
|
||||
});
|
||||
}, [document, ensureAssetUrl, getDocumentAsset, isVisible]);
|
||||
|
||||
const pageCount = getPageCount(document);
|
||||
const showMultiPageBadge = Number.isFinite(pageCount) && pageCount > 1;
|
||||
@@ -62,13 +112,15 @@ const DocumentThumbnailImage = ({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="document-thumbnail-wrapper">
|
||||
<div className="document-thumbnail-wrapper" ref={visibilityRef}>
|
||||
<div className={innerClasses.join(' ')} style={innerStyle}>
|
||||
{url ? (
|
||||
<img
|
||||
src={url}
|
||||
alt={alt || ''}
|
||||
className="document-thumbnail"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
onDragStart={(event) => event.preventDefault()}
|
||||
/>
|
||||
@@ -125,6 +177,7 @@ const DocumentsTable = ({
|
||||
viewMode = 'list',
|
||||
onViewModeChange,
|
||||
onClearSelection,
|
||||
showHeader = true,
|
||||
}) => {
|
||||
const showingSearchResults = searchResults !== null;
|
||||
const rows = showingSearchResults ? searchResults : documents;
|
||||
@@ -142,6 +195,18 @@ const DocumentsTable = ({
|
||||
[draggingDocumentIds],
|
||||
);
|
||||
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 gridIconSize = DEFAULT_GRID_ICON_SIZE;
|
||||
const handleSetViewMode = useCallback(
|
||||
@@ -156,6 +221,11 @@ const DocumentsTable = ({
|
||||
},
|
||||
[onViewModeChange],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (scrollRef.current) {
|
||||
scrollRef.current.scrollTop = 0;
|
||||
}
|
||||
}, [viewMode]);
|
||||
const isTagDragEvent = useCallback((event) => {
|
||||
const types = Array.from(event.dataTransfer?.types || []);
|
||||
return TAG_MIME_TYPES.some((type) => types.includes(type));
|
||||
@@ -263,16 +333,6 @@ const DocumentsTable = ({
|
||||
[isTagDragEvent, onDocumentTagDrop],
|
||||
);
|
||||
|
||||
const handleGridBackgroundClick = useCallback(
|
||||
(event) => {
|
||||
if (event.target !== event.currentTarget) {
|
||||
return;
|
||||
}
|
||||
onClearSelection?.();
|
||||
},
|
||||
[onClearSelection],
|
||||
);
|
||||
|
||||
const showDefaultEmptyState = !showingSearchResults && !subfolders.length && rows.length === 0;
|
||||
const showListSearchEmptyState =
|
||||
showingSearchResults && rows.length === 0 && !isGridView && !isSearchLoading;
|
||||
@@ -282,73 +342,53 @@ const DocumentsTable = ({
|
||||
|
||||
return (
|
||||
<section
|
||||
className={`documents-panel column documents-panel--view-${isGridView ? 'grid' : 'list'}`}
|
||||
className={`documents-panel documents-panel--view-${isGridView ? 'grid' : 'list'}`}
|
||||
>
|
||||
<div className="column-header">
|
||||
<div className="column-header__titles">
|
||||
<nav className="breadcrumb" aria-label="Folder breadcrumbs">
|
||||
{breadcrumbs.map((crumb, index) => {
|
||||
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 && (
|
||||
<div className="column-subtitle">Search results</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="header-actions">
|
||||
<div className="view-toggle" role="group" aria-label="Change view">
|
||||
{showHeader ? (
|
||||
<div className="panel-section__header">
|
||||
<div className="panel-section__titles">
|
||||
<h2>{currentFolderName}</h2>
|
||||
{showingSearchResults && (
|
||||
<div className="panel-section__subtitle">Search results</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="header-actions">
|
||||
<div className="view-toggle" role="group" aria-label="Change view">
|
||||
<button
|
||||
type="button"
|
||||
className={`view-toggle__button${isGridView ? '' : ' active'}`}
|
||||
onClick={() => handleSetViewMode('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={() => handleSetViewMode('grid')}
|
||||
aria-pressed={isGridView}
|
||||
title="Icons view"
|
||||
>
|
||||
<ViewGridIcon className="view-toggle__icon" size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={`view-toggle__button${isGridView ? '' : ' active'}`}
|
||||
onClick={() => handleSetViewMode('list')}
|
||||
aria-pressed={!isGridView}
|
||||
title="List view"
|
||||
onClick={onRequestCreateFolder}
|
||||
disabled={creatingFolder}
|
||||
>
|
||||
<ViewListIcon className="view-toggle__icon" size={18} />
|
||||
{creatingFolder ? 'Creating…' : 'New folder'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`view-toggle__button${isGridView ? ' active' : ''}`}
|
||||
onClick={() => handleSetViewMode('grid')}
|
||||
aria-pressed={isGridView}
|
||||
title="Icons view"
|
||||
>
|
||||
<ViewGridIcon className="view-toggle__icon" size={18} />
|
||||
<button className="secondary" onClick={onRefresh}>
|
||||
Refresh
|
||||
</button>
|
||||
<button className="secondary" type="button" onClick={onShowSkeuoWorkspace}>
|
||||
Desk View
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRequestCreateFolder}
|
||||
disabled={creatingFolder}
|
||||
>
|
||||
{creatingFolder ? 'Creating…' : 'New folder'}
|
||||
</button>
|
||||
<button className="secondary" onClick={onRefresh}>
|
||||
Refresh
|
||||
</button>
|
||||
<button className="secondary" type="button" onClick={onShowSkeuoWorkspace}>
|
||||
Desk View
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{showDefaultEmptyState && (
|
||||
<div className="empty-state">
|
||||
Drop files anywhere or onto a folder to upload documents.
|
||||
@@ -359,9 +399,9 @@ const DocumentsTable = ({
|
||||
No documents match the current filters.
|
||||
</div>
|
||||
)}
|
||||
<div className="column-body">
|
||||
<div className="panel-section__body">
|
||||
<div
|
||||
ref={scrollRef}
|
||||
ref={assignScrollRef}
|
||||
className="documents-scroll"
|
||||
onFocus={(event) => {
|
||||
if (event.target === scrollRef.current) {
|
||||
@@ -376,13 +416,22 @@ const DocumentsTable = ({
|
||||
onDocumentListKeyDown(event);
|
||||
}
|
||||
}}
|
||||
onClick={(event) => {
|
||||
if (event.target === event.currentTarget) {
|
||||
onClearSelection?.();
|
||||
}
|
||||
}}
|
||||
aria-activedescendant={isGridView ? undefined : activeDescendantId}
|
||||
>
|
||||
{showDefaultEmptyState ? null : isGridView ? (
|
||||
<div
|
||||
className="documents-grid"
|
||||
role="list"
|
||||
onClick={handleGridBackgroundClick}
|
||||
onClick={(event) => {
|
||||
if (event.target === event.currentTarget) {
|
||||
onClearSelection?.();
|
||||
}
|
||||
}}
|
||||
style={{ '--documents-grid-icon-size': `${gridIconSize}px` }}
|
||||
>
|
||||
{!showingSearchResults &&
|
||||
@@ -477,6 +526,7 @@ const DocumentsTable = ({
|
||||
getDocumentAsset={getDocumentAsset}
|
||||
alt={`Thumbnail for ${doc.title || doc.original_name}`}
|
||||
maxSize={gridIconSize}
|
||||
scrollRootRef={scrollRef}
|
||||
/>
|
||||
<div className="document-card__meta">
|
||||
<div
|
||||
@@ -619,13 +669,20 @@ const DocumentsTable = ({
|
||||
<td className="doc-list__name">
|
||||
<div className="doc-list__name-content">
|
||||
<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
|
||||
type="button"
|
||||
className="icon-button ghost doc-list__icon-button"
|
||||
className="icon-button ghost"
|
||||
title="Rename"
|
||||
aria-label={`Rename folder ${folder.name}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
if (!onFolderRename) return;
|
||||
const nextName = window.prompt('Rename folder', folder.name || '');
|
||||
if (!nextName) {
|
||||
return;
|
||||
@@ -636,28 +693,24 @@ const DocumentsTable = ({
|
||||
}
|
||||
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
|
||||
type="button"
|
||||
className="icon-button danger"
|
||||
title="Delete"
|
||||
aria-label={`Delete folder ${folder.name}`}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onFolderDelete(folder.id);
|
||||
}}
|
||||
>
|
||||
<TrashIcon className="icon-inline" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
<td>Folder</td>
|
||||
<td>—</td>
|
||||
<td className="actions">
|
||||
<button
|
||||
type="button"
|
||||
className="icon-button danger"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onFolderDelete(folder.id);
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
@@ -690,36 +743,13 @@ const DocumentsTable = ({
|
||||
ensureAssetUrl={ensureAssetUrl}
|
||||
getDocumentAsset={getDocumentAsset}
|
||||
alt={`Thumbnail for ${doc.title || doc.original_name}`}
|
||||
scrollRootRef={scrollRef}
|
||||
/>
|
||||
</td>
|
||||
<td className="doc-list__name">
|
||||
<div className="doc-name">
|
||||
<div className="doc-list__name-content">
|
||||
<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>
|
||||
{(doc.tags || []).length > 0 && (
|
||||
<div className="doc-name__tags">
|
||||
@@ -788,31 +818,59 @@ const DocumentsTable = ({
|
||||
</td>
|
||||
<td className="actions">
|
||||
<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 ? (
|
||||
<a
|
||||
className="button-link with-icon"
|
||||
className="icon-button"
|
||||
href={downloadHref}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title="Download"
|
||||
aria-label="Download document"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onAuxClick={(event) => event.stopPropagation()}
|
||||
onContextMenu={(event) => event.stopPropagation()}
|
||||
>
|
||||
<DownloadIcon className="icon-inline" />
|
||||
<span>Download</span>
|
||||
</a>
|
||||
) : (
|
||||
<span className="meta">No download</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="danger"
|
||||
className="icon-button danger"
|
||||
title="Delete"
|
||||
aria-label="Delete document"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onDocumentDelete?.(doc.id);
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
<TrashIcon className="icon-inline" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
+731
-164
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
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';
|
||||
|
||||
@@ -136,6 +136,19 @@ const Sidebar = ({
|
||||
correspondents = [],
|
||||
activeCorrespondentIds = [],
|
||||
onToggleCorrespondentFilter,
|
||||
onManageTags,
|
||||
onManageCorrespondents,
|
||||
searchQuery = '',
|
||||
onSearchChange,
|
||||
onSearchSubmit,
|
||||
onSearchClear,
|
||||
isFilterActive,
|
||||
appStatus,
|
||||
loading,
|
||||
previewActive,
|
||||
onLogout,
|
||||
status,
|
||||
onCollapse,
|
||||
}) => {
|
||||
const sortedCorrespondents = useMemo(
|
||||
() =>
|
||||
@@ -150,6 +163,27 @@ const Sidebar = ({
|
||||
);
|
||||
const handleToggleTag = onToggleTagFilter || (() => {});
|
||||
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(
|
||||
(ids, depth) =>
|
||||
@@ -193,30 +227,80 @@ const Sidebar = ({
|
||||
);
|
||||
|
||||
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 (
|
||||
<aside className="sidebar column">
|
||||
<div className="sidebar-section sidebar-section--folders">
|
||||
<div className="sidebar-section__header">
|
||||
<h3>Folders</h3>
|
||||
<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>
|
||||
<ul className="folder-tree">
|
||||
{rootNode && renderNodes([rootNode.id], 0)}
|
||||
</ul>
|
||||
</div>
|
||||
<div className="sidebar-section">
|
||||
<div className="sidebar-section__header">
|
||||
<h3>Tags</h3>
|
||||
<span className="meta">{tags.length}</span>
|
||||
<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__header">
|
||||
<h3>Folders</h3>
|
||||
</div>
|
||||
<ul className="folder-tree">
|
||||
{rootNode && renderNodes([rootNode.id], 0)}
|
||||
</ul>
|
||||
</div>
|
||||
<div
|
||||
className={`sidebar-tag-cloud${
|
||||
activeTagSet.size ? ' sidebar-tag-cloud--has-active' : ''
|
||||
}`}
|
||||
role="list"
|
||||
>
|
||||
{tags.length ? (
|
||||
tags.map((tag) => {
|
||||
<div className="sidebar-section">
|
||||
<div className="sidebar-section__header">
|
||||
<button
|
||||
type="button"
|
||||
className="sidebar-section__title"
|
||||
onClick={handleManageTags}
|
||||
>
|
||||
<h3>Tags</h3>
|
||||
<span className="meta">{tags.length}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
className={`sidebar-tag-cloud${
|
||||
activeTagSet.size ? ' sidebar-tag-cloud--has-active' : ''
|
||||
}`}
|
||||
role="list"
|
||||
>
|
||||
{tags.map((tag) => {
|
||||
const isActive = activeTagSet.has(tag.id);
|
||||
const style = getTagColorStyle(tag.color);
|
||||
const className = `sidebar-tag-pill${isActive ? ' active' : ''}`;
|
||||
@@ -249,20 +333,22 @@ const Sidebar = ({
|
||||
{tag.label}
|
||||
</button>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<span className="meta">No tags yet</span>
|
||||
)}
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="sidebar-section">
|
||||
<div className="sidebar-section__header">
|
||||
<h3>Correspondents</h3>
|
||||
<span className="meta">{correspondents.length}</span>
|
||||
</div>
|
||||
<ul className="sidebar-correspondent-list">
|
||||
{sortedCorrespondents.length ? (
|
||||
sortedCorrespondents.map((correspondent) => {
|
||||
<div className="sidebar-section">
|
||||
<div className="sidebar-section__header">
|
||||
<button
|
||||
type="button"
|
||||
className="sidebar-section__title"
|
||||
onClick={handleManageCorrespondents}
|
||||
>
|
||||
<h3>Correspondents</h3>
|
||||
<span className="meta">{correspondents.length}</span>
|
||||
</button>
|
||||
</div>
|
||||
<ul className="sidebar-correspondent-list">
|
||||
{sortedCorrespondents.map((correspondent) => {
|
||||
const isActive = activeCorrespondentSet.has(correspondent.id);
|
||||
const className = `sidebar-correspondent-item${isActive ? ' active' : ''}`;
|
||||
const label = correspondent.name || 'Unnamed';
|
||||
@@ -287,11 +373,14 @@ const Sidebar = ({
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<li className="meta">No correspondents yet</li>
|
||||
)}
|
||||
</ul>
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
<div className="sidebar__footer">
|
||||
<button className="secondary" type="button" onClick={handleLogoutClick}>
|
||||
Log out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
|
||||
@@ -13,57 +13,6 @@
|
||||
grid-column: 2 / -1;
|
||||
min-height: 0;
|
||||
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 {
|
||||
@@ -106,7 +55,6 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
transition: width 0.28s ease, height 0.28s ease;
|
||||
}
|
||||
|
||||
.skeuo-item:focus-visible {
|
||||
@@ -119,10 +67,6 @@
|
||||
transition: none;
|
||||
}
|
||||
|
||||
.skeuo-item.is-zoomed {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.skeuo-item.is-tag-target .skeuo-item__card {
|
||||
outline: 1em dashed var(--accent);
|
||||
outline-offset: 1.41em;
|
||||
|
||||
+303
-188
@@ -9,6 +9,7 @@ import React, {
|
||||
import { resolveDocumentAssetUrl, createAssetView } from './asset_manager';
|
||||
import { useAssetNavigator } from './hooks/useAssetNavigator';
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from './ui/icons';
|
||||
import PreviewZoomOverlay from './detail/PreviewZoomOverlay';
|
||||
import { getReadableTextColor } from './utils/colors';
|
||||
import './skeuomorphic_ws.css';
|
||||
|
||||
@@ -28,9 +29,6 @@ const resolveSizeKey = (doc) =>
|
||||
const CARD_MIN = 240;
|
||||
const CARD_MAX = 340;
|
||||
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 DEBUG_DRAG = false;
|
||||
@@ -52,6 +50,7 @@ const SkeuoPreviewCard = ({
|
||||
getDocumentAsset,
|
||||
navScale = 1,
|
||||
prefetch = 3,
|
||||
onNavigatorSnapshot,
|
||||
}) => {
|
||||
const navigator = useAssetNavigator({
|
||||
document: doc,
|
||||
@@ -61,7 +60,42 @@ const SkeuoPreviewCard = ({
|
||||
prefetch,
|
||||
});
|
||||
|
||||
const { currentUrl, cardinality, canGoPrev, canGoNext } = navigator;
|
||||
const { currentUrl, cardinality, canGoPrev, canGoNext, currentMetadata, ordinal } = navigator;
|
||||
const docId = doc?.id ?? null;
|
||||
|
||||
const metadataWidth = Number(currentMetadata?.width);
|
||||
const metadataHeight = Number(currentMetadata?.height);
|
||||
|
||||
useEffect(() => {
|
||||
if (!onNavigatorSnapshot || !docId) {
|
||||
return undefined;
|
||||
}
|
||||
const snapshot = {
|
||||
url: currentUrl || null,
|
||||
alt: title,
|
||||
canGoPrev,
|
||||
canGoNext,
|
||||
goPrev: navigator.goPrev,
|
||||
goNext: navigator.goNext,
|
||||
ordinal,
|
||||
width: Number.isFinite(metadataWidth) && metadataWidth > 0 ? metadataWidth : null,
|
||||
height: Number.isFinite(metadataHeight) && metadataHeight > 0 ? metadataHeight : null,
|
||||
};
|
||||
onNavigatorSnapshot(docId, snapshot);
|
||||
return () => onNavigatorSnapshot(docId, null);
|
||||
}, [
|
||||
docId,
|
||||
currentUrl,
|
||||
title,
|
||||
canGoPrev,
|
||||
canGoNext,
|
||||
ordinal,
|
||||
metadataWidth,
|
||||
metadataHeight,
|
||||
navigator.goPrev,
|
||||
navigator.goNext,
|
||||
onNavigatorSnapshot,
|
||||
]);
|
||||
const hasPreview = Boolean(currentUrl);
|
||||
const cardClasses = ['skeuo-item__card'];
|
||||
if (!hasPreview) cardClasses.push('skeuo-item__card--empty');
|
||||
@@ -303,7 +337,7 @@ const useDocumentDrag = ({
|
||||
setDraggingId,
|
||||
syncLayoutSnapshot,
|
||||
canvasSize,
|
||||
toggleZoom,
|
||||
openOverlayForDoc,
|
||||
}) => {
|
||||
const dragStateRef = useRef(null);
|
||||
|
||||
@@ -330,7 +364,7 @@ const useDocumentDrag = ({
|
||||
);
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(event, docId, { lockWhenZoomed = false } = {}) => {
|
||||
(event, docId) => {
|
||||
if (DEBUG_DRAG) {
|
||||
console.log(
|
||||
'[skeuo] handlePointerDown fired for doc',
|
||||
@@ -376,7 +410,7 @@ const useDocumentDrag = ({
|
||||
startY: event.clientY,
|
||||
rotation: entry?.rotation ?? 0,
|
||||
moved: false,
|
||||
locked: Boolean(lockWhenZoomed),
|
||||
locked: false,
|
||||
width: docWidth,
|
||||
height: docHeight,
|
||||
scale: baseScale,
|
||||
@@ -475,13 +509,19 @@ const useDocumentDrag = ({
|
||||
const docId = state.docId;
|
||||
finishDrag(event.pointerId);
|
||||
if (!moved) {
|
||||
toggleZoom(docId);
|
||||
const originInfo = {
|
||||
rotation: state.rotation || 0,
|
||||
scale: state.scale || 1,
|
||||
width: state.width,
|
||||
height: state.height,
|
||||
};
|
||||
openOverlayForDoc(docId, originInfo);
|
||||
}
|
||||
return;
|
||||
}
|
||||
finishDrag(event.pointerId);
|
||||
},
|
||||
[finishDrag, toggleZoom],
|
||||
[finishDrag, openOverlayForDoc],
|
||||
);
|
||||
|
||||
const handlePointerCancel = useCallback(
|
||||
@@ -524,6 +564,37 @@ const clamp = (value, min, max) => {
|
||||
return value;
|
||||
};
|
||||
|
||||
const clampCardDimensions = (width, height) => {
|
||||
let nextWidth = Number(width);
|
||||
let nextHeight = Number(height);
|
||||
if (!Number.isFinite(nextWidth) || nextWidth <= 0 || !Number.isFinite(nextHeight) || nextHeight <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const scaleDown = Math.min(1, CARD_MAX / nextWidth, CARD_MAX / nextHeight);
|
||||
nextWidth *= scaleDown;
|
||||
nextHeight *= scaleDown;
|
||||
|
||||
const minDim = Math.min(nextWidth, nextHeight);
|
||||
if (minDim > 0 && minDim < CARD_MIN) {
|
||||
const scaleUp = CARD_MIN / minDim;
|
||||
nextWidth *= scaleUp;
|
||||
nextHeight *= scaleUp;
|
||||
|
||||
const adjust = Math.min(1, CARD_MAX / nextWidth, CARD_MAX / nextHeight);
|
||||
nextWidth *= adjust;
|
||||
nextHeight *= adjust;
|
||||
}
|
||||
|
||||
nextWidth = clamp(nextWidth, CARD_MIN, CARD_MAX);
|
||||
nextHeight = clamp(nextHeight, CARD_MIN, CARD_MAX);
|
||||
|
||||
return {
|
||||
width: nextWidth,
|
||||
height: nextHeight,
|
||||
};
|
||||
};
|
||||
|
||||
const formatTransform = (x, y, rotation = 0, scale = 1) =>
|
||||
`translate3d(${x}px, ${y}px, 0) rotate(${rotation}deg) scale(${scale})`;
|
||||
|
||||
@@ -547,10 +618,6 @@ const getContrastingTextColor = (hex) => getReadableTextColor(hex, { light: '#1f
|
||||
const SkeuomorphicWorkspace = ({
|
||||
documents = [],
|
||||
searchResults = null,
|
||||
breadcrumbs = [],
|
||||
currentFolderName = 'Folder',
|
||||
onExit,
|
||||
onRefresh,
|
||||
onDocumentOpen,
|
||||
resolveThumbnailUrl,
|
||||
onAssignTagToDocument = null,
|
||||
@@ -560,7 +627,6 @@ const SkeuomorphicWorkspace = ({
|
||||
activeTagIds = [],
|
||||
}) => {
|
||||
const items = useMemo(() => (searchResults ? searchResults : documents), [documents, searchResults]);
|
||||
const showingSearchResults = searchResults !== null;
|
||||
|
||||
|
||||
const containerRef = useRef(null);
|
||||
@@ -572,14 +638,94 @@ const SkeuomorphicWorkspace = ({
|
||||
|
||||
const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 });
|
||||
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 [docSizeVersion, setDocSizeVersion] = useState(0);
|
||||
const [tagDropTargetId, setTagDropTargetId] = useState(null);
|
||||
const [pendingTagDocId, setPendingTagDocId] = useState(null);
|
||||
const [pendingRemovalTag, setPendingRemovalTag] = useState(null);
|
||||
const draggingTagRef = useRef(null);
|
||||
const pendingDocTagDragRef = useRef(null);
|
||||
const docSizeMapRef = useRef(new Map());
|
||||
const documentLookupRef = useRef(new Map());
|
||||
const removalCursorActiveRef = useRef(false);
|
||||
const applySnapshotDimensions = useCallback(
|
||||
(docId, snapshot) => {
|
||||
if (!docId || !snapshot) {
|
||||
return;
|
||||
}
|
||||
|
||||
const doc = documentLookupRef.current.get(docId);
|
||||
if (!doc) {
|
||||
return;
|
||||
}
|
||||
|
||||
const width = Number(snapshot.width);
|
||||
const height = Number(snapshot.height);
|
||||
if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalized = clampCardDimensions(width, height);
|
||||
if (!normalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
const key = resolveSizeKey(doc);
|
||||
const existing = docSizeMapRef.current.get(key);
|
||||
if (existing && existing.width === normalized.width && existing.height === normalized.height) {
|
||||
return;
|
||||
}
|
||||
|
||||
docSizeMapRef.current.set(key, normalized);
|
||||
setDocSizeVersion((value) => value + 1);
|
||||
},
|
||||
[],
|
||||
);
|
||||
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 &&
|
||||
prevSnapshot.ordinal === snapshot.ordinal &&
|
||||
prevSnapshot.width === snapshot.width &&
|
||||
prevSnapshot.height === snapshot.height;
|
||||
if (sameSnapshot) {
|
||||
return previous;
|
||||
}
|
||||
next.set(docId, snapshot);
|
||||
return next;
|
||||
});
|
||||
|
||||
if (snapshot) {
|
||||
applySnapshotDimensions(docId, snapshot);
|
||||
}
|
||||
},
|
||||
[applySnapshotDimensions],
|
||||
);
|
||||
const activeTagSet = useMemo(() => {
|
||||
if (!Array.isArray(activeTagIds) || activeTagIds.length === 0) {
|
||||
return new Set();
|
||||
@@ -604,6 +750,15 @@ const SkeuomorphicWorkspace = ({
|
||||
const resolvePreviewDimensions = useCallback(
|
||||
(doc) => {
|
||||
if (!doc) return null;
|
||||
|
||||
const snapshot = previewSnapshots.get(doc.id);
|
||||
if (snapshot && snapshot.width && snapshot.height) {
|
||||
return {
|
||||
width: snapshot.width,
|
||||
height: snapshot.height,
|
||||
};
|
||||
}
|
||||
|
||||
const asset = resolvePreviewAsset(doc);
|
||||
const view = createAssetView(asset);
|
||||
const metadata = view.getPrimaryMetadata() || {};
|
||||
@@ -614,7 +769,7 @@ const SkeuomorphicWorkspace = ({
|
||||
}
|
||||
return null;
|
||||
},
|
||||
[resolvePreviewAsset],
|
||||
[previewSnapshots, resolvePreviewAsset],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -721,48 +876,26 @@ const SkeuomorphicWorkspace = ({
|
||||
if (cache) {
|
||||
return cache;
|
||||
}
|
||||
let width;
|
||||
let height;
|
||||
|
||||
const intrinsic = resolvePreviewDimensions(doc);
|
||||
let normalized = null;
|
||||
if (intrinsic?.width && intrinsic?.height) {
|
||||
width = intrinsic.width;
|
||||
height = intrinsic.height;
|
||||
} else {
|
||||
normalized = clampCardDimensions(intrinsic.width, intrinsic.height);
|
||||
}
|
||||
|
||||
if (!normalized) {
|
||||
const seed = seededRandom(`${key}:size`);
|
||||
width = CARD_MIN + seed * (Math.min(CARD_MAX, CARD_MAX / EMPTY_CARD_ASPECT) - CARD_MIN);
|
||||
let width = CARD_MIN + seed * (Math.min(CARD_MAX, CARD_MAX / EMPTY_CARD_ASPECT) - CARD_MIN);
|
||||
width = clamp(width, CARD_MIN, Math.min(CARD_MAX, CARD_MAX / EMPTY_CARD_ASPECT));
|
||||
height = width * EMPTY_CARD_ASPECT;
|
||||
const height = width * EMPTY_CARD_ASPECT;
|
||||
normalized = clampCardDimensions(width, height);
|
||||
}
|
||||
|
||||
if (!Number.isFinite(width) || width <= 0) {
|
||||
width = CARD_MIN;
|
||||
}
|
||||
if (!Number.isFinite(height) || height <= 0) {
|
||||
height = CARD_MIN;
|
||||
if (!normalized) {
|
||||
normalized = { width: CARD_MIN, height: CARD_MIN };
|
||||
}
|
||||
|
||||
const scaleDown = Math.min(1, CARD_MAX / width, CARD_MAX / height);
|
||||
width *= scaleDown;
|
||||
height *= scaleDown;
|
||||
|
||||
const minDim = Math.min(width, height);
|
||||
if (minDim < CARD_MIN) {
|
||||
const scaleUp = CARD_MIN / minDim;
|
||||
width *= scaleUp;
|
||||
height *= scaleUp;
|
||||
|
||||
const adjust = Math.min(1, CARD_MAX / width, CARD_MAX / height);
|
||||
width *= adjust;
|
||||
height *= adjust;
|
||||
}
|
||||
|
||||
width = clamp(width, CARD_MIN, CARD_MAX);
|
||||
height = clamp(height, CARD_MIN, CARD_MAX);
|
||||
|
||||
const size = { width, height };
|
||||
docSizeMapRef.current.set(key, size);
|
||||
return size;
|
||||
docSizeMapRef.current.set(key, normalized);
|
||||
return normalized;
|
||||
}, [resolvePreviewDimensions]);
|
||||
|
||||
const documentLookup = useMemo(() => {
|
||||
@@ -775,74 +908,48 @@ const SkeuomorphicWorkspace = ({
|
||||
return map;
|
||||
}, [items]);
|
||||
|
||||
useEffect(() => {
|
||||
documentLookupRef.current = documentLookup;
|
||||
}, [documentLookup]);
|
||||
|
||||
useEffect(() => {
|
||||
docSizeMapRef.current = new Map();
|
||||
setDocSizeVersion((value) => value + 1);
|
||||
}, [items]);
|
||||
|
||||
const resolveZoomMetrics = useCallback(
|
||||
(doc, cardWidth, cardHeight) => {
|
||||
const canvasWidth = canvasSize.width || DEFAULT_CANVAS_WIDTH;
|
||||
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;
|
||||
const overlayDisplay = useMemo(() => {
|
||||
if (!overlayDocId) {
|
||||
return null;
|
||||
}
|
||||
const snapshot = previewSnapshots.get(overlayDocId);
|
||||
if (!snapshot || !snapshot.url) {
|
||||
return null;
|
||||
}
|
||||
const doc = documentLookup.get(overlayDocId);
|
||||
const alt = snapshot.alt || doc?.title || doc?.original_name || 'Document preview';
|
||||
return {
|
||||
url: snapshot.url,
|
||||
alt,
|
||||
canGoPrev: snapshot.canGoPrev,
|
||||
canGoNext: snapshot.canGoNext,
|
||||
goPrev: snapshot.goPrev,
|
||||
goNext: snapshot.goNext,
|
||||
};
|
||||
}, [overlayDocId, previewSnapshots, documentLookup]);
|
||||
|
||||
let zoomWidth = safeCardWidth;
|
||||
let zoomHeight = safeCardHeight;
|
||||
const closeOverlay = useCallback(() => {
|
||||
setOverlayDocId(null);
|
||||
setOverlayOriginRect(null);
|
||||
setOverlayOriginTransform(null);
|
||||
}, []);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if (!Number.isFinite(zoomWidth) || zoomWidth <= 0) {
|
||||
zoomWidth = safeCardWidth;
|
||||
}
|
||||
if (!Number.isFinite(zoomHeight) || zoomHeight <= 0) {
|
||||
zoomHeight = safeCardHeight;
|
||||
}
|
||||
|
||||
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 {
|
||||
zoomWidth,
|
||||
zoomHeight,
|
||||
zoomCenterX,
|
||||
zoomCenterY,
|
||||
};
|
||||
},
|
||||
[canvasSize.width, canvasSize.height, resolvePreviewDimensions],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (overlayDocId && !documentLookup.has(overlayDocId)) {
|
||||
setOverlayDocId(null);
|
||||
setOverlayOriginRect(null);
|
||||
setOverlayOriginTransform(null);
|
||||
}
|
||||
}, [overlayDocId, documentLookup]);
|
||||
|
||||
const resolveBaseMetrics = useCallback(
|
||||
(doc, cardWidth, cardHeight) => {
|
||||
@@ -876,7 +983,8 @@ const SkeuomorphicWorkspace = ({
|
||||
const container = containerRef.current;
|
||||
if (!container) return () => {};
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
const isDevEnv = typeof process !== 'undefined' && process?.env?.NODE_ENV !== 'production';
|
||||
if (isDevEnv) {
|
||||
console.log('[skeuo] canvas element', container);
|
||||
}
|
||||
|
||||
@@ -992,6 +1100,7 @@ const SkeuomorphicWorkspace = ({
|
||||
items,
|
||||
canvasSize.width,
|
||||
canvasSize.height,
|
||||
docSizeVersion,
|
||||
ensureDocumentSize,
|
||||
syncLayoutSnapshot,
|
||||
]);
|
||||
@@ -1014,17 +1123,62 @@ const SkeuomorphicWorkspace = ({
|
||||
[syncLayoutSnapshot],
|
||||
);
|
||||
|
||||
const toggleZoom = useCallback(
|
||||
(docId) => {
|
||||
setZoomedId((current) => {
|
||||
if (current === docId) {
|
||||
return null;
|
||||
}
|
||||
bringToFront(docId);
|
||||
return docId;
|
||||
});
|
||||
const openOverlayForDoc = useCallback(
|
||||
(docId, originInfo = null) => {
|
||||
if (!docId) {
|
||||
return;
|
||||
}
|
||||
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);
|
||||
setOverlayOriginRect(rect);
|
||||
setOverlayOriginTransform(originTransform);
|
||||
setOverlayDocId(docId);
|
||||
},
|
||||
[bringToFront],
|
||||
[
|
||||
bringToFront,
|
||||
previewSnapshots,
|
||||
itemRefs,
|
||||
setOverlayOriginTransform,
|
||||
ensureDocumentSize,
|
||||
resolveBaseMetrics,
|
||||
documentLookup,
|
||||
layoutRef,
|
||||
],
|
||||
);
|
||||
const { handlePointerDown, handlePointerMove, handlePointerUp, handlePointerCancel } = useDocumentDrag({
|
||||
layoutRef,
|
||||
@@ -1036,7 +1190,7 @@ const SkeuomorphicWorkspace = ({
|
||||
setDraggingId,
|
||||
syncLayoutSnapshot,
|
||||
canvasSize,
|
||||
toggleZoom,
|
||||
openOverlayForDoc,
|
||||
});
|
||||
|
||||
const handleTagDragEnterDoc = useCallback(
|
||||
@@ -1489,47 +1643,16 @@ const SkeuomorphicWorkspace = ({
|
||||
[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 (
|
||||
<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
|
||||
className="skeuo-canvas"
|
||||
ref={containerRef}
|
||||
onDragOver={handleCanvasDragOver}
|
||||
onDragLeave={handleCanvasDragLeave}
|
||||
onDrop={handleCanvasDrop}
|
||||
>
|
||||
<>
|
||||
<div className="skeuo-shell">
|
||||
<div
|
||||
className="skeuo-canvas"
|
||||
ref={containerRef}
|
||||
onDragOver={handleCanvasDragOver}
|
||||
onDragLeave={handleCanvasDragLeave}
|
||||
onDrop={handleCanvasDrop}
|
||||
>
|
||||
{items.length === 0 ? (
|
||||
<div className="skeuo-empty">
|
||||
<p>No documents to show here yet. Drop files to make this space come alive.</p>
|
||||
@@ -1550,31 +1673,17 @@ const SkeuomorphicWorkspace = ({
|
||||
typeof layout.centerX === 'number' ? layout.centerX : fallbackLayout.centerX;
|
||||
const layoutCenterY =
|
||||
typeof layout.centerY === 'number' ? layout.centerY : fallbackLayout.centerY;
|
||||
const isZoomed = zoomedId === doc.id;
|
||||
const { zoomWidth, zoomHeight, zoomCenterX, zoomCenterY } = resolveZoomMetrics(
|
||||
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 rotation = layout.rotation || 0;
|
||||
const zoomScale = baseScale;
|
||||
const transform = formatTransform(
|
||||
Math.round(targetCenterX),
|
||||
Math.round(targetCenterY),
|
||||
Math.round(layoutCenterX),
|
||||
Math.round(layoutCenterY),
|
||||
rotation,
|
||||
zoomScale,
|
||||
);
|
||||
const style = {
|
||||
transform,
|
||||
zIndex: isZoomed ? 9999 : layout.z ?? 1,
|
||||
zIndex: layout.z ?? 1,
|
||||
};
|
||||
const bodyStyle = {
|
||||
width: Math.round(baseWidth),
|
||||
@@ -1595,7 +1704,6 @@ const SkeuomorphicWorkspace = ({
|
||||
const dropPending = pendingTagDocId === doc.id;
|
||||
const itemClasses = ['skeuo-item'];
|
||||
if (dragging) itemClasses.push('is-dragging');
|
||||
if (isZoomed) itemClasses.push('is-zoomed');
|
||||
if (dropActive) itemClasses.push('is-tag-target');
|
||||
if (dropPending) itemClasses.push('is-tag-pending');
|
||||
if (!matchesFilter) itemClasses.push('is-filtered-out');
|
||||
@@ -1616,9 +1724,7 @@ const SkeuomorphicWorkspace = ({
|
||||
itemRefs.current.delete(doc.id);
|
||||
}
|
||||
}}
|
||||
onPointerDown={(event) =>
|
||||
handlePointerDown(event, doc.id, { lockWhenZoomed: isZoomed })
|
||||
}
|
||||
onPointerDown={(event) => handlePointerDown(event, doc.id)}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
onPointerCancel={handlePointerCancel}
|
||||
@@ -1640,6 +1746,7 @@ const SkeuomorphicWorkspace = ({
|
||||
ensureAssetUrl={ensureAssetUrl}
|
||||
getDocumentAsset={getDocumentAsset}
|
||||
navScale={inverseTagScale}
|
||||
onNavigatorSnapshot={handleNavigatorSnapshot}
|
||||
/>
|
||||
{tags.length > 0 && (
|
||||
<div className="skeuo-item__tags" aria-hidden="true" style={tagsStyle}>
|
||||
@@ -1685,8 +1792,16 @@ const SkeuomorphicWorkspace = ({
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<PreviewZoomOverlay
|
||||
open={Boolean(overlayDisplay?.url)}
|
||||
display={overlayDisplay}
|
||||
onClose={closeOverlay}
|
||||
originRect={overlayOriginRect}
|
||||
originTransform={overlayOriginTransform}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
+688
-363
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,22 @@
|
||||
import React, { useCallback, useMemo, useState } from 'react';
|
||||
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 [draftLabel, setDraftLabel] = useState('');
|
||||
const [draftColor, setDraftColor] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [deletingId, setDeletingId] = useState(null);
|
||||
const [createLabel, setCreateLabel] = useState('');
|
||||
const [createColor, setCreateColor] = useState('');
|
||||
const [creating, setCreating] = useState(false);
|
||||
|
||||
const startEdit = useCallback((tag) => {
|
||||
setEditingId(tag.id);
|
||||
@@ -98,25 +108,93 @@ function TagsPanel({ tags, onRefresh, onUpdateTag, onDeleteTag, 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 (
|
||||
<section className="tags-panel column">
|
||||
<div className="column-header">
|
||||
<div className="column-header__titles">
|
||||
<section className="tags-panel">
|
||||
<div className="panel-section__header">
|
||||
<div className="panel-section__titles">
|
||||
<h2>Tags</h2>
|
||||
<div className="column-subtitle">{tags.length} total</div>
|
||||
<div className="panel-section__subtitle">{tags.length} total</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
|
||||
className="secondary"
|
||||
type="button"
|
||||
onClick={onRefresh}
|
||||
disabled={saving || Boolean(deletingId)}
|
||||
disabled={saving || creating || Boolean(deletingId)}
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="column-body tags-panel__body">
|
||||
<div className="panel-section__body tags-panel__body">
|
||||
{tags.length === 0 ? (
|
||||
<div className="empty-state">No tags created yet.</div>
|
||||
) : (
|
||||
|
||||
@@ -9,6 +9,15 @@ import {
|
||||
IconLayoutGrid,
|
||||
IconArrowLeft,
|
||||
IconArrowRight,
|
||||
IconArrowUp,
|
||||
IconChevronsRight,
|
||||
IconChevronsLeft,
|
||||
IconAnalyze,
|
||||
IconWindowMaximize,
|
||||
IconTextScan2,
|
||||
IconFolderPlus,
|
||||
IconRefresh,
|
||||
IconMinusVertical,
|
||||
} from '@tabler/icons-react';
|
||||
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 {
|
||||
ChevronIcon,
|
||||
TrashIcon,
|
||||
@@ -130,4 +211,21 @@ export default {
|
||||
DownloadIcon,
|
||||
ViewListIcon,
|
||||
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}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -48,6 +48,8 @@ module.exports = {
|
||||
}),
|
||||
new webpack.DefinePlugin({
|
||||
'process.env.API_BASE_URL': JSON.stringify(API_BASE_URL),
|
||||
'process.env.OLLAMA_BASE_URL': JSON.stringify(process.env.OLLAMA_BASE_URL || ''),
|
||||
'process.env.OLLAMA_MODEL': JSON.stringify(process.env.OLLAMA_MODEL || ''),
|
||||
}),
|
||||
],
|
||||
devServer: {
|
||||
|
||||
Reference in New Issue
Block a user