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

feat(training): loading progress indicator #2499

Merged
merged 1 commit into from
Nov 25, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@
<li ngbNavItem class="nav-item" role="presentation" [destroyOnHide]="false">
<a ngbNavLink class="nav-link" [class.active]="activeTab === 'preview'" (click)="activeTab = 'preview'">Preview</a>
<ng-template ngbNavContent>
<iframe class="w-100 h-100" #iframe allow="cross-origin-isolated" [srcdoc]="'Loading...'"></iframe>
@let isLoading = percentProgress() < 100;
@if (isLoading) {
<div class="w-100 h-100 d-flex align-items-center justify-content-center p-2">
<df-progressbar [value]="percentProgress()" [text]="progressLabel()"></df-progressbar>
</div>
}
<iframe class="w-100 h-100" #iframe allow="cross-origin-isolated" [srcdoc]="'Loading...'" [class.invisible]="isLoading"></iframe>
</ng-template>
</li>
<li ngbNavItem class="nav-item" role="presentation" [destroyOnHide]="false">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ code-editor-control {
height: 100%;
}

df-progressbar {
min-width: 15em;
}

.terminal-active-indicator {
display: inline-block;
font-weight: bold;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
computed,
ElementRef,
inject,
Input,
Expand All @@ -10,6 +11,7 @@ import {
ViewEncapsulation
} from '@angular/core';
import {toSignal} from '@angular/core/rxjs-interop';
import {DfProgressbarModule} from '@design-factory/design-factory';
import {NgbNavModule} from '@ng-bootstrap/ng-bootstrap';
import {distinctUntilChanged, map, of, repeat, Subject, throttleTime, timeout} from 'rxjs';
import {WebContainerService} from '../../../services';
Expand All @@ -20,7 +22,8 @@ import {CodeEditorTerminalComponent} from '../code-editor-terminal';
standalone: true,
imports: [
CodeEditorTerminalComponent,
NgbNavModule
NgbNavModule,
DfProgressbarModule
],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
Expand Down Expand Up @@ -54,6 +57,19 @@ export class CodeEditorControlComponent implements OnDestroy, AfterViewInit {
*/
public readonly terminalActivity = new Subject<void>();

/**
* Loading progression (between 0 and 100)
*/
public readonly percentProgress = computed(() => {
const { currentStep, totalSteps } = this.webContainerService.runner.progress();
return Math.round(100 * currentStep / totalSteps);
});

/**
* Label to use on the load indicator
*/
public readonly progressLabel = computed(() => this.webContainerService.runner.progress().label);

/**
* Signal with value `true` if the terminal is active, `false` if idle
* The terminal is considered idle if no activity is received for 2 seconds.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,30 @@
@if (cwdTree$ | async; as tree) {
<as-split direction="vertical">
<as-split-area [size]="50">
<form [formGroup]="form" class="editor overflow-hidden h-100">
<as-split direction="horizontal">
<as-split-area [size]="25">
<monaco-tree (clickFile)="onClickFile($event)"
[tree]="tree"
[currentFile]="project?.startingFile"
[width]="'auto'"
[height]="'auto'"
class="w-100"></monaco-tree>
</as-split-area>
<as-split-area [size]="75">
<ngx-monaco-editor class="h-100 position-relative"
[options]="editorOptions$ | async"
formControlName="code">
</ngx-monaco-editor>
</as-split-area>
</as-split>
</form>
</as-split-area>
@if (editorMode === 'interactive') {
<as-split-area [size]="50">
<code-editor-control class="d-flex flex-column h-100" [showOutput]="project?.commands.length > 0 && tree.length > 0"></code-editor-control>
<as-split direction="vertical">
<as-split-area [size]="50">
<form [formGroup]="form" class="editor overflow-hidden h-100">
<as-split direction="horizontal">
<as-split-area [size]="25">
<monaco-tree (clickFile)="onClickFile($event)"
[tree]="(cwdTree$ | async) || []"
[currentFile]="project?.startingFile"
[width]="'auto'"
[height]="'auto'"
class="w-100 editor-view"></monaco-tree>
</as-split-area>
}
</as-split>
}
@else {
<div class="spinner-border" role="status"></div>
}
<as-split-area [size]="75" class="editor-view">
@let editorOptions = editorOptions$ | async;
@if (editorOptions) {
<ngx-monaco-editor class="h-100 position-relative"
[options]="editorOptions"
formControlName="code">
</ngx-monaco-editor>
}
</as-split-area>
</as-split>
</form>
</as-split-area>
@if (editorMode === 'interactive') {
<as-split-area [size]="50">
<code-editor-control class="d-flex flex-column h-100"></code-editor-control>
</as-split-area>
}
</as-split>
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
monaco-tree {
background: #1d1d1d;

.monaco-tree {
display: flex;
flex-direction: column;
Expand All @@ -24,3 +22,7 @@ ngx-monaco-editor {
max-height: 100% !important;
}
}

.editor-view {
background: #1d1d1d;
}
75 changes: 64 additions & 11 deletions apps/showcase/src/services/webcontainer/webcontainer-runner.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,22 @@
import { DestroyRef, inject, Injectable } from '@angular/core';
import { DestroyRef, inject, Injectable, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { type FileSystemTree, type IFSWatcher, WebContainer, type WebContainerProcess } from '@webcontainer/api';
import { Terminal } from '@xterm/xterm';
import {
BehaviorSubject,
combineLatest,
combineLatestWith,
distinctUntilChanged,
filter,
from,
fromEvent,
map,
Observable,
switchMap
of,
skip,
switchMap,
take,
timeout
} from 'rxjs';
import { withLatestFrom } from 'rxjs/operators';
import { createTerminalStream, killTerminal, makeProcessWritable } from './webcontainer.helpers';
Expand Down Expand Up @@ -43,9 +49,17 @@ export class WebContainerRunner {
};
private watcher: IFSWatcher | null = null;

private readonly progressWritable = signal({currentStep: 0, totalSteps: 3, label: 'Initializing web-container'});

/**
* Progress indicator of the loading of a project.
*/
public readonly progress = this.progressWritable.asReadonly();

constructor() {
const destroyRef = inject(DestroyRef);
this.instancePromise = WebContainer.boot().then((instance) => {
this.progressWritable.update(({totalSteps}) => ({currentStep: 1, totalSteps, label: 'Loading project'}));
// eslint-disable-next-line no-console
const unsubscribe = instance.on('error', console.error);
destroyRef.onDestroy(() => unsubscribe());
Expand All @@ -60,20 +74,33 @@ export class WebContainerRunner {
void this.runCommand(commandElements[0], commandElements.slice(1), cwd);
});

this.iframe.pipe(
filter((iframe): iframe is HTMLIFrameElement => !!iframe),
distinctUntilChanged(),
withLatestFrom(this.instancePromise),
switchMap(([iframe, instance]) => new Observable((subscriber) => {
combineLatest([
this.iframe.pipe(
filter((iframe): iframe is HTMLIFrameElement => !!iframe),
distinctUntilChanged()
),
this.instancePromise
]).pipe(
switchMap(([iframe, instance]) => new Observable<[typeof iframe, typeof instance, boolean]>((subscriber) => {
let shouldSkipFirstLoadEvent = true;
const serverReadyUnsubscribe = instance.on('server-ready', (_port: number, url: string) => {
this.progressWritable.update(({totalSteps}) => ({currentStep: totalSteps - 1, totalSteps, label: 'Bootstrapping application...'}));
iframe.removeAttribute('srcdoc');
iframe.src = url;
subscriber.next(url);
subscriber.next([iframe, instance, shouldSkipFirstLoadEvent]);
shouldSkipFirstLoadEvent = false;
});
return () => serverReadyUnsubscribe();
})),
switchMap(([iframe, _instance, shouldSkipFirstLoadEvent]) => fromEvent(iframe, 'load').pipe(
skip(shouldSkipFirstLoadEvent ? 1 : 0),
timeout({each: 20000, with: () => of([])}),
take(1)
)),
takeUntilDestroyed()
).subscribe();
).subscribe(() => {
this.progressWritable.update(({totalSteps}) => ({currentStep: totalSteps, totalSteps, label: 'Ready!'}));
});

this.commandOutput.process.pipe(
filter((process): process is WebContainerProcess => !!process && !process.output.locked),
Expand Down Expand Up @@ -147,10 +174,35 @@ export class WebContainerRunner {
const process = await instance.spawn(command, args, {cwd: cwd});
this.commandOutput.process.next(process);
const exitCode = await process.exit;
if (exitCode !== 0) {
if (exitCode === 0) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we prefer a switch case, in case we have to handle others exitCode or it should never happen ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's a matter of preference, I don't see any good reason to choose one or the other.
I could argue that with if we can more easily include ranges if (existCode >= 100 && exitCode < 200)
you can also do it with switch(true) { case (existCode >= 100 && exitCode < 200): ... } but at the end it looks more like an if than a switch/case

// The process has ended successfully
this.progressWritable.update(({currentStep, totalSteps}) => ({
currentStep: currentStep + 1,
totalSteps,
label: this.getCommandLabel(this.commands.value.queue[1])
}));
this.commands.next({queue: this.commands.value.queue.slice(1), cwd});
} else if (exitCode === 143) {
// The process was killed by switching to a new project
return;
} else {
// The process has ended with an error
throw new Error(`Command ${[command, ...args].join(' ')} failed with ${exitCode}!`);
}
this.commands.next({queue: this.commands.value.queue.slice(1), cwd});
}

private getCommandLabel(command: string) {
if (!command) {
return 'Waiting for server to start...';
} else {
if (/(npm|yarn) install/.test(command)) {
return 'Installing dependencies...';
} else if (/^(npm|yarn) (run .*:(build|serve)|(run )?build)/.test(command)) {
return 'Building application...';
} else {
return `Executing \`${command}\``;
}
}
}

/**
Expand All @@ -177,6 +229,7 @@ export class WebContainerRunner {
await instance.mount({[projectFolder]: {directory: files}});
}
this.treeUpdateCallback();
this.progressWritable.set({currentStep: 2, totalSteps: 3 + commands.length, label: this.getCommandLabel(commands[0])});
this.commands.next({queue: commands, cwd: projectFolder});
this.watcher = instance.fs.watch(`/${projectFolder}`, {encoding: 'utf8'}, this.treeUpdateCallback);
}
Expand Down