@innovatorved/code-lab 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/workbench.ts CHANGED
@@ -57,7 +57,7 @@
57
57
 
58
58
  // The bundler rewrites this literal from package.json at build time. Keeping
59
59
  // the fallback in sync lets tests require src/workbench.js directly.
60
- const CODELAB_VERSION = '0.1.8';
60
+ const CODELAB_VERSION = '0.1.10';
61
61
 
62
62
  // Ambient TypeScript declarations for Node.js built-ins inside Monaco
63
63
  const NODE_AMBIENT_DTS = `
@@ -1364,6 +1364,11 @@ declare module 'bun:sqlite' {
1364
1364
  this.explorerWidth = (typeof this.savedState?.explorerWidth === 'number' && this.savedState.explorerWidth >= 120)
1365
1365
  ? this.savedState.explorerWidth
1366
1366
  : 196;
1367
+ // 0 = use the default 44% track; otherwise a pixel width chosen by dragging
1368
+ // the preview splitter.
1369
+ this.previewSplitWidth = (typeof this.savedState?.previewSplitWidth === 'number' && this.savedState.previewSplitWidth >= 200)
1370
+ ? this.savedState.previewSplitWidth
1371
+ : 0;
1367
1372
  this.folderSwitcherOpen = false;
1368
1373
  this.creatingItem = null; // { type: 'file' | 'folder', parentFolder: string } | null
1369
1374
  this.renamingItem = null;
@@ -1376,6 +1381,10 @@ declare module 'bun:sqlite' {
1376
1381
  path: '/',
1377
1382
  url: '',
1378
1383
  frameMode: 'desktop', // 'desktop' | 'tablet' | 'mobile'
1384
+ dockMode: (options && options.previewDock === 'split') ? 'split' : 'bottom', // 'bottom' | 'split'
1385
+ maximized: false,
1386
+ consoleOpen: false,
1387
+ consoleLogs: [],
1379
1388
  loading: false,
1380
1389
  error: null,
1381
1390
  srcdoc: '',
@@ -1387,6 +1396,7 @@ declare module 'bun:sqlite' {
1387
1396
  this._previewSwRegistration = null;
1388
1397
  this._previewViolationHandler = null;
1389
1398
  this._swMessageHandler = null;
1399
+ this._beforeUnloadHandler = null;
1390
1400
  this._portToasts = new Map();
1391
1401
  this.isFullscreen = false;
1392
1402
  this.isRunning = false;
@@ -1733,6 +1743,11 @@ declare module 'bun:sqlite' {
1733
1743
  const key = `${this.mode}:${this.lang}`;
1734
1744
  const customFiles = (this.savedState && this.savedState.customFiles) || {};
1735
1745
  customFiles[key] = { ...this.files };
1746
+ const hasSnapshot = Object.assign(
1747
+ {},
1748
+ (this.savedState && this.savedState.hasSnapshot) || {},
1749
+ { [key]: true }
1750
+ );
1736
1751
  const completedArr = Array.from(this.completedSteps);
1737
1752
  const state = {
1738
1753
  mode: this.mode,
@@ -1740,12 +1755,14 @@ declare module 'bun:sqlite' {
1740
1755
  activeStepIndex: this.activeStepIndex,
1741
1756
  completedSteps: completedArr,
1742
1757
  customFiles,
1758
+ hasSnapshot,
1743
1759
  openTabs: Array.isArray(this.openTabs) ? [...this.openTabs] : undefined,
1744
1760
  activeFile: this.activeFile,
1745
1761
  folders: Array.from(this.folders || []),
1746
1762
  collapsedFolders: Array.from(this.collapsedFolders || []),
1747
1763
  explorerFolder: this.explorerFolder || '',
1748
- explorerWidth: typeof this.explorerWidth === 'number' ? this.explorerWidth : undefined
1764
+ explorerWidth: typeof this.explorerWidth === 'number' ? this.explorerWidth : undefined,
1765
+ previewSplitWidth: this.previewSplitWidth || undefined
1749
1766
  };
1750
1767
  this.savedState = state;
1751
1768
  if (this.options && this.options.persistState === false) {
@@ -1764,6 +1781,20 @@ declare module 'bun:sqlite' {
1764
1781
  safeStorageSet('codelab_progress_' + this.labId, JSON.stringify(completedArr), this.logger, recordErr),
1765
1782
  safeStorageSet('sd_codelab_' + this.labId, serialized, this.logger, recordErr)
1766
1783
  ];
1784
+ if (root.CodeLabStorage && typeof root.CodeLabStorage.createWorkspaceStorage === 'function') {
1785
+ try {
1786
+ if (!this._idbStorage) {
1787
+ this._idbStorage = root.CodeLabStorage.createWorkspaceStorage({ keyPrefix: STORAGE_PREFIX });
1788
+ }
1789
+ if (this._idbStorage && typeof this._idbStorage.save === 'function') {
1790
+ Promise.resolve(this._idbStorage.save(this.labId, state)).catch((err) => {
1791
+ this.logger.debug('Async WorkspaceStorage save skipped.', err);
1792
+ });
1793
+ }
1794
+ } catch (err) {
1795
+ this.logger.debug('WorkspaceStorage initialization skipped.', err);
1796
+ }
1797
+ }
1767
1798
  if (persisted.includes(false)) {
1768
1799
  this._reportPersistenceFailure(safeStorageSet._lastError);
1769
1800
  } else {
@@ -1916,6 +1947,9 @@ declare module 'bun:sqlite' {
1916
1947
  const key = `${this.mode}:${this.lang}`;
1917
1948
  const saved = this.savedState.customFiles?.[key];
1918
1949
  const base = this._getBaseFilesForModeAndLang(this.mode, this.lang);
1950
+ if (this.savedState && this.savedState.hasSnapshot && this.savedState.hasSnapshot[key] && saved && typeof saved === 'object') {
1951
+ return { ...saved };
1952
+ }
1919
1953
  if (saved && Object.keys(saved).length > 0) {
1920
1954
  return { ...base, ...saved };
1921
1955
  }
@@ -1990,7 +2024,9 @@ declare module 'bun:sqlite' {
1990
2024
  const themeAttr = this.themeOption !== 'auto' ? `data-theme="${escapeHtml(this.themeOption)}"` : '';
1991
2025
  const brandLabel = (this.title && this.title !== 'custom-lab' && this.title !== this.labId) ? this.title : 'code-lab';
1992
2026
  const isGuideCollapsed = !this.hasGuidedLab || this.mode === 'sandbox' || !this.steps.length;
1993
- const explorerStyle = `style="--cl-explorer-width:${Math.round(this.explorerWidth || 196)}px"`;
2027
+ const shellVars = [`--cl-explorer-width:${Math.round(this.explorerWidth || 196)}px`];
2028
+ if (this.previewSplitWidth) shellVars.push(`--cl-preview-split-width:${Math.round(this.previewSplitWidth)}px`);
2029
+ const explorerStyle = `style="${shellVars.join(';')}"`;
1994
2030
  this.container.innerHTML = `
1995
2031
  <div class="codelab codelab-workbench ${isGuideCollapsed ? 'guide-collapsed' : ''}" id="codelab-${escapeHtml(this.labId)}" ${themeAttr} ${explorerStyle}>
1996
2032
  <!-- Top Bar -->
@@ -2128,6 +2164,10 @@ declare module 'bun:sqlite' {
2128
2164
  <div class="codelab-empty-editor" id="cl-empty-editor" style="display:none"></div>
2129
2165
  </div>
2130
2166
  </div>
2167
+
2168
+ <!-- Right-Hand Split Web Preview Pane -->
2169
+ <div class="codelab-splitter-preview" id="cl-splitter-preview" role="separator" aria-orientation="vertical" title="Drag to resize web preview (double-click to reset)" style="display:none"></div>
2170
+ <div class="codelab-preview-split" id="cl-preview-split" aria-label="In-Browser Web Preview" style="display:none"></div>
2131
2171
  </div>
2132
2172
 
2133
2173
  <!-- Interactive Horizontal Splitter -->
@@ -3381,6 +3421,7 @@ declare module 'bun:sqlite' {
3381
3421
  }
3382
3422
 
3383
3423
  if (this.drawerTab === 'preview') {
3424
+ bodyEl.scrollTop = 0;
3384
3425
  this._renderWebPreview(bodyEl);
3385
3426
  return;
3386
3427
  }
@@ -4509,6 +4550,10 @@ declare module 'bun:sqlite' {
4509
4550
  type: level === 'error' ? 'stderr' : 'stdout',
4510
4551
  text: `[Preview ${level.toUpperCase()}] ${text}`
4511
4552
  });
4553
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
4554
+ this.previewState.consoleLogs.push({ level, text, timestamp: new Date().toLocaleTimeString() });
4555
+ if (this.previewState.consoleLogs.length > 200) this.previewState.consoleLogs.shift();
4556
+ this._updatePreviewConsoleUI();
4512
4557
  this._emitEvent('preview-console', { level, text, args });
4513
4558
  } else if (data.type === 'codelab:preview-error') {
4514
4559
  const msg = String(data.message || 'Uncaught runtime error');
@@ -4523,9 +4568,66 @@ declare module 'bun:sqlite' {
4523
4568
  type: 'stderr',
4524
4569
  text: `[Preview ERROR] ${msg}${data.stack ? '\n' + String(data.stack) : ''}`
4525
4570
  });
4571
+ if (!Array.isArray(this.previewState.consoleLogs)) this.previewState.consoleLogs = [];
4572
+ this.previewState.consoleLogs.push({
4573
+ level: 'error',
4574
+ text: `${msg}${data.stack ? '\n' + String(data.stack) : ''}`,
4575
+ timestamp: new Date().toLocaleTimeString()
4576
+ });
4577
+ this._updatePreviewConsoleUI();
4526
4578
  this._emitEvent('preview-error', this.previewState.runtimeError);
4527
4579
  } else if (data.type === 'codelab:preview-error-clear') {
4528
4580
  this.previewState.runtimeError = null;
4581
+ } else if (data.type === 'codelab:preview-fetch') {
4582
+ const reqId = data.reqId || data.id;
4583
+ const targetPort = Number(data.port) || this.previewState.port || this._firstListeningPort() || 3000;
4584
+ const reqPath = data.path ? (String(data.path).startsWith('/') ? String(data.path) : '/' + String(data.path)) : '/';
4585
+ const targetUrl = String(data.url || `http://127.0.0.1:${targetPort}${reqPath}`);
4586
+ this._dispatchPreviewRequest({
4587
+ port: targetPort,
4588
+ url: targetUrl,
4589
+ method: data.method || 'GET',
4590
+ headers: data.headers || {},
4591
+ body: data.body !== undefined ? data.body : null
4592
+ })
4593
+ .then((res) => {
4594
+ const netPill = this.container ? this.container.querySelector('#cl-network-pill') : null;
4595
+ if (netPill) netPill.textContent = `${(this.lastHttpTrace || []).length} reqs`;
4596
+ if (this.drawerTab === 'network') this._renderDrawerBody();
4597
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
4598
+ iframe.contentWindow.postMessage({
4599
+ type: 'codelab:preview-fetch-res',
4600
+ reqId,
4601
+ id: reqId,
4602
+ status: res.status || 200,
4603
+ statusText: res.statusText || 'OK',
4604
+ headers: res.headers || {},
4605
+ body: res.body || ''
4606
+ }, '*');
4607
+ }
4608
+ })
4609
+ .catch((err) => {
4610
+ if (iframe && iframe.contentWindow && typeof iframe.contentWindow.postMessage === 'function') {
4611
+ iframe.contentWindow.postMessage({
4612
+ type: 'codelab:preview-fetch-res',
4613
+ reqId,
4614
+ id: reqId,
4615
+ error: String((err && err.message) || err)
4616
+ }, '*');
4617
+ }
4618
+ });
4619
+ } else if (data.type === 'codelab:preview-navigate') {
4620
+ const navHref = data.href || (data.path ? (data.port ? `http://127.0.0.1:${data.port}${data.path}` : String(data.path)) : '');
4621
+ if (navHref) {
4622
+ this._previewGo(String(navHref));
4623
+ }
4624
+ } else if (data.type === 'codelab:preview-url-change') {
4625
+ if (data.path && typeof data.path === 'string') {
4626
+ this.previewState.path = data.path.startsWith('/') ? data.path : '/' + data.path;
4627
+ this.previewState.url = this._previewUrl();
4628
+ const input = this.container ? this.container.querySelector('#cl-preview-url-input') : null;
4629
+ if (input) input.value = this.previewState.url;
4630
+ }
4529
4631
  }
4530
4632
  };
4531
4633
  window.addEventListener('message', this._previewViolationHandler);
@@ -4589,7 +4691,12 @@ declare module 'bun:sqlite' {
4589
4691
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
4590
4692
  this.previewHistory.push(this.previewState.url);
4591
4693
  this.previewHistoryIdx = this.previewHistory.length - 1;
4592
- this.switchDrawerTab('preview');
4694
+ if (this.previewState.dockMode === 'split') {
4695
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4696
+ if (splitHost) this._renderWebPreview(splitHost);
4697
+ } else {
4698
+ this.switchDrawerTab('preview');
4699
+ }
4593
4700
  return this._previewLoadPromise || Promise.resolve();
4594
4701
  }
4595
4702
 
@@ -4708,7 +4815,12 @@ declare module 'bun:sqlite' {
4708
4815
  this.previewHistory = this.previewHistory.slice(0, this.previewHistoryIdx + 1);
4709
4816
  this.previewHistory.push(url);
4710
4817
  this.previewHistoryIdx = this.previewHistory.length - 1;
4711
- this.switchDrawerTab('preview');
4818
+ if (this.previewState.dockMode === 'split') {
4819
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4820
+ if (splitHost) this._renderWebPreview(splitHost);
4821
+ } else {
4822
+ this.switchDrawerTab('preview');
4823
+ }
4712
4824
  return this._previewLoadPromise || Promise.resolve();
4713
4825
  }
4714
4826
 
@@ -4749,6 +4861,97 @@ declare module 'bun:sqlite' {
4749
4861
  if (!['desktop', 'tablet', 'mobile'].includes(mode)) return;
4750
4862
  this.previewState.frameMode = mode;
4751
4863
  this._renderDrawerBody();
4864
+ if (this.previewState.dockMode === 'split') {
4865
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4866
+ if (splitHost) this._renderWebPreview(splitHost);
4867
+ }
4868
+ }
4869
+
4870
+ _togglePreviewDock() {
4871
+ this.previewState.dockMode = this.previewState.dockMode === 'split' ? 'bottom' : 'split';
4872
+ this._previewRenderKey = null;
4873
+ const ws = this.container ? this.container.querySelector('.codelab-workspace') : null;
4874
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4875
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
4876
+ if (this.previewState.dockMode === 'split') {
4877
+ if (ws) ws.classList.add('has-preview-split');
4878
+ if (splitBar) splitBar.style.display = 'block';
4879
+ if (splitHost) {
4880
+ splitHost.style.display = 'flex';
4881
+ this._renderWebPreview(splitHost);
4882
+ }
4883
+ if (this.drawerTab === 'preview') {
4884
+ this.switchDrawerTab('terminal');
4885
+ } else {
4886
+ this._renderDrawerBody();
4887
+ }
4888
+ } else {
4889
+ if (ws) ws.classList.remove('has-preview-split');
4890
+ if (splitBar) splitBar.style.display = 'none';
4891
+ if (splitHost) {
4892
+ splitHost.style.display = 'none';
4893
+ splitHost.innerHTML = '';
4894
+ }
4895
+ this.switchDrawerTab('preview');
4896
+ }
4897
+ if (this.editor && typeof this.editor.layout === 'function') {
4898
+ setTimeout(() => {
4899
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
4900
+ }, 30);
4901
+ }
4902
+ }
4903
+
4904
+ _togglePreviewMaximize() {
4905
+ this.previewState.maximized = !this.previewState.maximized;
4906
+ const previewEl = this.container ? this.container.querySelector('.codelab-preview') : null;
4907
+ if (previewEl) {
4908
+ previewEl.classList.toggle('is-maximized', Boolean(this.previewState.maximized));
4909
+ }
4910
+ const maxBtn = this.container ? this.container.querySelector('[data-cl-action="preview-maximize"]') : null;
4911
+ if (maxBtn) {
4912
+ maxBtn.classList.toggle('active', Boolean(this.previewState.maximized));
4913
+ }
4914
+ }
4915
+
4916
+ _togglePreviewConsole() {
4917
+ this.previewState.consoleOpen = !this.previewState.consoleOpen;
4918
+ this._updatePreviewConsoleUI();
4919
+ }
4920
+
4921
+ _clearPreviewConsole() {
4922
+ this.previewState.consoleLogs = [];
4923
+ this._updatePreviewConsoleUI();
4924
+ }
4925
+
4926
+ _updatePreviewConsoleUI() {
4927
+ if (!this.container) return;
4928
+ const consoleDrawer = this.container.querySelector('#cl-preview-console');
4929
+ const consoleBody = this.container.querySelector('#cl-preview-console-body');
4930
+ const consolePill = this.container.querySelector('#cl-preview-console-pill');
4931
+ const consoleBtn = this.container.querySelector('[data-cl-action="preview-console-toggle"]');
4932
+ const logs = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs : [];
4933
+ if (consolePill) {
4934
+ consolePill.textContent = String(logs.length);
4935
+ }
4936
+ if (consoleBtn) {
4937
+ consoleBtn.classList.toggle('active', Boolean(this.previewState.consoleOpen));
4938
+ }
4939
+ if (consoleDrawer) {
4940
+ consoleDrawer.style.display = this.previewState.consoleOpen ? 'flex' : 'none';
4941
+ }
4942
+ if (consoleBody) {
4943
+ if (logs.length === 0) {
4944
+ consoleBody.innerHTML = `<div class="codelab-preview-console__empty">No console output from preview frame yet.</div>`;
4945
+ } else {
4946
+ consoleBody.innerHTML = logs.map((entry) => `
4947
+ <div class="codelab-preview-console__row codelab-preview-console__row--${escapeHtml(entry.level || 'log')}">
4948
+ <span class="codelab-preview-console__time">${escapeHtml(entry.timestamp || '')}</span>
4949
+ <span class="codelab-preview-console__text">${escapeHtml(entry.text || '')}</span>
4950
+ </div>
4951
+ `).join('');
4952
+ consoleBody.scrollTop = consoleBody.scrollHeight;
4953
+ }
4954
+ }
4752
4955
  }
4753
4956
 
4754
4957
  _renderWebPreviewControls() {
@@ -4760,6 +4963,7 @@ declare module 'bun:sqlite' {
4760
4963
  if (backBtn) backBtn.disabled = this.previewHistoryIdx <= 0;
4761
4964
  const fwdBtn = this.container.querySelector('[data-cl-action="preview-forward"]');
4762
4965
  if (fwdBtn) fwdBtn.disabled = this.previewHistoryIdx >= this.previewHistory.length - 1;
4966
+ this._updatePreviewConsoleUI();
4763
4967
  }
4764
4968
 
4765
4969
  _popoutPreview() {
@@ -4780,8 +4984,35 @@ declare module 'bun:sqlite' {
4780
4984
  _renderWebPreview(bodyEl) {
4781
4985
  if (!bodyEl) return;
4782
4986
  this._warnPreviewIsolation();
4783
- const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this._previewSwReady}`;
4784
- if (bodyEl.querySelector && bodyEl.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
4987
+ const splitHost = this.container ? this.container.querySelector('#cl-preview-split') : null;
4988
+ const splitBar = this.container ? this.container.querySelector('#cl-splitter-preview') : null;
4989
+ const ws = this.container ? this.container.querySelector('.codelab-workspace') : null;
4990
+
4991
+ let targetHost = bodyEl;
4992
+ if (this.previewState.dockMode === 'split' && splitHost) {
4993
+ if (ws) ws.classList.add('has-preview-split');
4994
+ if (splitBar) splitBar.style.display = 'block';
4995
+ splitHost.style.display = 'flex';
4996
+ if (bodyEl !== splitHost) {
4997
+ bodyEl.innerHTML = `
4998
+ <div class="codelab-preview-split-notice">
4999
+ <span>Web Preview is docked to the right split pane.</span>
5000
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-dock-toggle">Dock to Bottom Drawer</button>
5001
+ </div>
5002
+ `;
5003
+ }
5004
+ targetHost = splitHost;
5005
+ } else {
5006
+ if (ws) ws.classList.remove('has-preview-split');
5007
+ if (splitBar) splitBar.style.display = 'none';
5008
+ if (splitHost && bodyEl !== splitHost) {
5009
+ splitHost.style.display = 'none';
5010
+ splitHost.innerHTML = '';
5011
+ }
5012
+ }
5013
+
5014
+ const renderKey = `${this.previewState.port}|${this.previewState.path}|${this.previewState.frameMode}|${this.previewState.dockMode}|${this._previewSwReady}`;
5015
+ if (targetHost.querySelector && targetHost.querySelector('.codelab-preview') && this._previewRenderKey === renderKey) {
4785
5016
  this._renderWebPreviewControls();
4786
5017
  return;
4787
5018
  }
@@ -4812,8 +5043,11 @@ declare module 'bun:sqlite' {
4812
5043
  ? 'Strict Content-Security-Policy: previews cannot reach any remote host.'
4813
5044
  : `Previews may load scripts, fonts and data from: ${cspHosts.join(', ') || 'no remote hosts'}. Use previewCsp: 'strict' to block remote hosts.`;
4814
5045
 
4815
- bodyEl.innerHTML = `
4816
- <div class="codelab-preview">
5046
+ const logsCount = Array.isArray(this.previewState.consoleLogs) ? this.previewState.consoleLogs.length : 0;
5047
+ const isSplit = this.previewState.dockMode === 'split';
5048
+
5049
+ targetHost.innerHTML = `
5050
+ <div class="codelab-preview ${this.previewState.maximized ? 'is-maximized' : ''}">
4817
5051
  <div class="codelab-preview-chrome">
4818
5052
  <div class="codelab-preview-nav">
4819
5053
  <button type="button" class="codelab-preview-btn" data-cl-action="preview-back" title="Back" ${this.previewHistoryIdx <= 0 ? 'disabled' : ''}>${CL_ICONS.arrowLeft || '←'}</button>
@@ -4829,11 +5063,30 @@ declare module 'bun:sqlite' {
4829
5063
  </div>
4830
5064
  <span class="codelab-preview-csp" id="cl-preview-csp-badge" title="${escapeHtml(cspBadgeTitle)}">${escapeHtml(cspBadge)}</span>
4831
5065
  <span class="codelab-preview-csp codelab-preview-csp--blocked" id="cl-preview-csp-status" role="status" hidden></span>
5066
+ <button type="button" class="codelab-preview-btn ${this.previewState.consoleOpen ? 'active' : ''}" data-cl-action="preview-console-toggle" title="Toggle Preview Console">
5067
+ ${CL_ICONS.terminal || '>_'} <span class="codelab-preview-console-pill" id="cl-preview-console-pill">${logsCount}</span>
5068
+ </button>
5069
+ <button type="button" class="codelab-preview-btn ${isSplit ? 'active' : ''}" data-cl-action="preview-dock-toggle" title="${isSplit ? 'Dock Preview to Bottom Drawer' : 'Dock Preview to Right Split Pane'}">
5070
+ ${CL_ICONS.layout || '◫'}
5071
+ </button>
5072
+ <button type="button" class="codelab-preview-btn ${this.previewState.maximized ? 'active' : ''}" data-cl-action="preview-maximize" title="Maximize / Restore Preview">
5073
+ ${CL_ICONS.maximize || '⛶'}
5074
+ </button>
4832
5075
  <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-popout" title="Open in a new browser tab">${CL_ICONS.externalLink || '↗'} <span>Pop Out</span></button>
4833
5076
  </div>
4834
5077
  <div class="codelab-preview-viewport codelab-preview-viewport--${this.previewState.frameMode}" id="cl-preview-viewport">
4835
5078
  <iframe class="codelab-preview-iframe" id="cl-preview-iframe" sandbox="allow-scripts allow-forms allow-modals" allow="camera 'none'; microphone 'none'; geolocation 'none'; payment 'none'; usb 'none'" referrerpolicy="no-referrer-when-downgrade" title="Web Preview"></iframe>
4836
5079
  </div>
5080
+ <div class="codelab-preview-console" id="cl-preview-console" style="display:${this.previewState.consoleOpen ? 'flex' : 'none'}">
5081
+ <div class="codelab-preview-console__bar">
5082
+ <span>Preview Console</span>
5083
+ <div style="display:flex;align-items:center;gap:6px;">
5084
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-clear">Clear</button>
5085
+ <button type="button" class="codelab-btn codelab-btn--sm" data-cl-action="preview-console-toggle">Close</button>
5086
+ </div>
5087
+ </div>
5088
+ <div class="codelab-preview-console__body" id="cl-preview-console-body"></div>
5089
+ </div>
4837
5090
  ${servers.length
4838
5091
  ? `<div class="codelab-preview-hint">Serving from the in-browser virtual runtime. Use Pop Out for a standalone tab.</div>`
4839
5092
  : `<div class="codelab-preview-empty">
@@ -4846,6 +5099,7 @@ declare module 'bun:sqlite' {
4846
5099
  </div>
4847
5100
  `;
4848
5101
  this._updatePreviewCspStatus();
5102
+ this._updatePreviewConsoleUI();
4849
5103
  this._loadPreviewFrame();
4850
5104
  }
4851
5105
 
@@ -4862,11 +5116,12 @@ declare module 'bun:sqlite' {
4862
5116
  this.previewState.error = 'No port selected';
4863
5117
  return Promise.resolve();
4864
5118
  }
5119
+ this._syncFilesToShellVfs();
4865
5120
  const fullUrl = this._previewUrl();
4866
5121
  this.previewState.loading = true;
4867
5122
  this.previewState.error = null;
4868
5123
 
4869
- if (this._previewSwReady) {
5124
+ if (this.options && this.options.useServiceWorkerForIframe === true && this._previewSwReady) {
4870
5125
  try {
4871
5126
  const u = new URL(fullUrl);
4872
5127
  if (typeof iframe.removeAttribute === 'function') iframe.removeAttribute('srcdoc');
@@ -4878,8 +5133,8 @@ declare module 'bun:sqlite' {
4878
5133
  }
4879
5134
  }
4880
5135
 
4881
- // Fallback (no Service Worker): dispatch via the virtual port table and
4882
- // inline the response with an injected <base> for relative asset URLs.
5136
+ // Direct virtual dispatch + srcdoc injection guarantees zero Service Worker
5137
+ // race conditions and 100% deterministic loading inside sandboxed iframes.
4883
5138
  return this._dispatchPreviewRequest({ port, url: fullUrl, method: 'GET' })
4884
5139
  .then((res) => {
4885
5140
  let body = res.body || '';
@@ -5265,7 +5520,7 @@ declare module 'bun:sqlite' {
5265
5520
  this.logger.debug(`Could not sync "${filename}" to shell VFS on edit.`, err);
5266
5521
  }
5267
5522
  }
5268
- if (this.drawerTab === 'preview' && this.previewState && this.previewState.port) {
5523
+ if ((this.drawerTab === 'preview' || (this.previewState && this.previewState.dockMode === 'split')) && this.previewState && this.previewState.port) {
5269
5524
  if (this._previewReloadTimer) {
5270
5525
  clearTimeout(this._previewReloadTimer);
5271
5526
  }
@@ -5441,6 +5696,16 @@ declare module 'bun:sqlite' {
5441
5696
  };
5442
5697
  if (typeof document !== 'undefined') {
5443
5698
  document.addEventListener('keydown', this._escHandler);
5699
+ this._beforeUnloadHandler = () => {
5700
+ if (document.visibilityState === 'hidden') {
5701
+ try {
5702
+ this._saveState();
5703
+ } catch (err) {
5704
+ void err;
5705
+ }
5706
+ }
5707
+ };
5708
+ document.addEventListener('visibilitychange', this._beforeUnloadHandler);
5444
5709
  }
5445
5710
 
5446
5711
  this.container.addEventListener('keydown', e => {
@@ -5887,15 +6152,29 @@ declare module 'bun:sqlite' {
5887
6152
  this._previewSetFrameMode(actionBtn.dataset.mode);
5888
6153
  } else if (action === 'preview-popout') {
5889
6154
  this._popoutPreview();
6155
+ } else if (action === 'preview-dock-toggle') {
6156
+ this._togglePreviewDock();
6157
+ } else if (action === 'preview-maximize') {
6158
+ this._togglePreviewMaximize();
6159
+ } else if (action === 'preview-console-toggle') {
6160
+ this._togglePreviewConsole();
6161
+ } else if (action === 'preview-console-clear') {
6162
+ this._clearPreviewConsole();
5890
6163
  } else if (action === 'open-port-client') {
5891
- const port = actionBtn.dataset.port;
6164
+ const port = actionBtn.dataset.port || actionBtn.dataset.clPort;
5892
6165
  if (port) {
5893
6166
  this.httpClientUrl = `http://localhost:${port}/`;
6167
+ if (this.httpClientState) {
6168
+ this.httpClientState.url = `http://localhost:${port}/`;
6169
+ }
5894
6170
  this._renderDrawerBody();
5895
6171
  }
5896
6172
  } else if (action === 'stop-port') {
5897
- const port = Number(actionBtn.dataset.port);
6173
+ const port = Number(actionBtn.dataset.port || actionBtn.dataset.clPort);
5898
6174
  if (port) {
6175
+ if (this.portTable && typeof this.portTable.closeServer === 'function') {
6176
+ this.portTable.closeServer(port);
6177
+ }
5899
6178
  if (this.shell && this.shell.portTable && typeof this.shell.portTable.unregister === 'function') {
5900
6179
  this.shell.portTable.unregister(port);
5901
6180
  }
@@ -5905,18 +6184,32 @@ declare module 'bun:sqlite' {
5905
6184
  } else if (action === 'http-send') {
5906
6185
  this._sendHttpClientRequest();
5907
6186
  } else if (action === 'http-tab') {
5908
- this.httpActiveTab = actionBtn.dataset.httpTab || 'headers';
6187
+ const nextTab = actionBtn.dataset.tab || actionBtn.dataset.clHttpTab || actionBtn.dataset.httpTab || 'preview';
6188
+ this.httpActiveTab = nextTab;
6189
+ if (this.httpClientState) {
6190
+ this.httpClientState.activeResponseTab = nextTab;
6191
+ }
5909
6192
  this._renderDrawerBody();
5910
6193
  } else if (action === 'clear-net-traces') {
5911
6194
  this.lastHttpTrace = [];
5912
6195
  this.selectedNetTraceIdx = null;
6196
+ if (this.networkFilter) {
6197
+ this.networkFilter.selectedTraceId = null;
6198
+ }
5913
6199
  this._renderDrawerBody();
5914
6200
  } else if (action === 'select-net-trace') {
6201
+ const traceId = actionBtn.dataset.traceId || actionBtn.dataset.clTraceId || null;
5915
6202
  const idx = Number(actionBtn.dataset.traceIdx);
5916
6203
  this.selectedNetTraceIdx = Number.isNaN(idx) ? null : idx;
6204
+ if (this.networkFilter) {
6205
+ this.networkFilter.selectedTraceId = traceId;
6206
+ }
5917
6207
  this._renderDrawerBody();
5918
6208
  } else if (action === 'close-net-detail') {
5919
6209
  this.selectedNetTraceIdx = null;
6210
+ if (this.networkFilter) {
6211
+ this.networkFilter.selectedTraceId = null;
6212
+ }
5920
6213
  this._renderDrawerBody();
5921
6214
  }
5922
6215
  return;
@@ -6416,6 +6709,46 @@ declare module 'bun:sqlite' {
6416
6709
  fSplitter.addEventListener('pointerup', onUp);
6417
6710
  });
6418
6711
  }
6712
+
6713
+ const pSplitter = this.container.querySelector('#cl-splitter-preview');
6714
+ if (pSplitter) {
6715
+ pSplitter.addEventListener('dblclick', () => {
6716
+ this.previewSplitWidth = 0;
6717
+ shell.style.removeProperty('--cl-preview-split-width');
6718
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
6719
+ this._saveState();
6720
+ });
6721
+
6722
+ pSplitter.addEventListener('pointerdown', e => {
6723
+ e.preventDefault();
6724
+ pSplitter.classList.add('is-dragging');
6725
+ shell.classList.add('is-resizing');
6726
+ try { pSplitter.setPointerCapture(e.pointerId); } catch (err) { this.logger.debug('setPointerCapture failed.', err); }
6727
+
6728
+ const onMove = ev => {
6729
+ const ws = this.container.querySelector('.codelab-workspace');
6730
+ const rect = (ws || shell).getBoundingClientRect();
6731
+ const minW = 240;
6732
+ const maxW = Math.max(minW, Math.floor(rect.width * 0.65));
6733
+ const nextW = Math.min(maxW, Math.max(minW, Math.round(rect.right - ev.clientX)));
6734
+ this.previewSplitWidth = nextW;
6735
+ shell.style.setProperty('--cl-preview-split-width', `${nextW}px`);
6736
+ if (this.editor && typeof this.editor.layout === 'function') this.editor.layout();
6737
+ };
6738
+
6739
+ const onUp = ev => {
6740
+ pSplitter.classList.remove('is-dragging');
6741
+ shell.classList.remove('is-resizing');
6742
+ try { pSplitter.releasePointerCapture(ev.pointerId); } catch (err) { this.logger.debug('releasePointerCapture failed.', err); }
6743
+ pSplitter.removeEventListener('pointermove', onMove);
6744
+ pSplitter.removeEventListener('pointerup', onUp);
6745
+ this._saveState();
6746
+ };
6747
+
6748
+ pSplitter.addEventListener('pointermove', onMove);
6749
+ pSplitter.addEventListener('pointerup', onUp);
6750
+ });
6751
+ }
6419
6752
  }
6420
6753
 
6421
6754
  selectStep(idx, shouldJump = true) {
@@ -6644,6 +6977,9 @@ declare module 'bun:sqlite' {
6644
6977
  if (this.savedState.customFiles) {
6645
6978
  delete this.savedState.customFiles[key];
6646
6979
  }
6980
+ if (this.savedState.hasSnapshot) {
6981
+ delete this.savedState.hasSnapshot[key];
6982
+ }
6647
6983
  this._saveState();
6648
6984
  this._syncAllModels();
6649
6985
  this._syncActiveFileToView();
@@ -7951,6 +8287,10 @@ declare module 'bun:sqlite' {
7951
8287
  if (this._escHandler && typeof document !== 'undefined') {
7952
8288
  document.removeEventListener('keydown', this._escHandler);
7953
8289
  }
8290
+ if (this._beforeUnloadHandler && typeof document !== 'undefined') {
8291
+ document.removeEventListener('visibilitychange', this._beforeUnloadHandler);
8292
+ }
8293
+ this._beforeUnloadHandler = null;
7954
8294
  if (this._previewViolationHandler && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
7955
8295
  window.removeEventListener('message', this._previewViolationHandler);
7956
8296
  }