Integrate CCN 2025-2026 files
This commit is contained in:
252
src/App.svelte
252
src/App.svelte
@ -9,22 +9,15 @@
|
||||
import AudioScope from "./lib/components/audio/AudioScope.svelte";
|
||||
import Spectrogram from "./lib/components/audio/Spectrogram.svelte";
|
||||
import ConfirmDialog from "./lib/components/ui/ConfirmDialog.svelte";
|
||||
import InputDialog from "./lib/components/ui/InputDialog.svelte";
|
||||
import TemplateDialog from "./lib/components/ui/TemplateDialog.svelte";
|
||||
import CsoundReference from "./lib/components/reference/CsoundReference.svelte";
|
||||
import {
|
||||
createCsoundDerivedStores,
|
||||
type LogEntry,
|
||||
type EvalSource,
|
||||
} from "./lib/csound";
|
||||
import { type CsoundProject } from "./lib/project-system";
|
||||
import {
|
||||
templateRegistry,
|
||||
type CsoundTemplate,
|
||||
} from "./lib/templates/template-registry";
|
||||
import { loadLastProjectId } from "./lib/project-system/persistence";
|
||||
import { type File } from "./lib/project-system";
|
||||
import { loadOpenTabs, loadCurrentFileId } from "./lib/project-system/persistence";
|
||||
import { createAppContext, setAppContext } from "./lib/contexts/app-context";
|
||||
import type { ProjectMode } from "./lib/project-system/types";
|
||||
import { themes, applyTheme } from "./lib/themes";
|
||||
import {
|
||||
Save,
|
||||
@ -42,9 +35,9 @@
|
||||
|
||||
const {
|
||||
csound,
|
||||
projectManager,
|
||||
fileManager,
|
||||
editorSettings,
|
||||
projectEditor,
|
||||
editorState,
|
||||
uiState,
|
||||
executionContext,
|
||||
} = appContext;
|
||||
@ -57,45 +50,39 @@
|
||||
let logsUnsubscribe: (() => void) | undefined;
|
||||
|
||||
onMount(async () => {
|
||||
await projectManager.init();
|
||||
await fileManager.init();
|
||||
await editorState.refreshFileCache();
|
||||
|
||||
const lastProjectId = loadLastProjectId();
|
||||
let projectToLoad: CsoundProject | null = null;
|
||||
// Try to restore open tabs
|
||||
const openTabIds = loadOpenTabs();
|
||||
const currentFileId = loadCurrentFileId();
|
||||
|
||||
if (lastProjectId) {
|
||||
const result = await projectManager.getProject(lastProjectId);
|
||||
if (result.success) {
|
||||
projectToLoad = result.data;
|
||||
if (openTabIds.length > 0) {
|
||||
// Restore tabs
|
||||
for (const fileId of openTabIds) {
|
||||
await editorState.openFile(fileId);
|
||||
}
|
||||
}
|
||||
|
||||
if (!projectToLoad) {
|
||||
const allProjectsResult = await projectManager.getAllProjects();
|
||||
if (allProjectsResult.success) {
|
||||
if (allProjectsResult.data.length > 0) {
|
||||
projectToLoad = allProjectsResult.data[0];
|
||||
} else {
|
||||
const classicTemplate = templateRegistry.getById("classic");
|
||||
if (classicTemplate) {
|
||||
const createResult = await projectManager.createProject({
|
||||
title: "Welcome",
|
||||
author: "System",
|
||||
content: classicTemplate.content,
|
||||
tags: [],
|
||||
mode: classicTemplate.mode,
|
||||
});
|
||||
if (createResult.success) {
|
||||
projectToLoad = createResult.data;
|
||||
}
|
||||
}
|
||||
// Switch to last current file
|
||||
if (currentFileId && openTabIds.includes(currentFileId)) {
|
||||
await editorState.switchToFile(currentFileId);
|
||||
}
|
||||
} else {
|
||||
// No tabs to restore, check if we have any files
|
||||
const allFilesResult = await fileManager.getAllFiles();
|
||||
if (allFilesResult.success && allFilesResult.data.length > 0) {
|
||||
// Open the first file
|
||||
await editorState.openFile(allFilesResult.data[0].id);
|
||||
} else {
|
||||
// No files at all, create a welcome file
|
||||
const welcomeContent = '<CsoundSynthesizer>\n<CsOptions>\n-odac\n</CsOptions>\n<CsInstruments>\n\nsr = 44100\nksmps = 32\nnchnls = 2\n0dbfs = 1\n\ninstr 1\n kEnv madsr 0.1, 0.2, 0.7, 0.5\n aOut oscil kEnv * 0.3, 440\n outs aOut, aOut\nendin\n\n</CsInstruments>\n<CsScore>\ni 1 0 2\n</CsScore>\n</CsoundSynthesizer>';
|
||||
const result = await fileManager.createFile({ title: 'Welcome.orc', content: welcomeContent });
|
||||
if (result.success) {
|
||||
await editorState.openFile(result.data.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (projectToLoad) {
|
||||
projectEditor.loadProject(projectToLoad);
|
||||
}
|
||||
|
||||
logsUnsubscribe = csoundLogs.subscribe((logs) => {
|
||||
interpreterLogs = logs;
|
||||
});
|
||||
@ -134,94 +121,65 @@
|
||||
}
|
||||
|
||||
function handleEditorChange(value: string) {
|
||||
projectEditor.setContent(value);
|
||||
editorState.setContent(value);
|
||||
}
|
||||
|
||||
async function handleNewEmptyFile() {
|
||||
const emptyTemplate = templateRegistry.getEmpty();
|
||||
const result = projectEditor.requestSwitch(async () =>
|
||||
await projectEditor.createNew(emptyTemplate.content, emptyTemplate.mode),
|
||||
);
|
||||
|
||||
if (result === "confirm-unsaved") {
|
||||
uiState.showUnsavedChangesDialog();
|
||||
}
|
||||
async function handleNewFile() {
|
||||
await editorState.createNewFile();
|
||||
}
|
||||
|
||||
function handleNewFromTemplate() {
|
||||
uiState.showTemplateDialog();
|
||||
async function handleFileOpen(fileId: string) {
|
||||
await editorState.openFile(fileId);
|
||||
}
|
||||
|
||||
async function handleTemplateSelect(template: CsoundTemplate) {
|
||||
uiState.hideTemplateDialog();
|
||||
|
||||
const result = projectEditor.requestSwitch(async () =>
|
||||
await projectEditor.createNew(template.content, template.mode),
|
||||
);
|
||||
|
||||
if (result === "confirm-unsaved") {
|
||||
uiState.showUnsavedChangesDialog();
|
||||
}
|
||||
async function handleFileDelete(fileId: string) {
|
||||
await editorState.deleteFile(fileId);
|
||||
}
|
||||
|
||||
function handleFileSelect(project: CsoundProject | null) {
|
||||
if (!project) return;
|
||||
|
||||
const result = projectEditor.requestSwitch(() =>
|
||||
projectEditor.loadProject(project),
|
||||
);
|
||||
|
||||
if (result === "confirm-unsaved") {
|
||||
uiState.showUnsavedChangesDialog();
|
||||
}
|
||||
async function handleFileRename(fileId: string, newTitle: string) {
|
||||
await editorState.renameFile(fileId, newTitle);
|
||||
}
|
||||
|
||||
async function handleExecute(code: string, source: EvalSource) {
|
||||
async function handleTabClick(fileId: string) {
|
||||
await editorState.switchToFile(fileId);
|
||||
}
|
||||
|
||||
async function handleTabClose(fileId: string) {
|
||||
await editorState.closeFile(fileId);
|
||||
}
|
||||
|
||||
async function handleExecuteFile() {
|
||||
try {
|
||||
await executionContext.execute(code, source);
|
||||
await executionContext.executeFile();
|
||||
} catch (error) {
|
||||
console.error("Execution error:", error);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExecuteBlock(code: string) {
|
||||
try {
|
||||
await executionContext.executeBlock(code);
|
||||
} catch (error) {
|
||||
console.error("Execution error:", error);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleExecuteSelection(code: string) {
|
||||
try {
|
||||
await executionContext.executeSelection(code);
|
||||
} catch (error) {
|
||||
console.error("Execution error:", error);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
await projectEditor.save();
|
||||
}
|
||||
|
||||
async function handleSaveAs(title: string) {
|
||||
const success = await projectEditor.saveAs(title);
|
||||
if (success) {
|
||||
uiState.hideSaveAsDialog();
|
||||
}
|
||||
}
|
||||
|
||||
async function handleMetadataUpdate(
|
||||
projectId: string,
|
||||
updates: {
|
||||
title?: string;
|
||||
author?: string;
|
||||
mode?: import("./lib/project-system/types").ProjectMode;
|
||||
},
|
||||
) {
|
||||
await projectEditor.updateMetadata(updates);
|
||||
}
|
||||
|
||||
async function handleSwitchSave() {
|
||||
await projectEditor.confirmSaveAndSwitch();
|
||||
uiState.hideUnsavedChangesDialog();
|
||||
}
|
||||
|
||||
function handleSwitchDiscard() {
|
||||
projectEditor.confirmDiscardAndSwitch();
|
||||
uiState.hideUnsavedChangesDialog();
|
||||
await editorState.save();
|
||||
}
|
||||
|
||||
async function handleShare() {
|
||||
if (!projectEditor.currentProjectId) return;
|
||||
if (!editorState.currentFileId) return;
|
||||
|
||||
const result = await projectManager.exportProjectToUrl(
|
||||
projectEditor.currentProjectId,
|
||||
);
|
||||
const result = await fileManager.exportFilesToUrl([editorState.currentFileId]);
|
||||
if (result.success) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(result.data);
|
||||
@ -262,18 +220,7 @@
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const mode = projectEditor.currentProject?.mode || "composition";
|
||||
const projectId = projectEditor.currentProjectId;
|
||||
|
||||
if (mode !== executionContext.mode) {
|
||||
executionContext.switchMode(mode).catch(console.error);
|
||||
}
|
||||
|
||||
executionContext.setContentProvider(() => projectEditor.content);
|
||||
|
||||
if (projectId) {
|
||||
executionContext.startSession(projectId).catch(console.error);
|
||||
}
|
||||
executionContext.setContentProvider(() => editorState.content);
|
||||
});
|
||||
|
||||
const panelTabs = [
|
||||
@ -301,12 +248,11 @@
|
||||
|
||||
{#snippet filesTabContent()}
|
||||
<FileBrowser
|
||||
{projectManager}
|
||||
onFileSelect={handleFileSelect}
|
||||
onNewEmptyFile={handleNewEmptyFile}
|
||||
onNewFromTemplate={handleNewFromTemplate}
|
||||
onMetadataUpdate={handleMetadataUpdate}
|
||||
selectedProjectId={projectEditor.currentProjectId}
|
||||
{fileManager}
|
||||
onFileOpen={handleFileOpen}
|
||||
onFileDelete={handleFileDelete}
|
||||
onFileRename={handleFileRename}
|
||||
onNewFile={handleNewFile}
|
||||
/>
|
||||
{/snippet}
|
||||
|
||||
@ -327,27 +273,27 @@
|
||||
</button>
|
||||
<button
|
||||
class="icon-button"
|
||||
onclick={handleNewFromTemplate}
|
||||
title="New from template"
|
||||
onclick={handleNewFile}
|
||||
title="New file"
|
||||
>
|
||||
<FileStack size={18} />
|
||||
</button>
|
||||
<button
|
||||
class="icon-button"
|
||||
onclick={handleSave}
|
||||
disabled={!projectEditor.hasUnsavedChanges}
|
||||
title="Save (Ctrl+S){projectEditor.hasUnsavedChanges
|
||||
disabled={!editorState.hasUnsavedChanges}
|
||||
title="Save (Ctrl+S){editorState.hasUnsavedChanges
|
||||
? ' - unsaved changes'
|
||||
: ''}"
|
||||
class:has-changes={projectEditor.hasUnsavedChanges}
|
||||
class:has-changes={editorState.hasUnsavedChanges}
|
||||
>
|
||||
<Save size={18} />
|
||||
</button>
|
||||
<button
|
||||
onclick={handleShare}
|
||||
class="icon-button"
|
||||
disabled={!projectEditor.currentProjectId}
|
||||
title="Share project"
|
||||
disabled={!editorState.currentFileId}
|
||||
title="Share current file"
|
||||
>
|
||||
<Share2 size={18} />
|
||||
</button>
|
||||
@ -357,7 +303,7 @@
|
||||
class="icon-button evaluate-button"
|
||||
disabled={!$initialized}
|
||||
class:is-running={$running}
|
||||
title="Evaluate (Cmd-E)"
|
||||
title="Evaluate Block (Cmd-E)"
|
||||
>
|
||||
<Play size={18} />
|
||||
</button>
|
||||
@ -417,12 +363,19 @@
|
||||
<div class="editor-area">
|
||||
<EditorWithLogs
|
||||
bind:this={editorWithLogsRef}
|
||||
value={projectEditor.content}
|
||||
value={editorState.content}
|
||||
fileName={editorState.currentFile?.title}
|
||||
onChange={handleEditorChange}
|
||||
onExecute={handleExecute}
|
||||
onExecuteFile={handleExecuteFile}
|
||||
onExecuteBlock={handleExecuteBlock}
|
||||
onExecuteSelection={handleExecuteSelection}
|
||||
logs={interpreterLogs}
|
||||
{editorSettings}
|
||||
mode={projectEditor.currentProject?.mode || 'composition'}
|
||||
openFiles={editorState.openFiles}
|
||||
currentFileId={editorState.currentFileId}
|
||||
unsavedFileIds={new Set(Array.from(editorState.unsavedChanges.keys()))}
|
||||
onTabClick={handleTabClick}
|
||||
onTabClose={handleTabClose}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@ -520,29 +473,6 @@
|
||||
{/snippet}
|
||||
</ResizablePopup>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:visible={uiState.unsavedChangesDialogVisible}
|
||||
title="Unsaved Changes"
|
||||
message="You have unsaved changes. What would you like to do?"
|
||||
confirmLabel="Save"
|
||||
cancelLabel="Discard"
|
||||
onConfirm={handleSwitchSave}
|
||||
onCancel={handleSwitchDiscard}
|
||||
/>
|
||||
|
||||
<InputDialog
|
||||
bind:visible={uiState.saveAsDialogVisible}
|
||||
title="Save As"
|
||||
label="File name"
|
||||
placeholder="Untitled"
|
||||
onConfirm={handleSaveAs}
|
||||
/>
|
||||
|
||||
<TemplateDialog
|
||||
bind:visible={uiState.templateDialogVisible}
|
||||
onSelect={handleTemplateSelect}
|
||||
onCancel={() => uiState.hideTemplateDialog()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
|
||||
@ -23,20 +23,34 @@
|
||||
|
||||
interface Props {
|
||||
value: string;
|
||||
fileName?: string;
|
||||
onChange?: (value: string) => void;
|
||||
onExecute?: (code: string, source: 'selection' | 'block' | 'document') => void;
|
||||
onExecuteFile?: () => void;
|
||||
onExecuteBlock?: (code: string) => void;
|
||||
onExecuteSelection?: (code: string) => void;
|
||||
editorSettings: EditorSettingsStore;
|
||||
mode: 'composition' | 'livecoding';
|
||||
}
|
||||
|
||||
let {
|
||||
value = '',
|
||||
fileName,
|
||||
onChange,
|
||||
onExecute,
|
||||
editorSettings,
|
||||
mode = 'composition'
|
||||
onExecuteFile,
|
||||
onExecuteBlock,
|
||||
onExecuteSelection,
|
||||
editorSettings
|
||||
}: Props = $props();
|
||||
|
||||
function getFileTypeFromExtension(fileName?: string): 'orc' | 'csd' | 'sco' {
|
||||
if (!fileName) return 'orc';
|
||||
const ext = fileName.split('.').pop()?.toLowerCase();
|
||||
if (ext === 'csd') return 'csd';
|
||||
if (ext === 'sco') return 'sco';
|
||||
return 'orc';
|
||||
}
|
||||
|
||||
const fileType = $derived(getFileTypeFromExtension(fileName));
|
||||
|
||||
let editorContainer: HTMLDivElement;
|
||||
let editorView: EditorView | null = null;
|
||||
|
||||
@ -47,40 +61,60 @@
|
||||
const hoverTooltipCompartment = new Compartment();
|
||||
const themeCompartment = new Compartment();
|
||||
|
||||
export function handleExecute() {
|
||||
export function handleExecuteFile() {
|
||||
if (!editorView) return;
|
||||
const doc = getDocument(editorView.state);
|
||||
flash(editorView, doc.from, doc.to);
|
||||
onExecuteFile?.();
|
||||
}
|
||||
|
||||
if (mode === 'composition') {
|
||||
const doc = getDocument(editorView.state);
|
||||
flash(editorView, doc.from, doc.to);
|
||||
onExecute?.(doc.text, 'document');
|
||||
return;
|
||||
}
|
||||
|
||||
const selection = getSelection(editorView.state);
|
||||
if (selection.text) {
|
||||
flash(editorView, selection.from, selection.to);
|
||||
onExecute?.(selection.text, 'selection');
|
||||
return;
|
||||
}
|
||||
|
||||
export function handleExecuteBlock() {
|
||||
if (!editorView) return;
|
||||
const block = getBlock(editorView.state);
|
||||
if (block.text) {
|
||||
flash(editorView, block.from, block.to);
|
||||
onExecute?.(block.text, 'block');
|
||||
return;
|
||||
onExecuteBlock?.(block.text);
|
||||
}
|
||||
|
||||
const doc = getDocument(editorView.state);
|
||||
flash(editorView, doc.from, doc.to);
|
||||
onExecute?.(doc.text, 'document');
|
||||
}
|
||||
|
||||
const evaluateKeymap = keymap.of([
|
||||
export function handleExecuteSelection() {
|
||||
if (!editorView) return;
|
||||
const selection = getSelection(editorView.state);
|
||||
if (selection.text) {
|
||||
flash(editorView, selection.from, selection.to);
|
||||
onExecuteSelection?.(selection.text);
|
||||
}
|
||||
}
|
||||
|
||||
export function handleExecute() {
|
||||
handleExecuteBlock();
|
||||
}
|
||||
|
||||
const evaluateBlockKeymap = keymap.of([
|
||||
{
|
||||
key: 'Mod-e',
|
||||
run: () => {
|
||||
handleExecute();
|
||||
handleExecuteBlock();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
const evaluateSelectionKeymap = keymap.of([
|
||||
{
|
||||
key: 'Alt-e',
|
||||
run: () => {
|
||||
handleExecuteSelection();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
const evaluateFileKeymap = keymap.of([
|
||||
{
|
||||
key: 'Mod-Shift-e',
|
||||
run: () => {
|
||||
handleExecuteFile();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -115,15 +149,15 @@
|
||||
|
||||
const initSettings = $editorSettings;
|
||||
|
||||
const fileType = mode === 'livecoding' ? 'orc' : 'csd';
|
||||
|
||||
editorView = new EditorView({
|
||||
doc: value,
|
||||
extensions: [
|
||||
...baseExtensions,
|
||||
languageCompartment.of(csoundMode({ fileType })),
|
||||
themeCompartment.of(createCodeMirrorTheme()),
|
||||
evaluateKeymap,
|
||||
evaluateBlockKeymap,
|
||||
evaluateSelectionKeymap,
|
||||
evaluateFileKeymap,
|
||||
flashField(),
|
||||
lineNumbersCompartment.of(initSettings.showLineNumbers ? lineNumbers() : []),
|
||||
lineWrappingCompartment.of(initSettings.enableLineWrapping ? EditorView.lineWrapping : []),
|
||||
@ -179,7 +213,6 @@
|
||||
$effect(() => {
|
||||
if (!editorView) return;
|
||||
|
||||
const fileType = mode === 'livecoding' ? 'orc' : 'csd';
|
||||
editorView.dispatch({
|
||||
effects: languageCompartment.reconfigure(csoundMode({ fileType }))
|
||||
});
|
||||
|
||||
@ -2,24 +2,41 @@
|
||||
import { onMount } from 'svelte';
|
||||
import Editor from './Editor.svelte';
|
||||
import LogPanel from './LogPanel.svelte';
|
||||
import Tabs from '../ui/Tabs.svelte';
|
||||
import type { EditorSettingsStore } from '../../stores/editorSettings';
|
||||
import type { File } from '../../project-system';
|
||||
|
||||
interface Props {
|
||||
value: string;
|
||||
fileName?: string;
|
||||
onChange?: (value: string) => void;
|
||||
onExecute?: (code: string, source: 'selection' | 'block' | 'document') => void;
|
||||
onExecuteFile?: () => void;
|
||||
onExecuteBlock?: (code: string) => void;
|
||||
onExecuteSelection?: (code: string) => void;
|
||||
logs?: string[];
|
||||
editorSettings: EditorSettingsStore;
|
||||
mode: 'composition' | 'livecoding';
|
||||
// Tab props
|
||||
openFiles?: File[];
|
||||
currentFileId?: string | null;
|
||||
unsavedFileIds?: Set<string>;
|
||||
onTabClick?: (fileId: string) => void;
|
||||
onTabClose?: (fileId: string) => void;
|
||||
}
|
||||
|
||||
let {
|
||||
value = '',
|
||||
fileName,
|
||||
onChange,
|
||||
onExecute,
|
||||
onExecuteFile,
|
||||
onExecuteBlock,
|
||||
onExecuteSelection,
|
||||
logs = [],
|
||||
editorSettings,
|
||||
mode = 'composition'
|
||||
openFiles = [],
|
||||
currentFileId = null,
|
||||
unsavedFileIds = new Set(),
|
||||
onTabClick,
|
||||
onTabClose
|
||||
}: Props = $props();
|
||||
|
||||
let editorRef: Editor;
|
||||
@ -85,14 +102,24 @@
|
||||
</script>
|
||||
|
||||
<div class="editor-with-logs">
|
||||
<Tabs
|
||||
files={openFiles}
|
||||
{currentFileId}
|
||||
{unsavedFileIds}
|
||||
{onTabClick}
|
||||
{onTabClose}
|
||||
/>
|
||||
|
||||
<div class="editor-section" style="height: {editorHeight}%;">
|
||||
<Editor
|
||||
bind:this={editorRef}
|
||||
{value}
|
||||
{fileName}
|
||||
{onChange}
|
||||
{onExecute}
|
||||
{onExecuteFile}
|
||||
{onExecuteBlock}
|
||||
{onExecuteSelection}
|
||||
{editorSettings}
|
||||
{mode}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@ -1,331 +1,280 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { File, FilePlus, FileStack, Trash2 } from 'lucide-svelte';
|
||||
import type { CsoundProject, ProjectManager } from '../../project-system';
|
||||
import { File as FileIcon, FilePlus, Trash2, Check, X, Lock } from 'lucide-svelte';
|
||||
import type { File, FileManager } from '../../project-system';
|
||||
import ConfirmDialog from './ConfirmDialog.svelte';
|
||||
|
||||
import type { ProjectMode } from '../../project-system/types';
|
||||
|
||||
interface Props {
|
||||
projectManager: ProjectManager;
|
||||
onFileSelect?: (project: CsoundProject | null) => void;
|
||||
onNewEmptyFile?: () => void;
|
||||
onNewFromTemplate?: () => void;
|
||||
onMetadataUpdate?: (projectId: string, updates: { title?: string; author?: string; mode?: ProjectMode }) => void;
|
||||
selectedProjectId?: string | null;
|
||||
fileManager: FileManager;
|
||||
onFileOpen?: (fileId: string) => void;
|
||||
onFileDelete?: (fileId: string) => void;
|
||||
onFileRename?: (fileId: string, newTitle: string) => void;
|
||||
onNewFile?: () => void;
|
||||
}
|
||||
|
||||
let { projectManager, onFileSelect, onNewEmptyFile, onNewFromTemplate, onMetadataUpdate, selectedProjectId = null }: Props = $props();
|
||||
let { fileManager, onFileOpen, onFileDelete, onFileRename, onNewFile }: Props = $props();
|
||||
|
||||
let projects = $state<CsoundProject[]>([]);
|
||||
let files = $state<File[]>([]);
|
||||
let loading = $state(true);
|
||||
let showDeleteConfirm = $state(false);
|
||||
let projectToDelete = $state<CsoundProject | null>(null);
|
||||
|
||||
let selectedProject = $derived(
|
||||
projects.find(p => p.id === selectedProjectId) || null
|
||||
);
|
||||
|
||||
let editTitle = $state('');
|
||||
let editAuthor = $state('');
|
||||
let editMode = $state<ProjectMode>('composition');
|
||||
|
||||
$effect(() => {
|
||||
if (selectedProject) {
|
||||
editTitle = selectedProject.title;
|
||||
editAuthor = selectedProject.author;
|
||||
editMode = selectedProject.mode;
|
||||
}
|
||||
});
|
||||
|
||||
export async function refresh() {
|
||||
await loadProjects();
|
||||
}
|
||||
let fileToDelete = $state<File | null>(null);
|
||||
let editingFileId = $state<string | null>(null);
|
||||
let editingTitle = $state('');
|
||||
|
||||
onMount(async () => {
|
||||
await loadProjects();
|
||||
await loadFiles();
|
||||
|
||||
const unsubscribe = projectManager.onProjectsChanged(() => {
|
||||
loadProjects();
|
||||
const unsubscribe = fileManager.onFilesChanged(() => {
|
||||
loadFiles();
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
});
|
||||
|
||||
async function loadProjects() {
|
||||
async function loadFiles() {
|
||||
loading = true;
|
||||
try {
|
||||
const result = await projectManager.getAllProjects();
|
||||
const result = await fileManager.getAllFiles();
|
||||
if (result.success) {
|
||||
projects = result.data.sort((a, b) =>
|
||||
new Date(b.dateModified).getTime() - new Date(a.dateModified).getTime()
|
||||
);
|
||||
files = result.data;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load projects:', error);
|
||||
console.error('Failed to load files:', error);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleNewEmptyFile() {
|
||||
onNewEmptyFile?.();
|
||||
function handleNewFile() {
|
||||
onNewFile?.();
|
||||
}
|
||||
|
||||
function handleNewFromTemplate() {
|
||||
onNewFromTemplate?.();
|
||||
function openFile(file: File) {
|
||||
if (editingFileId) return;
|
||||
onFileOpen?.(file.id);
|
||||
}
|
||||
|
||||
function selectProject(project: CsoundProject) {
|
||||
onFileSelect?.(project);
|
||||
}
|
||||
|
||||
function handleDeleteClick(project: CsoundProject, event: Event) {
|
||||
event.stopPropagation();
|
||||
projectToDelete = project;
|
||||
function startDelete(file: File) {
|
||||
fileToDelete = file;
|
||||
showDeleteConfirm = true;
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
if (!projectToDelete) return;
|
||||
|
||||
const result = await projectManager.deleteProject(projectToDelete.id);
|
||||
if (result.success) {
|
||||
await loadProjects();
|
||||
if (fileToDelete) {
|
||||
onFileDelete?.(fileToDelete.id);
|
||||
}
|
||||
projectToDelete = null;
|
||||
showDeleteConfirm = false;
|
||||
fileToDelete = null;
|
||||
}
|
||||
|
||||
function formatDate(dateString: string): string {
|
||||
const date = new Date(dateString);
|
||||
return date.toLocaleDateString('en-US', {
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
year: 'numeric'
|
||||
});
|
||||
function cancelDelete() {
|
||||
showDeleteConfirm = false;
|
||||
fileToDelete = null;
|
||||
}
|
||||
|
||||
function handleMetadataChange() {
|
||||
if (!selectedProject) return;
|
||||
function startEdit(file: File) {
|
||||
if (file.system) return;
|
||||
editingFileId = file.id;
|
||||
editingTitle = file.title;
|
||||
}
|
||||
|
||||
const hasChanges =
|
||||
editTitle !== selectedProject.title ||
|
||||
editAuthor !== selectedProject.author ||
|
||||
editMode !== selectedProject.mode;
|
||||
function saveEdit() {
|
||||
if (editingFileId && editingTitle.trim()) {
|
||||
onFileRename?.(editingFileId, editingTitle.trim());
|
||||
}
|
||||
editingFileId = null;
|
||||
editingTitle = '';
|
||||
}
|
||||
|
||||
if (hasChanges) {
|
||||
onMetadataUpdate?.(selectedProject.id, {
|
||||
title: editTitle,
|
||||
author: editAuthor,
|
||||
mode: editMode
|
||||
});
|
||||
function cancelEdit() {
|
||||
editingFileId = null;
|
||||
editingTitle = '';
|
||||
}
|
||||
|
||||
function handleKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
saveEdit();
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault();
|
||||
cancelEdit();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="file-browser">
|
||||
<div class="browser-header">
|
||||
<span class="browser-title">Files</span>
|
||||
<div class="header-actions">
|
||||
<button class="action-button" onclick={handleNewEmptyFile} title="New empty file">
|
||||
<FilePlus size={18} />
|
||||
</button>
|
||||
<button class="action-button" onclick={handleNewFromTemplate} title="New from template">
|
||||
<FileStack size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<div class="file-browser-header">
|
||||
<h3>Files</h3>
|
||||
<button
|
||||
class="new-file-button"
|
||||
onclick={handleNewFile}
|
||||
title="New file"
|
||||
>
|
||||
<FilePlus size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="browser-content">
|
||||
<div class="file-list">
|
||||
{#if loading}
|
||||
<div class="empty-state">Loading...</div>
|
||||
<div class="loading-state">Loading...</div>
|
||||
{:else if files.length === 0}
|
||||
<div class="empty-state">No files</div>
|
||||
{:else}
|
||||
<div class="project-list">
|
||||
{#each projects as project}
|
||||
<div
|
||||
class="project-item"
|
||||
class:selected={selectedProjectId === project.id}
|
||||
onclick={() => selectProject(project)}
|
||||
role="button"
|
||||
tabindex="0"
|
||||
>
|
||||
<div class="project-icon">
|
||||
<File size={16} />
|
||||
{#each files as file}
|
||||
<div
|
||||
class="file-item"
|
||||
class:editing={editingFileId === file.id}
|
||||
class:system={file.system}
|
||||
>
|
||||
{#if editingFileId === file.id}
|
||||
<div class="file-edit">
|
||||
<input
|
||||
type="text"
|
||||
bind:value={editingTitle}
|
||||
onkeydown={handleKeydown}
|
||||
class="file-title-input"
|
||||
autofocus
|
||||
/>
|
||||
<button class="icon-btn save" onclick={saveEdit} title="Save">
|
||||
<Check size={14} />
|
||||
</button>
|
||||
<button class="icon-btn cancel" onclick={cancelEdit} title="Cancel">
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
<div class="project-info">
|
||||
<div class="project-title">{project.title}</div>
|
||||
</div>
|
||||
<button
|
||||
class="delete-button"
|
||||
onclick={(e) => handleDeleteClick(project, e)}
|
||||
title="Delete"
|
||||
{:else}
|
||||
<div
|
||||
class="file-info"
|
||||
onclick={() => openFile(file)}
|
||||
ondblclick={() => startEdit(file)}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<FileIcon size={14} />
|
||||
<span class="file-title">{file.title}</span>
|
||||
</div>
|
||||
{#if file.system}
|
||||
<div class="lock-icon" title="System file (read-only)">
|
||||
<Lock size={14} />
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
class="delete-button"
|
||||
onclick={() => startDelete(file)}
|
||||
title="Delete file"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</button>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if selectedProject}
|
||||
<div class="metadata-editor">
|
||||
<div class="metadata-header">Metadata</div>
|
||||
<div class="metadata-fields">
|
||||
<div class="field">
|
||||
<label for="file-title">Name</label>
|
||||
<input
|
||||
id="file-title"
|
||||
type="text"
|
||||
bind:value={editTitle}
|
||||
onchange={handleMetadataChange}
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="file-author">Author</label>
|
||||
<input
|
||||
id="file-author"
|
||||
type="text"
|
||||
bind:value={editAuthor}
|
||||
onchange={handleMetadataChange}
|
||||
/>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="file-mode">Mode</label>
|
||||
<select
|
||||
id="file-mode"
|
||||
bind:value={editMode}
|
||||
onchange={handleMetadataChange}
|
||||
>
|
||||
<option value="composition">Composition</option>
|
||||
<option value="livecoding">Live Coding</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field readonly">
|
||||
<label>Number of Saves</label>
|
||||
<div class="readonly-value">{selectedProject.saveCount}</div>
|
||||
</div>
|
||||
<div class="field readonly">
|
||||
<label>Date Created</label>
|
||||
<div class="readonly-value">{formatDate(selectedProject.dateCreated)}</div>
|
||||
</div>
|
||||
<div class="field readonly">
|
||||
<label>Date Modified</label>
|
||||
<div class="readonly-value">{formatDate(selectedProject.dateModified)}</div>
|
||||
</div>
|
||||
<div class="field readonly">
|
||||
<label>Csound Version</label>
|
||||
<div class="readonly-value">{selectedProject.csoundVersion}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
<ConfirmDialog
|
||||
bind:visible={showDeleteConfirm}
|
||||
title="Delete File"
|
||||
message="Are you sure you want to delete '{fileToDelete?.title}'? This cannot be undone."
|
||||
confirmLabel="Delete"
|
||||
cancelLabel="Cancel"
|
||||
onConfirm={confirmDelete}
|
||||
onCancel={cancelDelete}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
bind:visible={showDeleteConfirm}
|
||||
title="Delete File"
|
||||
message="Are you sure you want to delete '{projectToDelete?.title}'?"
|
||||
confirmLabel="Delete"
|
||||
onConfirm={confirmDelete}
|
||||
/>
|
||||
|
||||
<style>
|
||||
.file-browser {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
background-color: var(--bg-color);
|
||||
background-color: var(--surface-color);
|
||||
}
|
||||
|
||||
.browser-header {
|
||||
.file-browser-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: var(--space-md);
|
||||
background-color: var(--surface-color);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.browser-title {
|
||||
font-size: var(--font-sm);
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: var(--font-lg);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.header-actions {
|
||||
display: flex;
|
||||
gap: var(--space-xs);
|
||||
}
|
||||
|
||||
.action-button {
|
||||
padding: 0.375rem;
|
||||
background-color: transparent;
|
||||
color: var(--text-secondary);
|
||||
.new-file-button {
|
||||
padding: var(--space-sm);
|
||||
background-color: var(--accent-color);
|
||||
color: white;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all var(--transition-base);
|
||||
}
|
||||
|
||||
.action-button:hover {
|
||||
color: var(--text-color);
|
||||
background-color: var(--editor-active-line);
|
||||
}
|
||||
|
||||
.browser-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
padding: var(--space-2xl) var(--space-lg);
|
||||
text-align: center;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.project-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.project-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-md);
|
||||
padding: var(--space-md);
|
||||
border-bottom: 1px solid var(--surface-color);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--transition-base);
|
||||
}
|
||||
|
||||
.project-item:hover {
|
||||
background-color: var(--surface-color);
|
||||
.new-file-button:hover {
|
||||
background-color: var(--accent-hover);
|
||||
}
|
||||
|
||||
.project-item.selected {
|
||||
background-color: rgba(100, 108, 255, 0.2);
|
||||
border-left: 3px solid var(--accent-color);
|
||||
.file-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: var(--space-sm);
|
||||
}
|
||||
|
||||
.project-icon {
|
||||
.loading-state,
|
||||
.empty-state {
|
||||
padding: var(--space-lg);
|
||||
text-align: center;
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--font-sm);
|
||||
}
|
||||
|
||||
.file-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: var(--space-sm);
|
||||
margin-bottom: var(--space-xs);
|
||||
background-color: var(--bg-color);
|
||||
border: 1px solid var(--border-color);
|
||||
cursor: pointer;
|
||||
transition: all var(--transition-base);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.project-info {
|
||||
.file-item:hover:not(.editing) {
|
||||
background-color: var(--surface-hover);
|
||||
border-color: var(--accent-color);
|
||||
}
|
||||
|
||||
.file-item.editing {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.file-item.system {
|
||||
background-color: var(--surface-color);
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.file-item.system:hover:not(.editing) {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.file-info {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-sm);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.project-title {
|
||||
font-size: var(--font-base);
|
||||
.file-title {
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-base);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@ -339,77 +288,67 @@
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0;
|
||||
transition: all var(--transition-base);
|
||||
transition: opacity var(--transition-base);
|
||||
}
|
||||
|
||||
.project-item:hover .delete-button {
|
||||
.file-item:hover .delete-button {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.delete-button:hover {
|
||||
color: rgba(255, 100, 100, 0.9);
|
||||
background-color: rgba(255, 0, 0, 0.1);
|
||||
color: var(--danger-color);
|
||||
}
|
||||
|
||||
.metadata-editor {
|
||||
border-top: 1px solid var(--surface-color);
|
||||
background-color: var(--bg-color);
|
||||
padding: var(--space-lg);
|
||||
}
|
||||
|
||||
.metadata-header {
|
||||
font-size: var(--font-sm);
|
||||
font-weight: 600;
|
||||
.lock-icon {
|
||||
padding: var(--space-xs);
|
||||
color: var(--text-secondary);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-bottom: var(--space-lg);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.metadata-fields {
|
||||
.file-edit {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-md);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-xs);
|
||||
width: 100%;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.field label {
|
||||
font-size: var(--font-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select {
|
||||
padding: var(--space-sm);
|
||||
background-color: var(--surface-color);
|
||||
border: 1px solid var(--border-color);
|
||||
.file-title-input {
|
||||
flex: 1;
|
||||
padding: var(--space-xs) var(--space-sm);
|
||||
background-color: var(--bg-color);
|
||||
border: 1px solid var(--accent-color);
|
||||
color: var(--text-color);
|
||||
font-size: var(--font-base);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.field input:focus,
|
||||
.field select:focus {
|
||||
border-color: var(--accent-color);
|
||||
}
|
||||
|
||||
.field select {
|
||||
.icon-btn {
|
||||
padding: var(--space-xs);
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
transition: background-color var(--transition-base);
|
||||
}
|
||||
|
||||
.field.readonly .readonly-value {
|
||||
padding: var(--space-sm);
|
||||
background-color: var(--bg-color);
|
||||
border: 1px solid var(--surface-color);
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--font-base);
|
||||
font-family: monospace;
|
||||
.icon-btn.save {
|
||||
background-color: var(--accent-color);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.icon-btn.save:hover {
|
||||
background-color: var(--accent-hover);
|
||||
}
|
||||
|
||||
.icon-btn.cancel {
|
||||
background-color: var(--border-color);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.icon-btn.cancel:hover {
|
||||
background-color: var(--surface-hover);
|
||||
}
|
||||
</style>
|
||||
|
||||
121
src/lib/components/ui/Tabs.svelte
Normal file
121
src/lib/components/ui/Tabs.svelte
Normal file
@ -0,0 +1,121 @@
|
||||
<script lang="ts">
|
||||
import { X } from 'lucide-svelte';
|
||||
import type { File } from '../../project-system';
|
||||
|
||||
interface Props {
|
||||
files: File[];
|
||||
currentFileId: string | null;
|
||||
unsavedFileIds: Set<string>;
|
||||
onTabClick?: (fileId: string) => void;
|
||||
onTabClose?: (fileId: string) => void;
|
||||
}
|
||||
|
||||
let { files, currentFileId, unsavedFileIds, onTabClick, onTabClose }: Props = $props();
|
||||
|
||||
function handleTabClick(fileId: string) {
|
||||
onTabClick?.(fileId);
|
||||
}
|
||||
|
||||
function handleClose(e: MouseEvent, fileId: string) {
|
||||
e.stopPropagation();
|
||||
onTabClose?.(fileId);
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="tabs-container">
|
||||
{#if files.length === 0}
|
||||
<div class="no-tabs">No files open</div>
|
||||
{:else}
|
||||
{#each files as file}
|
||||
<div
|
||||
class="tab"
|
||||
class:active={currentFileId === file.id}
|
||||
onclick={() => handleTabClick(file.id)}
|
||||
>
|
||||
<span class="tab-title">{file.title}</span>
|
||||
{#if unsavedFileIds.has(file.id)}
|
||||
<span class="unsaved-indicator">●</span>
|
||||
{/if}
|
||||
<button
|
||||
class="tab-close"
|
||||
onclick={(e) => handleClose(e, file.id)}
|
||||
title="Close"
|
||||
>
|
||||
<X size={14} />
|
||||
</button>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.tabs-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background-color: var(--bg-color);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
height: 32px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.no-tabs {
|
||||
padding: var(--space-sm) var(--space-md);
|
||||
color: var(--text-secondary);
|
||||
font-size: var(--font-sm);
|
||||
}
|
||||
|
||||
.tab {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-xs);
|
||||
padding: var(--space-xs) var(--space-md);
|
||||
background-color: var(--surface-color);
|
||||
border-right: 1px solid var(--border-color);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--transition-base);
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.tab:hover {
|
||||
background-color: var(--surface-hover);
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
background-color: var(--bg-color);
|
||||
border-bottom: 2px solid var(--accent-color);
|
||||
}
|
||||
|
||||
.tab-title {
|
||||
font-size: var(--font-sm);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.unsaved-indicator {
|
||||
color: var(--accent-color);
|
||||
font-size: 12px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.tab-close {
|
||||
padding: 2px;
|
||||
background-color: transparent;
|
||||
border: none;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
opacity: 0;
|
||||
transition: opacity var(--transition-base);
|
||||
}
|
||||
|
||||
.tab:hover .tab-close {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.tab-close:hover {
|
||||
color: var(--danger-color);
|
||||
}
|
||||
</style>
|
||||
@ -1,129 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { templateRegistry, type CsoundTemplate } from '../../templates/template-registry';
|
||||
|
||||
interface Props {
|
||||
visible: boolean;
|
||||
onSelect?: (template: CsoundTemplate) => void;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
let { visible = false, onSelect, onCancel }: Props = $props();
|
||||
|
||||
const templates = templateRegistry.getAll();
|
||||
|
||||
function handleSelect(template: CsoundTemplate) {
|
||||
onSelect?.(template);
|
||||
}
|
||||
|
||||
function handleBackdropClick(e: MouseEvent) {
|
||||
if (e.target === e.currentTarget) {
|
||||
onCancel?.();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if visible}
|
||||
<div class="modal-backdrop" onclick={handleBackdropClick}>
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h2>Choose Template</h2>
|
||||
<button class="close-button" onclick={() => onCancel?.()}>×</button>
|
||||
</div>
|
||||
|
||||
<div class="template-list">
|
||||
{#each templates as template}
|
||||
<button
|
||||
class="template-item"
|
||||
onclick={() => handleSelect(template)}
|
||||
>
|
||||
{template.name}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-color: rgba(0, 0, 0, 0.75);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.modal-content {
|
||||
background-color: var(--bg-color);
|
||||
border: 1px solid var(--border-color);
|
||||
width: 400px;
|
||||
max-height: 80vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: var(--space-lg);
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin: 0;
|
||||
font-size: var(--font-lg);
|
||||
font-weight: 600;
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.close-button {
|
||||
background: none;
|
||||
border: none;
|
||||
font-size: 2rem;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: color var(--transition-base);
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.close-button:hover {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.template-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.template-item {
|
||||
padding: var(--space-lg);
|
||||
background-color: transparent;
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--surface-color);
|
||||
color: var(--text-color);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: background-color var(--transition-base);
|
||||
font-size: var(--font-base);
|
||||
}
|
||||
|
||||
.template-item:hover {
|
||||
background-color: var(--surface-color);
|
||||
}
|
||||
|
||||
.template-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
</style>
|
||||
@ -1,37 +1,37 @@
|
||||
import { getContext, setContext } from 'svelte';
|
||||
import { ProjectManager } from '../project-system/project-manager';
|
||||
import { ProjectDatabase } from '../project-system/db';
|
||||
import { FileManager } from '../project-system/file-manager';
|
||||
import { FileDatabase } from '../project-system/db';
|
||||
import { createCsoundStore } from '../csound/store';
|
||||
import { ExecutionContext } from '../csound/execution-context';
|
||||
import { createEditorSettingsStore } from '../stores/editorSettings';
|
||||
import { ProjectEditor } from '../stores/projectEditor.svelte';
|
||||
import { EditorState } from '../stores/editorState.svelte';
|
||||
import { UIState } from '../stores/uiState.svelte';
|
||||
import type { CsoundStore } from '../csound/store';
|
||||
import type { EditorSettingsStore } from '../stores/editorSettings';
|
||||
|
||||
export interface AppContext {
|
||||
projectManager: ProjectManager;
|
||||
fileManager: FileManager;
|
||||
csound: CsoundStore;
|
||||
executionContext: ExecutionContext;
|
||||
editorSettings: EditorSettingsStore;
|
||||
projectEditor: ProjectEditor;
|
||||
editorState: EditorState;
|
||||
uiState: UIState;
|
||||
}
|
||||
|
||||
const APP_CONTEXT_KEY = Symbol('app-context');
|
||||
|
||||
export function createAppContext(): AppContext {
|
||||
const db = new ProjectDatabase();
|
||||
const projectManager = new ProjectManager(db);
|
||||
const db = new FileDatabase();
|
||||
const fileManager = new FileManager(db);
|
||||
const csound = createCsoundStore();
|
||||
const executionContext = new ExecutionContext(csound, 'composition');
|
||||
const executionContext = new ExecutionContext(csound);
|
||||
|
||||
return {
|
||||
projectManager,
|
||||
fileManager,
|
||||
csound,
|
||||
executionContext,
|
||||
editorSettings: createEditorSettingsStore(),
|
||||
projectEditor: new ProjectEditor(projectManager),
|
||||
editorState: new EditorState(fileManager),
|
||||
uiState: new UIState()
|
||||
};
|
||||
}
|
||||
|
||||
@ -1,102 +1,48 @@
|
||||
import type { CsoundStore } from './store';
|
||||
import type { ProjectMode } from '../project-system/types';
|
||||
import { CompositionStrategy, LiveCodingStrategy, type ExecutionStrategy } from './execution-strategies';
|
||||
|
||||
export type EvalSource = 'selection' | 'block' | 'document';
|
||||
|
||||
export interface ExecutionSession {
|
||||
mode: ProjectMode;
|
||||
projectId: string | null;
|
||||
isActive: boolean;
|
||||
startTime: Date;
|
||||
}
|
||||
export type EvalSource = 'selection' | 'block' | 'file';
|
||||
|
||||
export class ExecutionContext {
|
||||
private session: ExecutionSession | null = null;
|
||||
private strategy: ExecutionStrategy;
|
||||
private currentMode: ProjectMode;
|
||||
private contentProvider: (() => string) | null = null;
|
||||
|
||||
constructor(
|
||||
private csound: CsoundStore,
|
||||
mode: ProjectMode
|
||||
) {
|
||||
this.currentMode = mode;
|
||||
this.strategy = this.createStrategyForMode(mode);
|
||||
}
|
||||
|
||||
get mode(): ProjectMode {
|
||||
return this.currentMode;
|
||||
}
|
||||
|
||||
get activeSession(): ExecutionSession | null {
|
||||
return this.session;
|
||||
}
|
||||
constructor(private csound: CsoundStore) {}
|
||||
|
||||
setContentProvider(provider: () => string): void {
|
||||
this.contentProvider = provider;
|
||||
}
|
||||
|
||||
async startSession(projectId: string | null): Promise<void> {
|
||||
await this.endSession();
|
||||
|
||||
this.session = {
|
||||
mode: this.currentMode,
|
||||
projectId,
|
||||
isActive: true,
|
||||
startTime: new Date()
|
||||
};
|
||||
|
||||
if (this.currentMode === 'livecoding') {
|
||||
this.resetStrategy();
|
||||
}
|
||||
}
|
||||
|
||||
async endSession(): Promise<void> {
|
||||
if (!this.session?.isActive) return;
|
||||
|
||||
if (this.currentMode === 'livecoding') {
|
||||
await this.csound.stop();
|
||||
this.resetStrategy();
|
||||
/**
|
||||
* Execute entire file
|
||||
*/
|
||||
async executeFile(): Promise<void> {
|
||||
const content = this.contentProvider?.() ?? '';
|
||||
if (!content.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.session = { ...this.session, isActive: false };
|
||||
await this.csound.stop();
|
||||
await this.csound.evaluateCode(content);
|
||||
}
|
||||
|
||||
async execute(code: string, source: EvalSource): Promise<void> {
|
||||
if (this.currentMode === 'livecoding' && (!this.session || !this.session.isActive)) {
|
||||
await this.startSession(this.session?.projectId ?? null);
|
||||
/**
|
||||
* Execute code block (instrument, opcode, or paragraph)
|
||||
*/
|
||||
async executeBlock(code: string): Promise<void> {
|
||||
if (!code.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fullContent = this.contentProvider?.() ?? '';
|
||||
await this.strategy.execute(this.csound, code, fullContent, source);
|
||||
await this.csound.evaluateCode(code);
|
||||
}
|
||||
|
||||
async switchMode(newMode: ProjectMode): Promise<void> {
|
||||
if (newMode === this.currentMode) return;
|
||||
|
||||
await this.endSession();
|
||||
this.currentMode = newMode;
|
||||
this.strategy = this.createStrategyForMode(newMode);
|
||||
|
||||
if (newMode === 'composition') {
|
||||
await this.csound.stop();
|
||||
/**
|
||||
* Execute selected text
|
||||
*/
|
||||
async executeSelection(code: string): Promise<void> {
|
||||
if (!code.trim()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private createStrategyForMode(mode: ProjectMode): ExecutionStrategy {
|
||||
return mode === 'livecoding'
|
||||
? new LiveCodingStrategy()
|
||||
: new CompositionStrategy();
|
||||
}
|
||||
|
||||
private resetStrategy(): void {
|
||||
if (this.strategy instanceof LiveCodingStrategy) {
|
||||
this.strategy.reset();
|
||||
}
|
||||
}
|
||||
|
||||
async destroy(): Promise<void> {
|
||||
await this.endSession();
|
||||
await this.csound.evaluateCode(code);
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
import pako from 'pako';
|
||||
import type { CsoundProject, CompressedProject } from './types';
|
||||
import type { File, CompressedFiles } from './types';
|
||||
|
||||
const COMPRESSION_VERSION = 1;
|
||||
const COMPRESSION_VERSION = 3;
|
||||
|
||||
/**
|
||||
* Convert a string to a Uint8Array
|
||||
@ -59,12 +59,12 @@ function base64ToUint8Array(base64: string): Uint8Array {
|
||||
}
|
||||
|
||||
/**
|
||||
* Compress a project to a base64 string for sharing
|
||||
* Compress files to a base64 string for sharing
|
||||
*/
|
||||
export function compressProject(project: CsoundProject): CompressedProject {
|
||||
export function compressFiles(files: File[]): CompressedFiles {
|
||||
try {
|
||||
// Convert project to JSON string
|
||||
const jsonString = JSON.stringify(project);
|
||||
// Convert files to JSON string
|
||||
const jsonString = JSON.stringify(files);
|
||||
|
||||
// Convert to Uint8Array
|
||||
const uint8Array = stringToUint8Array(jsonString);
|
||||
@ -80,14 +80,14 @@ export function compressProject(project: CsoundProject): CompressedProject {
|
||||
version: COMPRESSION_VERSION,
|
||||
};
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to compress project: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
throw new Error(`Failed to compress files: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decompress a base64 string back to a project
|
||||
* Decompress a base64 string back to files
|
||||
*/
|
||||
export function decompressProject(compressed: CompressedProject): CsoundProject {
|
||||
export function decompressFiles(compressed: CompressedFiles): File[] {
|
||||
try {
|
||||
// Check version compatibility
|
||||
if (compressed.version !== COMPRESSION_VERSION) {
|
||||
@ -104,24 +104,24 @@ export function decompressProject(compressed: CompressedProject): CsoundProject
|
||||
const jsonString = uint8ArrayToString(decompressed);
|
||||
|
||||
// Parse JSON
|
||||
const project = JSON.parse(jsonString) as CsoundProject;
|
||||
const files = JSON.parse(jsonString) as File[];
|
||||
|
||||
// Validate that we have the required fields
|
||||
if (!project.id || !project.title || !project.content === undefined) {
|
||||
throw new Error('Invalid project data structure');
|
||||
// Validate that we have an array
|
||||
if (!Array.isArray(files)) {
|
||||
throw new Error('Invalid files data structure');
|
||||
}
|
||||
|
||||
return project;
|
||||
return files;
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to decompress project: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
throw new Error(`Failed to decompress files: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a shareable URL from a project
|
||||
* Create a shareable URL from files
|
||||
*/
|
||||
export function projectToShareUrl(project: CsoundProject, baseUrl: string = window.location.origin): string {
|
||||
const compressed = compressProject(project);
|
||||
export function filesToShareUrl(files: File[], baseUrl: string = window.location.origin): string {
|
||||
const compressed = compressFiles(files);
|
||||
const params = new URLSearchParams({
|
||||
v: compressed.version.toString(),
|
||||
d: compressed.data,
|
||||
@ -131,33 +131,33 @@ export function projectToShareUrl(project: CsoundProject, baseUrl: string = wind
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a project from a URL
|
||||
* Extract files from a URL
|
||||
*/
|
||||
export function projectFromShareUrl(url: string): CsoundProject {
|
||||
export function filesFromShareUrl(url: string): File[] {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
const params = urlObj.searchParams;
|
||||
|
||||
const version = parseInt(params.get('v') || '1', 10);
|
||||
const version = parseInt(params.get('v') || '3', 10);
|
||||
const data = params.get('d');
|
||||
|
||||
if (!data) {
|
||||
throw new Error('No project data found in URL');
|
||||
throw new Error('No files data found in URL');
|
||||
}
|
||||
|
||||
const compressed: CompressedProject = { version, data };
|
||||
return decompressProject(compressed);
|
||||
const compressed: CompressedFiles = { version, data };
|
||||
return decompressFiles(compressed);
|
||||
} catch (error) {
|
||||
throw new Error(`Failed to parse project from URL: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
throw new Error(`Failed to parse files 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);
|
||||
export function getCompressionRatio(files: File[]): number {
|
||||
const original = JSON.stringify(files);
|
||||
const compressed = compressFiles(files);
|
||||
|
||||
const originalSize = new TextEncoder().encode(original).length;
|
||||
const compressedSize = base64ToUint8Array(compressed.data).length;
|
||||
|
||||
@ -1,13 +1,13 @@
|
||||
import type { CsoundProject } from './types';
|
||||
import type { File } from './types';
|
||||
|
||||
const DB_NAME = 'csound-projects-db';
|
||||
const DB_VERSION = 1;
|
||||
const STORE_NAME = 'projects';
|
||||
const DB_NAME = 'csound-files-db';
|
||||
const DB_VERSION = 3;
|
||||
const STORE_NAME = 'files';
|
||||
|
||||
/**
|
||||
* Database wrapper for IndexedDB operations
|
||||
*/
|
||||
class ProjectDatabase {
|
||||
class FileDatabase {
|
||||
private db: IDBDatabase | null = null;
|
||||
private initPromise: Promise<void> | null = null;
|
||||
|
||||
@ -38,18 +38,19 @@ class ProjectDatabase {
|
||||
request.onupgradeneeded = (event) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
|
||||
// Create object store if it doesn't exist
|
||||
// Delete old stores if they exist
|
||||
if (db.objectStoreNames.contains('projects')) {
|
||||
db.deleteObjectStore('projects');
|
||||
}
|
||||
if (db.objectStoreNames.contains('workspaces')) {
|
||||
db.deleteObjectStore('workspaces');
|
||||
}
|
||||
|
||||
// Create files store if it doesn't exist
|
||||
if (!db.objectStoreNames.contains(STORE_NAME)) {
|
||||
const objectStore = db.createObjectStore(STORE_NAME, {
|
||||
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 });
|
||||
}
|
||||
};
|
||||
});
|
||||
@ -69,9 +70,9 @@ class ProjectDatabase {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a project by ID
|
||||
* Get a file by ID
|
||||
*/
|
||||
async get(id: string): Promise<CsoundProject | null> {
|
||||
async get(id: string): Promise<File | null> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
@ -84,15 +85,15 @@ class ProjectDatabase {
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get project: ${request.error?.message}`));
|
||||
reject(new Error(`Failed to get file: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all projects
|
||||
* Get all files
|
||||
*/
|
||||
async getAll(): Promise<CsoundProject[]> {
|
||||
async getAll(): Promise<File[]> {
|
||||
const db = await this.ensureDb();
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
@ -105,34 +106,34 @@ class ProjectDatabase {
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to get all projects: ${request.error?.message}`));
|
||||
reject(new Error(`Failed to get all files: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save or update a project
|
||||
* Save or update a file
|
||||
*/
|
||||
async put(project: CsoundProject): Promise<void> {
|
||||
async put(file: File): 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);
|
||||
const request = store.put(file);
|
||||
|
||||
request.onsuccess = () => {
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to save project: ${request.error?.message}`));
|
||||
reject(new Error(`Failed to save file: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a project by ID
|
||||
* Delete a file by ID
|
||||
*/
|
||||
async delete(id: string): Promise<void> {
|
||||
const db = await this.ensureDb();
|
||||
@ -147,57 +148,13 @@ class ProjectDatabase {
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to delete project: ${request.error?.message}`));
|
||||
reject(new Error(`Failed to delete file: ${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!)
|
||||
* Clear all files (use with caution!)
|
||||
*/
|
||||
async clear(): Promise<void> {
|
||||
const db = await this.ensureDb();
|
||||
@ -212,7 +169,7 @@ class ProjectDatabase {
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to clear projects: ${request.error?.message}`));
|
||||
reject(new Error(`Failed to clear files: ${request.error?.message}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
@ -229,4 +186,4 @@ class ProjectDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
export { ProjectDatabase };
|
||||
export { FileDatabase };
|
||||
|
||||
316
src/lib/project-system/file-manager.ts
Normal file
316
src/lib/project-system/file-manager.ts
Normal file
@ -0,0 +1,316 @@
|
||||
import type { File, CreateFileData, Result } from './types';
|
||||
import type { FileDatabase } from './db';
|
||||
import { compressFiles, decompressFiles, filesToShareUrl, filesFromShareUrl } from './compression';
|
||||
import { loadSystemFiles, isSystemFileId, getSystemFile } from './system-files';
|
||||
|
||||
async function wrapResult<T>(fn: () => Promise<T>, errorMsg: string): Promise<Result<T>> {
|
||||
try {
|
||||
const data = await fn();
|
||||
return { success: true, data };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error(errorMsg),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a unique ID
|
||||
*/
|
||||
function generateId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
|
||||
type FileChangeListener = () => void;
|
||||
|
||||
/**
|
||||
* File Manager - Main API for managing files
|
||||
*/
|
||||
export class FileManager {
|
||||
private db: FileDatabase;
|
||||
private changeListeners: Set<FileChangeListener> = new Set();
|
||||
|
||||
constructor(db: FileDatabase) {
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to file changes
|
||||
*/
|
||||
onFilesChanged(listener: FileChangeListener): () => void {
|
||||
this.changeListeners.add(listener);
|
||||
return () => this.changeListeners.delete(listener);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify all listeners that files have changed
|
||||
*/
|
||||
private notifyChange(): void {
|
||||
this.changeListeners.forEach(listener => listener());
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the file manager (initializes database)
|
||||
*/
|
||||
async init(): Promise<void> {
|
||||
await this.db.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new file
|
||||
*/
|
||||
async createFile(data: CreateFileData): Promise<Result<File>> {
|
||||
try {
|
||||
const file: File = {
|
||||
id: generateId(),
|
||||
title: data.title,
|
||||
content: data.content || '',
|
||||
};
|
||||
|
||||
await this.db.put(file);
|
||||
this.notifyChange();
|
||||
|
||||
return { success: true, data: file };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to create file'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a file by ID (checks both user and system files)
|
||||
*/
|
||||
async getFile(id: string): Promise<Result<File>> {
|
||||
try {
|
||||
if (isSystemFileId(id)) {
|
||||
const systemFile = getSystemFile(id);
|
||||
if (systemFile) {
|
||||
return { success: true, data: systemFile };
|
||||
}
|
||||
}
|
||||
|
||||
const file = await this.db.get(id);
|
||||
|
||||
if (!file) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`File not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, data: file };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to get file'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all files (user files + system files)
|
||||
*/
|
||||
async getAllFiles(): Promise<Result<File[]>> {
|
||||
try {
|
||||
const userFiles = await this.db.getAll();
|
||||
const systemFiles = await loadSystemFiles();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: [...systemFiles, ...userFiles],
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to get files'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a file (system files cannot be updated directly)
|
||||
*/
|
||||
async updateFile(id: string, updates: Partial<Pick<File, 'title' | 'content'>>): Promise<Result<File>> {
|
||||
try {
|
||||
if (isSystemFileId(id)) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error('Cannot update system files directly. Use "Save As" to create a copy.'),
|
||||
};
|
||||
}
|
||||
|
||||
const existingFile = await this.db.get(id);
|
||||
|
||||
if (!existingFile) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error(`File not found: ${id}`),
|
||||
};
|
||||
}
|
||||
|
||||
const updatedFile: File = {
|
||||
...existingFile,
|
||||
...(updates.title !== undefined && { title: updates.title }),
|
||||
...(updates.content !== undefined && { content: updates.content }),
|
||||
};
|
||||
|
||||
await this.db.put(updatedFile);
|
||||
this.notifyChange();
|
||||
|
||||
return { success: true, data: updatedFile };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to update file'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a file (system files cannot be deleted)
|
||||
*/
|
||||
async deleteFile(id: string): Promise<Result<void>> {
|
||||
if (isSystemFileId(id)) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error('Cannot delete system files'),
|
||||
};
|
||||
}
|
||||
|
||||
const result = await wrapResult(() => this.db.delete(id), 'Failed to delete file');
|
||||
if (result.success) {
|
||||
this.notifyChange();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Duplicate a file (works with both user and system files)
|
||||
*/
|
||||
async duplicateFile(id: string): Promise<Result<File>> {
|
||||
try {
|
||||
const result = await this.getFile(id);
|
||||
|
||||
if (!result.success) {
|
||||
return result;
|
||||
}
|
||||
|
||||
const originalFile = result.data;
|
||||
const duplicatedFile: File = {
|
||||
id: generateId(),
|
||||
title: `${originalFile.title} (copy)`,
|
||||
content: originalFile.content,
|
||||
};
|
||||
|
||||
await this.db.put(duplicatedFile);
|
||||
this.notifyChange();
|
||||
|
||||
return { success: true, data: duplicatedFile };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to duplicate file'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate unique untitled filename
|
||||
*/
|
||||
async generateUntitledFilename(): Promise<string> {
|
||||
const result = await this.getAllFiles();
|
||||
if (!result.success) {
|
||||
return 'Untitled-1.orc';
|
||||
}
|
||||
|
||||
const files = result.data;
|
||||
const untitledPattern = /^Untitled-(\d+)\.orc$/;
|
||||
let maxNum = 0;
|
||||
|
||||
files.forEach(file => {
|
||||
const match = file.title.match(untitledPattern);
|
||||
if (match) {
|
||||
const num = parseInt(match[1], 10);
|
||||
if (num > maxNum) {
|
||||
maxNum = num;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return `Untitled-${maxNum + 1}.orc`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Export files to a shareable URL
|
||||
*/
|
||||
async exportFilesToUrl(fileIds: string[], baseUrl?: string): Promise<Result<string>> {
|
||||
try {
|
||||
const files: File[] = [];
|
||||
|
||||
for (const id of fileIds) {
|
||||
const file = await this.db.get(id);
|
||||
if (file) {
|
||||
files.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
if (files.length === 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: new Error('No files to export'),
|
||||
};
|
||||
}
|
||||
|
||||
const url = filesToShareUrl(files, baseUrl);
|
||||
|
||||
return { success: true, data: url };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to export files'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import files from a URL
|
||||
*/
|
||||
async importFilesFromUrl(url: string): Promise<Result<File[]>> {
|
||||
try {
|
||||
const files = filesFromShareUrl(url);
|
||||
|
||||
// Generate new IDs for imported files
|
||||
const importedFiles = files.map(file => ({
|
||||
...file,
|
||||
id: generateId(),
|
||||
}));
|
||||
|
||||
for (const file of importedFiles) {
|
||||
await this.db.put(file);
|
||||
}
|
||||
|
||||
this.notifyChange();
|
||||
|
||||
return { success: true, data: importedFiles };
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error : new Error('Failed to import files'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all files (use with caution!)
|
||||
*/
|
||||
async clearAllFiles(): Promise<Result<void>> {
|
||||
const result = await wrapResult(() => this.db.clear(), 'Failed to clear files');
|
||||
if (result.success) {
|
||||
this.notifyChange();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@ -1,56 +1,40 @@
|
||||
/**
|
||||
* Csound Project Management System
|
||||
* Csound File Management System
|
||||
*
|
||||
* This module provides a complete project system for managing Csound code files
|
||||
* This module provides a file system for managing Csound 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,
|
||||
File,
|
||||
CreateFileData,
|
||||
CompressedFiles,
|
||||
Result,
|
||||
} from './types';
|
||||
|
||||
// Export main API
|
||||
export { ProjectManager } from './project-manager';
|
||||
export { FileManager } from './file-manager';
|
||||
|
||||
// Export database (for advanced usage)
|
||||
export { projectDb } from './db';
|
||||
// Export database
|
||||
export { FileDatabase } from './db';
|
||||
|
||||
// Export compression utilities (for advanced usage)
|
||||
// Export compression utilities
|
||||
export {
|
||||
compressProject,
|
||||
decompressProject,
|
||||
projectToShareUrl,
|
||||
projectFromShareUrl,
|
||||
compressFiles,
|
||||
decompressFiles,
|
||||
filesToShareUrl,
|
||||
filesFromShareUrl,
|
||||
getCompressionRatio,
|
||||
} from './compression';
|
||||
|
||||
// Export persistence utilities
|
||||
export {
|
||||
saveOpenTabs,
|
||||
loadOpenTabs,
|
||||
clearOpenTabs,
|
||||
saveCurrentFileId,
|
||||
loadCurrentFileId,
|
||||
clearCurrentFileId,
|
||||
} from './persistence';
|
||||
|
||||
@ -1,17 +1,39 @@
|
||||
const LAST_PROJECT_KEY = 'oldboy:lastProjectId';
|
||||
const OPEN_TABS_KEY = 'oldboy:openTabs';
|
||||
const CURRENT_FILE_KEY = 'oldboy:currentFileId';
|
||||
|
||||
export function saveLastProjectId(projectId: string | null): void {
|
||||
if (projectId === null) {
|
||||
localStorage.removeItem(LAST_PROJECT_KEY);
|
||||
} else {
|
||||
localStorage.setItem(LAST_PROJECT_KEY, projectId);
|
||||
export function saveOpenTabs(fileIds: string[]): void {
|
||||
localStorage.setItem(OPEN_TABS_KEY, JSON.stringify(fileIds));
|
||||
}
|
||||
|
||||
export function loadOpenTabs(): string[] {
|
||||
const stored = localStorage.getItem(OPEN_TABS_KEY);
|
||||
if (!stored) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(stored);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function loadLastProjectId(): string | null {
|
||||
return localStorage.getItem(LAST_PROJECT_KEY);
|
||||
export function clearOpenTabs(): void {
|
||||
localStorage.removeItem(OPEN_TABS_KEY);
|
||||
}
|
||||
|
||||
export function clearLastProjectId(): void {
|
||||
localStorage.removeItem(LAST_PROJECT_KEY);
|
||||
export function saveCurrentFileId(fileId: string | null): void {
|
||||
if (fileId === null) {
|
||||
localStorage.removeItem(CURRENT_FILE_KEY);
|
||||
} else {
|
||||
localStorage.setItem(CURRENT_FILE_KEY, fileId);
|
||||
}
|
||||
}
|
||||
|
||||
export function loadCurrentFileId(): string | null {
|
||||
return localStorage.getItem(CURRENT_FILE_KEY);
|
||||
}
|
||||
|
||||
export function clearCurrentFileId(): void {
|
||||
localStorage.removeItem(CURRENT_FILE_KEY);
|
||||
}
|
||||
|
||||
68
src/lib/project-system/system-files.ts
Normal file
68
src/lib/project-system/system-files.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import type { File } from './types';
|
||||
|
||||
const SYSTEM_FILES_DIR = '/system-files';
|
||||
|
||||
const SYSTEM_FILE_NAMES = [
|
||||
'archives.orc',
|
||||
'Documentation.orc',
|
||||
'examples.orc',
|
||||
'globals.orc',
|
||||
'lib.orc',
|
||||
'livecode.orc',
|
||||
'scale.orc',
|
||||
'synth.orc',
|
||||
] as const;
|
||||
|
||||
let systemFilesCache: File[] | null = null;
|
||||
|
||||
/**
|
||||
* Load all system files from the public directory
|
||||
*/
|
||||
export async function loadSystemFiles(): Promise<File[]> {
|
||||
if (systemFilesCache) {
|
||||
return systemFilesCache;
|
||||
}
|
||||
|
||||
const files: File[] = [];
|
||||
|
||||
for (const fileName of SYSTEM_FILE_NAMES) {
|
||||
try {
|
||||
const response = await fetch(`${SYSTEM_FILES_DIR}/${fileName}`);
|
||||
if (!response.ok) {
|
||||
console.error(`Failed to load system file: ${fileName}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = await response.text();
|
||||
files.push({
|
||||
id: `system:${fileName}`,
|
||||
title: fileName,
|
||||
content,
|
||||
readonly: true,
|
||||
system: true,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(`Error loading system file ${fileName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
systemFilesCache = files;
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file ID corresponds to a system file
|
||||
*/
|
||||
export function isSystemFileId(id: string): boolean {
|
||||
return id.startsWith('system:');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a system file by ID
|
||||
*/
|
||||
export function getSystemFile(id: string): File | undefined {
|
||||
if (!systemFilesCache) {
|
||||
return undefined;
|
||||
}
|
||||
return systemFilesCache.find((file) => file.id === id);
|
||||
}
|
||||
@ -1,68 +1,36 @@
|
||||
export type ProjectMode = 'composition' | 'livecoding';
|
||||
|
||||
/**
|
||||
* Core data structure for a Csound project
|
||||
* A single file
|
||||
*/
|
||||
export interface CsoundProject {
|
||||
/** Unique identifier for the project */
|
||||
export interface File {
|
||||
/** Unique identifier for the file */
|
||||
id: string;
|
||||
|
||||
/** User-defined project title */
|
||||
/** Filename (e.g., "kick.orc", "main.csd") */
|
||||
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[];
|
||||
/** Whether this file is read-only (can be viewed/edited but requires "Save As") */
|
||||
readonly?: boolean;
|
||||
|
||||
/** Csound version used to create this project */
|
||||
csoundVersion: string;
|
||||
|
||||
/** Execution mode: composition (full document) or livecoding (block evaluation) */
|
||||
mode: ProjectMode;
|
||||
/** Whether this is a system file (cannot be deleted, always visible) */
|
||||
system?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Data structure for creating a new project (omits auto-generated fields)
|
||||
* Data structure for creating a new file
|
||||
*/
|
||||
export interface CreateProjectData {
|
||||
export interface CreateFileData {
|
||||
title: string;
|
||||
author: string;
|
||||
content?: string;
|
||||
tags?: string[];
|
||||
mode?: ProjectMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Data structure for updating an existing project
|
||||
* Compressed files data for import/export via links
|
||||
*/
|
||||
export interface UpdateProjectData {
|
||||
id: string;
|
||||
title?: string;
|
||||
author?: string;
|
||||
content?: string;
|
||||
tags?: string[];
|
||||
mode?: ProjectMode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compressed project data for import/export via links
|
||||
*/
|
||||
export interface CompressedProject {
|
||||
/** Base64-encoded compressed project data */
|
||||
export interface CompressedFiles {
|
||||
/** Base64-encoded compressed files data */
|
||||
data: string;
|
||||
|
||||
/** Version of the compression format (for future compatibility) */
|
||||
|
||||
248
src/lib/stores/editorState.svelte.ts
Normal file
248
src/lib/stores/editorState.svelte.ts
Normal file
@ -0,0 +1,248 @@
|
||||
import type { File, FileManager } from '../project-system';
|
||||
import { saveOpenTabs, saveCurrentFileId } from '../project-system/persistence';
|
||||
|
||||
interface EditorStateData {
|
||||
openFileIds: string[];
|
||||
currentFileId: string | null;
|
||||
unsavedChanges: Map<string, string>; // fileId -> modified content
|
||||
files: Map<string, File>; // fileId -> file data
|
||||
}
|
||||
|
||||
export class EditorState {
|
||||
private fileManager: FileManager;
|
||||
|
||||
private state = $state<EditorStateData>({
|
||||
openFileIds: [],
|
||||
currentFileId: null,
|
||||
unsavedChanges: new Map(),
|
||||
files: new Map(),
|
||||
});
|
||||
|
||||
private pendingAction: (() => void) | null = null;
|
||||
|
||||
constructor(fileManager: FileManager) {
|
||||
this.fileManager = fileManager;
|
||||
}
|
||||
|
||||
get openFileIds() {
|
||||
return this.state.openFileIds;
|
||||
}
|
||||
|
||||
get currentFileId() {
|
||||
return this.state.currentFileId;
|
||||
}
|
||||
|
||||
get currentFile() {
|
||||
if (!this.state.currentFileId) {
|
||||
return null;
|
||||
}
|
||||
return this.state.files.get(this.state.currentFileId) ?? null;
|
||||
}
|
||||
|
||||
get content() {
|
||||
if (!this.state.currentFileId) {
|
||||
return '';
|
||||
}
|
||||
// Return unsaved content if exists, otherwise file content
|
||||
return this.state.unsavedChanges.get(this.state.currentFileId) ?? this.currentFile?.content ?? '';
|
||||
}
|
||||
|
||||
get hasUnsavedChanges() {
|
||||
if (!this.state.currentFileId) {
|
||||
return false;
|
||||
}
|
||||
return this.state.unsavedChanges.has(this.state.currentFileId);
|
||||
}
|
||||
|
||||
get isCurrentFileReadonly() {
|
||||
return this.currentFile?.readonly ?? false;
|
||||
}
|
||||
|
||||
get openFiles() {
|
||||
return this.state.openFileIds
|
||||
.map(id => this.state.files.get(id))
|
||||
.filter((f): f is File => f !== undefined);
|
||||
}
|
||||
|
||||
get unsavedChanges() {
|
||||
return this.state.unsavedChanges;
|
||||
}
|
||||
|
||||
hasUnsavedChangesForFile(fileId: string): boolean {
|
||||
return this.state.unsavedChanges.has(fileId);
|
||||
}
|
||||
|
||||
setContent(content: string) {
|
||||
if (!this.state.currentFileId) {
|
||||
return;
|
||||
}
|
||||
this.state.unsavedChanges.set(this.state.currentFileId, content);
|
||||
}
|
||||
|
||||
async openFile(fileId: string) {
|
||||
// Load file if not in cache
|
||||
if (!this.state.files.has(fileId)) {
|
||||
const result = await this.fileManager.getFile(fileId);
|
||||
if (!result.success) {
|
||||
return false;
|
||||
}
|
||||
this.state.files.set(fileId, result.data);
|
||||
}
|
||||
|
||||
// Add to open tabs if not already open
|
||||
if (!this.state.openFileIds.includes(fileId)) {
|
||||
this.state.openFileIds.push(fileId);
|
||||
saveOpenTabs(this.state.openFileIds);
|
||||
}
|
||||
|
||||
// Switch to this file
|
||||
this.state.currentFileId = fileId;
|
||||
saveCurrentFileId(fileId);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
async closeFile(fileId: string) {
|
||||
// Check for unsaved changes
|
||||
if (this.state.unsavedChanges.has(fileId)) {
|
||||
// TODO: prompt user?
|
||||
// For now, just discard changes
|
||||
}
|
||||
|
||||
// Remove from open tabs
|
||||
this.state.openFileIds = this.state.openFileIds.filter(id => id !== fileId);
|
||||
saveOpenTabs(this.state.openFileIds);
|
||||
|
||||
// Clear unsaved changes
|
||||
this.state.unsavedChanges.delete(fileId);
|
||||
|
||||
// If this was the current file, switch to another
|
||||
if (this.state.currentFileId === fileId) {
|
||||
if (this.state.openFileIds.length > 0) {
|
||||
this.state.currentFileId = this.state.openFileIds[0];
|
||||
saveCurrentFileId(this.state.currentFileId);
|
||||
} else {
|
||||
this.state.currentFileId = null;
|
||||
saveCurrentFileId(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async switchToFile(fileId: string) {
|
||||
if (!this.state.openFileIds.includes(fileId)) {
|
||||
return await this.openFile(fileId);
|
||||
}
|
||||
|
||||
this.state.currentFileId = fileId;
|
||||
saveCurrentFileId(fileId);
|
||||
return true;
|
||||
}
|
||||
|
||||
async save() {
|
||||
if (!this.state.currentFileId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const content = this.state.unsavedChanges.get(this.state.currentFileId);
|
||||
if (content === undefined) {
|
||||
return true; // Nothing to save
|
||||
}
|
||||
|
||||
const result = await this.fileManager.updateFile(this.state.currentFileId, { content });
|
||||
if (result.success) {
|
||||
// Update file cache
|
||||
this.state.files.set(this.state.currentFileId, result.data);
|
||||
// Clear unsaved changes
|
||||
this.state.unsavedChanges.delete(this.state.currentFileId);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async saveFile(fileId: string) {
|
||||
const content = this.state.unsavedChanges.get(fileId);
|
||||
if (content === undefined) {
|
||||
return true; // Nothing to save
|
||||
}
|
||||
|
||||
const result = await this.fileManager.updateFile(fileId, { content });
|
||||
if (result.success) {
|
||||
this.state.files.set(fileId, result.data);
|
||||
this.state.unsavedChanges.delete(fileId);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async createNewFile() {
|
||||
const title = await this.fileManager.generateUntitledFilename();
|
||||
const result = await this.fileManager.createFile({ title, content: '' });
|
||||
|
||||
if (result.success) {
|
||||
this.state.files.set(result.data.id, result.data);
|
||||
await this.openFile(result.data.id);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
async renameFile(fileId: string, newTitle: string) {
|
||||
const result = await this.fileManager.updateFile(fileId, { title: newTitle });
|
||||
if (result.success) {
|
||||
this.state.files.set(fileId, result.data);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async deleteFile(fileId: string) {
|
||||
const result = await this.fileManager.deleteFile(fileId);
|
||||
if (result.success) {
|
||||
this.state.files.delete(fileId);
|
||||
await this.closeFile(fileId);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async refreshFileCache() {
|
||||
const result = await this.fileManager.getAllFiles();
|
||||
if (result.success) {
|
||||
this.state.files.clear();
|
||||
result.data.forEach(file => {
|
||||
this.state.files.set(file.id, file);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
requestSwitch(action: () => void): 'proceed' | 'confirm-unsaved' {
|
||||
if (!this.hasUnsavedChanges) {
|
||||
action();
|
||||
return 'proceed';
|
||||
}
|
||||
|
||||
this.pendingAction = action;
|
||||
return 'confirm-unsaved';
|
||||
}
|
||||
|
||||
async confirmSaveAndSwitch(): Promise<void> {
|
||||
await this.save();
|
||||
this.pendingAction?.();
|
||||
this.pendingAction = null;
|
||||
}
|
||||
|
||||
confirmDiscardAndSwitch(): void {
|
||||
if (this.state.currentFileId) {
|
||||
this.state.unsavedChanges.delete(this.state.currentFileId);
|
||||
}
|
||||
this.pendingAction?.();
|
||||
this.pendingAction = null;
|
||||
}
|
||||
|
||||
cancelSwitch(): void {
|
||||
this.pendingAction = null;
|
||||
}
|
||||
}
|
||||
@ -9,8 +9,6 @@ export class UIState {
|
||||
sharePopupVisible = $state(false);
|
||||
audioPermissionPopupVisible = $state(true);
|
||||
unsavedChangesDialogVisible = $state(false);
|
||||
saveAsDialogVisible = $state(false);
|
||||
templateDialogVisible = $state(false);
|
||||
|
||||
shareUrl = $state('');
|
||||
|
||||
@ -58,20 +56,4 @@ export class UIState {
|
||||
hideUnsavedChangesDialog() {
|
||||
this.unsavedChangesDialogVisible = false;
|
||||
}
|
||||
|
||||
showSaveAsDialog() {
|
||||
this.saveAsDialogVisible = true;
|
||||
}
|
||||
|
||||
hideSaveAsDialog() {
|
||||
this.saveAsDialogVisible = false;
|
||||
}
|
||||
|
||||
showTemplateDialog() {
|
||||
this.templateDialogVisible = true;
|
||||
}
|
||||
|
||||
hideTemplateDialog() {
|
||||
this.templateDialogVisible = false;
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,162 +0,0 @@
|
||||
import type { ProjectMode } from '../project-system/types';
|
||||
|
||||
export interface CsoundTemplate {
|
||||
id: string;
|
||||
name: string;
|
||||
mode: ProjectMode;
|
||||
content: string;
|
||||
}
|
||||
|
||||
const EMPTY_TEMPLATE: CsoundTemplate = {
|
||||
id: 'empty',
|
||||
name: 'Empty',
|
||||
mode: 'composition',
|
||||
content: `<CsoundSynthesizer>
|
||||
<CsOptions>
|
||||
-odac
|
||||
</CsOptions>
|
||||
<CsInstruments>
|
||||
|
||||
sr = 48000
|
||||
ksmps = 32
|
||||
nchnls = 2
|
||||
0dbfs = 1
|
||||
|
||||
</CsInstruments>
|
||||
<CsScore>
|
||||
|
||||
</CsScore>
|
||||
</CsoundSynthesizer>
|
||||
`
|
||||
};
|
||||
|
||||
const CLASSIC_TEMPLATE: CsoundTemplate = {
|
||||
id: 'classic',
|
||||
name: 'Classic',
|
||||
mode: 'composition',
|
||||
content: `<CsoundSynthesizer>
|
||||
<CsOptions>
|
||||
-odac
|
||||
</CsOptions>
|
||||
<CsInstruments>
|
||||
|
||||
sr = 48000
|
||||
ksmps = 32
|
||||
nchnls = 2
|
||||
0dbfs = 1
|
||||
|
||||
instr 1
|
||||
iFreq = p4
|
||||
iAmp = p5
|
||||
|
||||
kEnv madsr 0.01, 0.1, 0.6, 0.2
|
||||
|
||||
aOsc oscili iAmp * kEnv, iFreq
|
||||
|
||||
outs aOsc, aOsc
|
||||
endin
|
||||
|
||||
</CsInstruments>
|
||||
<CsScore>
|
||||
i 1 0.0 0.5 261.63 0.3
|
||||
i 1 0.5 0.5 329.63 0.3
|
||||
i 1 1.0 0.5 392.00 0.3
|
||||
i 1 1.5 0.5 523.25 0.3
|
||||
</CsScore>
|
||||
</CsoundSynthesizer>
|
||||
`
|
||||
};
|
||||
|
||||
const LIVECODING_TEMPLATE: CsoundTemplate = {
|
||||
id: 'livecoding',
|
||||
name: 'Live Coding',
|
||||
mode: 'livecoding',
|
||||
content: `gaReverb init 0
|
||||
|
||||
instr 1
|
||||
kFreq chnget "freq"
|
||||
kFreq = (kFreq == 0 ? p4 : kFreq)
|
||||
kAmp = p5
|
||||
kEnv linsegr 0, 0.01, 1, 0.1, 0.7, 0.2, 0
|
||||
aOsc vco2 kAmp * kEnv, kFreq
|
||||
aFilt moogladder aOsc, 2000, 0.3
|
||||
outs aFilt, aFilt
|
||||
gaReverb = gaReverb + aFilt * 0.3
|
||||
endin
|
||||
|
||||
instr 2
|
||||
iFreq = p4
|
||||
iAmp = p5
|
||||
kEnv linsegr 0, 0.005, 1, 0.05, 0.5, 0.1, 0
|
||||
aOsc vco2 iAmp * kEnv, iFreq, 10
|
||||
aFilt butterlp aOsc, 800
|
||||
outs aFilt, aFilt
|
||||
endin
|
||||
|
||||
instr 99
|
||||
aL, aR freeverb gaReverb, gaReverb, 0.8, 0.5
|
||||
outs aL, aR
|
||||
gaReverb = 0
|
||||
endin
|
||||
|
||||
; Start reverb (always on)
|
||||
i 99 0 -1
|
||||
|
||||
|
||||
i 1 0 2 440 0.3
|
||||
|
||||
; Arpeggio
|
||||
i 1 0 0.5 261.63 0.2
|
||||
i 1 0.5 0.5 329.63 0.2
|
||||
i 1 1.0 0.5 392.00 0.2
|
||||
i 1 1.5 0.5 523.25 0.2
|
||||
|
||||
; Bass line
|
||||
i 2 0 0.5 130.81 0.4
|
||||
i 2 0.5 0.5 146.83 0.4
|
||||
i 2 1.0 0.5 164.81 0.4
|
||||
i 2 1.5 0.5 130.81 0.4
|
||||
|
||||
; Long note for channel control
|
||||
i 1 0 10 440 0.3
|
||||
|
||||
freq = 440
|
||||
|
||||
freq = 554.37
|
||||
|
||||
freq = 659.25
|
||||
|
||||
; Turn off instrument 1
|
||||
i -1 0 0
|
||||
`
|
||||
};
|
||||
|
||||
const TEMPLATE_REGISTRY: CsoundTemplate[] = [
|
||||
EMPTY_TEMPLATE,
|
||||
LIVECODING_TEMPLATE,
|
||||
CLASSIC_TEMPLATE
|
||||
];
|
||||
|
||||
export class TemplateRegistry {
|
||||
private templates: Map<string, CsoundTemplate>;
|
||||
|
||||
constructor() {
|
||||
this.templates = new Map(
|
||||
TEMPLATE_REGISTRY.map(template => [template.id, template])
|
||||
);
|
||||
}
|
||||
|
||||
getAll(): CsoundTemplate[] {
|
||||
return Array.from(this.templates.values());
|
||||
}
|
||||
|
||||
getById(id: string): CsoundTemplate | undefined {
|
||||
return this.templates.get(id);
|
||||
}
|
||||
|
||||
getEmpty(): CsoundTemplate {
|
||||
return EMPTY_TEMPLATE;
|
||||
}
|
||||
}
|
||||
|
||||
export const templateRegistry = new TemplateRegistry();
|
||||
Reference in New Issue
Block a user