[FEAT] First functional version.
This commit is contained in:
113
partitions/src/lib/api.ts
Normal file
113
partitions/src/lib/api.ts
Normal file
@@ -0,0 +1,113 @@
|
||||
import axios, { type AxiosError } from 'axios';
|
||||
import { auth } from '$lib/stores/auth';
|
||||
import { browser } from '$app/environment';
|
||||
import { get } from 'svelte/store';
|
||||
|
||||
const API_BASE_URL = browser ? 'http://localhost:8000' : 'http://localhost:8000';
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
export { api };
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const authState = get(auth);
|
||||
if (authState.token) {
|
||||
config.headers.Authorization = `Bearer ${authState.token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error: AxiosError) => {
|
||||
if (error.response?.status === 401) {
|
||||
auth.logout();
|
||||
if (browser) {
|
||||
window.location.href = '/';
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export interface Score {
|
||||
id: string;
|
||||
name: string;
|
||||
compositor: string;
|
||||
ressource?: string | null;
|
||||
instruments?: Instrument[];
|
||||
}
|
||||
|
||||
export interface Piece {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface Instrument {
|
||||
id: string;
|
||||
title: string;
|
||||
piece: string;
|
||||
parts: Part[];
|
||||
}
|
||||
|
||||
export interface Part {
|
||||
id: string;
|
||||
files: PdfFile[];
|
||||
}
|
||||
|
||||
export interface PdfFile {
|
||||
name: string;
|
||||
filename: string;
|
||||
path: string;
|
||||
part: string | null;
|
||||
key: string | null;
|
||||
clef: string | null;
|
||||
variant: string | null;
|
||||
}
|
||||
|
||||
export const apiService = {
|
||||
async login(username: string, password: string): Promise<{ token: string; user: { username: string; role: string } }> {
|
||||
const response = await api.post('/login', { username, password });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
async getScores(): Promise<Score[]> {
|
||||
const response = await api.get('/scores');
|
||||
return response.data.scores;
|
||||
},
|
||||
|
||||
async getScore(id: string): Promise<Score> {
|
||||
const response = await api.get(`/scores/${id}`);
|
||||
return response.data.score;
|
||||
},
|
||||
|
||||
async getInstruments(scoreId: string): Promise<Instrument[]> {
|
||||
const response = await api.get(`/scores/${scoreId}/instruments`);
|
||||
return response.data.instruments;
|
||||
},
|
||||
|
||||
async getPieces(scoreId: string): Promise<Piece[]> {
|
||||
const response = await api.get(`/pieces/${scoreId}`);
|
||||
return response.data.pieces;
|
||||
},
|
||||
|
||||
async downloadPdf(path: string): Promise<Blob> {
|
||||
const response = await api.get(`/download/${path}`, {
|
||||
responseType: 'blob'
|
||||
});
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getDownloadUrl(path: string): string {
|
||||
let token = '';
|
||||
auth.subscribe((state) => {
|
||||
token = state.token || '';
|
||||
})();
|
||||
return `${API_BASE_URL}/download/${path}?token=${token}`;
|
||||
}
|
||||
};
|
||||
206
partitions/src/lib/components/PdfViewer.svelte
Normal file
206
partitions/src/lib/components/PdfViewer.svelte
Normal file
@@ -0,0 +1,206 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from 'svelte';
|
||||
import * as pdfjsLib from 'pdfjs-dist';
|
||||
import { api } from '$lib/api';
|
||||
|
||||
pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs';
|
||||
|
||||
interface Props {
|
||||
pdfUrl: string;
|
||||
title?: string;
|
||||
key?: string;
|
||||
}
|
||||
|
||||
let { pdfUrl, title = 'Partition', key = '' }: Props = $props();
|
||||
|
||||
// Force re-render when key changes
|
||||
$effect(() => {
|
||||
if (key) {
|
||||
loadPdf();
|
||||
}
|
||||
});
|
||||
|
||||
let canvas: HTMLCanvasElement;
|
||||
let pdfDoc: pdfjsLib.PDFDocumentProxy | null = null;
|
||||
let currentPage = $state(1);
|
||||
let totalPages = $state(0);
|
||||
let scale = $state(1.2);
|
||||
let loading = $state(true);
|
||||
let error = $state('');
|
||||
let rendering = $state(false);
|
||||
|
||||
async function loadPdf() {
|
||||
loading = true;
|
||||
error = '';
|
||||
try {
|
||||
// Load PDF via axios to include auth token
|
||||
const path = pdfUrl.split('/download/')[1];
|
||||
const response = await api.get(`/download/${path}`, {
|
||||
responseType: 'blob'
|
||||
});
|
||||
const blob = new Blob([response.data], { type: 'application/pdf' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
|
||||
const loadingTask = pdfjsLib.getDocument(url);
|
||||
pdfDoc = await loadingTask.promise;
|
||||
totalPages = pdfDoc.numPages;
|
||||
await renderPage(currentPage);
|
||||
} catch (err) {
|
||||
console.error('Error loading PDF:', err);
|
||||
error = 'Erreur lors du chargement du PDF';
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function renderPage(pageNum: number) {
|
||||
if (!pdfDoc || rendering) return;
|
||||
rendering = true;
|
||||
|
||||
try {
|
||||
const page = await pdfDoc.getPage(pageNum);
|
||||
const viewport = page.getViewport({ scale });
|
||||
const context = canvas.getContext('2d');
|
||||
|
||||
if (!context) return;
|
||||
|
||||
canvas.height = viewport.height;
|
||||
canvas.width = viewport.width;
|
||||
|
||||
await page.render({
|
||||
canvasContext: context,
|
||||
viewport
|
||||
}).promise;
|
||||
} catch (err) {
|
||||
console.error('Error rendering page:', err);
|
||||
} finally {
|
||||
rendering = false;
|
||||
}
|
||||
}
|
||||
|
||||
function prevPage() {
|
||||
if (currentPage > 1) {
|
||||
currentPage--;
|
||||
renderPage(currentPage);
|
||||
}
|
||||
}
|
||||
|
||||
function nextPage() {
|
||||
if (currentPage < totalPages) {
|
||||
currentPage++;
|
||||
renderPage(currentPage);
|
||||
}
|
||||
}
|
||||
|
||||
function zoomIn() {
|
||||
scale = Math.min(scale + 0.2, 3);
|
||||
renderPage(currentPage);
|
||||
}
|
||||
|
||||
function zoomOut() {
|
||||
scale = Math.max(scale - 0.2, 0.5);
|
||||
renderPage(currentPage);
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
|
||||
prevPage();
|
||||
} else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
|
||||
nextPage();
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
loadPdf();
|
||||
window.addEventListener('keydown', handleKeydown);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
window.removeEventListener('keydown', handleKeydown);
|
||||
if (pdfDoc) {
|
||||
pdfDoc.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (pdfUrl) {
|
||||
loadPdf();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="flex flex-col h-full">
|
||||
<div class="bg-ohmj-dark text-white px-4 py-2 flex items-center justify-between">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-semibold">{title}</span>
|
||||
{#if totalPages > 0}
|
||||
<span class="text-gray-400">| Page {currentPage} / {totalPages}</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
onclick={zoomOut}
|
||||
class="px-2 py-1 bg-gray-700 hover:bg-gray-600 rounded text-sm"
|
||||
title="Zoom -"
|
||||
>
|
||||
➖
|
||||
</button>
|
||||
<span class="text-sm w-16 text-center">{Math.round(scale * 100)}%</span>
|
||||
<button
|
||||
onclick={zoomIn}
|
||||
class="px-2 py-1 bg-gray-700 hover:bg-gray-600 rounded text-sm"
|
||||
title="Zoom +"
|
||||
>
|
||||
➕
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 overflow-auto bg-gray-800 flex items-start justify-center p-4">
|
||||
{#if loading}
|
||||
<div class="text-white">
|
||||
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"></div>
|
||||
<p>Chargement du PDF...</p>
|
||||
</div>
|
||||
{:else if error}
|
||||
<div class="text-red-400 text-center">
|
||||
<p class="text-xl mb-2">⚠️</p>
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
{:else}
|
||||
<canvas bind:this={canvas} class="shadow-2xl"></canvas>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<div class="bg-ohmj-dark text-white px-4 py-3 flex items-center justify-center gap-4">
|
||||
<button
|
||||
onclick={prevPage}
|
||||
disabled={currentPage <= 1}
|
||||
class="px-4 py-2 bg-ohmj-primary hover:bg-ohmj-secondary disabled:opacity-50 disabled:cursor-not-allowed rounded transition-colors"
|
||||
>
|
||||
◀ Précédent
|
||||
</button>
|
||||
|
||||
<div class="flex gap-1">
|
||||
{#each Array(Math.min(5, totalPages)) as _, i}
|
||||
{@const pageNum = Math.max(1, Math.min(currentPage - 2, totalPages - 4)) + i}
|
||||
{#if pageNum <= totalPages}
|
||||
<button
|
||||
onclick={() => { currentPage = pageNum; renderPage(pageNum); }}
|
||||
class="w-8 h-8 rounded {currentPage === pageNum ? 'bg-ohmj-secondary text-ohmj-dark font-bold' : 'bg-gray-700 hover:bg-gray-600'}"
|
||||
>
|
||||
{pageNum}
|
||||
</button>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onclick={nextPage}
|
||||
disabled={currentPage >= totalPages}
|
||||
class="px-4 py-2 bg-ohmj-primary hover:bg-ohmj-secondary disabled:opacity-50 disabled:cursor-not-allowed rounded transition-colors"
|
||||
>
|
||||
Suivant ▶
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
43
partitions/src/lib/stores/auth.ts
Normal file
43
partitions/src/lib/stores/auth.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import { browser } from '$app/environment';
|
||||
|
||||
interface User {
|
||||
username: string;
|
||||
role: string;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
token: string | null;
|
||||
user: User | null;
|
||||
}
|
||||
|
||||
function createAuthStore() {
|
||||
const stored = browser ? localStorage.getItem('auth') : null;
|
||||
const initial: AuthState = stored ? JSON.parse(stored) : { token: null, user: null };
|
||||
|
||||
const { subscribe, set, update } = writable<AuthState>(initial);
|
||||
|
||||
return {
|
||||
subscribe,
|
||||
login: (token: string, user: User) => {
|
||||
const state = { token, user };
|
||||
set(state);
|
||||
if (browser) {
|
||||
localStorage.setItem('auth', JSON.stringify(state));
|
||||
}
|
||||
},
|
||||
logout: () => {
|
||||
set({ token: null, user: null });
|
||||
if (browser) {
|
||||
localStorage.removeItem('auth');
|
||||
}
|
||||
},
|
||||
getToken: () => {
|
||||
let token: string | null = null;
|
||||
update((s) => (token = s.token));
|
||||
return token;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const auth = createAuthStore();
|
||||
Reference in New Issue
Block a user