mirror of
https://github.com/stackblitz/bolt.new
synced 2024-11-28 06:52:47 +00:00
43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
|
import type { WebContainer } from '@webcontainer/api';
|
||
|
import { atom } from 'nanostores';
|
||
|
|
||
|
export interface PreviewInfo {
|
||
|
port: number;
|
||
|
ready: boolean;
|
||
|
baseUrl: string;
|
||
|
}
|
||
|
|
||
|
export class PreviewsStore {
|
||
|
#availablePreviews = new Map<number, PreviewInfo>();
|
||
|
#webcontainer: Promise<WebContainer>;
|
||
|
|
||
|
previews = atom<PreviewInfo[]>([]);
|
||
|
|
||
|
constructor(webcontainerPromise: Promise<WebContainer>) {
|
||
|
this.#webcontainer = webcontainerPromise;
|
||
|
|
||
|
this.#init();
|
||
|
}
|
||
|
|
||
|
async #init() {
|
||
|
const webcontainer = await this.#webcontainer;
|
||
|
|
||
|
webcontainer.on('port', (port, type, url) => {
|
||
|
let previewInfo = this.#availablePreviews.get(port);
|
||
|
|
||
|
const previews = this.previews.get();
|
||
|
|
||
|
if (!previewInfo) {
|
||
|
previewInfo = { port, ready: type === 'open', baseUrl: url };
|
||
|
this.#availablePreviews.set(port, previewInfo);
|
||
|
previews.push(previewInfo);
|
||
|
}
|
||
|
|
||
|
previewInfo.ready = type === 'open';
|
||
|
previewInfo.baseUrl = url;
|
||
|
|
||
|
this.previews.set([...previews]);
|
||
|
});
|
||
|
}
|
||
|
}
|