feat fix stuff

This commit is contained in:
Torsten Dittmann committed 2025-04-27 04:57:44 +02:00
1 parent 6418870f1d
commit e7983570d5
33 files changed
+1346 -437

No files matched your search

+2 -2
View File
@@ -29,13 +29,11 @@
"@popperjs/core": "^2.11.8",
"@sentry/sveltekit": "^8.38.0",
"@stripe/stripe-js": "^3.5.0",
"@xterm/xterm": "^5.5.0",
"ai": "^2.2.37",
"analytics": "^0.8.16",
"cron-parser": "^4.9.0",
"dayjs": "^1.11.13",
"deep-equal": "^2.2.3",
"dotenv": "^16.4.7",
"echarts": "^5.6.0",
"envfile": "^7.1.0",
"ignore": "^6.0.2",
@@ -69,6 +67,8 @@
"@typescript-eslint/eslint-plugin": "^8.28.0",
"@typescript-eslint/parser": "^8.28.0",
"@vitest/ui": "^3.0.9",
"@xterm/addon-fit": "^0.10.0",
"@xterm/xterm": "^5.5.0",
"eslint": "^9.23.0",
"eslint-config-prettier": "^10.1.0",
"eslint-plugin-svelte": "^3.3.3",
+15 -6
View File
@@ -32,9 +32,6 @@ importers:
'@stripe/stripe-js':
specifier: ^3.5.0
version: 3.5.0
'@xterm/xterm':
specifier: ^5.5.0
version: 5.5.0
ai:
specifier: ^2.2.37
version: 2.2.37(react@18.3.1)(solid-js@1.9.5)(svelte@5.25.3)(vue@3.5.13(typescript@5.8.2))
@@ -50,9 +47,6 @@ importers:
deep-equal:
specifier: ^2.2.3
version: 2.2.3
dotenv:
specifier: ^16.4.7
version: 16.4.7
echarts:
specifier: ^5.6.0
version: 5.6.0
@@ -147,6 +141,12 @@ importers:
'@vitest/ui':
specifier: ^3.0.9
version: 3.0.9(vitest@3.0.9)
'@xterm/addon-fit':
specifier: ^0.10.0
version: 0.10.0(@xterm/xterm@5.5.0)
'@xterm/xterm':
specifier: ^5.5.0
version: 5.5.0
eslint:
specifier: ^9.23.0
version: 9.23.0
@@ -1495,6 +1495,11 @@ packages:
'@vue/shared@3.5.13':
resolution: {integrity: sha512-/hnE/qP5ZoGpol0a5mDi45bOd7t3tjYJBjsgCsivow7D48cJeV5l05RD82lPqi7gRiphZM37rnhW1l6ZoCNNnQ==}
'@xterm/addon-fit@0.10.0':
resolution: {integrity: sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==}
peerDependencies:
'@xterm/xterm': ^5.0.0
'@xterm/xterm@5.5.0':
resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
@@ -5153,6 +5158,10 @@ snapshots:
'@vue/shared@3.5.13': {}
'@xterm/addon-fit@0.10.0(@xterm/xterm@5.5.0)':
dependencies:
'@xterm/xterm': 5.5.0
'@xterm/xterm@5.5.0': {}
acorn-import-attributes@1.9.5(acorn@8.14.1):
+11 -10
View File
@@ -15,7 +15,7 @@
import { newOrgModal } from '$lib/stores/organization';
import { Click, trackEvent } from '$lib/actions/analytics';
import { page } from '$app/stores';
import { artifacts } from '$routes/(console)/project-[project]/store';
import type { Artifact } from '$lib/sdk/imagine';
type Project = {
name: string;
@@ -73,13 +73,14 @@
export let organizations: Organization[] = [];
$: displayArtifacts = $page.url.pathname.includes('artifact') && isStudio ? $artifacts : [];
$: displayArtifacts = (
$page.url.pathname.includes('artifact') && isStudio ? $page.data.artifacts.artifacts : []
) as Artifact[];
$: selectedOrg = organizations.find((organization) => organization.isSelected);
$: selectedProject = selectedOrg?.projects.find((project) => project.isSelected);
$: selectedArtifact = displayArtifacts.find((artifact) =>
$page.url.pathname.endsWith(artifact.$id)
);
$: selectedArtifact = displayArtifacts.find(
(artifact) => $page.params.artifact === artifact.$id
) as Artifact;
let organisationBottomSheetOpen = false;
let projectsBottomSheetOpen = false;
@@ -203,7 +204,7 @@
.map((artifact, index) => {
if (index < 4) {
return {
name: artifact.title,
name: artifact.name,
href: `${base}/project-${selectedProject.$id}/studio/artifact-${artifact.$id}`
};
} else if (index === 4) {
@@ -417,7 +418,7 @@
class="trigger"
use:melt={$triggerArtifacts}
aria-label="Open artifacts tab">
<span class="projectName">{selectedArtifact.title}</span>
<span class="projectName">{selectedArtifact?.name}</span>
<Icon icon={IconChevronDown} size="s" />
</button>
{:else}
@@ -426,7 +427,7 @@
class="trigger"
on:click={() => (artifactsBottomSheetOpen = true)}
aria-label="Open artifacts tab">
<span class="projectName">{selectedArtifact.title}</span>
<span class="projectName">{selectedArtifact.name}</span>
<Icon icon={IconChevronDown} size="s" />
</button>
{/if}
@@ -440,7 +441,7 @@
<ActionMenu.Root>
<ActionMenu.Item.Anchor
href={`${base}/project-${selectedProject.$id}/studio/artifact-${artifact.$id}`}
>{artifact.title}</ActionMenu.Item.Anchor
>{artifact.name}</ActionMenu.Item.Anchor
></ActionMenu.Root>
</div>
{:else if index === 4}
@@ -1 +1 @@
<slot />
<slot />
+92 -19
View File
@@ -1,22 +1,87 @@
<script lang="ts">
import { Divider, Typography, Layout, Button, Icon } from '@appwrite.io/pink-svelte';
import { Divider, Typography, Layout, Button, Icon, Spinner } from '@appwrite.io/pink-svelte';
import {
IconArrowUp,
IconChevronDown,
IconChevronLeft,
IconPaperClip
IconPaperClip,
IconSpin
} from '@appwrite.io/pink-icons-svelte';
import { isSmallViewport } from '$lib/stores/viewport';
import Conversation from './conversation.svelte';
import { showChat } from '$lib/stores/chat';
import { conversation, showChat } from '$lib/stores/chat';
import type { StreamParser } from './parser';
import type { EventHandler } from 'svelte/elements';
import { sdk } from '$lib/stores/sdk';
import { page } from '$app/state';
type Props = {
width: number;
hasSubNavigation: boolean;
parser: StreamParser;
};
let { width, hasSubNavigation }: Props = $props();
let { width, hasSubNavigation, parser }: Props = $props();
let minimizeChat = $state($isSmallViewport ? true : false);
let message = $state('');
let sending = $state(false);
const onkeydown: EventHandler<KeyboardEvent, HTMLTextAreaElement> = (event) => {
if (event.key === 'Enter') {
if (!event.metaKey && !event.ctrlKey) return;
event.preventDefault();
createMessage();
}
};
const onsubmit: EventHandler<SubmitEvent, HTMLFormElement> = (event) => {
event.preventDefault();
createMessage();
};
async function createMessage() {
try {
sending = true;
const response = await fetch(
`${sdk.forProject.client.config.endpoint}/imagine/artifacts/${$conversation.artifactId}/conversations/${$conversation.$id}/messages`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Appwrite-Project': page.params.project,
'X-Appwrite-Mode': 'admin'
},
credentials: 'include',
body: JSON.stringify({
content: message,
type: 'text'
})
}
);
if (!response.ok) {
throw new Error(`${response.status} Error: ${await response.text()}`);
}
parser.chunk(`\n\n${message}\n\n`);
message = '';
const reader = response.body.getReader();
const decoder = new TextDecoder();
let chunk = await reader.read();
while (!chunk.done) {
parser.chunk(decoder.decode(chunk.value));
chunk = await reader.read();
}
} catch (error) {
if (error instanceof Error) {
parser.chunk(error.message);
}
console.log(error);
} finally {
sending = false;
}
}
</script>
<section
@@ -49,31 +114,42 @@
</header>
<Divider />
<Conversation />
<Conversation {parser} />
{/if}
<div class="input" class:minimize-chat={minimizeChat}>
<form {onsubmit} class="input" class:minimize-chat={minimizeChat}>
<Layout.Stack
direction={minimizeChat ? 'row' : 'column'}
alignItems={minimizeChat ? 'center' : 'flex-end'}>
<textarea
{onkeydown}
disabled={sending}
bind:value={message}
name="conversation"
placeholder="Chat with Imagine..."
on:focus={() => {
onfocus={() => {
minimizeChat = false;
}}></textarea>
<div class="options">
<Layout.Stack direction="row" justifyContent="flex-end">
<Button.Button icon variant="secondary" size="s"
><Icon
icon={IconPaperClip}
color="--fgcolor-neutral-tertiary" /></Button.Button>
<Button.Button icon variant="secondary" size="s"
><Icon
icon={IconArrowUp}
color="--fgcolor-neutral-tertiary" /></Button.Button>
<Button.Button icon variant="secondary" size="s">
<Icon icon={IconPaperClip} color="--fgcolor-neutral-tertiary" />
</Button.Button>
<Button.Button
icon
variant="secondary"
size="s"
type="submit"
disabled={sending}>
{#if sending}
<Spinner size="s" />
{:else}
<Icon icon={IconArrowUp} color="--fgcolor-neutral-tertiary" />
{/if}
</Button.Button>
</Layout.Stack>
</div>
</Layout.Stack>
</div>
</form>
</div>
</section>
<div
@@ -162,9 +238,6 @@
min-height: 100px;
resize: none;
}
.options {
}
}
.input.minimize-chat {
+13 -44
View File
@@ -1,17 +1,7 @@
<script lang="ts">
import 'highlight.js/styles/atom-one-light.css';
import { createStreamParser } from './parser';
import data from './text.txt?raw';
import {
Badge,
Button,
Card,
Fieldset,
Icon,
Layout,
Tag,
Input
} from '@appwrite.io/pink-svelte';
import { StreamParser } from './parser';
import { Badge, Card, Icon, Layout, Tag } from '@appwrite.io/pink-svelte';
import Markdown, { type Plugin } from 'svelte-exmarkdown';
import Li from './(markdown)/Li.svelte';
import H1 from './(markdown)/H1.svelte';
@@ -23,10 +13,17 @@
import Ol from './(markdown)/Ol.svelte';
import rehypeHighlight from 'rehype-highlight';
import { IconArrowDown, IconCheck, IconClock } from '@appwrite.io/pink-icons-svelte';
import type { UIEventHandler, WheelEventHandler } from 'svelte/elements';
import { slide } from 'svelte/transition';
import { showPrompt } from '$lib/stores/chat';
import type { UIEventHandler, WheelEventHandler } from 'svelte/elements';
type Props = {
parser: StreamParser;
autoscroll?: boolean;
streaming?: boolean;
};
let { parser, autoscroll = $bindable(true), streaming = $bindable(false) }: Props = $props();
const chunks = parser.parsed;
const plugins: Plugin[] = [
{
rehypePlugin: rehypeHighlight,
@@ -43,40 +40,12 @@
}
];
const parser = createStreamParser();
const chunks = parser.parsed;
let autoscroll = true;
let streaming = false;
$: if ($showPrompt) {
exampleStream();
}
let chunkSize = 40;
let delayMs = 25;
function scrollToBottom(smooth: boolean = true) {
document
.getElementById('bottom')
.scrollIntoView({ behavior: smooth ? 'smooth' : 'instant' });
}
function exampleStream(): void {
let position = 0;
const processNextChunk = () => {
if (position < data.length) {
streaming = true;
const chunk = data.substring(position, position + chunkSize);
parser.chunk(chunk);
position += chunkSize;
if (autoscroll) scrollToBottom();
setTimeout(processNextChunk, delayMs);
} else {
streaming = false;
}
};
processNextChunk();
}
const onwheel: WheelEventHandler<HTMLDivElement> = (event) => {
if (streaming) autoscroll = false;
};
@@ -131,7 +100,7 @@
{/if}
{/each}
{#if !streaming}
<Layout.Stack>
<!-- <Layout.Stack>
<Fieldset legend="Demo">
<Layout.Stack>
<Input.Number required label="chunk size" bind:value={chunkSize} />
@@ -141,7 +110,7 @@
>reset</Button.Button>
</Layout.Stack>
</Fieldset>
</Layout.Stack>
</Layout.Stack> -->
{/if}
<div id="bottom"></div>
</section>
-34
View File
@@ -1,34 +0,0 @@
Databases are the largest organizational unit in Appwrite.
Each database contains a group of [collections](/docs/products/databases/collections).
In future versions, different databases may be backed by a different database technology of your choosing.
## Create in Console
The easiest way to create a database using the Appwrite Console.
You can create a database by navigating to the **Databases** page and clicking **Create database**.
## Create using Server SDKs
You can programmatically create databases using a [Server SDK](/docs/sdks#server). Appwrite [Server SDKs](/docs/sdks#server) require an [API key](/docs/advanced/platform/api-keys).
```js
const sdk = require('node-appwrite');
// Init SDK
const client = new sdk.Client();
const databases = new sdk.Databases(client);
client
.setEndpoint('https://cloud.appwrite.io/v1')
.setProject('<PROJECT_ID>')
.setKey('919c2d18fb5d4...a2ae413da83346ad2')
;
const promise = databases.create('<DATABASE_ID>'
, '[NAME]');
promise.then(function (response) {
console.log(response);
}, function (error) {
console.log(error);
});
```
+17 -15
View File
@@ -253,12 +253,12 @@ const client = new Client();
parser.chunk('<action type="file" src="test.js">console.log("test");</ac');
parser.chunk('tion>');
parser.end();
let items: ParsedItem[] = [];
parser.parsed.subscribe((value) => {
items = value;
})();
expect(items.length).toBe(1);
const [item] = items;
expectAction(item);
@@ -267,14 +267,16 @@ const client = new Client();
});
it('should handle multiple adjacent actions without text between', () => {
parser.chunk('<action type="file" src="file1.js">code1</action><action type="file" src="file2.js">code2</action>');
parser.chunk(
'<action type="file" src="file1.js">code1</action><action type="file" src="file2.js">code2</action>'
);
parser.end();
let items: ParsedItem[] = [];
parser.parsed.subscribe((value) => {
items = value;
})();
expect(items.length).toBe(2);
const [action1, action2] = items;
expectAction(action1);
@@ -288,12 +290,12 @@ const client = new Client();
it('should handle empty action content correctly', () => {
parser.chunk('<action type="shell"></action>');
parser.end();
let items: ParsedItem[] = [];
parser.parsed.subscribe((value) => {
items = value;
})();
expect(items.length).toBe(1);
const [item] = items;
expectAction(item);
@@ -304,12 +306,12 @@ const client = new Client();
it('should filter out empty text chunks', () => {
parser.chunk(' \n <action type="shell">command</action> \n ');
parser.end();
let items: ParsedItem[] = [];
parser.parsed.subscribe((value) => {
items = value;
})();
// Only the action should remain, empty text chunks should be filtered
expect(items.length).toBe(1);
const [item] = items;
@@ -321,12 +323,12 @@ const client = new Client();
parser.chunk('<action type="file" src="test.js" unclosed');
parser.chunk('>content</action>');
parser.end();
let items: ParsedItem[] = [];
parser.parsed.subscribe((value) => {
items = value;
})();
expect(items.length).toBe(1);
const [item] = items;
expectAction(item);
@@ -340,12 +342,12 @@ const client = new Client();
parser.chunk(largeText);
parser.chunk('</action>');
parser.end();
let items: ParsedItem[] = [];
parser.parsed.subscribe((value) => {
items = value;
})();
expect(items.length).toBe(2);
const [text, action] = items;
expectText(text);
@@ -357,12 +359,12 @@ const client = new Client();
parser.chunk('<action type="file" src="test.js">content');
// No closing tag, but end() is called
parser.end();
let items: ParsedItem[] = [];
parser.parsed.subscribe((value) => {
items = value;
})();
expect(items.length).toBe(1);
const [item] = items;
expectAction(item);
+25 -1
View File
@@ -30,10 +30,30 @@ export class StreamParser {
private isFirstActionContent = false;
private skipCurrentAction = false;
private pendingText = '';
private callbacksEnabled = true;
private callbacks: Record<'complete', Array<(action: Action) => void | Promise<void>>> = {
complete: []
};
public parsed: Readable<ParsedItem[]> = this.store;
constructor() {}
private triggerCallbacks(event: keyof typeof this.callbacks, action: Action) {
if (!this.callbacksEnabled) return;
this.callbacks.complete.forEach((callback) => callback(action));
}
public on(event: 'complete', callback: (action: Action) => void | Promise<void>): void {
this.callbacks[event].push(callback);
}
public init(text: string): void {
this.reset();
this.callbacksEnabled = false;
this.chunk(text);
this.callbacksEnabled = true;
}
public chunk(text: string): void {
this.buffer += text;
this.parse();
@@ -100,6 +120,7 @@ export class StreamParser {
}
this.currentAction.complete = true;
this.triggerCallbacks('complete', this.currentAction);
this.updateStore();
}
@@ -187,7 +208,7 @@ export class StreamParser {
private parseAttributes(attributeString: string): Record<string, string> {
const attributes: Record<string, string> = {};
const regex = /(\w+)=["']([^"']*)["']/g;
let match;
let match: RegExpExecArray;
while ((match = regex.exec(attributeString)) !== null) {
attributes[match[1]] = match[2];
@@ -206,6 +227,7 @@ export class StreamParser {
// Reset the parser state
public reset(): void {
this.items = [];
this.callbacksEnabled = true;
this.currentAction = null;
this.currentTextChunk = null;
this.isFirstActionContent = false;
@@ -269,6 +291,7 @@ export class StreamParser {
);
}
this.currentAction.complete = true;
this.triggerCallbacks('complete', this.currentAction);
} else {
this.addToTextChunk(this.buffer);
}
@@ -286,6 +309,7 @@ export class StreamParser {
);
}
this.currentAction.complete = true;
this.triggerCallbacks('complete', this.currentAction);
this.updateStore();
}
@@ -1,23 +1,27 @@
import type { FileSystem } from '../filesystem';
import type { ComponentType } from 'svelte';
import {
IconArrowLeft,
IconFolder,
IconFolderOpen,
IconJs,
IconSvelte,
IconCss3
IconCss3,
IconDocument,
IconHtml5
} from '@appwrite.io/pink-icons-svelte';
export const icons = {
export const icons: Record<Icon, ComponentType> = {
svelte: IconSvelte,
file: IconDocument,
folder: IconFolder,
html: IconHtml5,
folderOpen: IconFolderOpen,
js: IconJs,
highlight: IconArrowLeft,
css: IconCss3
};
type Icon = 'svelte' | 'folder' | 'js' | 'css';
type Icon = 'svelte' | 'folder' | 'folderOpen' | 'html' | 'js' | 'css' | 'file' | 'highlight';
export type TreeItem = {
path: string;
@@ -29,15 +33,17 @@ export type TreeItem = {
function getIcon(filename: string): Icon {
if (filename.endsWith('.js')) return 'js';
if (filename.endsWith('.ts')) return 'js';
if (filename.endsWith('.html')) return 'svelte';
if (filename.endsWith('.html')) return 'html';
if (filename.endsWith('.css')) return 'css';
return 'folder';
if (filename.endsWith('.svelte')) return 'svelte';
return 'file';
}
export function treeFromFilesystem(fs: FileSystem): TreeItem[] {
export function treeFromFilesystem(files: string[]): TreeItem[] {
const tree: TreeItem[] = [];
for (const path of fs) {
for (const path of files) {
const parts = path.split('/');
let currentLevel = tree;
+28 -3
View File
@@ -6,6 +6,8 @@
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';
import { throttle } from '$lib/helpers/functions';
import { app } from '$lib/stores/app';
let editorElement: HTMLDivElement;
let editor: monaco.editor.IStandaloneCodeEditor;
@@ -18,6 +20,16 @@
editor.setModel(model);
}
export function resize(height: number, width: number) {
editor?.layout(
{
height,
width
},
true
);
}
onMount(async () => {
self.MonacoEnvironment = {
getWorker(_workerId: string, label: string) {
@@ -40,23 +52,36 @@
monaco.languages.typescript.typescriptDefaults.setEagerModelSync(true);
editor = monaco.editor.create(editorElement, {
automaticLayout: true,
theme: 'vs-light'
theme: $app.themeInUse === 'light' ? 'vs-light' : 'vs-dark'
});
loadCode(code, 'typescript');
const resizer = throttle(() => {
if (!editorElement) return;
editor.layout({
height: editorElement.offsetHeight,
width: editorElement.offsetWidth
});
}, 50);
const observer = new ResizeObserver(resizer);
observer.observe(editorElement);
});
onDestroy(() => {
monaco?.editor.getModels().forEach((model) => model.dispose());
editor?.dispose();
});
$: monaco.editor.setTheme($app.themeInUse === 'light' ? 'vs-light' : 'vs-dark');
</script>
<div class="editor" bind:this={editorElement}></div>
<style>
.editor {
height: 80vh;
height: 100%;
overflow: hidden;
}
</style>
+3 -4
View File
@@ -2,14 +2,13 @@
import { createTreeView } from '@melt-ui/svelte';
import { setContext } from 'svelte';
import { treeFromFilesystem } from './(filesystem)';
import type { FileSystem } from './filesystem';
import Tree from './(filesystem)/tree.svelte';
type Props = {
filesystem: FileSystem;
files: string[];
onopenfile?: (path: string) => void;
};
let { filesystem, onopenfile = null }: Props = $props();
let { files, onopenfile = null }: Props = $props();
const ctx = createTreeView();
setContext('tree', ctx);
@@ -19,7 +18,7 @@
states: { selectedItem }
} = ctx;
const items = $derived(treeFromFilesystem(filesystem));
const items = $derived(treeFromFilesystem(files));
$effect(() => {
if ($selectedItem && onopenfile) {
if ($selectedItem.dataset['file'] === 'true') {
+2 -2
View File
@@ -1,5 +1,5 @@
import { writable } from 'svelte/store';
export type FileSystem = string[];
export type FileSystem = Record<string, string>;
export const createFileSystem = (initial: FileSystem = []) => writable(initial);
export const filesystem = writable<FileSystem>({});
+111 -15
View File
@@ -1,21 +1,117 @@
<script>
// const xtermPkg = require('@xterm/xterm');
// const { Terminal } = xtermPkg;
// import { onMount } from 'svelte';
// import '@xterm/xterm/css/xterm.css';
//
// let terminalContainer;
export let height;
//
// onMount(() => {
// const term = new Terminal();
// term.open(terminalContainer);
// term.write('Hello from xterm.js!\r\n');
// });
<script lang="ts">
import '@xterm/xterm/css/xterm.css';
import type { Action } from 'svelte/action';
import type { Terminal } from '@xterm/xterm';
type Props = {
height: number;
onmessage: (message: MessageEvent, terminal: Terminal) => void | Promise<void>;
};
let { height, onmessage }: Props = $props();
function connect(term: Terminal) {
const socket = new WebSocket(`wss://terminal.appwrite.torsten.work/dummy`);
socket.onopen = () => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(
JSON.stringify({
type: 'terminal',
operation: 'updateSize',
params: {
cols: term.cols,
rows: term.rows
},
requestId: Date.now().toString()
})
);
}
};
socket.onmessage = (msg) => {
onmessage(msg, term);
};
socket.onerror = (err) => {
console.error('WebSocket error:', err);
};
return socket;
}
const terminal: Action = (node) => {
const init = async () => {
const [{ Terminal }, { FitAddon }] = await Promise.all([
import('@xterm/xterm'),
import('@xterm/addon-fit')
]);
const term = new Terminal({
cursorBlink: true,
allowProposedApi: true,
fontSize: 14,
fontFamily: 'Menlo, Monaco, "Courier New", monospace',
convertEol: true
});
term.loadAddon(new FitAddon());
term.open(node);
const socket = connect(term);
let buffer = '';
term.onKey(({ domEvent }) => {
if (domEvent.key === 'Enter') {
if (socket.readyState === WebSocket.OPEN) {
const terminalOperation = {
type: 'terminal',
operation: 'createCommand',
params: {
command: buffer
},
requestId: Date.now().toString()
};
socket.send(JSON.stringify(terminalOperation));
buffer = '';
term.write('\r\n');
}
}
if (domEvent.key === 'Backspace') {
if (domEvent.metaKey) {
buffer = '';
term.write('\x1b[2K\r');
} else {
buffer = buffer.slice(0, -1);
term.write('\b \b');
}
return;
}
if (domEvent.metaKey) {
return;
}
if (
domEvent.key.length === 1 &&
!domEvent.ctrlKey &&
!domEvent.altKey &&
!domEvent.metaKey
) {
buffer += domEvent.key;
term.write(domEvent.key);
return;
}
if (domEvent.key === 'ArrowUp') {
return;
}
});
};
init();
};
</script>
<div class="terminal-container" style:height={`${height}px`}>
<!-- <div bind:this={terminalContainer}></div>-->
<div use:terminal></div>
</div>
<style>
+2 -1
View File
@@ -64,7 +64,8 @@ export enum Dependencies {
MESSAGING_TOPIC_SUBSCRIBERS = 'dependency:messaging_topic_subscribers',
SITE = 'dependency:site',
SITES = 'dependency:sites',
SITES_DOMAINS = 'dependency:sites_domains'
SITES_DOMAINS = 'dependency:sites_domains',
ARTIFACTS = 'dependency:artifacts'
}
export const defaultScopes: string[] = [
+8 -10
View File
@@ -1,12 +1,10 @@
export const throttle = (fn: () => void, delay: number) => {
let timeout = false;
return () => {
if (!timeout) {
timeout = true;
fn.apply(this);
setTimeout(() => {
timeout = false;
}, delay);
export function throttle(callback: () => void, delay: number): () => void {
let lastCall = 0;
return function () {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
callback();
}
};
};
}
+67 -24
View File
@@ -1,8 +1,6 @@
<script lang="ts">
import { AvatarInitials, Breadcrumbs, BottomSheet } from '$lib/components/index.js';
import {
Avatar,
Divider,
Layout,
Card,
Typography,
@@ -34,11 +32,13 @@
} from '@appwrite.io/pink-icons-svelte';
import { base } from '$app/paths';
import { isTabletViewport, isSmallViewport } from '$lib/stores/viewport';
import { derived, writable } from 'svelte/store';
import { logout } from '$lib/helpers/logout';
import { Click, trackEvent } from '$lib/actions/analytics';
import { showChat } from '$lib/stores/chat';
import { artifacts } from '$routes/(console)/project-[project]/store';
import { conversation, showChat } from '$lib/stores/chat';
import { createStreamParser } from '$lib/components/chat/parser';
import { setContext, type Snippet } from 'svelte';
import { sdk } from '$lib/stores/sdk';
import { filesystem } from '$lib/components/editor/filesystem';
let hasProjectSidebar = $state(false);
@@ -46,11 +46,12 @@
hasProjectSidebar = page.url.pathname.startsWith(base + '/project');
});
type Props = {
interface Props {
loadedProjects: Array<NavbarProject>;
};
children?: Snippet;
}
let { loadedProjects = [] }: Props = $props();
let { loadedProjects = [], children }: Props = $props();
let showSideNavigation = $state(false);
let shouldAnimateThemeToggle = $state(false);
@@ -101,7 +102,7 @@
});
$effect(() => {
if ($isSmallViewport || page.url.pathname.includes('artifact-')) {
if ($isSmallViewport || page.params.artifact) {
showChat.set(true);
}
});
@@ -109,7 +110,7 @@
let resizer = $state(null);
let resizerLeftPosition = $state(page.data?.subNavigation ? 524 : 500);
let resizerLeftOffset = $state(page.data?.subNavigation ? 52 : 52);
let chatWidth = $state(resizerLeftPosition - resizerLeftOffset);
let chatWidth = $derived(resizerLeftPosition - resizerLeftOffset);
$effect(() => {
chatWidth = resizerLeftPosition - resizerLeftOffset;
@@ -117,20 +118,20 @@
let isResizing = false;
function startResize(event) {
function startResize() {
isResizing = true;
window.addEventListener('mousemove', resize);
window.addEventListener('mouseup', stopResize);
window.addEventListener('touchmove', resize);
window.addEventListener('touchend', stopResize);
document.body.style.userSelect = 'none';
document.getElementById('preview-iframe').style.pointerEvents = 'none';
}
function resize(event) {
function resize(event: TouchEvent | MouseEvent) {
if (!isResizing) return;
if (resizer) {
resizerLeftPosition = (event.touches ? event.touches[0].clientX : event.clientX) - 10;
resizerLeftPosition =
('touches' in event ? event.touches[0].clientX : event.clientX) - 10;
const maxSize = page.data?.subNavigation
? window.innerWidth - 660
: window.innerWidth - 460;
@@ -152,8 +153,46 @@
window.removeEventListener('touchmove', resize);
window.removeEventListener('touchend', stopResize);
document.body.style.userSelect = '';
document.getElementById('preview-iframe').style.pointerEvents = '';
}
const parser = createStreamParser();
async function getConversation(artifactId: string) {
const { conversations } = await sdk.forProject.imagine.listConversations(artifactId);
if (conversations.length === 0) {
const convo = await sdk.forProject.imagine.createConversation(
artifactId,
`Conversation ${new Date().getTime()}`
);
conversation.set(convo);
} else {
conversation.set(conversations[0]);
}
}
$effect(() => {
if (page.params.artifact && !$conversation) {
getConversation(page.params.artifact);
}
});
conversation.subscribe(async (convo) => {
if (!convo) return;
const { messages } = await sdk.forProject.imagine.listMessages(convo.artifactId, convo.$id);
const text = messages.reduce((curr, next) => {
return curr + next.content;
}, '');
parser.init(text);
});
parser.on('complete', (action) => {
if (action.type === 'file') {
$filesystem = {
...$filesystem,
[action.src]: action.content
};
}
});
</script>
<main>
@@ -271,22 +310,24 @@
class:sub-navigation={page.data.subNavigation}>
{#if $isSmallViewport}
{#if hasProjectSidebar}
<Chat width={chatWidth} hasSubNavigation={page.data?.subNavigation} />
<Chat {parser} width={chatWidth} hasSubNavigation={page.data?.subNavigation} />
{/if}
<Card.Base>
<Layout.Stack>
{#if page.data?.subNavigation}
<svelte:component this={page.data.subNavigation} />
{@const Component = page.data.subNavigation}
<Component />
{/if}
<slot />
{@render children()}
</Layout.Stack>
</Card.Base>
{:else}
<Layout.Stack direction="row" gap="l">
{#if hasProjectSidebar}
<Chat width={chatWidth} hasSubNavigation={false} />
<Chat {parser} width={chatWidth} hasSubNavigation={false} />
{#if $showChat}
<div
role="presentation"
class="resizer"
style:left={`${resizerLeftPosition}px`}
bind:this={resizer}
@@ -297,22 +338,24 @@
{/if}
<Card.Base>
{@const Header = page.data.header}
{#if page.data.subNavigation}
<svelte:component this={page.data.subNavigation} />
{@const SubNavigation = page.data.subNavigation}
<SubNavigation />
<div style:padding-left="200px" style:min-height="calc(100vh - 98px)">
<Layout.Stack>
{#if page.data?.header}
<svelte:component this={page.data.header} />
<Header />
{/if}
<slot />
{@render children()}
</Layout.Stack>
</div>
{:else}
<Layout.Stack>
{#if page.data?.header}
<svelte:component this={page.data.header} />
<Header />
{/if}
<slot />
{@render children()}
</Layout.Stack>
{/if}
</Card.Base>
+698
View File
@@ -0,0 +1,698 @@
import { AppwriteException } from '@appwrite.io/console';
import type { Client, Payload } from '@appwrite.io/console';
export class Imagine {
client: Client;
constructor(client: Client) {
this.client = client;
}
/**
* List all artifacts. This endpoint supports pagination and searching.
*
* @param {string[]} queries
* @param {string} search
* @throws {AppwriteException}
* @returns {Promise<ArtifactsList>}
*/
list(queries?: string[], search?: string): Promise<ArtifactsList> {
const apiPath = '/imagine/artifacts';
const payload: Payload = {};
if (typeof queries !== 'undefined') {
payload['queries'] = queries;
}
if (typeof search !== 'undefined') {
payload['search'] = search;
}
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('get', uri, apiHeaders, payload);
}
/**
* Create a new artifact. You can pass a custom ID or generate a random ID with `ID.unique()`.
*
* @param {string} artifactId
* @throws {AppwriteException}
* @returns {Promise<Artifact>}
*/
create(artifactId: string): Promise<Artifact> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
const apiPath = '/imagine/artifacts';
const payload: Payload = {};
if (typeof artifactId !== 'undefined') {
payload['artifactId'] = artifactId;
}
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('post', uri, apiHeaders, payload);
}
/**
* Get an artifact by its unique ID.
*
* @param {string} artifactId
* @throws {AppwriteException}
* @returns {Promise<Artifact>}
*/
get(artifactId: string): Promise<Artifact> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
const apiPath = '/imagine/artifacts/{artifactId}'.replace('{artifactId}', artifactId);
const payload: Payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('get', uri, apiHeaders, payload);
}
/**
* Update an artifact name by its unique ID.
*
* @param {string} artifactId
* @param {string} name
* @throws {AppwriteException}
* @returns {Promise<Artifact>}
*/
update(artifactId: string, name?: string): Promise<Artifact> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
const apiPath = '/imagine/artifacts/{artifactId}'.replace('{artifactId}', artifactId);
const payload: Payload = {};
if (typeof name !== 'undefined') {
payload['name'] = name;
}
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('patch', uri, apiHeaders, payload);
}
/**
* Delete an artifact by its unique ID. Once deleted, the artifact will no longer be available
and all associated resources will be removed.
*
* @param {string} artifactId
* @throws {AppwriteException}
* @returns {Promise<{}>}
*/
delete(artifactId: string): Promise<{}> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
const apiPath = '/imagine/artifacts/{artifactId}'.replace('{artifactId}', artifactId);
const payload: Payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('delete', uri, apiHeaders, payload);
}
/**
* List all conversations for an artifact. This endpoint supports pagination and searching.
*
* @param {string} artifactId
* @param {string[]} queries
* @param {string} search
* @throws {AppwriteException}
* @returns {Promise<ConversationsList>}
*/
listConversations(
artifactId: string,
queries?: string[],
search?: string
): Promise<ConversationsList> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
const apiPath = '/imagine/artifacts/{artifactId}/conversations'.replace(
'{artifactId}',
artifactId
);
const payload: Payload = {};
if (typeof queries !== 'undefined') {
payload['queries'] = queries;
}
if (typeof search !== 'undefined') {
payload['search'] = search;
}
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('get', uri, apiHeaders, payload);
}
/**
* Create a new conversation for an artifact.
*
* @param {string} artifactId
* @param {string} name
* @throws {AppwriteException}
* @returns {Promise<Conversation>}
*/
createConversation(artifactId: string, name: string): Promise<Conversation> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
if (typeof name === 'undefined') {
throw new AppwriteException('Missing required parameter: "name"');
}
const apiPath = '/imagine/artifacts/{artifactId}/conversations'.replace(
'{artifactId}',
artifactId
);
const payload: Payload = {};
if (typeof name !== 'undefined') {
payload['name'] = name;
}
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('post', uri, apiHeaders, payload);
}
/**
* Get a conversation by its unique ID.
*
* @param {string} artifactId
* @param {string} conversationId
* @throws {AppwriteException}
* @returns {Promise<Conversation>}
*/
getConversation(artifactId: string, conversationId: string): Promise<Conversation> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
if (typeof conversationId === 'undefined') {
throw new AppwriteException('Missing required parameter: "conversationId"');
}
const apiPath = '/imagine/artifacts/{artifactId}/conversations/{conversationId}'
.replace('{artifactId}', artifactId)
.replace('{conversationId}', conversationId);
const payload: Payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('get', uri, apiHeaders, payload);
}
/**
* Update a conversation by its unique ID. This endpoint allows you to update the conversation&#039;s name,
messages, and status.
*
* @param {string} artifactId
* @param {string} conversationId
* @param {string} name
* @throws {AppwriteException}
* @returns {Promise<Conversation>}
*/
updateConversation(
artifactId: string,
conversationId: string,
name?: string
): Promise<Conversation> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
if (typeof conversationId === 'undefined') {
throw new AppwriteException('Missing required parameter: "conversationId"');
}
const apiPath = '/imagine/artifacts/{artifactId}/conversations/{conversationId}'
.replace('{artifactId}', artifactId)
.replace('{conversationId}', conversationId);
const payload: Payload = {};
if (typeof name !== 'undefined') {
payload['name'] = name;
}
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('patch', uri, apiHeaders, payload);
}
/**
* Delete a conversation by its unique ID. Once deleted, the conversation will no longer be available.
*
* @param {string} artifactId
* @param {string} conversationId
* @throws {AppwriteException}
* @returns {Promise<{}>}
*/
deleteConversation(artifactId: string, conversationId: string): Promise<{}> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
if (typeof conversationId === 'undefined') {
throw new AppwriteException('Missing required parameter: "conversationId"');
}
const apiPath = '/imagine/artifacts/{artifactId}/conversations/{conversationId}'
.replace('{artifactId}', artifactId)
.replace('{conversationId}', conversationId);
const payload: Payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('delete', uri, apiHeaders, payload);
}
/**
* List all messages in a conversation. This endpoint supports pagination and searching.
*
* @param {string} artifactId
* @param {string} conversationId
* @param {string[]} queries
* @param {string} search
* @throws {AppwriteException}
* @returns {Promise<ConversationsMessagesList>}
*/
listMessages(
artifactId: string,
conversationId: string,
queries?: string[],
search?: string
): Promise<ConversationsMessagesList> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
if (typeof conversationId === 'undefined') {
throw new AppwriteException('Missing required parameter: "conversationId"');
}
const apiPath = '/imagine/artifacts/{artifactId}/conversations/{conversationId}/messages'
.replace('{artifactId}', artifactId)
.replace('{conversationId}', conversationId);
const payload: Payload = {};
if (typeof queries !== 'undefined') {
payload['queries'] = queries;
}
if (typeof search !== 'undefined') {
payload['search'] = search;
}
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('get', uri, apiHeaders, payload);
}
/**
* Create a new message in a conversation.
*
* @param {string} artifactId
* @param {string} conversationId
* @param {Type} type
* @param {string} content
* @throws {AppwriteException}
* @returns {Promise<Message>}
*/
createMessage(
artifactId: string,
conversationId: string,
type: Type,
content: string
): Promise<Message> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
if (typeof conversationId === 'undefined') {
throw new AppwriteException('Missing required parameter: "conversationId"');
}
if (typeof type === 'undefined') {
throw new AppwriteException('Missing required parameter: "type"');
}
if (typeof content === 'undefined') {
throw new AppwriteException('Missing required parameter: "content"');
}
const apiPath = '/imagine/artifacts/{artifactId}/conversations/{conversationId}/messages'
.replace('{artifactId}', artifactId)
.replace('{conversationId}', conversationId);
const payload: Payload = {};
if (typeof type !== 'undefined') {
payload['type'] = type;
}
if (typeof content !== 'undefined') {
payload['content'] = content;
}
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('post', uri, apiHeaders, payload);
}
/**
* Get a message by its unique ID.
*
* @param {string} artifactId
* @param {string} conversationId
* @param {string} messageId
* @throws {AppwriteException}
* @returns {Promise<ConversationsMessage>}
*/
getMessage(
artifactId: string,
conversationId: string,
messageId: string
): Promise<ConversationsMessage> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
if (typeof conversationId === 'undefined') {
throw new AppwriteException('Missing required parameter: "conversationId"');
}
if (typeof messageId === 'undefined') {
throw new AppwriteException('Missing required parameter: "messageId"');
}
const apiPath =
'/imagine/artifacts/{artifactId}/conversations/{conversationId}/messages/{messageId}'
.replace('{artifactId}', artifactId)
.replace('{conversationId}', conversationId)
.replace('{messageId}', messageId);
const payload: Payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('get', uri, apiHeaders, payload);
}
/**
* Update a message by its unique ID. This endpoint allows you to update the message&#039;s content and type.
*
* @param {string} artifactId
* @param {string} conversationId
* @param {string} messageId
* @param {string} content
* @param {string} type
* @throws {AppwriteException}
* @returns {Promise<ConversationsMessage>}
*/
updateMessage(
artifactId: string,
conversationId: string,
messageId: string,
content?: string,
type?: string
): Promise<ConversationsMessage> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
if (typeof conversationId === 'undefined') {
throw new AppwriteException('Missing required parameter: "conversationId"');
}
if (typeof messageId === 'undefined') {
throw new AppwriteException('Missing required parameter: "messageId"');
}
const apiPath =
'/imagine/artifacts/{artifactId}/conversations/{conversationId}/messages/{messageId}'
.replace('{artifactId}', artifactId)
.replace('{conversationId}', conversationId)
.replace('{messageId}', messageId);
const payload: Payload = {};
if (typeof content !== 'undefined') {
payload['content'] = content;
}
if (typeof type !== 'undefined') {
payload['type'] = type;
}
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('patch', uri, apiHeaders, payload);
}
/**
* Delete a message by its unique ID. Once deleted, the message will no longer be available.
*
* @param {string} artifactId
* @param {string} conversationId
* @param {string} messageId
* @throws {AppwriteException}
* @returns {Promise<{}>}
*/
deleteMessage(artifactId: string, conversationId: string, messageId: string): Promise<{}> {
if (typeof artifactId === 'undefined') {
throw new AppwriteException('Missing required parameter: "artifactId"');
}
if (typeof conversationId === 'undefined') {
throw new AppwriteException('Missing required parameter: "conversationId"');
}
if (typeof messageId === 'undefined') {
throw new AppwriteException('Missing required parameter: "messageId"');
}
const apiPath =
'/imagine/artifacts/{artifactId}/conversations/{conversationId}/messages/{messageId}'
.replace('{artifactId}', artifactId)
.replace('{conversationId}', conversationId)
.replace('{messageId}', messageId);
const payload: Payload = {};
const uri = new URL(this.client.config.endpoint + apiPath);
const apiHeaders: { [header: string]: string } = {
'content-type': 'application/json'
};
return this.client.call('delete', uri, apiHeaders, payload);
}
}
export enum Type {
Text = 'text',
Image = 'image'
}
export type Artifact = {
/**
* Artifact unique ID.
*/
$id: string;
/**
* Artifact creation date in ISO 8601 format.
*/
$createdAt: string;
/**
* Artifact update date in ISO 8601 format.
*/
$updatedAt: string;
/**
* Artifact name.
*/
name: string;
/**
* Artifact description.
*/
description?: string;
/**
* Artifact version.
*/
version?: string;
/**
* Framework used in the artifact.
*/
framework?: string;
/**
* Technology stack used in the artifact.
*/
stack?: string[];
/**
* Original prompt used to generate the artifact.
*/
prompt?: string;
/**
* Current status of the artifact. Possible values: draft, processing, completed, failed.
*/
status: string;
};
/**
* Conversation
*/
export type Conversation = {
/**
* Conversation unique ID.
*/
$id: string;
/**
* Conversation creation date in ISO 8601 format.
*/
$createdAt: string;
/**
* Conversation update date in ISO 8601 format.
*/
$updatedAt: string;
/**
* ID of the artifact this conversation belongs to.
*/
artifactId: string;
/**
* Conversation name.
*/
name: string;
/**
* Search index string.
*/
search: string;
};
/**
* ConversationsMessage
*/
export type ConversationsMessage = {
/**
* Message unique ID.
*/
$id: string;
/**
* Message creation date in ISO 8601 format.
*/
$createdAt: string;
/**
* Message update date in ISO 8601 format.
*/
$updatedAt: string;
/**
* Artifact unique ID.
*/
artifactId: string;
/**
* Conversation unique ID.
*/
conversationId: string;
/**
* Message type.
*/
type: string;
/**
* Message content.
*/
content: string;
/**
* Message role.
*/
role: string;
};
/**
* Artifacts List
*/
export type ArtifactsList = {
/**
* Total number of artifacts documents that matched your query.
*/
total: number;
/**
* List of artifacts.
*/
artifacts: Artifact[];
};
/**
* Conversations List
*/
export type ConversationsList = {
/**
* Total number of conversations documents that matched your query.
*/
total: number;
/**
* List of conversations.
*/
conversations: Conversation[];
};
/**
* Conversations Messages List
*/
export type ConversationsMessagesList = {
/**
* Total number of messages documents that matched your query.
*/
total: number;
/**
* List of messages.
*/
messages: ConversationsMessage[];
};
/**
* Message
*/
export type Message = {
/**
* Message ID.
*/
$id: string;
/**
* Message creation time in ISO 8601 format.
*/
$createdAt: string;
/**
* Message update date in ISO 8601 format.
*/
$updatedAt: string;
/**
* Message provider type.
*/
providerType: string;
/**
* Topic IDs set as recipients.
*/
topics: string[];
/**
* User IDs set as recipients.
*/
users: string[];
/**
* Target IDs set as recipients.
*/
targets: string[];
/**
* The scheduled time for message.
*/
scheduledAt?: string;
/**
* The time when the message was delivered.
*/
deliveredAt?: string;
/**
* Delivery errors if any.
*/
deliveryErrors?: string[];
/**
* Number of recipients the message was delivered to.
*/
deliveredTotal: number;
/**
* Data of the message.
*/
data: object;
/**
* Status of delivery.
*/
status: string;
};
+2
View File
@@ -1,4 +1,6 @@
import { writable } from 'svelte/store';
import type { Conversation } from '$lib/sdk/imagine';
export const showChat = writable(false);
export const showPrompt = writable(false);
export const conversation = writable<Conversation>();
+3 -1
View File
@@ -27,6 +27,7 @@ import { Backups } from '../sdk/backups';
import { Domains } from '$lib/sdk/domains';
import { Sources } from '$lib/sdk/sources';
import { building } from '$app/environment';
import { Imagine } from '$lib/sdk/imagine';
export function getApiEndpoint(): string {
if (VARS.APPWRITE_ENDPOINT) return VARS.APPWRITE_ENDPOINT;
@@ -61,7 +62,8 @@ const sdkForProject = {
vcs: new Vcs(clientProject),
proxy: new Proxy(clientProject),
migrations: new Migrations(clientProject),
sites: new Sites(clientProject)
sites: new Sites(clientProject),
imagine: new Imagine(clientProject)
};
export const getSdkForProject = (projectId: string) => {
+1 -1
View File
@@ -331,7 +331,7 @@
<CommandCenter />
{#if consoleProfile.hasChatLayout}
<ShellStudio bind:loadedProjects><slot /></ShellStudio>
<ShellStudio {loadedProjects}><slot /></ShellStudio>
{:else}
<Shell
showSideNavigation={page.url.pathname !== '/console' &&
@@ -8,7 +8,6 @@ import { isCloud } from '$lib/system';
import type { Organization } from '$lib/stores/organization';
import { defaultRoles, defaultScopes } from '$lib/constants';
import type { Plan } from '$lib/sdk/billing';
import { artifacts } from '$routes/(console)/project-[project]/store';
export const load: LayoutLoad = async ({ params, depends }) => {
depends(Dependencies.PROJECT);
@@ -39,28 +38,6 @@ export const load: LayoutLoad = async ({ params, depends }) => {
}
}
// todo replace with actual artifacts from API
artifacts.set([
{
$id: 'RE1xJXnaCX',
title: 'Dashboard',
url: null,
previewUrl: 'https://getbootstrap.com/docs/5.3/examples/blog/'
},
{
$id: 'jABosmZQhY',
title: 'Sign in screen',
url: 's-130328439.imagine.dev',
previewUrl: 'https://getbootstrap.com/'
},
{
$id: 'U1aolAia1m',
title: 'Mobile app',
url: null,
previewUrl: 'https://www.posthog.com/'
}
]);
return {
project,
organization,
@@ -44,11 +44,3 @@ function createStats() {
}
export const stats = createStats();
export const artifacts = writable<
Array<{
$id: string;
title: string;
url?: string | null;
previewUrl?: string;
}>
>([]);
@@ -0,0 +1,22 @@
import { Dependencies } from '$lib/constants';
import { sdk } from '$lib/stores/sdk';
import { error } from '@sveltejs/kit';
import type { LayoutLoad } from './$types';
import { preferences } from '$lib/stores/preferences';
import { failedInvoice } from '$lib/stores/billing';
import { isCloud } from '$lib/system';
import type { Organization } from '$lib/stores/organization';
import { defaultRoles, defaultScopes } from '$lib/constants';
import type { Plan } from '$lib/sdk/billing';
export const load: LayoutLoad = async ({ params, depends }) => {
depends(Dependencies.ARTIFACTS);
try {
return {
artifacts: await sdk.forProject.imagine.list()
};
} catch (e) {
error(e.code, e.message);
}
};
@@ -1,21 +1,22 @@
<script>
import {
Badge,
Divider,
Icon,
Typography,
Card,
Layout,
Table,
Status
} from '@appwrite.io/pink-svelte';
import { Divider, Typography, Card, Layout, Status } from '@appwrite.io/pink-svelte';
import { Button } from '$lib/elements/forms';
import { artifacts } from '$routes/(console)/project-[project]/store.js';
import { base } from '$app/paths';
import { page } from '$app/state';
import Placeholder from './assets/placeholder.svg';
import { sdk } from '$lib/stores/sdk';
import { ID } from '@appwrite.io/console';
import { goto, invalidate } from '$app/navigation';
import { Dependencies } from '$lib/constants';
const projectId = page.data?.project?.$id ?? '';
const { data } = $props();
async function createArtifact() {
const artifact = await sdk.forProject.imagine.create(ID.unique());
await goto(`${base}/project-${page.params.project}/studio/artifact-${artifact.$id}`);
invalidate(Dependencies.ARTIFACTS);
}
</script>
<Layout.Stack>
@@ -23,23 +24,22 @@
<Typography.Text variant="m-500" color="--fgcolor-neutral-secondary"
>Artifacts</Typography.Text>
<Button size="s" on:click={() => {}} event="create_project">Create artifact</Button>
<Button size="s" on:click={createArtifact} event="create_artifact">Create artifact</Button>
</Layout.Stack>
<Divider />
<Layout.Grid gap="l" columnsS={1} columns={3} columnsL={3} columnsXL={4}>
{#each $artifacts as artifact}
<a href={`${base}/project-${projectId}/studio/artifact-${artifact.$id}`}>
{#each data.artifacts.artifacts as artifact}
<a href={`${base}/project-${page.params.project}/studio/artifact-${artifact.$id}`}>
<Card.Base padding="xxs">
<Layout.Stack gap="xs">
<img
src={Placeholder}
alt={`Screenshot of latest ${artifact.title} version`} />
<Typography.Text variant="m-500" color="--fgcolor-neutral-primary"
>{artifact.title}</Typography.Text>
<Status
status={artifact.url ? 'complete' : 'waiting'}
label={artifact.url ?? 'Not released'}></Status>
alt={`Screenshot of latest ${artifact.name} version`} />
<Typography.Text variant="m-500" color="--fgcolor-neutral-primary">
{artifact.name}
</Typography.Text>
<Status status="waiting" label="Not released"></Status>
</Layout.Stack>
</Card.Base></a>
{/each}
@@ -0,0 +1,137 @@
<script lang="ts">
import { Layout, Card, Typography, Divider, Icon } from '@appwrite.io/pink-svelte';
import { isTabSelected } from '$lib/helpers/load';
import { page } from '$app/state';
import { Tab, Tabs, Terminal } from '$lib/components';
import { base } from '$app/paths';
import { isSmallViewport } from '$lib/stores/viewport';
import { IconChevronDoubleUp, IconTerminal } from '@appwrite.io/pink-icons-svelte';
const { children } = $props();
const projectId = page.params.project;
const artifactId = page.params.artifact;
const path = `${base}/project-${projectId}/studio/artifact-${artifactId}`;
const tabs = [
{
href: path,
title: 'Preview',
event: 'preview',
hasChildren: true
},
{
href: `${path}/code`,
title: 'Code',
event: 'code',
hasChildren: true
}
];
let terminalOpen = $state(false);
let asideRef: HTMLElement;
let isResizing = false;
let terminalHeight = $state(300);
function startResize() {
isResizing = true;
window.addEventListener('mousemove', resize);
window.addEventListener('mouseup', stopResize);
window.addEventListener('touchmove', resize);
window.addEventListener('touchend', stopResize);
document.body.style.userSelect = 'none';
}
function resize(event: MouseEvent | TouchEvent) {
if (!isResizing) return;
const clientY = 'touches' in event ? event.touches[0].clientY : event.clientY;
const maxHeight = window.innerHeight - 400;
let height =
asideRef.getBoundingClientRect().y -
clientY +
asideRef.getBoundingClientRect().height -
32;
terminalHeight = height < maxHeight ? height : maxHeight;
}
function stopResize() {
isResizing = false;
window.removeEventListener('mousemove', resize);
window.removeEventListener('mouseup', stopResize);
window.removeEventListener('touchmove', resize);
window.removeEventListener('touchend', stopResize);
document.body.style.userSelect = '';
}
</script>
<Layout.Stack
direction="column"
height={$isSmallViewport ? 'calc(100vh - 218px)' : 'calc(100vh - 120px)'}
gap="none">
<Layout.Stack direction="column">
<Tabs>
{#each tabs as tab}
<Tab
href={tab.href}
selected={isTabSelected(tab, page.url.pathname, path, tabs)}
event={tab.event}>
{tab.title}
</Tab>
{/each}
</Tabs>
<Divider />
</Layout.Stack>
{@render children()}
<aside bind:this={asideRef}>
<details bind:open={terminalOpen}>
<summary
onmousedown={startResize}
ontouchmove={startResize}
class:terminal-slider={terminalOpen}>
<Layout.Stack direction="row" justify="space-between">
<Layout.Stack direction="row" alignItems="center" gap="xs">
<Icon icon={IconTerminal} color="--fgcolor-neutral-tertiary" />
<Typography.Text>Terminal</Typography.Text>
</Layout.Stack>
<Icon icon={IconChevronDoubleUp} color="--fgcolor-neutral-tertiary" />
</Layout.Stack>
</summary>
<Terminal height={terminalHeight} onmessage={(msg) => console.log(msg.data)}></Terminal>
</details>
</aside>
</Layout.Stack>
<style>
aside {
background-color: var(--bgcolor-neutral-default);
margin-inline-start: -25px;
margin-block-end: calc(-1 * var(--space-9));
padding: var(--space-3);
border-bottom-left-radius: var(--border-radius-m);
border-bottom-right-radius: var(--border-radius-m);
border: 1px solid var(--border-neutral);
width: calc(100% - var(--space-7));
position: fixed;
bottom: 116px;
@media (min-width: 768px) {
width: calc(100% + 2 * var(--space-9));
margin-inline-start: calc(-1 * var(--space-9));
position: static;
border: 0;
}
}
summary {
cursor: pointer;
}
.terminal-slider {
cursor: row-resize;
}
</style>
@@ -0,0 +1,8 @@
import { sdk } from '$lib/stores/sdk';
import type { LayoutLoad } from './$types';
export const load: LayoutLoad = async ({ params, parent }) => {
return {
artifact: await sdk.forProject.imagine.get(params.artifact)
};
};
@@ -1,160 +1,30 @@
<script lang="ts">
import { Layout, Card, Typography, Divider, Icon } from '@appwrite.io/pink-svelte';
import { isTabSelected } from '$lib/helpers/load';
import { page } from '$app/state';
import { Tab, Tabs, Terminal } from '$lib/components';
import { base } from '$app/paths';
import { isSmallViewport } from '$lib/stores/viewport';
import InputText from '$lib/elements/forms/inputText.svelte';
import {
IconChevronDoubleUp,
IconDeviceMobile,
IconExternalLink,
IconRefresh,
IconTerminal
IconRefresh
} from '@appwrite.io/pink-icons-svelte';
import { InputText } from '$lib/elements/forms';
import { artifacts } from '$routes/(console)/project-[project]/store';
import { Layout, Icon } from '@appwrite.io/pink-svelte';
const projectId = page.params.project;
let selectedArtifact = $derived(
$artifacts.find((artifact) => page.params.artifact === artifact.$id)
);
let frameUrl = $derived.by(() => {
return selectedArtifact.previewUrl;
});
console.log('frameUrl', frameUrl);
const path = `${base}/project-${projectId}/studio`;
const tabs = [
{
href: path,
title: 'Preview',
event: 'preview',
hasChildren: true
},
{
href: `${path}/code`,
title: 'Code',
event: 'code',
hasChildren: true
}
];
let terminalOpen = $state(false);
let asideRef;
let isResizing = false;
let terminalHeight = $state(300);
function startResize(event) {
isResizing = true;
window.addEventListener('mousemove', resize);
window.addEventListener('mouseup', stopResize);
window.addEventListener('touchmove', resize);
window.addEventListener('touchend', stopResize);
document.body.style.userSelect = 'none';
document.getElementById('preview-iframe').style.pointerEvents = 'none';
}
function resize(event) {
if (!isResizing) return;
const clientY = event.touches ? event.touches[0].clientY : event.clientY;
const maxHeight = window.innerHeight - 400;
let height =
asideRef.getBoundingClientRect().y -
clientY +
asideRef.getBoundingClientRect().height -
32;
terminalHeight = height < maxHeight ? height : maxHeight;
}
function stopResize() {
isResizing = false;
window.removeEventListener('mousemove', resize);
window.removeEventListener('mouseup', stopResize);
window.removeEventListener('touchmove', resize);
window.removeEventListener('touchend', stopResize);
document.body.style.userSelect = '';
document.getElementById('preview-iframe').style.pointerEvents = '';
}
const previewUrl = 'https://getbootstrap.com/docs/5.3/examples/blog';
</script>
<Layout.Stack
direction="column"
height={$isSmallViewport ? 'calc(100vh - 218px)' : 'calc(100vh - 120px)'}
gap="none">
<Layout.Stack direction="column">
<Tabs>
{#each tabs as tab}
<Tab
href={tab.href}
selected={isTabSelected(tab, page.url.pathname, path, tabs)}
event={tab.event}>
{tab.title}
</Tab>
{/each}
</Tabs>
<Divider />
<Layout.Stack direction="row" alignItems="center">
<Icon icon={IconRefresh} color="--fgcolor-neutral-tertiary" />
<InputText id="previewUrl" value={frameUrl} />
<Icon icon={IconDeviceMobile} color="--fgcolor-neutral-tertiary" />
<Icon icon={IconExternalLink} color="--fgcolor-neutral-tertiary" />
</Layout.Stack>
<div></div>
<Layout.Stack direction="column">
<Layout.Stack direction="row" alignItems="center">
<Icon icon={IconRefresh} color="--fgcolor-neutral-tertiary" />
<InputText id="previewUrl" value={previewUrl} />
<Icon icon={IconDeviceMobile} color="--fgcolor-neutral-tertiary" />
<Icon icon={IconExternalLink} color="--fgcolor-neutral-tertiary" />
</Layout.Stack>
<div class="iframe-container">
<iframe src={frameUrl} id="preview-iframe"></iframe>
</div>
<div></div>
<aside bind:this={asideRef}>
<details bind:open={terminalOpen}>
<summary
on:mousedown={startResize}
on:touchmove={startResize}
class:terminal-slider={terminalOpen}>
<Layout.Stack direction="row" justify="space-between">
<Layout.Stack direction="row" alignItems="center" gap="xs">
<Icon icon={IconTerminal} color="--fgcolor-neutral-tertiary" />
<Typography.Text>Terminal</Typography.Text>
</Layout.Stack>
<Icon icon={IconChevronDoubleUp} color="--fgcolor-neutral-tertiary" />
</Layout.Stack>
</summary>
<Terminal bind:height={terminalHeight}></Terminal>
</details>
</aside>
</Layout.Stack>
<div class="iframe-container">
<iframe src={previewUrl} id="preview-iframe" title="preview"></iframe>
</div>
<style>
aside {
background-color: var(--bgcolor-neutral-default);
margin-inline-start: -25px;
margin-block-end: calc(-1 * var(--space-9));
padding: var(--space-3);
border-bottom-left-radius: var(--border-radius-m);
border-bottom-right-radius: var(--border-radius-m);
border: 1px solid var(--border-neutral);
width: calc(100% - var(--space-7));
position: fixed;
bottom: 116px;
@media (min-width: 768px) {
width: calc(100% + 2 * var(--space-9));
margin-inline-start: calc(-1 * var(--space-9));
position: static;
border: 0;
}
}
summary {
cursor: pointer;
}
<style lang="scss">
.iframe-container {
height: calc(100vh - 296px);
height: 100%;
@media (min-width: 768px) {
flex-grow: 1;
@@ -167,8 +37,4 @@
height: 100%;
margin-inline-start: calc(-1 * var(--space-9));
}
.terminal-slider {
cursor: row-resize;
}
</style>
@@ -1,40 +1,34 @@
<script lang="ts">
import Editor from '$lib/components/editor/editor.svelte';
import { createFileSystem } from '$lib/components/editor/filesystem';
import { filesystem } from '$lib/components/editor/filesystem';
import Filesystem from '$lib/components/editor/filesystem.svelte';
import { Layout } from '@appwrite.io/pink-svelte';
import html from '../../../../../../app.html?raw';
import js from './app.js?raw';
import css from './app.css?raw';
const files = {
'app.html': html,
'src/app.js': js,
'src/app.css': css
};
const filesystem = createFileSystem(Object.keys(files));
const files = $derived(Object.keys($filesystem));
let instance: Editor;
function getLanguageFromExtensions(path: string) {
if (path.endsWith('.js')) return 'javascript';
if (path.endsWith('.ts')) return 'typescript';
if (path.endsWith('.js') || path.endsWith('.jsx')) return 'javascript';
if (path.endsWith('.ts') || path.endsWith('.tsx')) return 'typescript';
if (path.endsWith('.html')) return 'html';
if (path.endsWith('.css')) return 'css';
return 'folder';
return 'file';
}
function openFile(path: string) {
instance?.loadCode(files[path], getLanguageFromExtensions(path));
instance?.loadCode($filesystem[path], getLanguageFromExtensions(path));
}
</script>
<Layout.Stack direction="row">
<div style:width="30%">
<Filesystem filesystem={$filesystem} onopenfile={openFile} />
</div>
<div style:width="70%">
<Editor bind:this={instance} />
</div>
</Layout.Stack>
<main>
<Filesystem {files} onopenfile={openFile} />
<Editor bind:this={instance} />
</main>
<style lang="scss">
main {
height: 100%;
display: grid;
grid-template-columns: 25% 75%;
}
</style>
+5 -5
View File
@@ -1,6 +1,6 @@
{
"bgcolor-accent": "var(--neutral-50)",
"bgcolor-accent-secondary": "var(--neutral-100)",
"bgcolor-accent-tertiary": "var(--neutral-150)",
"fgcolor-on-accent": "var(--neutral-950)"
}
"bgcolor-accent": "var(--neutral-50)",
"bgcolor-accent-secondary": "var(--neutral-100)",
"bgcolor-accent-tertiary": "var(--neutral-150)",
"fgcolor-on-accent": "var(--neutral-950)"
}
+4 -4
View File
@@ -1,5 +1,5 @@
{
"bgcolor-accent": "var(--neutral-1000)",
"bgcolor-accent-secondary": "var(--neutral-900)",
"bgcolor-accent-tertiary": "var(--neutral-850)"
}
"bgcolor-accent": "var(--neutral-1000)",
"bgcolor-accent-secondary": "var(--neutral-900)",
"bgcolor-accent-tertiary": "var(--neutral-850)"
}
-1
View File
@@ -1,7 +1,6 @@
import adapter from '@sveltejs/adapter-static';
import { sveltePreprocess } from 'svelte-preprocess';
import { preprocessMeltUI, sequence } from '@melt-ui/pp';
import 'dotenv/config';
/** @type {import('@sveltejs/kit').Config} */
const config = {
+1 -1
View File
@@ -12,7 +12,7 @@ export default defineConfig({
project: 'console'
}
}),
sveltekit(),
sveltekit()
],
optimizeDeps: {
include: ['echarts', 'prismjs']