Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 31 additions & 7 deletions src/lib/client/ecs/component/component-manager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { type Unsubscriber, get, writable } from 'svelte/store';

import { getId, resetSubscriptions } from '../utils';
import { useProject } from '$lib/client/project';

import { componentTransformer, componentsTransformer } from '../transformers';
import { resetSubscriptions } from '../utils';
import { ComponentHandle } from './component-handle';
import type { Component } from './component.type';

Expand All @@ -26,12 +29,27 @@ export class ComponentManager {
return get(_storage);
}

add(component: Omit<Component, 'id' | 'path'> & Partial<Pick<Component, 'path'>>) {
const components = get(_storage);
const id = getId(this.data, component.name);
components.push({ ...component, id, path: component.path ?? `components/${id}.ts` });
_storage.set(components);
return id;
async create(name: string) {
const { actions, fs } = useProject();
const component = await actions.package.createComponent({ componentName: name });
this._add(componentTransformer(component));
const dir = await fs.getDirectory();
await dir.readdir(true);
}

async import(names: [string, ...string[]]) {
const { actions, ecs, fs } = useProject();
await actions.package.addComponents({ componentNames: names });
await this.sync();
await ecs.components.sync();
const dir = await fs.getDirectory();
await dir.readdir(true);
}

async sync() {
const { actions } = useProject();
const components = await actions.package.getComponents();
_storage.set(componentsTransformer(components));
}

get(id: string): ComponentHandle {
Expand All @@ -56,6 +74,12 @@ export class ComponentManager {
}
}

private _add(component: Component) {
const components = get(_storage);
components.push(component);
_storage.set(components);
}

private _subscribe(id: string, handle: ComponentHandle) {
setTimeout(() => {
const subscriptions = get(_subscriptions);
Expand Down
38 changes: 31 additions & 7 deletions src/lib/client/ecs/system/system-manager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { type Unsubscriber, get, writable } from 'svelte/store';

import { getId, resetSubscriptions } from '../utils';
import { useProject } from '$lib/client/project';

import { systemTransformer, systemsTransformer } from '../transformers';
import { resetSubscriptions } from '../utils';
import { SystemHandle } from './system-handle';
import type { System } from './system.type';

Expand All @@ -25,12 +28,27 @@ export class SystemManager {
return get(_storage);
}

add(system: Omit<System, 'id' | 'path'> & Partial<Pick<System, 'path'>>): string {
const systems = get(_storage);
const id = getId(this.data, system.name);
systems.push({ ...system, id, path: system.path ?? `systems/${id}.ts` });
_storage.set(systems);
return id;
async create(name: string) {
const { actions, fs } = useProject();
const system = await actions.package.createSystem({ systemName: name });
this._add(systemTransformer(system));
const dir = await fs.getDirectory();
await dir.readdir(true);
}

async import(names: [string, ...string[]]) {
const { actions, ecs, fs } = useProject();
await actions.package.addSystems({ systemNames: names });
await this.sync();
await ecs.components.sync();
const dir = await fs.getDirectory();
await dir.readdir(true);
}

async sync() {
const { actions } = useProject();
const systems = await actions.package.getSystems();
_storage.set(systemsTransformer(systems));
}

get(id: string): SystemHandle {
Expand All @@ -55,6 +73,12 @@ export class SystemManager {
}
}

private _add(system: System) {
const systems = get(_storage);
systems.push(system);
_storage.set(systems);
}

private _subscribe(id: string, handle: SystemHandle) {
setTimeout(() => {
const subscriptions = get(_subscriptions);
Expand Down
38 changes: 22 additions & 16 deletions src/lib/client/ecs/transformers.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,34 @@
import type { Component, Library, Scene, System } from '$lib/client/ecs';
import type { ComponentPackage, SystemPackage } from '$lib/server/project/package';

import type { Save } from '@utils/types';
import type { Save, SaveLibrary } from '@utils/types';

export const componentTransformer = (component: ComponentPackage): Component => ({
id: component.manifest.id,
name: component.manifest.name,
path: component.save.path,
params: component.manifest.params,
});

export const componentsTransformer = (components: ComponentPackage[]): Component[] =>
components.map((component) => ({
id: component.manifest.id,
name: component.manifest.name,
path: component.save.path,
params: component.manifest.params,
}));
components.map(componentTransformer);

export const systemTransformer = (system: SystemPackage): System => ({
id: system.manifest.id,
name: system.manifest.name,
path: system.save.path,
});

export const systemsTransformer = (systems: SystemPackage[]): System[] =>
systems.map((system) => ({
id: system.manifest.id,
name: system.manifest.name,
path: system.save.path,
}));
systems.map(systemTransformer);

export const libraryTransformer = (lib: SaveLibrary): Library => ({
id: lib.path,
name: lib.name,
});

export const librariesTransformer = (save: Save): Library[] =>
save.libraries.map((lib) => ({
id: lib.path,
name: lib.name,
}));
save.libraries.map(libraryTransformer);

export const scenesTransformer = (save: Save): Scene[] => [
{
Expand Down
2 changes: 2 additions & 0 deletions src/lib/client/sync-file-system/sfs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export class SyncFileSystem {

async init(): Promise<void> {
await this.treeCache?.init();
const dir = await this.getDirectory();
await dir.readdir(true);
}

async getFile(path: string): Promise<SfsFile> {
Expand Down
15 changes: 12 additions & 3 deletions src/lib/components/Widget/ecs-tree/dialogs/dialog-name.svelte
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
<script lang="ts">
import { Input } from '$lib/components/ui/input';
import { InputDialog } from '$lib/components/dialogs';
import type { MaybePromise } from '@utils/types';

interface Props {
open?: boolean;
title?: string;
nameText?: string;
nameValue?: string;
confirmText?: string;
onConfirm?: (name: string) => void;
onConfirm?: (name: string) => MaybePromise<void>;
validate?: (name: string) => string | null;
}

let {
Expand All @@ -18,6 +20,7 @@
nameValue = $bindable(''),
confirmText,
onConfirm,
validate,
}: Props = $props();

const handleEnterConfirm = (confirm: () => void) => (e: KeyboardEvent) => {
Expand All @@ -28,12 +31,15 @@
}
};

const handleConfirm = () => {
const handleConfirm = async () => {
if (validate?.(nameValue.trim())) return;
const n = nameValue.trim();
if (!n) throw 'Name is required';
onConfirm?.(n);
await onConfirm?.(n);
};

const error = $derived(validate?.(nameValue.trim()));

const reset = () => {
nameValue = '';
};
Expand All @@ -54,6 +60,9 @@
bind:value={nameValue}
onkeydown={handleEnterConfirm(confirm)}
/>
{#if error}
<span class="text-xs text-destructive">Error: {error}</span>
{/if}
</div>
{/snippet}
</InputDialog>
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
<script lang="ts">
import DialogName from '../dialogs/dialog-name.svelte';
import type { MaybePromise } from '@utils/types';

interface Props {
name: string;
open: boolean;
onConfirm: (name: string) => void;
onConfirm: (name: string) => MaybePromise<void>;
validate?: (name: string) => string | null;
}

let { name, open = $bindable(false), onConfirm }: Props = $props();
let { name, open = $bindable(false), onConfirm, validate }: Props = $props();
</script>

<DialogName title={`Create ${name}`} nameText={`${name} name`} bind:open {onConfirm} />
<DialogName title={`Create ${name}`} nameText={`${name} name`} bind:open {onConfirm} {validate} />
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@
</TooltipText>
{/if}
<Button
disabled={type === 'library'}
variant="ghost"
size="icon"
class="text-destructive hover:text-destructive hover:bg-destructive/20"
Expand All @@ -146,7 +147,7 @@
</ContextMenuItem>
<ContextMenuSeparator />
{/if}
<ContextMenuItem variant="destructive" onclick={onDelete}>
<ContextMenuItem disabled={type === 'library'} variant="destructive" onclick={onDelete}>
<span class="i-ic-baseline-delete"></span>
Delete
</ContextMenuItem>
Expand Down
38 changes: 24 additions & 14 deletions src/lib/components/Widget/ecs-tree/packages/package-tab.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import type { ComponentManager, SystemManager, LibraryManager } from '$lib/client/ecs';
import type { Writable } from 'svelte/store';
import type { Package } from '../types';
import { formatFrom } from '@utils/format';

type Props =
| {
Expand Down Expand Up @@ -53,24 +54,33 @@
let createOpen = $state(false);
let importOpen = $state(false);

const handleCreate = (name: string) => {
// @todo create package
manager.add({
name,
params: [],
});
const handleCreate = async (name: string) => {
if (!('create' in manager))
throw new Error(`Cannot create in library - use the "Import Library" button instead.`);
await manager.create(name);
};

const handleImport = (name: string) => {
// @todo import package
manager.add({
name,
params: [],
});
const handleImport = async (names: string) => {
if (!('import' in manager)) throw new Error(`Cannot import in library`);
// if (names.length === 0) throw new Error('No elements selected');
await manager.import([names] as [string, ...string[]]);
};

const validate = (raw: string, suffix: string = nameCapitalized) => {
if (!raw) return 'Name is required';
const name = `${formatFrom.all(raw)[type === 'system' ? 'toCamel' : 'toPascal']()}${suffix}`;
console.log(name, $packages);
if ($packages.find((p) => p.id === name)) return `${nameCapitalized} already exists`;
return null;
};
</script>

<DialogCreatePackage name={nameCapitalized} bind:open={createOpen} onConfirm={handleCreate} />
<DialogCreatePackage
name={nameCapitalized}
bind:open={createOpen}
onConfirm={handleCreate}
{validate}
/>
<DialogImportPackage name={nameCapitalized} bind:open={importOpen} onConfirm={handleImport} />

<div class="flex flex-col flex-1 min-h-0">
Expand All @@ -93,7 +103,7 @@
{/if}
</InputGroup>
<DropdownMenu>
<DropdownMenuTrigger>
<DropdownMenuTrigger disabled={type === 'library'}>
{#snippet child({ props })}
<Button
{...props}
Expand Down
21 changes: 17 additions & 4 deletions src/lib/components/dialogs/base-dialog.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
DialogDescription,
} from '$lib/components/ui/dialog';
import type { Snippet } from 'svelte';
import type { MaybePromise } from '@utils/types';
import { LoadingButton } from '$lib/components/ui/loading-button';

interface Props {
open?: boolean;
Expand All @@ -19,7 +21,7 @@
cancelText?: string;
confirmDisabled?: boolean;
onOpenChange?: (open: boolean) => void;
onConfirm?: (...args: any[]) => void;
onConfirm?: (...args: any[]) => MaybePromise<void>;
}

let {
Expand All @@ -34,8 +36,17 @@
onConfirm,
}: Props = $props();

const confirm = () => {
onConfirm?.();
let isLoading = $state(false);

const confirm = async () => {
isLoading = true;
try {
await onConfirm?.();
} catch (e) {
isLoading = false;
throw e;
}
isLoading = false;
open = false;
onOpenChange?.(false);
};
Expand All @@ -61,7 +72,9 @@
{@render children?.(confirm, cancel)}
<DialogFooter>
<Button variant="ghost" onclick={cancel}>{cancelText ?? 'Cancel'}</Button>
<Button disabled={confirmDisabled} onclick={confirm}>{confirmText ?? 'Confirm'}</Button>
<LoadingButton loading={isLoading} disabled={confirmDisabled} onclick={confirm}>
{confirmText ?? 'Confirm'}
</LoadingButton>
</DialogFooter>
</DialogContent>
</Dialog>
3 changes: 2 additions & 1 deletion src/lib/components/dialogs/input-dialog.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import BaseDialog from './base-dialog.svelte';
import type { MaybePromise } from '@utils/types';

interface Props {
open?: boolean;
Expand All @@ -12,7 +13,7 @@
confirmDisabled?: boolean;
onOpenChange?: (open: boolean) => void;
reset?: () => void;
onConfirm?: (...args: any[]) => void;
onConfirm?: (...args: any[]) => MaybePromise<void>;
}

let { open = $bindable(false), onOpenChange, reset, ...props }: Props = $props();
Expand Down
Loading
Loading