Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Print files owned by current user to console #347

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion packages/backend/pkg/src/index.ts
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think RpcResult<Array<[string, string]>>> is probably wrong here and reflects the weird front-end types you couldn't parse earlier.

Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,20 @@ export type { UserSummary } from "./UserSummary.ts";
export type { UsernameStatus } from "./UsernameStatus.ts";
export type { UserProfile } from "./UserProfile.ts";

export type QubitServer = { new_ref: Mutation<[content: JsonValue, ], RpcResult<string>>, get_doc: Query<[ref_id: string, ], RpcResult<RefDoc>>, head_snapshot: Query<[ref_id: string, ], RpcResult<JsonValue>>, save_snapshot: Mutation<[data: RefContent, ], RpcResult<null>>, get_permissions: Query<[ref_id: string, ], RpcResult<Permissions>>, set_permissions: Mutation<[ref_id: string, new: NewPermissions, ], RpcResult<null>>, sign_up_or_sign_in: Mutation<[], RpcResult<null>>, user_by_username: Query<[username: string, ], RpcResult<UserSummary | null>>, username_status: Query<[username: string, ], RpcResult<UsernameStatus>>, get_active_user_profile: Query<[], RpcResult<UserProfile>>, set_active_user_profile: Mutation<[user: UserProfile, ], RpcResult<null>> };
export type QubitServer = {
new_ref: Mutation<[content: JsonValue], RpcResult<string>>;
get_doc: Query<[ref_id: string], RpcResult<RefDoc>>;
head_snapshot: Query<[ref_id: string], RpcResult<JsonValue>>;
save_snapshot: Mutation<[data: RefContent], RpcResult<null>>;
get_permissions: Query<[ref_id: string], RpcResult<Permissions>>;
set_permissions: Mutation<
[ref_id: string, new: NewPermissions],
RpcResult<null>
>;
sign_up_or_sign_in: Mutation<[], RpcResult<null>>;
user_by_username: Query<[username: string], RpcResult<UserSummary | null>>;
username_status: Query<[username: string], RpcResult<UsernameStatus>>;
get_active_user_profile: Query<[], RpcResult<UserProfile>>;
set_active_user_profile: Mutation<[user: UserProfile], RpcResult<null>>;
get_user_refs_and_titles: Query<[username: string], RpcResult<Array<[string, string]>>>;
};
6 changes: 6 additions & 0 deletions packages/backend/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub fn router() -> Router<AppState> {
.handler(username_status)
.handler(get_active_user_profile)
.handler(set_active_user_profile)
.handler(get_user_refs_and_titles)
}

#[handler(mutation)]
Expand Down Expand Up @@ -119,6 +120,11 @@ async fn user_by_username(ctx: AppCtx, username: &str) -> RpcResult<Option<user:
user::user_by_username(ctx.state, username).await.into()
}

#[handler(query)]
async fn get_user_refs_and_titles(ctx: AppCtx, username: &str) -> RpcResult<Vec<(Uuid, String)>> {
user::get_user_refs_and_titles(ctx, username).await.into()
}

#[handler(query)]
async fn username_status(ctx: AppCtx, username: &str) -> RpcResult<user::UsernameStatus> {
user::username_status(ctx.state, username).await.into()
Expand Down
26 changes: 26 additions & 0 deletions packages/backend/src/user.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use regex::Regex;
use serde::{Deserialize, Serialize};
use ts_rs::TS;
use uuid::Uuid;

use super::app::{AppCtx, AppError, AppState};

Expand Down Expand Up @@ -160,6 +161,31 @@ pub fn is_username_valid(username: &str) -> bool {
&& ends_alpha.is_match(username)
}

/// Get references and titles for a given username.
pub async fn get_user_refs_and_titles(
ctx: AppCtx,
username: &str,
) -> Result<Vec<(Uuid, String)>, AppError> {
let query = sqlx::query!(
r#"
SELECT snapshots.for_ref, snapshots.content->>'name' as title
FROM snapshots
JOIN refs ON snapshots.for_ref = refs.id
JOIN permissions ON refs.id = permissions.object
JOIN users ON permissions.subject = users.id
WHERE users.username = $1
AND permissions.level = 'own'
"#,
username
);

let results = query.fetch_all(&ctx.state.db).await?;
Ok(results
.into_iter()
.map(|row| (row.for_ref, row.title.unwrap_or("untitled".to_string())))
.collect())
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
22 changes: 22 additions & 0 deletions packages/frontend/src/user/profile.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
.files {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1rem;
padding: 1rem;
background: whitesmoke;
border-radius: 6px;
border: 1px solid lightgray;
}

.filebutton {
display: block;
padding: 1rem;
text-align: center;
background: white;
border-radius: 4px;
border: 1px solid #e1e4e8;
transition: all 0.2s ease;
text-decoration: none;
color: #0366d6;
box-shadow: none;
}
69 changes: 65 additions & 4 deletions packages/frontend/src/user/profile.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { type SubmitHandler, createForm, reset } from "@modular-forms/solid";
import { createEffect, createResource } from "solid-js";
import { Fragment, Show, createEffect, createResource, createSignal } from "solid-js";
import invariant from "tiny-invariant";

import type { UserProfile } from "catcolab-api";
Expand All @@ -8,37 +8,98 @@ import { FormGroup, TextInputItem } from "../components";
import { BrandedToolbar } from "../page";
import { LoginGate } from "./login";

import "./profile.css";

/** Page to configure user profile. */
export default function UserProfilePage() {
const [myRefs, setMyRefs] = createSignal<[string, string][] | null>(null);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having to pass these refs around is a code smell. Also, I don't understand the types. This isn't how you usually create a ref.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The refs are going to be a list of [string,string]s giving a document's ref and name. Is the problem that it's already been stringified rather than passing around actual document objects, or something like that?


return (
<div class="growable-container">
<BrandedToolbar />
<div class="page-container">
<LoginGate>
<h2>Public profile</h2>
<UserProfileForm />
<UserProfileForm onRefsLoaded={setMyRefs} />
<div style="margin-top: 1rem;">
<h3
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No inline styles. Use the external stylesheet.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should/can we lint directly for the keyword style, then, if we're not allowing even one-liners?

style="
margin: 0 0 0.5rem 0;
color: #24292e;
font-size: 1.25rem;
font-weight: 500;
"
>
Your Documents
</h3>
<Show when={myRefs()} fallback={<div> Loading user files... </div>} keyed>
{(items) => {
return (
<div class="files">
{items.map(([id, title]: [string, string]) => (
<Fragment key={id}>
<a
href={`${import.meta.env.VITE_SERVER_URL}/model/${id}`}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't need this env variable. Use Solid Router's A component.

class="filebutton"
onMouseOver={(e) => {
e.currentTarget.style.boxShadow =
"0 2px 8px rgba(0,0,0,0.1)";
}}
onMouseOut={(e) => {
e.currentTarget.style.boxShadow = "none";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ditto about inline styles, and also you shouldn't use mouse over events to change styles. Use the appropriate CSS selectors.

}}
>
{title || "(Untitled)"}
</a>
</Fragment>
))}
</div>
);
}}
</Show>
</div>
</LoginGate>
</div>
</div>
);
}

/** Form to configure user proifle. */
export function UserProfileForm() {
export function UserProfileForm(props: {
onRefsLoaded: (refs: [string, string][] | null) => void;
}) {
const api = useApi();

const [currentProfile, { refetch: refetchProfile }] = createResource(async () => {
const result = await api.rpc.get_active_user_profile.query();
invariant(result.tag === "Ok");
console.log("cpTest", result.content);
return result.content;
});
const [userRefs, setUserRefs] = createSignal<[string, string][] | null>(null);
createEffect(() => {
if (userRefs()) {
props.onRefsLoaded?.(userRefs());
}
});

const [form, { Form, Field }] = createForm<UserProfile>();

createEffect(() => {
reset(form, { initialValues: currentProfile() });
});

createEffect(async () => {
const profile = currentProfile();
if (!profile) {
return;
}
invariant(profile.username != null, "Profile username must be defined and not null");
const result = await api.rpc.get_user_refs_and_titles.query(profile.username);
invariant(result.tag === "Ok");
console.log("get_refs_test", result.content);
setUserRefs(result.content);
});

const onSubmit: SubmitHandler<UserProfile> = async (values) => {
await api.rpc.set_active_user_profile.mutate({
username: values.username ? values.username : null,
Expand Down
Loading