Init
This commit is contained in:
47
src/App.svelte
Normal file
47
src/App.svelte
Normal file
@ -0,0 +1,47 @@
|
||||
<script lang="ts">
|
||||
import svelteLogo from './assets/svelte.svg'
|
||||
import viteLogo from '/vite.svg'
|
||||
import Counter from './lib/Counter.svelte'
|
||||
</script>
|
||||
|
||||
<main>
|
||||
<div>
|
||||
<a href="https://vite.dev" target="_blank" rel="noreferrer">
|
||||
<img src={viteLogo} class="logo" alt="Vite Logo" />
|
||||
</a>
|
||||
<a href="https://svelte.dev" target="_blank" rel="noreferrer">
|
||||
<img src={svelteLogo} class="logo svelte" alt="Svelte Logo" />
|
||||
</a>
|
||||
</div>
|
||||
<h1>Vite + Svelte</h1>
|
||||
|
||||
<div class="card">
|
||||
<Counter />
|
||||
</div>
|
||||
|
||||
<p>
|
||||
Check out <a href="https://github.com/sveltejs/kit#readme" target="_blank" rel="noreferrer">SvelteKit</a>, the official Svelte app framework powered by Vite!
|
||||
</p>
|
||||
|
||||
<p class="read-the-docs">
|
||||
Click on the Vite and Svelte logos to learn more
|
||||
</p>
|
||||
</main>
|
||||
|
||||
<style>
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.svelte:hover {
|
||||
filter: drop-shadow(0 0 2em #ff3e00aa);
|
||||
}
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
</style>
|
||||
79
src/app.css
Normal file
79
src/app.css
Normal file
@ -0,0 +1,79 @@
|
||||
:root {
|
||||
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
|
||||
color-scheme: light dark;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
background-color: #242424;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: 500;
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
place-items: center;
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 3.2em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
#app {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
padding: 0.6em 1.2em;
|
||||
font-size: 1em;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
background-color: #1a1a1a;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.25s;
|
||||
}
|
||||
button:hover {
|
||||
border-color: #646cff;
|
||||
}
|
||||
button:focus,
|
||||
button:focus-visible {
|
||||
outline: 4px auto -webkit-focus-ring-color;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color: #213547;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
a:hover {
|
||||
color: #747bff;
|
||||
}
|
||||
button {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
}
|
||||
1
src/assets/svelte.svg
Normal file
1
src/assets/svelte.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="26.6" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 308"><path fill="#FF3E00" d="M239.682 40.707C211.113-.182 154.69-12.301 113.895 13.69L42.247 59.356a82.198 82.198 0 0 0-37.135 55.056a86.566 86.566 0 0 0 8.536 55.576a82.425 82.425 0 0 0-12.296 30.719a87.596 87.596 0 0 0 14.964 66.244c28.574 40.893 84.997 53.007 125.787 27.016l71.648-45.664a82.182 82.182 0 0 0 37.135-55.057a86.601 86.601 0 0 0-8.53-55.577a82.409 82.409 0 0 0 12.29-30.718a87.573 87.573 0 0 0-14.963-66.244"></path><path fill="#FFF" d="M106.889 270.841c-23.102 6.007-47.497-3.036-61.103-22.648a52.685 52.685 0 0 1-9.003-39.85a49.978 49.978 0 0 1 1.713-6.693l1.35-4.115l3.671 2.697a92.447 92.447 0 0 0 28.036 14.007l2.663.808l-.245 2.659a16.067 16.067 0 0 0 2.89 10.656a17.143 17.143 0 0 0 18.397 6.828a15.786 15.786 0 0 0 4.403-1.935l71.67-45.672a14.922 14.922 0 0 0 6.734-9.977a15.923 15.923 0 0 0-2.713-12.011a17.156 17.156 0 0 0-18.404-6.832a15.78 15.78 0 0 0-4.396 1.933l-27.35 17.434a52.298 52.298 0 0 1-14.553 6.391c-23.101 6.007-47.497-3.036-61.101-22.649a52.681 52.681 0 0 1-9.004-39.849a49.428 49.428 0 0 1 22.34-33.114l71.664-45.677a52.218 52.218 0 0 1 14.563-6.398c23.101-6.007 47.497 3.036 61.101 22.648a52.685 52.685 0 0 1 9.004 39.85a50.559 50.559 0 0 1-1.713 6.692l-1.35 4.116l-3.67-2.693a92.373 92.373 0 0 0-28.037-14.013l-2.664-.809l.246-2.658a16.099 16.099 0 0 0-2.89-10.656a17.143 17.143 0 0 0-18.398-6.828a15.786 15.786 0 0 0-4.402 1.935l-71.67 45.674a14.898 14.898 0 0 0-6.73 9.975a15.9 15.9 0 0 0 2.709 12.012a17.156 17.156 0 0 0 18.404 6.832a15.841 15.841 0 0 0 4.402-1.935l27.345-17.427a52.147 52.147 0 0 1 14.552-6.397c23.101-6.006 47.497 3.037 61.102 22.65a52.681 52.681 0 0 1 9.003 39.848a49.453 49.453 0 0 1-22.34 33.12l-71.664 45.673a52.218 52.218 0 0 1-14.563 6.398"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.9 KiB |
10
src/lib/Counter.svelte
Normal file
10
src/lib/Counter.svelte
Normal file
@ -0,0 +1,10 @@
|
||||
<script lang="ts">
|
||||
let count: number = $state(0)
|
||||
const increment = () => {
|
||||
count += 1
|
||||
}
|
||||
</script>
|
||||
|
||||
<button onclick={increment}>
|
||||
count is {count}
|
||||
</button>
|
||||
166
src/lib/project-system/compression.ts
Normal file
166
src/lib/project-system/compression.ts
Normal file
@ -0,0 +1,166 @@
|
||||
import pako from 'pako';
|
||||
import type { CsoundProject, CompressedProject } from './types';
|
||||
|
||||
const COMPRESSION_VERSION = 1;
|
||||
|
||||
/**
|
||||
* Convert a string to a Uint8Array
|
||||
*/
|
||||
function stringToUint8Array(str: string): Uint8Array {
|
||||
const encoder = new TextEncoder();
|
||||
return encoder.encode(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a Uint8Array to a string
|
||||
*/
|
||||
function uint8ArrayToString(arr: Uint8Array): string {
|
||||
const decoder = new TextDecoder();
|
||||
return decoder.decode(arr);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert Uint8Array to base64 string (URL-safe)
|
||||
*/
|
||||
function uint8ArrayToBase64(arr: Uint8Array): string {
|
||||
let binary = '';
|
||||
const len = arr.byteLength;
|
||||
for (let i = 0; i < len; i++) {
|
||||
binary += String.fromCharCode(arr[i]);
|
||||
}
|
||||
return btoa(binary)
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=/g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert base64 string (URL-safe) to Uint8Array
|
||||
*/
|
||||
function base64ToUint8Array(base64: string): Uint8Array {
|
||||
// Restore standard base64
|
||||
const standardBase64 = base64
|
||||
.replace(/-/g, '+')
|
||||
.replace(/_/g, '/');
|
||||
|
||||
// Add padding if needed
|
||||
const padding = '='.repeat((4 - (standardBase64.length % 4)) % 4);
|
||||
const paddedBase64 = standardBase64 + padding;
|
||||
|
||||
const binary = atob(paddedBase64);
|
||||
const len = binary.length;
|
||||
const arr = new Uint8Array(len);
|
||||
|
||||
for (let i = 0; i < len; i++) {
|
||||
arr[i] = binary.charCodeAt(i);
|
||||
}
|
||||
|
||||
return arr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compress a project to a base64 string for sharing
|
||||
*/
|
||||
export function compressProject(project: CsoundProject): CompressedProject {
|
||||
try {
|
||||
// Convert project to JSON string
|
||||
const jsonString = JSON.stringify(project);
|
||||
|
||||
// Convert to Uint8Array
|
||||
const uint8Array = stringToUint8Array(jsonString);
|
||||
|
||||
// Compress using pako (gzip)
|
||||
const compressed = pako.deflate(uint8Array, { level: 9 });
|
||||
|
||||
// Convert to base64
|
||||
const base64 = uint8ArrayToBase64(compressed);
|
||||
|
||||
return {
|
||||
data: base64,
|
||||
version: COMPRESSION_VERSION,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to compress project: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompress a base64 string back to a project
|
||||
*/
|
||||
export function decompressProject(compressed: CompressedProject): CsoundProject {
|
||||
try {
|
||||
// Check version compatibility
|
||||
if (compressed.version !== COMPRESSION_VERSION) {
|
||||
throw new Error(`Unsupported compression version: ${compressed.version}`);
|
||||
}
|
||||
|
||||
// Convert base64 to Uint8Array
|
||||
const uint8Array = base64ToUint8Array(compressed.data);
|
||||
|
||||
// Decompress using pako
|
||||
const decompressed = pako.inflate(uint8Array);
|
||||
|
||||
// Convert to string
|
||||
const jsonString = uint8ArrayToString(decompressed);
|
||||
|
||||
// Parse JSON
|
||||
const project = JSON.parse(jsonString) as CsoundProject;
|
||||
|
||||
// Validate that we have the required fields
|
||||
if (!project.id || !project.title || !project.content === undefined) {
|
||||
throw new Error('Invalid project data structure');
|
||||
}
|
||||
|
||||
return project;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to decompress project: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a shareable URL from a project
|
||||
*/
|
||||
export function projectToShareUrl(project: CsoundProject, baseUrl: string = window.location.origin): string {
|
||||
const compressed = compressProject(project);
|
||||
const params = new URLSearchParams({
|
||||
v: compressed.version.toString(),
|
||||
d: compressed.data,
|
||||
});
|
||||
|
||||
return `${baseUrl}?${params.toString()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a project from a URL
|
||||
*/
|
||||
export function projectFromShareUrl(url: string): CsoundProject {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
const params = urlObj.searchParams;
|
||||
|
||||
const version = parseInt(params.get('v') || '1', 10);
|
||||
const data = params.get('d');
|
||||
|
||||
if (!data) {
|
||||
throw new Error('No project data found in URL');
|
||||
}
|
||||
|
||||
const compressed: CompressedProject = { version, data };
|
||||
return decompressProject(compressed);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse project from URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the approximate compression ratio
|
||||
*/
|
||||
export function getCompressionRatio(project: CsoundProject): number {
|
||||
const original = JSON.stringify(project);
|
||||
const compressed = compressProject(project);
|
||||
|
||||
const originalSize = new TextEncoder().encode(original).length;
|
||||
const compressedSize = base64ToUint8Array(compressed.data).length;
|
||||
|
||||
return originalSize / compressedSize;
|
||||
}
|
||||
233
src/lib/project-system/db.ts
Normal file
233
src/lib/project-system/db.ts
Normal file
@ -0,0 +1,233 @@
|
||||
import type { CsoundProject } from './types';
|
||||
|
||||
const DB_NAME = 'csound-projects-db';
|
||||
const DB_VERSION = 1;
|
||||
const STORE_NAME = 'projects';
|
||||
|
||||
/**
|
||||
* Database wrapper for IndexedDB operations
|
||||
*/
|
||||
class ProjectDatabase {
|
||||
private db: IDBDatabase | null = null;
|
||||
private initPromise: Promise<void> | null = null;
|
||||
|
||||
/**
|
||||
* Initialize the database connection
|
||||
*/
|
||||
async init(): Promise<void> {
|
||||
if (this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.initPromise) {
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
this.initPromise = new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to open database: ${request.error?.message}`));
|
||||
};
|
||||
|
||||
request.onsuccess = () => {
|
||||
this.db = request.result;
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onupgradeneeded = (event) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
|
||||
// Create object store if it doesn't exist
|
||||
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
||||
const objectStore = db.createObjectStore(STORE_NAME, {
|
||||
keyPath: 'id',
|
||||
});
|
||||
|
||||
// Create indexes for efficient querying
|
||||
objectStore.createIndex('title', 'title', { unique: false });
|
||||
objectStore.createIndex('author', 'author', { unique: false });
|
||||
objectStore.createIndex('dateCreated', 'dateCreated', { unique: false });
|
||||
objectStore.createIndex('dateModified', 'dateModified', { unique: false });
|
||||
objectStore.createIndex('tags', 'tags', { unique: false, multiEntry: true });
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
return this.initPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure database is initialized
|
||||
*/
|
||||
private async ensureDb(): Promise<IDBDatabase> {
|
||||
await this.init();
|
||||
if (!this.db) {
|
||||
throw new Error('Database not initialized');
|
||||
}
|
||||
return this.db;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a project by ID
|
||||
*/
|
||||
async get(id: string): Promise<CsoundProject | null> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readonly');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.get(id);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result || null);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get project: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all projects
|
||||
*/
|
||||
async getAll(): Promise<CsoundProject[]> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readonly');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.getAll();
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result || []);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get all projects: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save or update a project
|
||||
*/
|
||||
async put(project: CsoundProject): Promise<void> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readwrite');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.put(project);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to save project: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a project by ID
|
||||
*/
|
||||
async delete(id: string): Promise<void> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readwrite');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.delete(id);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to delete project: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects by tag
|
||||
*/
|
||||
async getByTag(tag: string): Promise<CsoundProject[]> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readonly');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const index = store.index('tags');
|
||||
const request = index.getAll(tag);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result || []);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get projects by tag: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects by author
|
||||
*/
|
||||
async getByAuthor(author: string): Promise<CsoundProject[]> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readonly');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const index = store.index('author');
|
||||
const request = index.getAll(author);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve(request.result || []);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get projects by author: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all projects (use with caution!)
|
||||
*/
|
||||
async clear(): Promise<void> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = db.transaction([STORE_NAME], 'readwrite');
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const request = store.clear();
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to clear projects: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the database connection
|
||||
*/
|
||||
close(): void {
|
||||
if (this.db) {
|
||||
this.db.close();
|
||||
this.db = null;
|
||||
this.initPromise = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const projectDb = new ProjectDatabase();
|
||||
56
src/lib/project-system/index.ts
Normal file
56
src/lib/project-system/index.ts
Normal file
@ -0,0 +1,56 @@
|
||||
/**
|
||||
* Csound Project Management System
|
||||
*
|
||||
* This module provides a complete project system for managing Csound code files
|
||||
* with browser-based storage (IndexedDB) and import/export functionality via
|
||||
* compressed URLs.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { projectManager } from './lib/project-system';
|
||||
*
|
||||
* // Initialize
|
||||
* await projectManager.init();
|
||||
*
|
||||
* // Create a new project
|
||||
* const result = await projectManager.createProject({
|
||||
* title: 'My First Csound Project',
|
||||
* author: 'John Doe',
|
||||
* content: '<CsoundSynthesizer>...</CsoundSynthesizer>',
|
||||
* tags: ['synth', 'experiment']
|
||||
* });
|
||||
*
|
||||
* // Get all projects
|
||||
* const projects = await projectManager.getAllProjects();
|
||||
*
|
||||
* // Export to shareable URL
|
||||
* const urlResult = await projectManager.exportProjectToUrl(result.data.id);
|
||||
*
|
||||
* // Import from URL
|
||||
* const imported = await projectManager.importProjectFromUrl(url);
|
||||
* ```
|
||||
*/
|
||||
|
||||
// Export types
|
||||
export type {
|
||||
CsoundProject,
|
||||
CreateProjectData,
|
||||
UpdateProjectData,
|
||||
CompressedProject,
|
||||
Result,
|
||||
} from './types';
|
||||
|
||||
// Export main API
|
||||
export { ProjectManager, projectManager } from './project-manager';
|
||||
|
||||
// Export database (for advanced usage)
|
||||
export { projectDb } from './db';
|
||||
|
||||
// Export compression utilities (for advanced usage)
|
||||
export {
|
||||
compressProject,
|
||||
decompressProject,
|
||||
projectToShareUrl,
|
||||
projectFromShareUrl,
|
||||
getCompressionRatio,
|
||||
} from './compression';
|
||||
343
src/lib/project-system/project-manager.ts
Normal file
343
src/lib/project-system/project-manager.ts
Normal file
@ -0,0 +1,343 @@
|
||||
import type { CsoundProject, CreateProjectData, UpdateProjectData, Result } from './types';
|
||||
import { projectDb } from './db';
|
||||
import { compressProject, decompressProject, projectToShareUrl, projectFromShareUrl } from './compression';
|
||||
|
||||
const CSOUND_VERSION = '7.0.0'; // This should be detected from @csound/browser
|
||||
|
||||
/**
|
||||
* Generate a unique ID for a project
|
||||
*/
|
||||
function generateId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current ISO timestamp
|
||||
*/
|
||||
function getCurrentTimestamp(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Project Manager - Main API for managing Csound projects
|
||||
*/
|
||||
export class ProjectManager {
|
||||
/**
|
||||
* Initialize the project manager (initializes database)
|
||||
*/
|
||||
async init(): Promise<void> {
|
||||
await projectDb.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new project
|
||||
*/
|
||||
async createProject(data: CreateProjectData): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const now = getCurrentTimestamp();
|
||||
|
||||
const project: CsoundProject = {
|
||||
id: generateId(),
|
||||
title: data.title,
|
||||
author: data.author,
|
||||
dateCreated: now,
|
||||
dateModified: now,
|
||||
saveCount: 0,
|
||||
content: data.content || '',
|
||||
tags: data.tags || [],
|
||||
csoundVersion: CSOUND_VERSION,
|
||||
};
|
||||
|
||||
await projectDb.put(project);
|
||||
|
||||
return { success: true, data: project };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to create project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a project by ID
|
||||
*/
|
||||
async getProject(id: string): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const project = await projectDb.get(id);
|
||||
|
||||
if (!project) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, data: project };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to get project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all projects
|
||||
*/
|
||||
async getAllProjects(): Promise<Result<CsoundProject[]>> {
|
||||
try {
|
||||
const projects = await projectDb.getAll();
|
||||
return { success: true, data: projects };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to get projects'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update an existing project
|
||||
*/
|
||||
async updateProject(data: UpdateProjectData): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const existingProject = await projectDb.get(data.id);
|
||||
|
||||
if (!existingProject) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${data.id}`),
|
||||
};
|
||||
}
|
||||
|
||||
const updatedProject: CsoundProject = {
|
||||
...existingProject,
|
||||
...(data.title !== undefined && { title: data.title }),
|
||||
...(data.author !== undefined && { author: data.author }),
|
||||
...(data.content !== undefined && { content: data.content }),
|
||||
...(data.tags !== undefined && { tags: data.tags }),
|
||||
dateModified: getCurrentTimestamp(),
|
||||
saveCount: existingProject.saveCount + 1,
|
||||
};
|
||||
|
||||
await projectDb.put(updatedProject);
|
||||
|
||||
return { success: true, data: updatedProject };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to update project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a project
|
||||
*/
|
||||
async deleteProject(id: string): Promise<Result<void>> {
|
||||
try {
|
||||
await projectDb.delete(id);
|
||||
return { success: true, data: undefined };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to delete project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects by tag
|
||||
*/
|
||||
async getProjectsByTag(tag: string): Promise<Result<CsoundProject[]>> {
|
||||
try {
|
||||
const projects = await projectDb.getByTag(tag);
|
||||
return { success: true, data: projects };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to search projects by tag'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search projects by author
|
||||
*/
|
||||
async getProjectsByAuthor(author: string): Promise<Result<CsoundProject[]>> {
|
||||
try {
|
||||
const projects = await projectDb.getByAuthor(author);
|
||||
return { success: true, data: projects };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to search projects by author'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a project to a shareable URL
|
||||
*/
|
||||
async exportProjectToUrl(id: string, baseUrl?: string): Promise<Result<string>> {
|
||||
try {
|
||||
const project = await projectDb.get(id);
|
||||
|
||||
if (!project) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
const url = projectToShareUrl(project, baseUrl);
|
||||
|
||||
return { success: true, data: url };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to export project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Export a project to compressed data (for copying to clipboard, etc.)
|
||||
*/
|
||||
async exportProjectToCompressed(id: string): Promise<Result<string>> {
|
||||
try {
|
||||
const project = await projectDb.get(id);
|
||||
|
||||
if (!project) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
const compressed = compressProject(project);
|
||||
|
||||
return { success: true, data: compressed.data };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to export project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import a project from a URL
|
||||
*/
|
||||
async importProjectFromUrl(url: string): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const project = projectFromShareUrl(url);
|
||||
|
||||
// Generate a new ID and reset timestamps
|
||||
const now = getCurrentTimestamp();
|
||||
const importedProject: CsoundProject = {
|
||||
...project,
|
||||
id: generateId(),
|
||||
dateCreated: now,
|
||||
dateModified: now,
|
||||
saveCount: 0,
|
||||
title: `${project.title} (imported)`,
|
||||
};
|
||||
|
||||
await projectDb.put(importedProject);
|
||||
|
||||
return { success: true, data: importedProject };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to import project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import a project from compressed data
|
||||
*/
|
||||
async importProjectFromCompressed(compressedData: string): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const project = decompressProject({
|
||||
data: compressedData,
|
||||
version: 1,
|
||||
});
|
||||
|
||||
// Generate a new ID and reset timestamps
|
||||
const now = getCurrentTimestamp();
|
||||
const importedProject: CsoundProject = {
|
||||
...project,
|
||||
id: generateId(),
|
||||
dateCreated: now,
|
||||
dateModified: now,
|
||||
saveCount: 0,
|
||||
title: `${project.title} (imported)`,
|
||||
};
|
||||
|
||||
await projectDb.put(importedProject);
|
||||
|
||||
return { success: true, data: importedProject };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to import project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Duplicate a project
|
||||
*/
|
||||
async duplicateProject(id: string): Promise<Result<CsoundProject>> {
|
||||
try {
|
||||
const originalProject = await projectDb.get(id);
|
||||
|
||||
if (!originalProject) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`Project not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
const now = getCurrentTimestamp();
|
||||
const duplicatedProject: CsoundProject = {
|
||||
...originalProject,
|
||||
id: generateId(),
|
||||
title: `${originalProject.title} (copy)`,
|
||||
dateCreated: now,
|
||||
dateModified: now,
|
||||
saveCount: 0,
|
||||
};
|
||||
|
||||
await projectDb.put(duplicatedProject);
|
||||
|
||||
return { success: true, data: duplicatedProject };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to duplicate project'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all projects (use with caution!)
|
||||
*/
|
||||
async clearAllProjects(): Promise<Result<void>> {
|
||||
try {
|
||||
await projectDb.clear();
|
||||
return { success: true, data: undefined };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to clear projects'),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton instance
|
||||
export const projectManager = new ProjectManager();
|
||||
70
src/lib/project-system/types.ts
Normal file
70
src/lib/project-system/types.ts
Normal file
@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Core data structure for a Csound project
|
||||
*/
|
||||
export interface CsoundProject {
|
||||
/** Unique identifier for the project */
|
||||
id: string;
|
||||
|
||||
/** User-defined project title */
|
||||
title: string;
|
||||
|
||||
/** Project author name */
|
||||
author: string;
|
||||
|
||||
/** Date when the project was created (ISO string) */
|
||||
dateCreated: string;
|
||||
|
||||
/** Date when the project was last modified (ISO string) */
|
||||
dateModified: string;
|
||||
|
||||
/** Number of times the project has been saved */
|
||||
saveCount: number;
|
||||
|
||||
/** The Csound code content */
|
||||
content: string;
|
||||
|
||||
/** Optional tags for categorization */
|
||||
tags: string[];
|
||||
|
||||
/** Csound version used to create this project */
|
||||
csoundVersion: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Data structure for creating a new project (omits auto-generated fields)
|
||||
*/
|
||||
export interface CreateProjectData {
|
||||
title: string;
|
||||
author: string;
|
||||
content?: string;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Data structure for updating an existing project
|
||||
*/
|
||||
export interface UpdateProjectData {
|
||||
id: string;
|
||||
title?: string;
|
||||
author?: string;
|
||||
content?: string;
|
||||
tags?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Compressed project data for import/export via links
|
||||
*/
|
||||
export interface CompressedProject {
|
||||
/** Base64-encoded compressed project data */
|
||||
data: string;
|
||||
|
||||
/** Version of the compression format (for future compatibility) */
|
||||
version: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result type for async operations
|
||||
*/
|
||||
export type Result<T, E = Error> =
|
||||
| { success: true; data: T }
|
||||
| { success: false; error: E };
|
||||
9
src/main.ts
Normal file
9
src/main.ts
Normal file
@ -0,0 +1,9 @@
|
||||
import { mount } from 'svelte'
|
||||
import './app.css'
|
||||
import App from './App.svelte'
|
||||
|
||||
const app = mount(App, {
|
||||
target: document.getElementById('app')!,
|
||||
})
|
||||
|
||||
export default app
|
||||
Reference in New Issue
Block a user