Implement dev mode nice UI (#17471)
Implement a nice terminal UI for dev mode using INK <img width="1512" height="721" alt="image" src="https://github.com/user-attachments/assets/79a71f37-1b31-4761-9e8d-718ef029ceb8" />
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
import { createLogger } from '@/cli/utilities/build/common/logger';
|
||||
import {
|
||||
type ManifestBuildResult,
|
||||
runManifestBuild,
|
||||
@@ -9,13 +8,16 @@ import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { FileUploader } from '@/cli/utilities/file/file-uploader';
|
||||
import { type FileFolder } from 'twenty-shared/types';
|
||||
import { validateManifest } from '@/cli/utilities/build/manifest/manifest-validate';
|
||||
|
||||
const logger = createLogger('dev-mode');
|
||||
import type { Location } from 'esbuild';
|
||||
import { type DevUiStateManager } from '@/cli/utilities/dev/dev-ui-state-manager';
|
||||
import { relative } from 'path';
|
||||
import { type EventName } from 'chokidar/handler.js';
|
||||
|
||||
export type DevModeOrchestratorOptions = {
|
||||
appPath: string;
|
||||
debounceMs?: number;
|
||||
handleManifestBuilt: (result: ManifestBuildResult) => void | Promise<void>;
|
||||
uiStateManager: DevUiStateManager;
|
||||
};
|
||||
|
||||
export class DevModeOrchestrator {
|
||||
@@ -24,16 +26,24 @@ export class DevModeOrchestrator {
|
||||
|
||||
private builtFileInfos = new Map<
|
||||
string,
|
||||
{ checksum: string; builtPath: string; fileFolder: FileFolder }
|
||||
{
|
||||
checksum: string;
|
||||
builtPath: string;
|
||||
sourcePath: string;
|
||||
fileFolder: FileFolder;
|
||||
}
|
||||
>();
|
||||
|
||||
private fileUploader: FileUploader | null = null;
|
||||
private apiService = new ApiService();
|
||||
private apiService = new ApiService({ disableInterceptors: true });
|
||||
|
||||
private activeUploads = new Set<Promise<void>>();
|
||||
|
||||
private syncTimer: NodeJS.Timeout | null = null;
|
||||
private isSyncing = false;
|
||||
private uiStateManager: DevUiStateManager;
|
||||
private serverChecked = false;
|
||||
private serverCheckedLogged = false;
|
||||
|
||||
private handleManifestBuilt: (
|
||||
result: ManifestBuildResult,
|
||||
@@ -43,57 +53,132 @@ export class DevModeOrchestrator {
|
||||
this.appPath = options.appPath;
|
||||
this.debounceMs = options.debounceMs ?? 200;
|
||||
this.handleManifestBuilt = options.handleManifestBuilt;
|
||||
this.uiStateManager = options.uiStateManager;
|
||||
}
|
||||
|
||||
async handleChangeDetected(filePath: string) {
|
||||
logger.log(`File changed: ${filePath}`);
|
||||
private async checkServer(): Promise<void> {
|
||||
this.serverChecked = await this.apiService.validateAuth();
|
||||
|
||||
if (!this.serverChecked && !this.serverCheckedLogged) {
|
||||
this.uiStateManager.addEvent({
|
||||
message:
|
||||
'Please check your server is up and your credentials are correct: "yarn auth:login"',
|
||||
status: 'error',
|
||||
});
|
||||
this.uiStateManager.updateManifestState({
|
||||
manifestStatus: 'error',
|
||||
});
|
||||
this.serverCheckedLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
async handleChangeDetected(sourcePath: string, event: EventName) {
|
||||
if (!this.serverChecked) {
|
||||
await this.checkServer();
|
||||
}
|
||||
|
||||
if (!this.serverChecked) {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedSourcePath = this.normalizeFilePath(sourcePath);
|
||||
|
||||
this.uiStateManager.addEvent({
|
||||
message: `Change detected: ${normalizedSourcePath}`,
|
||||
status: 'info',
|
||||
});
|
||||
|
||||
if (event === 'unlink') {
|
||||
this.uiStateManager.removeEntity(normalizedSourcePath);
|
||||
} else {
|
||||
this.uiStateManager.updateFileStatus(normalizedSourcePath, 'building');
|
||||
}
|
||||
|
||||
this.scheduleSync();
|
||||
}
|
||||
|
||||
handleFileBuildError(errors: string[]): void {
|
||||
logger.error(`Build failed:`);
|
||||
handleFileBuildError(
|
||||
errors: { error: string; location: Location | null }[],
|
||||
): void {
|
||||
this.uiStateManager.addEvent({
|
||||
message: 'Build failed:',
|
||||
status: 'error',
|
||||
});
|
||||
for (const error of errors) {
|
||||
logger.error(` ${error}`);
|
||||
this.uiStateManager.addEvent({
|
||||
message: error.error,
|
||||
status: 'error',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
handleFileBuilt({
|
||||
fileFolder,
|
||||
builtPath,
|
||||
filePath,
|
||||
sourcePath,
|
||||
checksum,
|
||||
}: {
|
||||
fileFolder: FileFolder;
|
||||
builtPath: string;
|
||||
filePath: string;
|
||||
sourcePath: string;
|
||||
checksum: string;
|
||||
}): void {
|
||||
logger.success(`✓ Successfully built ${filePath}`);
|
||||
this.uiStateManager.addEvent({
|
||||
message: `Successfully built ${builtPath}`,
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
this.builtFileInfos.set(builtPath, { checksum, builtPath, fileFolder });
|
||||
this.builtFileInfos.set(builtPath, {
|
||||
checksum,
|
||||
builtPath,
|
||||
sourcePath,
|
||||
fileFolder,
|
||||
});
|
||||
|
||||
if (this.fileUploader) {
|
||||
this.uploadFile(builtPath, fileFolder);
|
||||
this.uploadFile(builtPath, sourcePath, fileFolder);
|
||||
}
|
||||
|
||||
this.scheduleSync();
|
||||
}
|
||||
|
||||
private uploadFile(builtPath: string, fileFolder: FileFolder): void {
|
||||
logger.log(`Uploading ${builtPath}...`);
|
||||
private normalizeFilePath(filePath: string): string {
|
||||
return relative(this.appPath, filePath);
|
||||
}
|
||||
|
||||
private uploadFile(
|
||||
builtPath: string,
|
||||
sourcePath: string,
|
||||
fileFolder: FileFolder,
|
||||
): void {
|
||||
this.uiStateManager.addEvent({
|
||||
message: `Uploading ${builtPath}`,
|
||||
status: 'info',
|
||||
});
|
||||
this.uiStateManager.updateFileStatus(sourcePath, 'uploading');
|
||||
const uploadPromise = this.fileUploader!.uploadFile({
|
||||
builtPath,
|
||||
fileFolder,
|
||||
})
|
||||
.then((result) => {
|
||||
if (result.success) {
|
||||
logger.success(`Successfully uploaded ${builtPath}`);
|
||||
this.uiStateManager.addEvent({
|
||||
message: `Successfully uploaded ${builtPath}`,
|
||||
status: 'success',
|
||||
});
|
||||
this.uiStateManager.updateFileStatus(sourcePath, 'success');
|
||||
} else {
|
||||
logger.error(`Failed to upload ${builtPath}: ${result.error}`);
|
||||
this.uiStateManager.addEvent({
|
||||
message: `Failed to upload ${builtPath}: ${result.error}`,
|
||||
status: 'error',
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
logger.error(`Upload failed for ${builtPath}: ${error}`);
|
||||
this.uiStateManager.addEvent({
|
||||
message: `Upload failed for ${builtPath}: ${error}`,
|
||||
status: 'error',
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
this.activeUploads.delete(uploadPromise);
|
||||
@@ -126,24 +211,47 @@ export class DevModeOrchestrator {
|
||||
this.isSyncing = true;
|
||||
|
||||
try {
|
||||
logger.log(`Building manifest...`);
|
||||
this.uiStateManager.addEvent({
|
||||
message: 'Building manifest',
|
||||
status: 'info',
|
||||
});
|
||||
this.uiStateManager.updateManifestState({
|
||||
manifestStatus: 'building',
|
||||
});
|
||||
|
||||
const result = await runManifestBuild(this.appPath);
|
||||
|
||||
if (result.error || !result.manifest) {
|
||||
logger.error(
|
||||
`Failed to build manifest: ${result.error ?? 'Unknown error'}`,
|
||||
);
|
||||
this.uiStateManager.updateManifestState({
|
||||
manifestStatus: 'error',
|
||||
});
|
||||
this.uiStateManager.addEvent({
|
||||
message: result.error ?? 'Unknown error',
|
||||
status: 'error',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const validation = validateManifest(result.manifest);
|
||||
|
||||
this.uiStateManager.updateManifestState({
|
||||
appName: result.manifest.application.displayName,
|
||||
});
|
||||
|
||||
this.uiStateManager.updateAllFilesTypes({
|
||||
manifestFilePaths: result.filePaths,
|
||||
});
|
||||
|
||||
if (!validation.isValid) {
|
||||
const messages = validation.errors
|
||||
.map((e) => ` • ${e.path}: ${e.message}`)
|
||||
.join('\n');
|
||||
logger.error(`Invalid manifest:\n${messages}`);
|
||||
for (const e of validation.errors) {
|
||||
this.uiStateManager.addEvent({
|
||||
message: `${e.path}: ${e.message}`,
|
||||
status: 'error',
|
||||
});
|
||||
this.uiStateManager.updateManifestState({
|
||||
manifestStatus: 'error',
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -151,11 +259,17 @@ export class DevModeOrchestrator {
|
||||
if (validation.warnings.length > 0) {
|
||||
for (const warning of validation.warnings) {
|
||||
const path = warning.path ? `${warning.path}: ` : '';
|
||||
logger.warn(`⚠ ${path}${warning.message}`);
|
||||
this.uiStateManager.addEvent({
|
||||
message: `⚠ ${path}${warning.message}`,
|
||||
status: 'warning',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
logger.success(`Successfully built manifest`);
|
||||
this.uiStateManager.addEvent({
|
||||
message: 'Successfully built manifest',
|
||||
status: 'success',
|
||||
});
|
||||
|
||||
await this.handleManifestBuilt(result);
|
||||
|
||||
@@ -167,9 +281,9 @@ export class DevModeOrchestrator {
|
||||
});
|
||||
for (const [
|
||||
builtPath,
|
||||
{ fileFolder },
|
||||
{ fileFolder, sourcePath },
|
||||
] of this.builtFileInfos.entries()) {
|
||||
this.uploadFile(builtPath, fileFolder);
|
||||
this.uploadFile(builtPath, sourcePath, fileFolder);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,21 +295,54 @@ export class DevModeOrchestrator {
|
||||
manifest: result.manifest,
|
||||
builtFileInfos: this.builtFileInfos,
|
||||
});
|
||||
this.uiStateManager.addEvent({
|
||||
message: 'Manifest checksums set',
|
||||
status: 'info',
|
||||
});
|
||||
|
||||
await writeManifestToOutput(this.appPath, manifest);
|
||||
|
||||
logger.log('Syncing...');
|
||||
this.uiStateManager.addEvent({
|
||||
message: 'Manifest saved to output directory',
|
||||
status: 'info',
|
||||
});
|
||||
|
||||
this.uiStateManager.addEvent({
|
||||
message: 'Syncing manifest',
|
||||
status: 'info',
|
||||
});
|
||||
this.uiStateManager.updateManifestState({
|
||||
manifestStatus: 'syncing',
|
||||
});
|
||||
const syncResult = await this.apiService.syncApplication(manifest);
|
||||
|
||||
this.uiStateManager.updateAllFilesStatus('success');
|
||||
|
||||
if (syncResult.success) {
|
||||
logger.success('✓ Synced');
|
||||
this.uiStateManager.addEvent({
|
||||
message: '✓ Synced',
|
||||
status: 'success',
|
||||
});
|
||||
this.uiStateManager.updateManifestState({
|
||||
manifestStatus: 'synced',
|
||||
});
|
||||
} else {
|
||||
logger.error(
|
||||
`✗ Sync failed: ${JSON.stringify(syncResult.error, null, 2)}`,
|
||||
);
|
||||
this.uiStateManager.addEvent({
|
||||
message: `Sync failed: ${JSON.stringify(syncResult.error, null, 2)}`,
|
||||
status: 'error',
|
||||
});
|
||||
this.uiStateManager.updateManifestState({
|
||||
manifestStatus: 'error',
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`✗ Sync failed: ${JSON.stringify(error)}`);
|
||||
this.uiStateManager.addEvent({
|
||||
message: `Sync failed: ${JSON.stringify(error, null, 2)}`,
|
||||
status: 'error',
|
||||
});
|
||||
this.uiStateManager.updateManifestState({
|
||||
manifestStatus: 'error',
|
||||
});
|
||||
} finally {
|
||||
this.isSyncing = false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
import { SyncableEntity } from 'twenty-shared/application';
|
||||
import {
|
||||
type FileStatus,
|
||||
type Listener,
|
||||
type ManifestStatus,
|
||||
type UiEvent,
|
||||
type DevUiState,
|
||||
} from '@/cli/utilities/dev/dev-ui-state';
|
||||
import { type EntityFilePaths } from '@/cli/utilities/build/manifest/manifest-build';
|
||||
|
||||
const MAX_EVENT_NUMBER = 200;
|
||||
|
||||
export class DevUiStateManager {
|
||||
private state: DevUiState;
|
||||
private eventIdCounter = 0;
|
||||
private listeners = new Set<Listener>();
|
||||
|
||||
constructor({
|
||||
appPath,
|
||||
frontendUrl,
|
||||
}: {
|
||||
appPath: string;
|
||||
frontendUrl?: string;
|
||||
}) {
|
||||
this.state = {
|
||||
appPath,
|
||||
frontendUrl,
|
||||
appName: null,
|
||||
appDescription: null,
|
||||
appUniversalIdentifier: null,
|
||||
manifestStatus: 'idle',
|
||||
entities: new Map(),
|
||||
events: [],
|
||||
};
|
||||
}
|
||||
|
||||
getSnapshot(): DevUiState {
|
||||
return this.state;
|
||||
}
|
||||
|
||||
subscribe(listener: Listener): () => void {
|
||||
this.listeners.add(listener);
|
||||
listener(this.getSnapshot());
|
||||
return () => this.listeners.delete(listener);
|
||||
}
|
||||
|
||||
private notify(): void {
|
||||
for (const listener of this.listeners) {
|
||||
listener(this.state);
|
||||
}
|
||||
}
|
||||
|
||||
addEvent({
|
||||
message,
|
||||
status = 'info',
|
||||
}: {
|
||||
message: string;
|
||||
status: UiEvent['status'];
|
||||
}): void {
|
||||
const event: UiEvent = {
|
||||
id: ++this.eventIdCounter,
|
||||
timestamp: new Date(),
|
||||
message,
|
||||
status,
|
||||
};
|
||||
|
||||
this.state = {
|
||||
...this.state,
|
||||
events: [...this.state.events.slice(-MAX_EVENT_NUMBER - 1), event],
|
||||
};
|
||||
|
||||
this.notify();
|
||||
}
|
||||
|
||||
updateManifestState({
|
||||
manifestStatus,
|
||||
appName,
|
||||
}: {
|
||||
manifestStatus?: ManifestStatus;
|
||||
appName?: string;
|
||||
}): void {
|
||||
this.state = {
|
||||
...this.state,
|
||||
...(manifestStatus ? { manifestStatus } : {}),
|
||||
...(appName ? { appName } : {}),
|
||||
};
|
||||
|
||||
this.notify();
|
||||
}
|
||||
|
||||
convertEntityTypeToSyncableEntity(
|
||||
entityType: string,
|
||||
): SyncableEntity | undefined {
|
||||
switch (entityType) {
|
||||
case 'objects':
|
||||
return SyncableEntity.Object;
|
||||
case 'objectExtensions':
|
||||
return SyncableEntity.ObjectExtension;
|
||||
case 'functions':
|
||||
return SyncableEntity.Function;
|
||||
case 'frontComponents':
|
||||
return SyncableEntity.FrontComponent;
|
||||
case 'roles':
|
||||
return SyncableEntity.Role;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
updateAllFilesTypes({
|
||||
manifestFilePaths,
|
||||
}: {
|
||||
manifestFilePaths: EntityFilePaths;
|
||||
}): void {
|
||||
const entityMaps = new Map<string, SyncableEntity>();
|
||||
|
||||
(Object.entries(manifestFilePaths) as [SyncableEntity, string[]][]).forEach(
|
||||
([entityType, filePaths]) => {
|
||||
filePaths.forEach((filePath) => {
|
||||
const syncableEntity =
|
||||
this.convertEntityTypeToSyncableEntity(entityType);
|
||||
|
||||
if (!syncableEntity) {
|
||||
return;
|
||||
}
|
||||
entityMaps.set(filePath, syncableEntity);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const entities = new Map(this.state.entities);
|
||||
|
||||
for (const [filePath, entity] of entities) {
|
||||
entities.set(filePath, {
|
||||
...entity,
|
||||
type: entityMaps.get(filePath),
|
||||
});
|
||||
}
|
||||
this.state = { ...this.state, entities };
|
||||
|
||||
this.notify();
|
||||
}
|
||||
|
||||
updateAllFilesStatus(status: FileStatus): void {
|
||||
const entities = new Map(this.state.entities);
|
||||
|
||||
for (const [filePath, entity] of entities) {
|
||||
entities.set(filePath, {
|
||||
...entity,
|
||||
status: status,
|
||||
});
|
||||
}
|
||||
this.state = { ...this.state, entities };
|
||||
|
||||
this.notify();
|
||||
}
|
||||
|
||||
removeEntity(filePath: string) {
|
||||
const entities = new Map(this.state.entities);
|
||||
entities.delete(filePath);
|
||||
this.state = { ...this.state, entities };
|
||||
}
|
||||
|
||||
updateFileStatus(filePath: string, status: FileStatus): void {
|
||||
const entities = new Map(this.state.entities);
|
||||
|
||||
entities.set(filePath, {
|
||||
name: filePath,
|
||||
path: filePath,
|
||||
status: status,
|
||||
});
|
||||
|
||||
this.state = { ...this.state, entities };
|
||||
|
||||
this.notify();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { type SyncableEntity } from 'twenty-shared/application';
|
||||
|
||||
export type UiEvent = {
|
||||
id: number;
|
||||
timestamp: Date;
|
||||
message: string;
|
||||
status: 'info' | 'success' | 'error' | 'warning';
|
||||
};
|
||||
|
||||
export type ManifestStatus =
|
||||
| 'idle'
|
||||
| 'building'
|
||||
| 'syncing'
|
||||
| 'synced'
|
||||
| 'error';
|
||||
|
||||
export type FileStatus = 'pending' | 'building' | 'uploading' | 'success';
|
||||
|
||||
export type EntityInfo = {
|
||||
name: string;
|
||||
path: string;
|
||||
type?: SyncableEntity;
|
||||
status: FileStatus;
|
||||
};
|
||||
|
||||
export type DevUiState = {
|
||||
appPath: string;
|
||||
appName: string | null;
|
||||
appDescription: string | null;
|
||||
appUniversalIdentifier: string | null;
|
||||
frontendUrl?: string | null;
|
||||
manifestStatus: ManifestStatus;
|
||||
entities: Map<string, EntityInfo>;
|
||||
events: UiEvent[];
|
||||
};
|
||||
|
||||
export type Listener = (state: DevUiState) => void;
|
||||
@@ -0,0 +1,293 @@
|
||||
import {
|
||||
type UiEvent,
|
||||
type DevUiState,
|
||||
type FileStatus,
|
||||
type EntityInfo,
|
||||
} from '@/cli/utilities/dev/dev-ui-state';
|
||||
import { SyncableEntity } from 'twenty-shared/application';
|
||||
import { type DevUiStateManager } from '@/cli/utilities/dev/dev-ui-state-manager';
|
||||
|
||||
const SPINNER_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
||||
const UPLOAD_FRAMES = ['↑', '⇡', '↟', '⤒'];
|
||||
|
||||
const STATUS_ICONS: Record<FileStatus, string> = {
|
||||
pending: '○',
|
||||
building: '◐',
|
||||
uploading: '↑',
|
||||
success: '✓',
|
||||
};
|
||||
|
||||
const STATUS_COLORS: Record<FileStatus, string> = {
|
||||
pending: 'gray',
|
||||
building: 'yellow',
|
||||
uploading: 'cyan',
|
||||
success: 'green',
|
||||
};
|
||||
|
||||
const ENTITY_LABELS: Record<SyncableEntity, string> = {
|
||||
[SyncableEntity.Object]: 'Objects',
|
||||
[SyncableEntity.ObjectExtension]: 'Object Extensions',
|
||||
[SyncableEntity.Function]: 'Functions',
|
||||
[SyncableEntity.FrontComponent]: 'Front Components',
|
||||
[SyncableEntity.Role]: 'Roles',
|
||||
};
|
||||
|
||||
const ENTITY_ORDER = Object.keys(ENTITY_LABELS) as SyncableEntity[];
|
||||
|
||||
const EVENT_COLORS: Record<UiEvent['status'], string> = {
|
||||
info: 'gray',
|
||||
success: 'green',
|
||||
error: 'red',
|
||||
warning: 'yellow',
|
||||
};
|
||||
|
||||
const groupEntitiesByType = (
|
||||
entities: Map<string, EntityInfo>,
|
||||
): Map<SyncableEntity, EntityInfo[]> => {
|
||||
const grouped = new Map<SyncableEntity, EntityInfo[]>();
|
||||
|
||||
for (const type of ENTITY_ORDER) {
|
||||
grouped.set(type, []);
|
||||
}
|
||||
|
||||
for (const entity of entities.values()) {
|
||||
if (!entity.type) {
|
||||
continue;
|
||||
}
|
||||
const list = grouped.get(entity.type) ?? [];
|
||||
list.push(entity);
|
||||
grouped.set(entity.type, list);
|
||||
}
|
||||
|
||||
return grouped;
|
||||
};
|
||||
|
||||
const formatTime = (date: Date): string => {
|
||||
return date.toLocaleTimeString('en-US', {
|
||||
hour12: false,
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
});
|
||||
};
|
||||
|
||||
const shortenPath = (path: string, maxLength = 40): string => {
|
||||
if (path.length <= maxLength) return path;
|
||||
const parts = path.split('/');
|
||||
if (parts.length <= 2) return path;
|
||||
return `.../${parts.slice(-2).join('/')}`;
|
||||
};
|
||||
|
||||
const getApplicationUrl = (snapshot: DevUiState): string | null => {
|
||||
if (!snapshot.frontendUrl || !snapshot.appUniversalIdentifier) {
|
||||
return null;
|
||||
}
|
||||
return `${snapshot.frontendUrl}/settings/applications`;
|
||||
};
|
||||
|
||||
export const renderDevUI = async (
|
||||
uiStateManager: DevUiStateManager,
|
||||
): Promise<{ unmount: () => void }> => {
|
||||
const [React, ink] = await Promise.all([import('react'), import('ink')]);
|
||||
|
||||
const { useState, useEffect } = React;
|
||||
const { render, Box, Text, Static } = ink;
|
||||
|
||||
const useSpinner = (frames: string[], interval = 80): string => {
|
||||
const [frameIndex, setFrameIndex] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
setFrameIndex((prev) => (prev + 1) % frames.length);
|
||||
}, interval);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [frames.length, interval]);
|
||||
|
||||
return frames[frameIndex];
|
||||
};
|
||||
|
||||
const EventItem = ({ event }: { event: UiEvent }): React.ReactElement => {
|
||||
const color = EVENT_COLORS[event.status];
|
||||
const time = formatTime(event.timestamp);
|
||||
|
||||
return (
|
||||
<Box>
|
||||
<Text dimColor>{time} </Text>
|
||||
<Text color={color}>{event.message}</Text>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const StatusIcon = ({
|
||||
status,
|
||||
}: {
|
||||
status: FileStatus;
|
||||
}): React.ReactElement => {
|
||||
const buildingFrame = useSpinner(SPINNER_FRAMES, 200);
|
||||
const uploadingFrame = useSpinner(UPLOAD_FRAMES, 200);
|
||||
|
||||
const iconByStatus: Record<FileStatus, string> = {
|
||||
building: buildingFrame,
|
||||
uploading: uploadingFrame,
|
||||
pending: STATUS_ICONS.pending,
|
||||
success: STATUS_ICONS.success,
|
||||
};
|
||||
|
||||
return <Text color={STATUS_COLORS[status]}>{iconByStatus[status]} </Text>;
|
||||
};
|
||||
|
||||
const EntityRow = ({
|
||||
entity,
|
||||
}: {
|
||||
entity: EntityInfo;
|
||||
}): React.ReactElement => {
|
||||
return (
|
||||
<Box>
|
||||
<StatusIcon status={entity.status} />
|
||||
<Text>{entity.name}</Text>
|
||||
{entity.path !== entity.name && (
|
||||
<Text dimColor> ({shortenPath(entity.path)})</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const EntitySection = ({
|
||||
type,
|
||||
entities,
|
||||
}: {
|
||||
type: SyncableEntity;
|
||||
entities: EntityInfo[];
|
||||
}): React.ReactElement | null => {
|
||||
if (entities.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
<Text bold dimColor>
|
||||
{ENTITY_LABELS[type]}
|
||||
</Text>
|
||||
{entities.map((entity) => (
|
||||
<EntityRow key={entity.path} entity={entity} />
|
||||
))}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const MANIFEST_STATUS_CONFIG = {
|
||||
synced: { color: 'green', icon: '✓', text: 'Synced' },
|
||||
building: { color: 'yellow', icon: null, text: 'Building...' },
|
||||
syncing: { color: 'yellow', icon: null, text: 'Syncing...' },
|
||||
error: { color: 'red', icon: 'x', text: 'Error' },
|
||||
idle: { color: 'gray', icon: 'o', text: 'Idle' },
|
||||
} as const;
|
||||
|
||||
const UnifiedStatusIndicator = ({
|
||||
snapshot,
|
||||
}: {
|
||||
snapshot: DevUiState;
|
||||
}): React.ReactElement => {
|
||||
const spinnerFrame = useSpinner(SPINNER_FRAMES, 80);
|
||||
const config = MANIFEST_STATUS_CONFIG[snapshot.manifestStatus];
|
||||
const icon = config.icon ?? spinnerFrame;
|
||||
|
||||
return (
|
||||
<Text color={config.color}>
|
||||
{icon} {config.text}
|
||||
</Text>
|
||||
);
|
||||
};
|
||||
|
||||
const ApplicationPanel = ({
|
||||
snapshot,
|
||||
}: {
|
||||
snapshot: DevUiState;
|
||||
}): React.ReactElement => {
|
||||
const groupedEntities = groupEntitiesByType(snapshot.entities);
|
||||
const appUrl = getApplicationUrl(snapshot);
|
||||
|
||||
return (
|
||||
<Box
|
||||
flexDirection="column"
|
||||
borderStyle="classic"
|
||||
borderColor="gray"
|
||||
paddingX={1}
|
||||
>
|
||||
<Text bold color="cyan">
|
||||
Application
|
||||
</Text>
|
||||
<Box marginLeft={2} flexDirection="column">
|
||||
<Box>
|
||||
<Text dimColor>Name: </Text>
|
||||
<Text bold>{snapshot.appName ?? 'Loading...'}</Text>
|
||||
</Box>
|
||||
{snapshot.appDescription && (
|
||||
<Box>
|
||||
<Text dimColor>Description: </Text>
|
||||
<Text>{snapshot.appDescription}</Text>
|
||||
</Box>
|
||||
)}
|
||||
<Box>
|
||||
<Text dimColor>Status: </Text>
|
||||
<UnifiedStatusIndicator snapshot={snapshot} />
|
||||
</Box>
|
||||
{appUrl && (
|
||||
<Box>
|
||||
<Text dimColor>Open:</Text>
|
||||
<Text bold color="cyan">
|
||||
{' '}
|
||||
{appUrl}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box marginLeft={2} flexDirection="column">
|
||||
{ENTITY_ORDER.map((type) => {
|
||||
const entities = groupedEntities.get(type) ?? [];
|
||||
return <EntitySection key={type} type={type} entities={entities} />;
|
||||
})}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const Legend = (): React.ReactElement => (
|
||||
<Box marginTop={1}>
|
||||
<Text dimColor>
|
||||
<Text color={STATUS_COLORS.pending}>{STATUS_ICONS.pending}</Text>{' '}
|
||||
pending <Text color={STATUS_COLORS.building}>{SPINNER_FRAMES[0]}</Text>{' '}
|
||||
building <Text color={STATUS_COLORS.uploading}>{UPLOAD_FRAMES[0]}</Text>{' '}
|
||||
uploading{' '}
|
||||
<Text color={STATUS_COLORS.success}>{STATUS_ICONS.success}</Text>{' '}
|
||||
success
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
|
||||
const DevUI = (): React.ReactElement => {
|
||||
const [snapshot, setSnapshot] = useState<DevUiState>(
|
||||
uiStateManager.getSnapshot(),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
return uiStateManager.subscribe(setSnapshot);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Static items={snapshot.events}>
|
||||
{(event: UiEvent) => <EventItem key={event.id} event={event} />}
|
||||
</Static>
|
||||
|
||||
<Box marginTop={1} flexDirection="column">
|
||||
<ApplicationPanel snapshot={snapshot} />
|
||||
<Legend />
|
||||
</Box>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const { unmount } = render(<DevUI />);
|
||||
return { unmount };
|
||||
};
|
||||
Reference in New Issue
Block a user