Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Svelte 5 POC #561

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
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
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"devDependencies": {
"@playwright/test": "^1.37.1",
"@sveltejs/adapter-vercel": "3.0.3",
"@sveltejs/kit": "^1.24.1",
"@sveltejs/kit": "^1.27.0",
"@sveltejs/site-kit": "6.0.0-next.39",
"@types/diff": "^5.0.3",
"@types/prismjs": "^1.26.0",
Expand All @@ -27,8 +27,8 @@
"prettier": "^3.0.3",
"prettier-plugin-svelte": "^3.0.3",
"shiki-twoslash": "^3.1.2",
"svelte": "^4.2.0",
"svelte-check": "^3.5.1",
"svelte": "^5.0.0-next.31",
"svelte-check": "^3.6.0",
"tiny-glob": "^0.2.9",
"typescript": "^5.2.2",
"vite": "^4.4.9"
Expand Down
238 changes: 108 additions & 130 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

84 changes: 28 additions & 56 deletions src/lib/client/adapters/webcontainer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { escape_html, get_depth } from '../../../utils.js';
import { ready } from '../common/index.js';

/**
* @typedef {import("../../../../routes/tutorial/[slug]/state.js").CompilerWarning} CompilerWarning
* @typedef {import("../../../../routes/tutorial/[slug]/state.svelte.js").CompilerWarning} CompilerWarning
*/

const converter = new AnsiToHtml({
Expand All @@ -17,15 +17,11 @@ const converter = new AnsiToHtml({
let vm;

/**
* @param {import('svelte/store').Writable<string | null>} base
* @param {import('svelte/store').Writable<Error | null>} error
* @param {import('svelte/store').Writable<{ value: number, text: string }>} progress
* @param {import('svelte/store').Writable<string[]>} logs
* @param {import('svelte/store').Writable<Record<string, CompilerWarning[]>>} warnings
* @param {typeof import('../../../../routes/tutorial/[slug]/adapter.svelte.js').a} state
* @returns {Promise<import('$lib/types').Adapter>}
*/
export async function create(base, error, progress, logs, warnings) {
progress.set({ value: 0, text: 'loading files' });
export async function create(state) {
state.progress = { value: 0, text: 'loading files' };

const q = yootils.queue(1);
/** @type {Map<string, Array<import('$lib/types').FileStub>>} */
Expand All @@ -34,10 +30,10 @@ export async function create(base, error, progress, logs, warnings) {
/** Paths and contents of the currently loaded file stubs */
let current_stubs = stubs_to_map([]);

progress.set({ value: 1 / 5, text: 'booting webcontainer' });
state.progress = { value: 1 / 5, text: 'booting webcontainer' };
vm = await WebContainer.boot();

progress.set({ value: 2 / 5, text: 'writing virtual files' });
state.progress = { value: 2 / 5, text: 'writing virtual files' };
const common = await ready;
await vm.mount({
'common.zip': {
Expand All @@ -48,48 +44,31 @@ export async function create(base, error, progress, logs, warnings) {
}
});

/** @type {Record<string, CompilerWarning[]>} */
let $warnings;
warnings.subscribe((value) => $warnings = value);

/** @type {any} */
let timeout;

/** @param {number} msec */
function schedule_to_update_warning(msec) {
clearTimeout(timeout);
timeout = setTimeout(() => warnings.set($warnings), msec);
}

const log_stream = () =>
new WritableStream({
write(chunk) {
if (chunk === '\x1B[1;1H') {
// clear screen
logs.set([]);

state.logs = [];
} else if (chunk?.startsWith('svelte:warnings:')) {
/** @type {CompilerWarning} */
const warn = JSON.parse(chunk.slice(16));
const current = $warnings[warn.filename];
const current = state.warnings[warn.filename];

if (!current) {
$warnings[warn.filename] = [warn];
// the exact same warning may be given multiple times in a row
} else if (!current.some((s) => (s.code === warn.code && s.pos === warn.pos))) {
state.warnings[warn.filename] = [warn];
// the exact same warning may be given multiple times in a row
} else if (!current.some((s) => s.code === warn.code && s.pos === warn.pos)) {
current.push(warn);
}

schedule_to_update_warning(100);

} else {
const log = converter.toHtml(escape_html(chunk)).replace(/\n/g, '<br>');
logs.update(($logs) => [...$logs, log]);
state.logs = [...state.logs, log];
}
}
});

progress.set({ value: 3 / 5, text: 'unzipping files' });
state.progress = { value: 3 / 5, text: 'unzipping files' };
const unzip = await vm.spawn('node', ['unzip.cjs']);
unzip.output.pipeTo(log_stream());
const code = await unzip.exit;
Expand All @@ -101,11 +80,11 @@ export async function create(base, error, progress, logs, warnings) {
await vm.spawn('chmod', ['a+x', 'node_modules/vite/bin/vite.js']);

vm.on('server-ready', (_port, url) => {
base.set(url);
state.base = url;
});

vm.on('error', ({ message }) => {
error.set(new Error(message));
state.error = new Error(message);
});

let launched = false;
Expand All @@ -114,7 +93,7 @@ export async function create(base, error, progress, logs, warnings) {
if (launched) return;
launched = true;

progress.set({ value: 4 / 5, text: 'starting dev server' });
state.progress = { value: 4 / 5, text: 'starting dev server' };

await new Promise(async (fulfil, reject) => {
const error_unsub = vm.on('error', (error) => {
Expand All @@ -124,7 +103,7 @@ export async function create(base, error, progress, logs, warnings) {

const ready_unsub = vm.on('server-ready', (_port, base) => {
ready_unsub();
progress.set({ value: 5 / 5, text: 'ready' });
state.progress = { value: 5 / 5, text: 'ready' };
fulfil(base); // this will be the last thing that happens if everything goes well
});

Expand Down Expand Up @@ -179,30 +158,26 @@ export async function create(base, error, progress, logs, warnings) {
// Don't delete the node_modules folder when switching from one exercise to another
// where, as this crashes the dev server.
const to_delete = [
...Array.from(current_stubs.keys()).filter(
(s) => !s.startsWith('/node_modules')
),
...Array.from(current_stubs.keys()).filter((s) => !s.startsWith('/node_modules')),
...force_delete
];

// initialize warnings of written files
to_write
.filter((stub) => stub.type === 'file' && $warnings[stub.name])
.forEach((stub) => $warnings[stub.name] = []);
.filter((stub) => stub.type === 'file' && state.warnings[stub.name])
.forEach((stub) => (state.warnings[stub.name] = []));
// remove warnings of deleted files
to_delete
.filter((stubname) => $warnings[stubname])
.forEach((stubname) => delete $warnings[stubname]);

warnings.set($warnings);
.filter((stubname) => state.warnings[stubname])
.forEach((stubname) => delete state.warnings[stubname]);

current_stubs = stubs_to_map(stubs);

// For some reason, server-ready is fired again when the vite dev server is restarted.
// We need to wait for it to finish before we can continue, else we might
// request files from Vite before it's ready, leading to a timeout.
const will_restart = launched &&
(to_write.some(is_config) || to_delete.some(is_config_path));
const will_restart =
launched && (to_write.some(is_config) || to_delete.some(is_config_path));
const promise = will_restart ? wait_for_restart_vite() : Promise.resolve();

for (const file of to_delete) {
Expand All @@ -223,14 +198,13 @@ export async function create(base, error, progress, logs, warnings) {
});
},
update: (file) => {

let queue = q_per_file.get(file.name);
if (queue) {
queue.push(file);
return Promise.resolve(false);
}

q_per_file.set(file.name, queue = [file]);
q_per_file.set(file.name, (queue = [file]));

return q.add(async () => {
/** @type {import('@webcontainer/api').FileSystemTree} */
Expand All @@ -257,16 +231,14 @@ export async function create(base, error, progress, logs, warnings) {
const will_restart = is_config(file);

while (queue && queue.length > 0) {

// if the file is updated many times rapidly, get the most recently updated one
const file = /** @type {import('$lib/types').FileStub} */ (queue.pop());
queue.length = 0
queue.length = 0;

tree[basename] = to_file(file);

// initialize warnings of this file
$warnings[file.name] = [];
schedule_to_update_warning(100);
state.warnings[file.name] = [];

await vm.mount(root);

Expand All @@ -280,7 +252,7 @@ export async function create(base, error, progress, logs, warnings) {
await new Promise((f) => setTimeout(f, 50));
}

q_per_file.delete(file.name)
q_per_file.delete(file.name);

return will_restart;
});
Expand Down
7 changes: 5 additions & 2 deletions src/lib/components/Modal.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<script>
import { onMount } from 'svelte';

/** @type {{ onclose?: () => void; children: import('svelte').Snippet }}*/
let { onclose, children } = $props();

/** @type {HTMLDialogElement} */
let modal;

Expand Down Expand Up @@ -41,8 +44,8 @@

<div class="modal-background" />

<dialog class="modal" tabindex="-1" bind:this={modal} on:close>
<slot />
<dialog class="modal" tabindex="-1" bind:this={modal} {onclose}>
{@render children()}
</dialog>

<style>
Expand Down
4 changes: 2 additions & 2 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import '@sveltejs/site-kit/styles/index.css';
import '../app.css';

export let data;
let { data, children } = $props();
</script>

<Shell>
Expand Down Expand Up @@ -46,7 +46,7 @@
</svelte:fragment>
</Nav>

<slot />
{@render children()}
</Shell>

{#if browser}
Expand Down
Loading
Loading