Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

💄 style(desktop): polish the dev loading progress overlay (#20101)

Innei7c3cb6d8a097
diff --git a/plugins/vite/devLoadingProgress.test.ts b/plugins/vite/devLoadingProgress.test.ts
index 373e8cec083..bffe6c670b2 100644
--- a/plugins/vite/devLoadingProgress.test.ts
+++ b/plugins/vite/devLoadingProgress.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import { devLoadingProgress } from './devLoadingProgress';
@@ -12,7 +12,7 @@ const createServer = (server: Record<string, unknown> = {}) => ({
...server,
},
},
- hot: { send: vi.fn() },
+ hot: { on: vi.fn(), send: vi.fn() },
});
const setup = (server = createServer()) => {
@@ -22,14 +22,87 @@ const setup = (server = createServer()) => {
};
describe('devLoadingProgress', () => {
- it('injects a client script pointing at the HMR websocket', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ document.body.innerHTML = '';
+ localStorage.clear();
+ });
+
+ it('injects themed styles and a client script pointing at the HMR websocket', () => {
const { plugin } = setup();
- const [tag] = plugin.transformIndexHtml();
+ const [styleTag, scriptTag] = plugin.transformIndexHtml();
- expect(tag.tag).toBe('script');
- expect(tag.children).toContain('"ws://127.0.0.1:5173"');
- expect(tag.children).toContain('loading-dev-progress');
+ expect(styleTag).toMatchObject({ injectTo: 'head', tag: 'style' });
+ expect(styleTag.children).toContain("html[data-theme='dark'] #loading-dev-progress");
+ expect(scriptTag).toMatchObject({ injectTo: 'body', tag: 'script' });
+ expect(scriptTag.children).toContain('"ws://127.0.0.1:5173"');
+ });
+
+ it('sends the current progress to a client that connects after transforms', () => {
+ const { plugin, server } = setup();
+ const [event, onConnect] = server.hot.on.mock.calls[0];
+ const client = { send: vi.fn() };
+
+ onConnect(undefined, client);
+ expect(client.send).not.toHaveBeenCalled();
+
+ plugin.transform('', '/repo/src/a.tsx');
+ onConnect(undefined, client);
+
+ expect(event).toBe('vite:client:connect');
+ expect(client.send).toHaveBeenCalledWith('lobe:dev-loading-progress', {
+ count: 1,
+ file: 'src/a.tsx',
+ });
+ });
+
+ it('renders estimated progress and remembers the final count once boot finishes', () => {
+ vi.useFakeTimers({
+ toFake: ['setInterval', 'clearInterval', 'setTimeout', 'clearTimeout', 'performance'],
+ });
+ const sockets: any[] = [];
+ vi.stubGlobal(
+ 'WebSocket',
+ class {
+ onmessage?: (e: { data: string }) => void;
+ close = vi.fn();
+ constructor() {
+ sockets.push(this);
+ }
+ },
+ );
+ localStorage.setItem('lobe-dev-loading-progress:total', '200');
+ document.body.innerHTML = '<div id="loading-screen"></div>';
+ const { plugin } = setup();
+ const [, scriptTag] = plugin.transformIndexHtml();
+
+ new Function(scriptTag.children)();
+ sockets[0].onmessage({
+ data: JSON.stringify({
+ data: { count: 50, file: 'src/features/Chat/index.tsx' },
+ event: 'lobe:dev-loading-progress',
+ type: 'custom',
+ }),
+ });
+ vi.advanceTimersByTime(400);
+
+ const root = document.getElementById('loading-dev-progress')!;
+ expect(root.classList.contains('ldp-shown')).toBe(true);
+ expect(root.querySelector('.ldp-count')!.textContent).toBe('50 / ~200');
+ expect((root.querySelector('.ldp-bar') as HTMLElement).style.transform).toBe('scaleX(0.25)');
+ expect(root.querySelector('.ldp-detail')!.textContent).toContain('…/Chat/index.tsx');
+
+ vi.advanceTimersByTime(1500);
+ expect(root.querySelector('.ldp-detail')!.textContent).toContain('mounting app');
+
+ document.getElementById('loading-screen')!.remove();
+ vi.advanceTimersByTime(700);
+
+ expect(root.isConnected).toBe(false);
+ expect(sockets[0].close).toHaveBeenCalled();
+ expect(localStorage.getItem('lobe-dev-loading-progress:total')).toBe('50');
+ vi.unstubAllGlobals();
});
it('injects nothing when HMR is disabled', () => {
@@ -54,6 +127,5 @@ describe('devLoadingProgress', () => {
event: 'lobe:dev-loading-progress',
type: 'custom',
});
- vi.useRealTimers();
});
});
diff --git a/plugins/vite/devLoadingProgress.ts b/plugins/vite/devLoadingProgress.ts
index a3c18a59428..27e3670d9a2 100644
--- a/plugins/vite/devLoadingProgress.ts
+++ b/plugins/vite/devLoadingProgress.ts
@@ -2,6 +2,7 @@ import type { Plugin, ViteDevServer } from 'vite';
const EVENT = 'lobe:dev-loading-progress';
const BROADCAST_INTERVAL_MS = 80;
+const ESTIMATE_STORAGE_KEY = 'lobe-dev-loading-progress:total';
const resolveHmrUrl = (server: ViteDevServer) => {
const { hmr, host, port } = server.config.server;
@@ -16,36 +17,124 @@ const resolveHmrUrl = (server: ViteDevServer) => {
// then the React boot shell / route fallback skeletons that follow it in dev.
const PLACEHOLDER_IDS = ['loading-screen', 'boot-shell', 'app-shell-fallback'];
+const style = `
+#loading-dev-progress {
+ --ldp-fg: #1f1f1f;
+ position: fixed;
+ inset-block-end: 16px;
+ inset-inline: 0;
+ z-index: 100000;
+ width: min(320px, calc(100vw - 32px));
+ margin-inline: auto;
+ direction: ltr;
+ color: var(--ldp-fg);
+ font: 11px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-variant-numeric: tabular-nums;
+ pointer-events: none;
+ opacity: 0;
+ transition: opacity 200ms ease;
+}
+html[data-theme='dark'] #loading-dev-progress { --ldp-fg: #f0f0f0; }
+#loading-dev-progress.ldp-shown { opacity: 0.6; }
+#loading-dev-progress .ldp-head { display: flex; align-items: center; gap: 10px; }
+#loading-dev-progress .ldp-track {
+ position: relative;
+ flex: 1;
+ height: 2px;
+ overflow: hidden;
+ border-radius: 1px;
+ background: color-mix(in srgb, currentcolor 15%, transparent);
+}
+#loading-dev-progress .ldp-bar {
+ position: absolute;
+ inset: 0;
+ background: currentcolor;
+ transform: scaleX(0);
+ transform-origin: left;
+ transition: transform 200ms ease-out;
+}
+#loading-dev-progress.ldp-indeterminate .ldp-bar {
+ width: 30%;
+ transform: none;
+ animation: ldp-slide 1.2s ease-in-out infinite;
+}
+#loading-dev-progress .ldp-count { flex: none; min-width: 16ch; text-align: end; }
+#loading-dev-progress .ldp-detail {
+ margin-block-start: 4px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ opacity: 0.75;
+}
+@keyframes ldp-slide { from { translate: -100%; } to { translate: 340%; } }
+@media (prefers-reduced-motion: reduce) {
+ #loading-dev-progress .ldp-bar { transition: none; }
+ #loading-dev-progress.ldp-indeterminate .ldp-bar { width: 100%; opacity: 0.3; animation: none; }
+}
+`;
+
const clientScript = (hmrUrl: string) => `(function () {
var ids = ${JSON.stringify(PLACEHOLDER_IDS)};
- var el = document.createElement('div');
- el.id = 'loading-dev-progress';
- el.style.cssText = 'position: fixed; inset-block-end: 12px; inset-inline: 0; z-index: 100000; pointer-events: none; text-align: center; font: 12px ui-monospace, monospace; opacity: 0.55; white-space: nowrap;';
- var count = 0, file = '', start = performance.now();
+ var storageKey = ${JSON.stringify(ESTIMATE_STORAGE_KEY)};
+ var root = document.createElement('div');
+ root.id = 'loading-dev-progress';
+ root.innerHTML = '<div class="ldp-head"><div class="ldp-track"><div class="ldp-bar"></div></div><span class="ldp-count"></span></div><div class="ldp-detail"></div>';
+ var bar = root.querySelector('.ldp-bar');
+ var countEl = root.querySelector('.ldp-count');
+ var detailEl = root.querySelector('.ldp-detail');
+ var count = 0, file = '', start = performance.now(), lastChange = start, goneSince = 0, estimate = 0, ws;
+ try { estimate = Number(localStorage.getItem(storageKey)) || 0; } catch (_) {}
function placeholderVisible() {
for (var i = 0; i < ids.length; i++) if (document.getElementById(ids[i])) return true;
return false;
}
+ function fmt(n) { return n.toLocaleString('en-US'); }
+ function shorten(path) {
+ var parts = path.split('/');
+ return parts.length > 2 ? '…/' + parts.slice(-2).join('/') : path;
+ }
+ function finish() {
+ clearInterval(timer);
+ root.remove();
+ if (ws) ws.close();
+ if (count > 0) try { localStorage.setItem(storageKey, String(count)); } catch (_) {}
+ }
function render() {
- var visible = placeholderVisible();
- if (visible && !el.isConnected) document.body.appendChild(el);
- if (!visible && el.isConnected) el.remove();
- if (visible) el.textContent = 'vite dev · ' + count + ' modules · ' + ((performance.now() - start) / 1000).toFixed(1) + 's · ' + file;
- requestAnimationFrame(render);
+ var now = performance.now();
+ if (!placeholderVisible()) {
+ root.classList.remove('ldp-shown');
+ goneSince = goneSince || now;
+ if (now - goneSince >= 500) finish();
+ return;
+ }
+ goneSince = 0;
+ if (!root.isConnected) document.body.appendChild(root);
+ if (now - start >= 300) root.classList.add('ldp-shown');
+ var total = estimate && Math.max(estimate, count);
+ root.classList.toggle('ldp-indeterminate', !total);
+ if (total) bar.style.transform = 'scaleX(' + Math.min(count / total, 0.95) + ')';
+ countEl.textContent = total ? fmt(count) + ' / ~' + fmt(total) : fmt(count) + ' modules';
+ var status = count === 0 ? 'waiting for vite…' : now - lastChange >= 1500 ? 'compiled · mounting app…' : shorten(file);
+ detailEl.textContent = ((now - start) / 1000).toFixed(1) + 's · ' + status;
}
+ var timer = setInterval(render, 100);
render();
try {
- var ws = new WebSocket(${JSON.stringify(hmrUrl)}, 'vite-hmr');
+ ws = new WebSocket(${JSON.stringify(hmrUrl)}, 'vite-hmr');
ws.onmessage = function (e) {
var m = JSON.parse(e.data);
- if (m.type === 'custom' && m.event === ${JSON.stringify(EVENT)}) { count = m.data.count; file = m.data.file; }
+ if (m.type !== 'custom' || m.event !== ${JSON.stringify(EVENT)}) return;
+ if (m.data.count !== count) lastChange = performance.now();
+ count = m.data.count;
+ file = m.data.file;
};
} catch (_) {}
})();`;
/**
* Dev-only: streams Vite's transform progress onto the static loading screen so a
- * cold `dev` start shows "N modules · Xs · current file" instead of a frozen logo.
+ * cold `dev` start shows a progress bar estimated from the previous boot's module
+ * count instead of a frozen logo.
*/
export const devLoadingProgress = (): Plugin => {
let server: ViteDevServer | undefined;
@@ -65,6 +154,10 @@ export const devLoadingProgress = (): Plugin => {
apply: 'serve',
configureServer(devServer) {
server = devServer;
+ // A reload reuses already-transformed modules, so no broadcast would ever reach it.
+ devServer.hot.on('vite:client:connect', (_data, client) => {
+ if (count > 0) client.send(EVENT, { count, file: latest });
+ });
},
name: 'dev-loading-progress',
transform(_code, id) {
@@ -76,7 +169,10 @@ export const devLoadingProgress = (): Plugin => {
transformIndexHtml() {
const hmrUrl = server && resolveHmrUrl(server);
if (!hmrUrl) return [];
- return [{ children: clientScript(hmrUrl), injectTo: 'body', tag: 'script' }];
+ return [
+ { children: style, injectTo: 'head', tag: 'style' },
+ { children: clientScript(hmrUrl), injectTo: 'body', tag: 'script' },
+ ];
},
};
};