@khanglvm/relay 0.16.0 → 0.17.0

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/ui/blocks.js CHANGED
@@ -42,8 +42,8 @@
42
42
  // ---------- local file paths → click-to-open links ----------
43
43
  // Agents routinely write a path (~/clip.mp4, ./src/app.js, /abs/file) and the
44
44
  // user expects to click it open, not copy it into a terminal. We turn such
45
- // paths into links that POST to /api/open, where the server opens them in the
46
- // OS default app. FILE_PATH_RE / looksLikeLocalPath MUST match the same logic
45
+ // paths into links that preview files in a dialog, with an explicit app-open
46
+ // fallback. FILE_PATH_RE / looksLikeLocalPath MUST match the same logic
47
47
  // in server.js so the page only links what the server will agree to open.
48
48
  // The body class also excludes \0 (the placeholder delimiter mdInline uses
49
49
  // below) so a path butted against a stashed span can't swallow it; \0 never
@@ -73,7 +73,7 @@
73
73
  const cls = 'rly-filelink' + (codeStyle ? ' rly-filelink-code' : '');
74
74
  return (
75
75
  `<a class="${cls}" role="link" tabindex="0" data-rly-open="${raw}" ` +
76
- `title="Open ${raw} in the default app">` +
76
+ `title="Preview ${raw}" aria-haspopup="dialog">` +
77
77
  `<span class="rly-filelink-ico" aria-hidden="true"></span>` +
78
78
  `<span class="rly-filelink-txt">${label}</span></a>`
79
79
  );
@@ -1888,6 +1888,24 @@
1888
1888
  }
1889
1889
 
1890
1890
  // ---------- image ----------
1891
+ let activeRegionMode = null;
1892
+ let viewerSpacePan = false;
1893
+ const setViewerSpacePan = (enabled) => {
1894
+ viewerSpacePan = Boolean(enabled);
1895
+ document.body.classList.toggle('blk-space-pan', viewerSpacePan);
1896
+ };
1897
+ document.addEventListener('keydown', (e) => {
1898
+ const tag = e.target && e.target.tagName ? e.target.tagName.toLowerCase() : '';
1899
+ if (e.code === 'Space' && !e.repeat && !['input', 'textarea', 'select'].includes(tag)) {
1900
+ setViewerSpacePan(true);
1901
+ e.preventDefault();
1902
+ }
1903
+ });
1904
+ document.addEventListener('keyup', (e) => {
1905
+ if (e.code === 'Space') setViewerSpacePan(false);
1906
+ });
1907
+ window.addEventListener('blur', () => setViewerSpacePan(false));
1908
+
1891
1909
  // src is a remote URL, or absent for embedded local files (served by the
1892
1910
  // board server at /img/b/<id>). Same sizing rule as diagrams: never upscale
1893
1911
  // past natural width; zoom/full-screen viewer attached once loaded.
@@ -1901,8 +1919,10 @@
1901
1919
  src,
1902
1920
  alt: block.alt || 'image',
1903
1921
  loading: 'lazy',
1904
- title: ctx.canComment === false ? '' : 'Hold briefly, then drag to comment on an area',
1922
+ draggable: 'false',
1923
+ title: ctx.canComment === false ? '' : 'Drag to draw a comment area · Space-drag to pan',
1905
1924
  });
1925
+ img.addEventListener('dragstart', (e) => e.preventDefault());
1906
1926
  const stage = el('div', { class: 'blk-imgstage' }, img);
1907
1927
  // Inline default: the image fills its full width (container width, never
1908
1928
  // upscaled past natural) so it's readable without manual zoom; the CONTAINER
@@ -1914,27 +1934,28 @@
1914
1934
  container.replaceChildren(el('div', { class: 'blk-error' }, 'Image failed to load'));
1915
1935
  });
1916
1936
  container.append(stage);
1937
+ const region = ctx.annotate && ctx.canComment !== false
1938
+ ? enableImageRegions({
1939
+ host: stage,
1940
+ surface: img,
1941
+ panHost: container,
1942
+ sourceForSide: () => img,
1943
+ sideAtPoint: () => null,
1944
+ ctx,
1945
+ blockId,
1946
+ label: block.alt || 'Image',
1947
+ })
1948
+ : null;
1917
1949
  const attachImgViewer = () =>
1918
1950
  attachViewer(container, {
1919
1951
  zoomEl: stage,
1920
1952
  natural: () => (img.naturalWidth > 0 ? { w: img.naturalWidth, h: img.naturalHeight } : null),
1921
1953
  label: 'image',
1922
1954
  comment: wholeBlockComment(ctx, blockId, 'image'),
1955
+ region,
1923
1956
  });
1924
1957
  if (img.complete && img.naturalWidth > 0) attachImgViewer();
1925
1958
  else img.addEventListener('load', attachImgViewer, { once: true });
1926
- if (ctx.annotate && ctx.canComment !== false) {
1927
- enableImageRegions({
1928
- host: stage,
1929
- surface: img,
1930
- panHost: container,
1931
- sourceForSide: () => img,
1932
- sideAtPoint: () => null,
1933
- ctx,
1934
- blockId,
1935
- label: block.alt || 'Image',
1936
- });
1937
- }
1938
1959
  if (ctx.annotate && block.pins === true) {
1939
1960
  enableImagePins(stage, img, ctx, blockId, block.alt || 'Image');
1940
1961
  } else if (ctx.annotate) {
@@ -2009,11 +2030,14 @@
2009
2030
  const selection = el('div', { class: 'blk-region-selection' });
2010
2031
  layer.append(selection);
2011
2032
  host.append(layer);
2033
+ panHost._rlyHasRegions = true;
2034
+ panHost.classList.add('blk-has-regions');
2012
2035
  let pending = null;
2013
2036
  let active = false;
2014
- let holdTimer = 0;
2015
2037
  let status = null;
2016
- const HOLD_MS = 280;
2038
+ let modeActive = false;
2039
+ const modeHooks = new Set();
2040
+ let controller = null;
2017
2041
  const MIN_REGION = 0.012;
2018
2042
 
2019
2043
  const localPoint = (e) => {
@@ -2030,8 +2054,6 @@
2030
2054
  host.append(status);
2031
2055
  };
2032
2056
  const reset = () => {
2033
- clearTimeout(holdTimer);
2034
- holdTimer = 0;
2035
2057
  active = false;
2036
2058
  pending = null;
2037
2059
  panHost._rlyRegionSelecting = false;
@@ -2039,6 +2061,30 @@
2039
2061
  selection.style.display = 'none';
2040
2062
  clearStatus();
2041
2063
  };
2064
+ const setModeActive = (next) => {
2065
+ const enabled = Boolean(next);
2066
+ if (enabled && activeRegionMode && activeRegionMode !== controller) {
2067
+ activeRegionMode.setModeActive(false);
2068
+ }
2069
+ if (!enabled && pending) reset();
2070
+ if (modeActive === enabled) return;
2071
+ modeActive = enabled;
2072
+ panHost._rlyRegionMode = enabled;
2073
+ host.classList.toggle('blk-region-mode', enabled);
2074
+ activeRegionMode = enabled ? controller : (activeRegionMode === controller ? null : activeRegionMode);
2075
+ for (const fn of modeHooks) { try { fn(enabled); } catch (_) {} }
2076
+ };
2077
+ controller = {
2078
+ setModeActive,
2079
+ isModeActive: () => modeActive,
2080
+ onModeChange: (fn) => {
2081
+ if (typeof fn === 'function') modeHooks.add(fn);
2082
+ return () => modeHooks.delete(fn);
2083
+ },
2084
+ };
2085
+ document.addEventListener('keydown', (e) => {
2086
+ if (e.key === 'Escape' && modeActive) setModeActive(false);
2087
+ });
2042
2088
  const draw = (a, b) => {
2043
2089
  const x = Math.min(a.x, b.x), y = Math.min(a.y, b.y);
2044
2090
  const w = Math.abs(a.x - b.x), h = Math.abs(a.y - b.y);
@@ -2048,6 +2094,34 @@
2048
2094
  selection.style.height = (h * 100) + '%';
2049
2095
  return { x, y, w, h };
2050
2096
  };
2097
+ const createRegionZone = (target, count, provisional = false) => {
2098
+ const badge = el('span', { class: 'blk-imgregion-badge', 'aria-hidden': 'true' });
2099
+ badge.innerHTML = ICON_COMMENT;
2100
+ badge.append(el('span', { class: 'blk-imgregion-count' }, String(count)));
2101
+ const sideLabel = target.side ? target.side + ' ' : '';
2102
+ const region = el('button', {
2103
+ class: 'blk-imgregion' + (provisional ? ' blk-imgregion-provisional' : ''),
2104
+ type: 'button',
2105
+ title: provisional
2106
+ ? `Add a comment to this ${sideLabel}area`
2107
+ : `${target.side ? target.side + ' · ' : ''}${count} ${count === 1 ? 'comment' : 'comments'}`,
2108
+ 'aria-label': provisional
2109
+ ? `New ${sideLabel}image area comment`
2110
+ : `${sideLabel}image area with ${count} ${count === 1 ? 'comment' : 'comments'}`,
2111
+ }, badge);
2112
+ region.style.left = (target.x * 100) + '%';
2113
+ region.style.top = (target.y * 100) + '%';
2114
+ region.style.width = (target.w * 100) + '%';
2115
+ region.style.height = (target.h * 100) + '%';
2116
+ region.addEventListener('pointerdown', (e) => e.stopPropagation());
2117
+ if (!provisional) {
2118
+ region.addEventListener('click', (e) => {
2119
+ e.stopPropagation();
2120
+ ctx.annotate.openExternal({ blockId, questionId: ctx.questionId, target }, region);
2121
+ });
2122
+ }
2123
+ return region;
2124
+ };
2051
2125
  const beginSelection = (pointerId) => {
2052
2126
  if (!pending || active) return;
2053
2127
  active = true;
@@ -2091,6 +2165,8 @@
2091
2165
  side: side || undefined,
2092
2166
  label,
2093
2167
  };
2168
+ const provisional = createRegionZone(target, 0, true);
2169
+ layer.append(provisional);
2094
2170
  showStatus('Saving selected area…');
2095
2171
  try {
2096
2172
  target.crop = await cropRegion(sourceForSide(side), region);
@@ -2098,12 +2174,21 @@
2098
2174
  target.cropUnavailable = true;
2099
2175
  }
2100
2176
  clearStatus();
2101
- ctx.annotate.openExternal({ blockId, questionId: ctx.questionId, target }, host);
2177
+ ctx.annotate.openExternal({
2178
+ blockId,
2179
+ questionId: ctx.questionId,
2180
+ target,
2181
+ onClose: () => provisional.remove(),
2182
+ }, provisional);
2102
2183
  };
2103
2184
 
2104
2185
  surface.addEventListener('pointerdown', (e) => {
2105
- if (e.button !== 0 || ctx.canComment === false) return;
2186
+ if (e.button !== 0 || viewerSpacePan || ctx.canComment === false) return;
2106
2187
  if (e.target.closest && e.target.closest('.cmp-handle, .blk-imgregion, .blk-tools')) return;
2188
+ if (modeActive) {
2189
+ e.preventDefault();
2190
+ e.stopPropagation();
2191
+ }
2107
2192
  const p = localPoint(e);
2108
2193
  pending = {
2109
2194
  start: p,
@@ -2111,38 +2196,41 @@
2111
2196
  clientX: e.clientX,
2112
2197
  clientY: e.clientY,
2113
2198
  pointerId: e.pointerId,
2114
- startedAt: performance.now(),
2199
+ explicitMode: modeActive,
2115
2200
  side: sideAtPoint(p.x),
2116
2201
  };
2117
2202
  host.classList.add('blk-region-arming');
2118
- holdTimer = setTimeout(() => beginSelection(e.pointerId), HOLD_MS);
2203
+ if (modeActive) beginSelection(e.pointerId);
2119
2204
  });
2120
2205
  surface.addEventListener('pointermove', (e) => {
2121
2206
  if (!pending) return;
2122
2207
  const moved = Math.hypot(e.clientX - pending.clientX, e.clientY - pending.clientY);
2123
- // Timers can be throttled while an automation host or background tab owns
2124
- // the event loop. The first post-hold move is also authoritative, so a
2125
- // genuine hold still enters area mode even if setTimeout fired late.
2126
- if (!active && performance.now() - pending.startedAt >= HOLD_MS) beginSelection(pending.pointerId);
2208
+ if (!active && moved > 5) beginSelection(pending.pointerId);
2127
2209
  if (!active) {
2128
- if (moved > 5) reset();
2129
2210
  return;
2130
2211
  }
2131
2212
  e.preventDefault();
2213
+ e.stopPropagation();
2132
2214
  pending.last = localPoint(e);
2133
2215
  draw(pending.start, pending.last);
2134
2216
  });
2135
2217
  const end = (e) => {
2136
2218
  if (!pending) return;
2137
- clearTimeout(holdTimer);
2138
2219
  if (!active) { reset(); return; }
2139
2220
  e.preventDefault();
2140
2221
  const region = draw(pending.start, pending.last || localPoint(e));
2141
2222
  const side = pending.side;
2223
+ const explicitMode = pending.explicitMode;
2142
2224
  surface._rlySuppressPointClick = true;
2143
2225
  reset();
2144
2226
  clearStatus();
2145
- if (region.w >= MIN_REGION && region.h >= MIN_REGION) finishRegion(region, side);
2227
+ if (region.w >= MIN_REGION && region.h >= MIN_REGION) {
2228
+ if (explicitMode) setModeActive(false);
2229
+ finishRegion(region, side);
2230
+ } else if (explicitMode) {
2231
+ showStatus('Drag a larger area');
2232
+ setTimeout(clearStatus, 1200);
2233
+ }
2146
2234
  };
2147
2235
  surface.addEventListener('pointerup', end);
2148
2236
  // Some Chromium/CDP paths emit pointercancel immediately after granting
@@ -2151,7 +2239,7 @@
2151
2239
  surface.addEventListener('pointercancel', (e) => active ? end(e) : reset());
2152
2240
 
2153
2241
  const syncRegions = () => {
2154
- for (const node of Array.from(layer.querySelectorAll('.blk-imgregion'))) node.remove();
2242
+ for (const node of Array.from(layer.querySelectorAll('.blk-imgregion:not(.blk-imgregion-provisional)'))) node.remove();
2155
2243
  const groups = new Map();
2156
2244
  for (const a of ctx.annotate.list()) {
2157
2245
  if (a.blockId !== blockId || !a.target || a.target.kind !== 'image-region') continue;
@@ -2162,27 +2250,12 @@
2162
2250
  groups.set(key, group);
2163
2251
  }
2164
2252
  for (const { target, count } of groups.values()) {
2165
- const region = el('button', {
2166
- class: 'blk-imgregion',
2167
- type: 'button',
2168
- 'data-count': String(count),
2169
- title: `${target.side ? target.side + ' · ' : ''}${count} ${count === 1 ? 'comment' : 'comments'}`,
2170
- 'aria-label': `${target.side ? target.side + ' image area' : 'image area'} with ${count} ${count === 1 ? 'comment' : 'comments'}`,
2171
- });
2172
- region.style.left = (target.x * 100) + '%';
2173
- region.style.top = (target.y * 100) + '%';
2174
- region.style.width = (target.w * 100) + '%';
2175
- region.style.height = (target.h * 100) + '%';
2176
- region.addEventListener('pointerdown', (e) => e.stopPropagation());
2177
- region.addEventListener('click', (e) => {
2178
- e.stopPropagation();
2179
- ctx.annotate.openExternal({ blockId, questionId: ctx.questionId, target }, region);
2180
- });
2181
- layer.append(region);
2253
+ layer.append(createRegionZone(target, count));
2182
2254
  }
2183
2255
  };
2184
2256
  if (ctx.annotate.onBadgeRefresh) ctx.annotate.onBadgeRefresh(syncRegions);
2185
2257
  syncRegions();
2258
+ return controller;
2186
2259
  }
2187
2260
 
2188
2261
  // ---------- palette ----------
@@ -2333,19 +2406,20 @@
2333
2406
  if (r.width) { pos = Math.max(0, Math.min(100, ((clientX - r.left) / r.width) * 100)); apply(); }
2334
2407
  };
2335
2408
  frame.addEventListener('pointerdown', (e) => {
2336
- if (e.target.closest && e.target.closest('.blk-imgregion')) return;
2409
+ const handleTarget = e.target.closest('.cmp-handle');
2410
+ if (!handleTarget || frame._rlyRegionMode) return;
2337
2411
  dragging = true;
2338
2412
  dragMoved = false;
2339
2413
  dragStartX = e.clientX;
2340
2414
  try { frame.setPointerCapture(e.pointerId); } catch (_) {}
2341
2415
  });
2342
2416
  frame.addEventListener('pointermove', (e) => {
2343
- if (!dragging || frame._rlyRegionSelecting) return;
2417
+ if (!dragging || frame._rlyRegionMode || frame._rlyRegionSelecting) return;
2344
2418
  if (Math.abs(e.clientX - dragStartX) > 3) dragMoved = true;
2345
2419
  if (dragMoved) { setFromX(e.clientX); e.preventDefault(); }
2346
2420
  });
2347
2421
  frame.addEventListener('pointerup', (e) => {
2348
- if (dragging && !dragMoved && !frame._rlyRegionSelecting) setFromX(e.clientX);
2422
+ if (dragging && !dragMoved && !frame._rlyRegionMode && !frame._rlyRegionSelecting) setFromX(e.clientX);
2349
2423
  dragging = false;
2350
2424
  });
2351
2425
  frame.addEventListener('pointercancel', () => { dragging = false; dragMoved = false; });
@@ -2353,9 +2427,10 @@
2353
2427
  if (e.key === 'ArrowLeft') { pos = Math.max(0, pos - 2); apply(); e.preventDefault(); }
2354
2428
  else if (e.key === 'ArrowRight') { pos = Math.min(100, pos + 2); apply(); e.preventDefault(); }
2355
2429
  });
2430
+ let region = null;
2356
2431
  if (ctx.annotate && ctx.canComment !== false) {
2357
- frame.title = 'Hold briefly, then drag to comment on the visible Before or After image';
2358
- enableImageRegions({
2432
+ frame.title = 'Drag to draw a comment area · drag the divider handle to compare';
2433
+ region = enableImageRegions({
2359
2434
  host: frame,
2360
2435
  surface: frame,
2361
2436
  panHost: frame,
@@ -2366,7 +2441,12 @@
2366
2441
  label: 'Comparison',
2367
2442
  });
2368
2443
  }
2369
- attachViewer(wrap, { zoomEl: null, label: 'comparison', comment: wholeBlockComment(ctx, blockId, 'comparison') });
2444
+ attachViewer(wrap, {
2445
+ zoomEl: null,
2446
+ label: 'comparison',
2447
+ comment: wholeBlockComment(ctx, blockId, 'comparison'),
2448
+ region,
2449
+ });
2370
2450
  return wrap;
2371
2451
  }
2372
2452
 
@@ -2399,6 +2479,10 @@
2399
2479
  const ICON_COMMENT =
2400
2480
  '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
2401
2481
  '<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8z"/></svg>';
2482
+ const ICON_REGION =
2483
+ '<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
2484
+ '<rect x="3" y="4" width="14" height="12" rx="2" stroke-dasharray="3 2"/>' +
2485
+ '<path d="M14 14.5h6.5v4H18l-2.5 2v-2H14z" fill="currentColor" stroke="none"/></svg>';
2402
2486
 
2403
2487
  function exitFull() {
2404
2488
  if (!fullOpen) return;
@@ -2413,7 +2497,7 @@
2413
2497
  if (c._rlyZoom) c._rlyZoom.reapply(); // restore the compact inline height cap
2414
2498
  }
2415
2499
  document.addEventListener('keydown', (e) => {
2416
- if (e.key === 'Escape' && fullOpen) exitFull();
2500
+ if (e.key === 'Escape' && fullOpen && !document.querySelector('.rly-file-dialog[open]')) exitFull();
2417
2501
  });
2418
2502
 
2419
2503
  // Enter full-screen for a viewer container (shared by the toolbar button and
@@ -2520,7 +2604,8 @@
2520
2604
  const refresh = () => scrollEl.classList.toggle('blk-pannable', pannable());
2521
2605
 
2522
2606
  scrollEl.addEventListener('pointerdown', (e) => {
2523
- if (e.button !== 0 || !pannable()) return;
2607
+ const panGesture = e.button === 1 || (e.button === 0 && (!scrollEl._rlyHasRegions || viewerSpacePan));
2608
+ if (!panGesture || scrollEl._rlyRegionMode || !pannable()) return;
2524
2609
  // leave the toolbar, the diagram editor, and real controls interactive
2525
2610
  if (e.target.closest && e.target.closest('.blk-tools, .blk-editor, button, a, input, textarea, select')) return;
2526
2611
  pending = true; active = false;
@@ -2530,7 +2615,7 @@
2530
2615
  });
2531
2616
  scrollEl.addEventListener('pointermove', (e) => {
2532
2617
  if (!pending) return;
2533
- if (scrollEl._rlyRegionSelecting) { pending = false; active = false; return; }
2618
+ if (scrollEl._rlyRegionMode || scrollEl._rlyRegionSelecting) { pending = false; active = false; return; }
2534
2619
  const dx = e.clientX - sx, dy = e.clientY - sy;
2535
2620
  if (!active) {
2536
2621
  if (Math.abs(dx) < THRESH && Math.abs(dy) < THRESH) return;
@@ -2581,6 +2666,10 @@
2581
2666
  // comment (optional) = { open(anchor), active(), subscribe(fn) } wiring the
2582
2667
  // "comment on the whole block" button + its already-commented style.
2583
2668
  function attachViewer(container, opts) {
2669
+ if (container._rlyRegionHook) {
2670
+ try { container._rlyRegionHook(); } catch (_) {}
2671
+ container._rlyRegionHook = null;
2672
+ }
2584
2673
  if (container._rlyTools) container._rlyTools.remove();
2585
2674
  container.classList.add('blk-viewer');
2586
2675
  const zoomable = Boolean(opts && opts.zoomEl);
@@ -2695,6 +2784,34 @@
2695
2784
  }
2696
2785
  }
2697
2786
 
2787
+ if (opts && opts.region) {
2788
+ const regionCtl = opts.region;
2789
+ const regionLabel = el('span', { class: 'tool-region-label' }, 'Area');
2790
+ const regionBtn = el('button', {
2791
+ class: 'tool-region',
2792
+ type: 'button',
2793
+ title: 'Draw an area comment',
2794
+ 'aria-label': 'Draw an area comment',
2795
+ 'aria-pressed': 'false',
2796
+ });
2797
+ regionBtn.innerHTML = ICON_REGION;
2798
+ regionBtn.append(regionLabel);
2799
+ const syncRegionMode = (enabled) => {
2800
+ regionBtn.classList.toggle('is-active', enabled);
2801
+ regionBtn.setAttribute('aria-pressed', enabled ? 'true' : 'false');
2802
+ regionBtn.title = enabled ? 'Cancel area comment' : 'Draw an area comment';
2803
+ regionBtn.setAttribute('aria-label', regionBtn.title);
2804
+ regionLabel.textContent = enabled ? 'Drawing' : 'Area';
2805
+ };
2806
+ regionBtn.addEventListener('click', (e) => {
2807
+ e.stopPropagation();
2808
+ regionCtl.setModeActive(!regionCtl.isModeActive());
2809
+ });
2810
+ container._rlyRegionHook = regionCtl.onModeChange(syncRegionMode);
2811
+ syncRegionMode(regionCtl.isModeActive());
2812
+ tools.append(regionBtn);
2813
+ }
2814
+
2698
2815
  if (zoomable) {
2699
2816
  // cmd/ctrl+wheel zoom, bound ONCE (re-binding per render would stack);
2700
2817
  // delegates to the current controller so it never uses a stale zoomEl
@@ -2901,6 +3018,125 @@
2901
3018
  }
2902
3019
 
2903
3020
  // ---------- file-link open behavior ----------
3021
+ let fileDialog = null;
3022
+ const fileAuthHeaders = () => {
3023
+ const token = new URLSearchParams(location.search).get('token');
3024
+ return token ? { 'x-relay-share-token': token } : {};
3025
+ };
3026
+
3027
+ async function previewFilePath(a) {
3028
+ const p = a.dataset.rlyOpen;
3029
+ if (!p) return;
3030
+ if (fileDialog) fileDialog.close();
3031
+ const dialog = el('dialog', { class: 'rly-file-dialog', 'aria-label': 'File preview' });
3032
+ const title = el('h2', {}, p.split(/[\\/]/).pop());
3033
+ const pathLabel = el('div', { class: 'rly-file-location', title: p }, p);
3034
+ const close = el('button', { type: 'button', class: 'btn', autofocus: '', 'aria-label': 'Close file preview' }, 'Close');
3035
+ const open = el('button', { type: 'button', class: 'btn' }, 'Open in app');
3036
+ open.dataset.rlyOpen = p;
3037
+ open.addEventListener('click', () => openFilePath(open));
3038
+ const actions = el('div', { class: 'rly-file-actions' }, open, close);
3039
+ const body = el('div', { class: 'rly-file-body', tabindex: '0', 'aria-busy': 'true' });
3040
+ const status = el('p', { role: 'status' }, 'Loading preview…');
3041
+ body.append(status);
3042
+ dialog.append(el('header', { class: 'rly-file-header' }, el('div', { class: 'rly-file-heading' }, title, pathLabel), actions), body);
3043
+ const controller = new AbortController();
3044
+ const previousFocus = document.activeElement;
3045
+ close.addEventListener('click', () => dialog.close());
3046
+ dialog.addEventListener('close', () => {
3047
+ controller.abort();
3048
+ dialog.querySelectorAll('video,audio').forEach((media) => { media.pause(); media.removeAttribute('src'); media.load(); });
3049
+ dialog.remove();
3050
+ if (fileDialog === dialog) fileDialog = null;
3051
+ if (previousFocus && previousFocus.isConnected) previousFocus.focus({ preventScroll: true });
3052
+ });
3053
+ document.body.append(dialog);
3054
+ fileDialog = dialog;
3055
+ dialog.showModal();
3056
+ try {
3057
+ const response = await fetch('/api/file-preview', {
3058
+ method: 'POST', headers: { 'content-type': 'application/json', ...fileAuthHeaders() },
3059
+ body: JSON.stringify({ path: p }), signal: controller.signal,
3060
+ });
3061
+ let data;
3062
+ try { data = await response.json(); }
3063
+ catch { throw new Error('File previews need a current Relay browser board. Reconnect this board with the updated CLI.'); }
3064
+ if (!response.ok || !data.ok) {
3065
+ if (response.status === 403) open.disabled = true;
3066
+ throw new Error(data.error || 'Preview unavailable. Reconnect this board with the updated CLI.');
3067
+ }
3068
+ if (!dialog.open) return;
3069
+ title.textContent = data.name;
3070
+ dialog.setAttribute('aria-label', 'File preview: ' + data.name);
3071
+ body.replaceChildren();
3072
+ const source = () => {
3073
+ body.replaceChildren();
3074
+ const lines = String(data.text || '').replace(/\r\n?/g, '\n').replace(/\n$/, '').split('\n');
3075
+ const list = el('div', { class: 'rly-file-source' });
3076
+ lines.forEach((line, i) => {
3077
+ const number = i + 1;
3078
+ const code = el('code');
3079
+ code.innerHTML = tintCode(line, data.lang) || ' ';
3080
+ const row = el('div', { class: 'rly-file-line', 'data-line': String(number) },
3081
+ el('span', { class: 'rly-file-line-number', 'aria-hidden': 'true' }, String(number)), code);
3082
+ if (data.line && number >= data.line && number <= data.endLine) row.classList.add('is-target');
3083
+ list.append(row);
3084
+ });
3085
+ if (data.line > lines.length) body.append(el('p', { role: 'status' }, 'Line ' + data.line + ' is beyond this file’s ' + lines.length + ' lines.'));
3086
+ body.append(list);
3087
+ requestAnimationFrame(() => {
3088
+ const target = list.querySelector('.is-target');
3089
+ if (!target || !dialog.open) return;
3090
+ body.scrollTop += target.getBoundingClientRect().top - body.getBoundingClientRect().top - body.clientHeight / 2 + target.clientHeight / 2;
3091
+ body.scrollLeft = 0;
3092
+ });
3093
+ };
3094
+ const rendered = () => {
3095
+ body.replaceChildren();
3096
+ if (data.kind === 'markdown') {
3097
+ const md = el('div', { class: 'blk-markdown' });
3098
+ md.append(renderMarkdown(data.text));
3099
+ body.append(md);
3100
+ } else if (data.kind === 'table') {
3101
+ body.append(renderTable(data.block, { canComment: false }, 'file-preview'));
3102
+ } else if (data.kind === 'html') {
3103
+ // Empty sandbox prevents scripts, forms and same-origin access. CSP
3104
+ // also prevents authored markup from fetching local or remote URLs.
3105
+ const frame = el('iframe', { class: 'rly-file-frame', title: data.name, sandbox: '', referrerpolicy: 'no-referrer' });
3106
+ frame.srcdoc = '<meta http-equiv="Content-Security-Policy" content="default-src &#39;none&#39;; style-src &#39;unsafe-inline&#39;; img-src data:; font-src data:">' + data.text;
3107
+ body.append(frame);
3108
+ }
3109
+ };
3110
+ if (['markdown', 'html', 'table'].includes(data.kind)) {
3111
+ let viewingSource = !!data.line;
3112
+ const toggle = el('button', { type: 'button', class: 'btn' }, viewingSource ? 'Preview' : 'Source');
3113
+ toggle.addEventListener('click', () => {
3114
+ viewingSource = !viewingSource;
3115
+ toggle.textContent = viewingSource ? 'Preview' : 'Source';
3116
+ viewingSource ? source() : rendered();
3117
+ });
3118
+ actions.prepend(toggle);
3119
+ viewingSource ? source() : rendered();
3120
+ } else if (data.kind === 'code') source();
3121
+ else if (data.kind === 'unsupported') body.append(el('p', { role: 'status' }, data.reason));
3122
+ else {
3123
+ const params = new URLSearchParams({ path: p });
3124
+ const token = new URLSearchParams(location.search).get('token');
3125
+ if (token) params.set('token', token);
3126
+ const url = '/api/file-content?' + params;
3127
+ const tag = { image: 'img', pdf: 'iframe', video: 'video', audio: 'audio' }[data.kind];
3128
+ if (!tag) throw new Error('This file type cannot be previewed.');
3129
+ const media = el(tag, { class: 'rly-file-media rly-file-' + data.kind, src: url, title: data.name });
3130
+ if (tag === 'img') media.alt = data.name;
3131
+ if (tag === 'video' || tag === 'audio') { media.controls = true; media.preload = 'metadata'; }
3132
+ media.addEventListener('error', () => body.append(el('p', { role: 'status' }, 'Your browser could not display this file. Use Open in app.')), { once: true });
3133
+ body.append(media);
3134
+ }
3135
+ } catch (err) {
3136
+ if (err.name !== 'AbortError' && dialog.open) body.replaceChildren(el('p', { role: 'alert' }, err.message || 'Could not reach the board server.'));
3137
+ } finally { body.setAttribute('aria-busy', 'false'); }
3138
+ }
3139
+
2904
3140
  // A small toast pinned top-center (reuses the .toast style from style.css).
2905
3141
  // tone 'err' adds .toast-err so failures read as a problem, not a success.
2906
3142
  function fileToast(message, tone) {
@@ -2918,7 +3154,7 @@
2918
3154
  try {
2919
3155
  const r = await fetch('/api/open', {
2920
3156
  method: 'POST',
2921
- headers: { 'content-type': 'application/json' },
3157
+ headers: { 'content-type': 'application/json', ...fileAuthHeaders() },
2922
3158
  body: JSON.stringify({ path: p }),
2923
3159
  });
2924
3160
  let data = {};
@@ -2948,14 +3184,14 @@
2948
3184
  const a = hit(e);
2949
3185
  if (!a) return;
2950
3186
  e.preventDefault();
2951
- openFilePath(a);
3187
+ previewFilePath(a);
2952
3188
  });
2953
3189
  document.addEventListener('keydown', (e) => {
2954
3190
  if (e.key !== 'Enter' && e.key !== ' ' && e.key !== 'Spacebar') return;
2955
3191
  const a = hit(e);
2956
3192
  if (!a) return;
2957
3193
  e.preventDefault();
2958
- openFilePath(a);
3194
+ previewFilePath(a);
2959
3195
  });
2960
3196
  }
2961
3197
  initFileLinks();