Attachment form and table, MusicXML renderer

This commit is contained in:
2024-11-24 13:37:26 +01:00
parent a347a77e11
commit 02b4c08e7d
12 changed files with 1603 additions and 61 deletions

View File

@@ -68,7 +68,7 @@ const app = new Elysia()
console.log(`${timestamp} ${method} ${request.url} ${ip}`);
})
// --- AUTHENTICATION ------------------------------------------------------
// --- MARK: AUTHENTICATION ------------------------------------------------
.get("/me", async ({ user }) => {
@@ -145,7 +145,7 @@ const app = new Elysia()
.execute();
})
// --- PIECE CRUD ----------------------------------------------------------
// --- MARK: PIECE CRUD ----------------------------------------------------
.post("/piece", async ({ db, body: { name, composer, lyricist, arranger }, user }) => {
@@ -248,7 +248,7 @@ const app = new Elysia()
}),
})
// --- ATTACHMENT CRUD -----------------------------------------------------
// --- MARK: ATTACHMENT CRUD -----------------------------------------------
.post("piece/:pieceId/attachment", async ({ db, body: { filename, mediaType, data }, params: { pieceId }, user }) => {
@@ -264,8 +264,8 @@ const app = new Elysia()
await db
.insertInto("File")
.ignore()
.values({ sha256, data: dataArray })
.onConflict((cb) => cb.column("sha256").doNothing())
.execute();
const res = await db

View File

@@ -18,6 +18,7 @@
"dependencies": {
"@elysiajs/eden": "catalog:",
"common": "workspace:^",
"opensheetmusicdisplay": "catalog:",
"react": "catalog:",
"react-dom": "catalog:",
"react-router-dom": "catalog:"

View File

@@ -0,0 +1,110 @@
import { mapProp, Update } from "./store";
export function FileReducer(prev: FileReducer.State, action: FileReducer.Action): FileReducer.State {
switch (action.type) {
case "reset":
return FileReducer.initial;
case "file":
if (prev.file !== null) {
if (action.file !== null) {
if (prev.file.name === prev.filename && prev.file.type === prev.mediaType) {
return Object.freeze<FileReducer.State>({
filename: action.file.name,
mediaType: action.file.type,
file: action.file,
});
} else {
return mapProp("file", action.file as File | null)(prev);
}
} else {
if (prev.file.name === prev.filename && prev.file.type === prev.mediaType) {
return FileReducer.initial;
} else {
return mapProp("file", action.file as File | null)(prev);
}
}
} else {
if (action.file !== null) {
if (prev.filename === "" && prev.mediaType === "") {
return Object.freeze<FileReducer.State>({
filename: action.file.name,
mediaType: action.file.type,
file: action.file,
});
} else {
return mapProp("file", action.file as File | null)(prev);
}
} else {
return prev;
}
}
case "filename":
return mapProp("filename", action.filename)(prev);
case "mediaType":
return mapProp("mediaType", action.mediaType)(prev);
}
}
export namespace FileReducer {
export interface ResetAction {
readonly type: "reset";
}
export const reset: ResetAction = Object.freeze<ResetAction>({
type: "reset",
});
export interface SetFileAction {
readonly type: "file";
readonly file: File | null;
}
export function setFile(file: File | null): SetFileAction {
return Object.freeze<SetFileAction>({
type: "file",
file,
});
}
export interface SetFilenameAction {
readonly type: "filename";
readonly filename: Update<string>;
}
export function setFilename(filename: Update<string>): SetFilenameAction {
return Object.freeze<SetFilenameAction>({
type: "filename",
filename,
});
}
export interface SetMediaTypeAction {
readonly type: "mediaType";
readonly mediaType: Update<string>;
}
export function setMediaType(mediaType: Update<string>): SetMediaTypeAction {
return Object.freeze<SetMediaTypeAction>({
type: "mediaType",
mediaType,
});
}
export type Action = ResetAction |
SetFileAction |
SetFilenameAction |
SetMediaTypeAction;
export interface State {
readonly filename: string;
readonly mediaType: string;
readonly file: File | null;
}
export const initial: State = Object.freeze<State>({
filename: "",
mediaType: "",
file: null,
});
}

View File

@@ -1,6 +1,7 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { Attachment } from "./routes/Attachment";
import { Home } from "./routes/Home";
import { Login } from "./routes/Login";
import { Piece } from "./routes/Piece";
@@ -18,8 +19,17 @@ const router = createBrowserRouter([
},
{
path: "piece/:pieceId",
children: [
{
index: true,
Component: Piece,
},
{
path: "attachment/:attachmentId",
Component: Attachment,
}
]
},
],
},
{

View File

@@ -1,8 +1,11 @@
import { Treaty } from "@elysiajs/eden";
import { ELYSIA_FORM_DATA } from "elysia";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useStore } from "./store";
type FormDataFix<T> = T extends { [ELYSIA_FORM_DATA]: infer U } ? U : T;
export type LoadingResult<R extends Record<number, unknown>> =
| {
isLoading: true,
@@ -10,7 +13,7 @@ export type LoadingResult<R extends Record<number, unknown>> =
error: null,
} | {
isLoading: false,
data: R[200],
data: FormDataFix<R[200]>,
error: null,
} | {
isLoading: false,

View File

@@ -0,0 +1,62 @@
import { AttachmentId, PieceId } from "common";
import { OpenSheetMusicDisplay } from "opensheetmusicdisplay";
import { useEffect, useRef } from "react";
import { useParams } from "react-router-dom";
import { client } from "../client";
import { useLoading } from "../loading";
// TODO: Lazy load `opensheetmusicdisplay` (don't bundle into main script).
export function Attachment() {
const params = useParams();
const pieceId = PieceId(params.pieceId!);
const attachmentId = AttachmentId(params.attachmentId!);
const { isLoading, error, data } = useLoading(() => client.piece({ pieceId }).attachment({ attachmentId }).get());
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (isLoading || error !== null) return;
const url = URL.createObjectURL(data?.data);
const render = () => osmd.render();
const osmd = new OpenSheetMusicDisplay(containerRef.current!, {
autoResize: false,
drawTitle: false,
drawComposer: false,
drawMeasureNumbers: true,
drawMeasureNumbersOnlyAtSystemStart: true,
//measureNumberInterval: 5,
//renderSingleHorizontalStaffline: true,
});
osmd.load(url).then(render);
window.addEventListener("resize", render);
return () => {
URL.revokeObjectURL(url);
window.removeEventListener("resize", render);
};
}, [isLoading, data]);
if (isLoading) {
return (
<div className="w-full h-full overflow-hidden flex items-center justify-center">
<div>Ładowanie</div>
</div>
);
}
if (error !== null) {
<div className="w-full h-full overflow-hidden flex items-center justify-center">
<div>Wystąpił błąd: {error.value}</div>
</div>
}
return <div ref={containerRef} className="w-full h-full overflow-scroll sheet-music-display" />;
}

View File

@@ -1,9 +1,9 @@
import { FormEventHandler, useId, useRef, useState } from "react";
import { FormEventHandler, ReactNode, useId, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { client } from "../client";
import { useLoading } from "../loading";
import { Button } from "../styled/Button";
import { Input } from "../styled/Input";
import { Link } from "react-router-dom";
export function Home() {
@@ -18,45 +18,48 @@ export function Home() {
}
return (
<div className="p-4 overflow-y-auto flex flex-wrap gap-4">
<div className="p-4 overflow-y-auto flex flex-wrap items-start gap-4">
{error !== null ? (
`Wystąpił błąd: ${error.value}`
) : (
<table className="grow">
<thead>
<tr>
<th className="p-1 border">ID</th>
<th className="p-1 border">Tytuł</th>
<th className="p-1 border">Kompozytor</th>
<th className="p-1 border">Słowa</th>
<th className="p-1 border">Opracowanie</th>
<th className="p-1 border">Data dodania</th>
<th className="p-1 border">Dodane przez</th>
<th className="p-1 border">Data modyfikacji</th>
<th className="p-1 border">Zmodyfikowane przez</th>
<th className="p-1 border">Twórcy</th>
<th className="p-1 border">Dodano</th>
<th className="p-1 border">Zmodyfikowano</th>
</tr>
</thead>
<tbody>
{data.map((piece) => (
{data.map((piece) => {
const composerParts: ReactNode[] = [];
if (piece.composer !== null) composerParts.push(piece.composer);
if (piece.arranger !== null) composerParts.push(`opracowanie: ${piece.arranger}`);
if (piece.lyricist !== null) composerParts.push(`słowa: ${piece.lyricist}`);
if (composerParts.length === 0) composerParts.push(<em>Nieznani</em>);
return (
<tr key={piece.pieceId}>
<td className="p-1 border font-mono text-center text-sm"><Link to={`piece/${piece.pieceId}`}>{piece.pieceId}</Link></td>
<td className="p-1 border">{piece.name}</td>
<td className="p-1 border">{piece.composer}</td>
<td className="p-1 border">{piece.lyricist}</td>
<td className="p-1 border">{piece.arranger}</td>
<td className="p-1 border text-center">{piece.createdAt}</td>
<td className="p-1 border font-mono text-center text-sm">{piece.createdBy}</td>
<td className="p-1 border text-center">{piece.modifiedAt ?? "\u2014"}</td>
<td className="p-1 border font-mono text-center text-sm">{piece.modifiedBy ?? "\u2014"}</td>
<td className="p-1 border"><Link className="underline" to={`piece/${piece.pieceId}`}>{piece.name}</Link></td>
<td className="p-1 border">{...composerParts.flatMap((x, i, a) => i < a.length - 1 ? [x, <br />] : [x])}</td>
<td className="p-1 border text-center font-mono text-sm">
{piece.createdAt}
{piece.createdBy !== null && <><br />przez {piece.createdBy}</>}
</td>
<td className="p-1 border text-center font-mono text-sm">
{piece.modifiedAt === null && piece.modifiedBy === null ? "\u2014"
: piece.modifiedAt !== null && piece.modifiedBy === null ? piece.modifiedAt
: piece.modifiedAt === null ? `przez ${piece.createdBy}`
: <>{piece.createdAt}<br />przez {piece.createdBy}</>}
</td>
</tr>
))}
);
})}
</tbody>
</table>
)}
<div>
<PieceForm />
</div>
</div>
);
}

View File

@@ -1,8 +1,10 @@
import type { Piece } from "backend/database";
import { PieceId } from "common";
import { FormEventHandler, useId, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import type { Attachment, Piece } from "backend/database";
import { AttachmentId, PieceId } from "common";
import { ELYSIA_FORM_DATA } from "elysia";
import { FormEventHandler, useId, useReducer, useRef, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { client } from "../client";
import { FileReducer } from "../FileReducer";
import { useLoading } from "../loading";
import { Button } from "../styled/Button";
import { Input } from "../styled/Input";
@@ -11,9 +13,10 @@ export function Piece() {
const id = PieceId(useParams().pieceId!);
const { isLoading, error, data } = useLoading(() => client.piece.get({ query: { id } }));
const piece = useLoading(() => client.piece.get({ query: { id } }));
const attachments = useLoading(() => client.piece({ pieceId: id }).attachment.get());
if (isLoading) {
if (piece.isLoading || attachments.isLoading) {
return (
<div className="w-full h-full overflow-hidden flex items-center justify-center">
<div>Ładowanie</div>
@@ -22,30 +25,32 @@ export function Piece() {
}
return (
<div className="p-4 overflow-y-auto flex flex-wrap gap-4">
{error !== null ? (
`Wystąpił błąd: ${error.value}`
) : data[0] === undefined ? (
<div className="p-4 overflow-y-auto flex flex-wrap items-start gap-4">
{piece.error !== null || attachments.error !== null ? (
`Wystąpił błąd: ${[piece.error?.value, attachments.error?.value].filter(Boolean).join(", ")}`
) : piece.data[0] === undefined ? (
"Utwór nie istnieje"
) : (
<PieceForm data={data[0]} />
)}
) : (<>
<PieceForm piece={piece.data[0]} />
<Attachments pieceId={piece.data[0].pieceId} attachments={attachments.data} />
<AttachmentForm pieceId={piece.data[0].pieceId} />
</>)}
</div>
);
}
namespace PieceForm {
export interface Props {
readonly data: Piece;
readonly piece: Piece;
}
}
function PieceForm(props: PieceForm.Props) {
const [name, setName] = useState(props.data.name);
const [composer, setComposer] = useState(props.data.composer ?? "");
const [lyricist, setLyricist] = useState(props.data.lyricist ?? "");
const [arranger, setArranger] = useState(props.data.arranger ?? "");
const [name, setName] = useState(props.piece.name);
const [composer, setComposer] = useState(props.piece.composer ?? "");
const [lyricist, setLyricist] = useState(props.piece.lyricist ?? "");
const [arranger, setArranger] = useState(props.piece.arranger ?? "");
const nameId = useId();
const composerId = useId();
@@ -56,11 +61,8 @@ function PieceForm(props: PieceForm.Props) {
const onSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
e.preventDefault();
if (props.data === null) {
return;
}
const { error } = await client.piece({ pieceId: props.data.pieceId }).put({
const { error } = await client.piece({ pieceId: props.piece.pieceId }).put({
name,
composer: composer.length > 0 ? composer : null,
lyricist: lyricist.length > 0 ? lyricist : null,
@@ -84,7 +86,6 @@ function PieceForm(props: PieceForm.Props) {
type="text"
value={name}
required
disabled={props.data === null}
onChange={(e) => setName(e.target.value)}
/>
<label htmlFor={composerId}>Kompozytor</label>
@@ -92,7 +93,6 @@ function PieceForm(props: PieceForm.Props) {
id={composerId}
type="text"
value={composer}
disabled={props.data === null}
onChange={(e) => setComposer(e.target.value)}
/>
<label htmlFor={lyricistId}>Słowa</label>
@@ -100,7 +100,6 @@ function PieceForm(props: PieceForm.Props) {
id={lyricistId}
type="text"
value={lyricist}
disabled={props.data === null}
onChange={(e) => setLyricist(e.target.value)}
/>
<label htmlFor={arrangerId}>Opracowanie</label>
@@ -108,12 +107,157 @@ function PieceForm(props: PieceForm.Props) {
id={arrangerId}
type="text"
value={arranger}
disabled={props.data === null}
onChange={(e) => setArranger(e.target.value)}
/>
<Button type="submit" disabled={props.data === null}>
<Button type="submit">
Zapisz
</Button>
</form>
);
}
namespace Attachments {
export interface Props {
readonly pieceId: PieceId;
readonly attachments: readonly Attachment[];
}
}
function Attachments(props: Attachments.Props) {
const download = (attachmentId: AttachmentId) => async () => {
const { error, data: _data } = await client
.piece({ pieceId: props.pieceId })
.attachment({ attachmentId })
.get();
if (error !== null) {
console.error(error.value);
return;
}
const data = _data as unknown as typeof _data[ELYSIA_FORM_DATA];
const url = URL.createObjectURL(data.data);
const a = document.createElement("a");
a.href = url;
a.download = data.filename;
a.click();
URL.revokeObjectURL(url);
};
return (
<table className="grow">
<thead>
<tr>
<th className="p-1 border">Nazwa pliku</th>
<th className="p-1 border">Typ</th>
<th className="p-1 border">Dodano</th>
<th className="p-1 border">Zmodyfikowano</th>
<th className="p-1 border">Pobierz</th>
</tr>
</thead>
<tbody>
{props.attachments.map((attachment) => (
<tr key={attachment.attachmentId}>
<td className="p-1 border">
{attachment.mediaType === "application/vnd.recordare.musicxml"
|| attachment.mediaType === "application/vnd.recordare.musicxml+xml" ? (
<Link className="underline" to={`attachment/${attachment.attachmentId}`}>
{attachment.filename}
</Link>
) : (
attachment.filename
)}
</td>
<td className="p-1 border">{attachment.mediaType}</td>
<td className="p-1 border text-center font-mono text-sm">
{attachment.createdAt}
{attachment.createdBy !== null && <><br />przez {attachment.createdBy}</>}
</td>
<td className="p-1 border text-center font-mono text-sm">
{attachment.modifiedAt === null && attachment.modifiedBy === null ? "\u2014"
: attachment.modifiedAt !== null && attachment.modifiedBy === null ? attachment.modifiedAt
: attachment.modifiedAt === null ? `przez ${attachment.createdBy}`
: <>{attachment.createdAt}<br />przez {attachment.createdBy}</>}
</td>
<td className="p-1 border text-center">
<Button type="button" onClick={download(attachment.attachmentId)}>
Pobierz
</Button>
</td>
</tr>
))}
</tbody>
</table>
);
}
namespace AttachmentForm {
export interface Props {
readonly pieceId: PieceId;
}
}
function AttachmentForm(props: AttachmentForm.Props) {
const [{ filename, mediaType, file }, reduce] = useReducer(FileReducer, FileReducer.initial);
const filenameId = useId();
const mediaTypeId = useId();
const fileId = useId();
const fileInputRef = useRef<HTMLInputElement>(null);
const onSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
e.preventDefault();
const { error } = await client.piece({ pieceId: props.pieceId }).attachment.post({
filename,
mediaType,
data: file!,
});
if (error) {
console.error(error.value);
return;
}
reduce(FileReducer.reset);
if (fileInputRef.current !== null) {
fileInputRef.current.files = null;
}
}
return (
<form className="p-2 flex flex-col gap-2 border rounded" onSubmit={onSubmit}>
<label htmlFor={filenameId}>Nazwa pliku</label>
<Input
id={filenameId}
type="text"
value={filename}
required
onChange={(e) => reduce(FileReducer.setFilename(e.target.value))}
/>
<label htmlFor={mediaTypeId}>Typ</label>
<Input
id={mediaTypeId}
type="text"
value={mediaType}
onChange={(e) => reduce(FileReducer.setMediaType(e.target.value))}
/>
<label htmlFor={fileId}>Plik</label>
<Input
ref={fileInputRef}
id={fileId}
type="file"
onChange={(e) => {
const file = e.target.files?.item(0) ?? null;
reduce(FileReducer.setFile(file));
}}
/>
<Button type="submit">
Dodaj
</Button>
</form>
);
}

View File

@@ -30,7 +30,7 @@ export function Root() {
const { error } = await client.logout.post();
if (error !== null) {
console.error("Response was not ok");
console.error(error.value);
}
setUser(null);

View File

@@ -1,3 +1,17 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
.sheet-music-display * {
color: black;
stroke: black;
fill: black;
}
@media (prefers-color-scheme: dark) {
.sheet-music-display * {
color: white;
stroke: white;
fill: white;
}
}

1194
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,6 +12,7 @@ catalog:
elysia: '^1.1.25'
kysely: '^0.27.4'
kysely-bun-sqlite: '^0.3.2'
opensheetmusicdisplay: '^1.8.9'
postcss: '^8.4.49'
react: '^18.3.1'
react-dom: '^18.3.1'