Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(frontend): runtime self-captured skeleton bones (plan 50 phase 3)

Juan Denis3333ede87b9d
diff --git a/frontend/scripts/capture-skeletons.mjs b/frontend/scripts/capture-skeletons.mjs
index 09456b99..46b9d084 100644
--- a/frontend/scripts/capture-skeletons.mjs
+++ b/frontend/scripts/capture-skeletons.mjs
@@ -13,11 +13,12 @@
* (SCSS-classed absolutely-positioned divs), so the shipped product never
* imports boneyard or runs a browser — it just reads the baked JSON.
*
- * The in-page snapshot below is a faithful port of boneyard-js `snapshotBones`
- * (github: boneyard-js, `packages/boneyard/src/extract.ts`). We embed it rather
- * than injecting the npm ESM bundle into the page so the script stays runnable
- * from a fresh checkout; `boneyard-js` is kept as a devDependency for parity and
- * as the upstream source of truth for the bone format.
+ * The in-page snapshot is `src/utils/snapshotBones.js` — a faithful port of
+ * boneyard-js `snapshotBones` (`packages/boneyard/src/extract.ts`), shared with
+ * the runtime self-capture hook. We inject its source into the page rather than
+ * the npm ESM bundle so the script stays runnable from a fresh checkout;
+ * `boneyard-js` is kept as a devDependency for parity and as the upstream source
+ * of truth for the bone format.
*
* Usage:
* 1. Start the dev stack (backend on :47927, `npm run dev` frontend) with
@@ -36,6 +37,7 @@
import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
+import { snapshotBones } from '../src/utils/snapshotBones.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const FRONTEND_DIR = path.resolve(__dirname, '..');
@@ -57,73 +59,6 @@ const TARGETS = [
const log = (...a) => console.log('[bones]', ...a);
-// ---- the in-page snapshot (faithful port of boneyard snapshotBones) --------
-// Serialized into the page via Playwright's evaluate. Returns a SkeletonResult:
-// { name, viewportWidth, width, height, bones: [{x, y, w, h, r, c?}] }
-// x/w are percentages of the root width; y/h are absolute px from the root top.
-function inPageSnapshot(el, name) {
- const round = (n) => Math.round(n);
- const round4 = (n) => Math.round(n * 10000) / 10000;
- const MEDIA = new Set(['IMG', 'SVG', 'VIDEO', 'CANVAS']);
- const FORM = new Set(['INPUT', 'BUTTON', 'TEXTAREA', 'SELECT']);
- const LEAF_TAGS = new Set(['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'LI', 'TD', 'TH']);
- const rootRect = el.getBoundingClientRect();
- const bones = [];
-
- const parseRadius = (cs) => {
- const r = cs.borderTopLeftRadius;
- if (!r || r === '0px') return null;
- const px = parseFloat(r);
- return Number.isFinite(px) ? px : null;
- };
- const visible = (node) => {
- const cs = getComputedStyle(node);
- return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0';
- };
- const relX = (rect) => round4(((rect.left - rootRect.left) / rootRect.width) * 100);
- const relW = (rect) => round4((rect.width / rootRect.width) * 100);
-
- const walk = (node) => {
- if (!(node instanceof Element) || !visible(node)) return;
- const cs = getComputedStyle(node);
- const kids = Array.from(node.children).filter((c) => c instanceof Element && visible(c));
- const tag = node.tagName;
- const isLeaf = kids.length === 0 || MEDIA.has(tag) || FORM.has(tag) || LEAF_TAGS.has(tag);
-
- if (isLeaf) {
- const rect = node.getBoundingClientRect();
- if (rect.width < 1 || rect.height < 1) return;
- const squarish = MEDIA.has(tag) && Math.abs(rect.width - rect.height) < 4;
- const r = squarish ? '50%' : (parseRadius(cs) ?? 8);
- bones.push({ x: relX(rect), y: round(rect.top - rootRect.top), w: relW(rect), h: round(rect.height), r });
- return;
- }
-
- // Non-leaf: emit a lighter container bone for visual surfaces, then recurse.
- const hasBg = cs.backgroundColor && cs.backgroundColor !== 'rgba(0, 0, 0, 0)' && cs.backgroundColor !== 'transparent';
- const hasBgImage = cs.backgroundImage && cs.backgroundImage !== 'none';
- const hasBorder = parseFloat(cs.borderTopWidth) > 0
- && cs.borderTopColor && cs.borderTopColor !== 'rgba(0, 0, 0, 0)';
- const hasRadius = parseFloat(cs.borderTopLeftRadius) > 0;
- if (hasBg || hasBgImage || (hasBorder && hasRadius)) {
- const rect = node.getBoundingClientRect();
- if (rect.width >= 1 && rect.height >= 1) {
- bones.push({ x: relX(rect), y: round(rect.top - rootRect.top), w: relW(rect), h: round(rect.height), r: parseRadius(cs) ?? 8, c: true });
- }
- }
- kids.forEach(walk);
- };
-
- Array.from(el.children).forEach(walk);
- return {
- name: name || 'component',
- viewportWidth: round(rootRect.width),
- width: round(rootRect.width),
- height: round(rootRect.height),
- bones,
- };
-}
-
// ---- driver ---------------------------------------------------------------
async function loadPlaywright() {
try {
@@ -181,7 +116,7 @@ async function main() {
const fn = new Function(`return (${fnSrc})`)();
return fn(el, key);
},
- { selector: t.selector, key: t.key, fnSrc: inPageSnapshot.toString() },
+ { selector: t.selector, key: t.key, fnSrc: snapshotBones.toString() },
);
if (!snapshot || !snapshot.bones.length) throw new Error(`no bones captured for ${t.selector}`);
await writeFile(path.join(OUT_DIR, `${t.key}.json`), JSON.stringify(snapshot, null, 2) + '\n');
diff --git a/frontend/src/components/SkeletonBoundary.jsx b/frontend/src/components/SkeletonBoundary.jsx
index 2af38777..64da412b 100644
--- a/frontend/src/components/SkeletonBoundary.jsx
+++ b/frontend/src/components/SkeletonBoundary.jsx
@@ -1,4 +1,4 @@
-import { Children, useEffect, useState } from 'react';
+import { Children, forwardRef, useEffect, useState } from 'react';
import { cn } from '@/lib/utils';
import { renderBones } from './renderBones';
@@ -39,7 +39,7 @@ import { renderBones } from './renderBones';
* @param {string} [as] Container tag name (default 'div').
* @param {string} [className] Extra classes on the boundary container.
*/
-export function SkeletonBoundary({
+export const SkeletonBoundary = forwardRef(function SkeletonBoundary({
loading,
skeleton,
bones = null,
@@ -48,7 +48,7 @@ export function SkeletonBoundary({
as: Tag = 'div',
className = '',
...rest
-}) {
+}, ref) {
// Keep the skeleton mounted through a short fade-out when `transition` is on.
const [showSkeleton, setShowSkeleton] = useState(loading);
const leaving = !loading && showSkeleton;
@@ -72,6 +72,7 @@ export function SkeletonBoundary({
return (
<Tag
+ ref={ref}
className={cn('skeleton-boundary', className)}
data-loading={loading ? 'true' : undefined}
aria-busy={loading ? 'true' : undefined}
@@ -93,6 +94,6 @@ export function SkeletonBoundary({
)}
</Tag>
);
-}
+});
export default SkeletonBoundary;
diff --git a/frontend/src/hooks/useSelfCapturedBones.js b/frontend/src/hooks/useSelfCapturedBones.js
new file mode 100644
index 00000000..0aa81531
--- /dev/null
+++ b/frontend/src/hooks/useSelfCapturedBones.js
@@ -0,0 +1,87 @@
+import { useEffect, useRef } from 'react';
+import { snapshotBones } from '@/utils/snapshotBones';
+
+// Bump when a wired page's layout changes so cached bones from the old shape are
+// discarded instead of replayed. (Runtime self-capture is a best-effort accuracy
+// nicety; the composed skeleton is always the fallback.)
+export const BONES_CACHE_VERSION = 1;
+
+const keyFor = (key) => `sk-bones:${key}`;
+
+function readCache(key, version) {
+ if (typeof localStorage === 'undefined') return null;
+ try {
+ const raw = localStorage.getItem(keyFor(key));
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ if (parsed.v !== version || !parsed.snapshot?.bones?.length) {
+ localStorage.removeItem(keyFor(key)); // purge stale/mismatched entries
+ return null;
+ }
+ return parsed.snapshot;
+ } catch {
+ return null;
+ }
+}
+
+function writeCache(key, version, snapshot) {
+ if (typeof localStorage === 'undefined') return;
+ try {
+ localStorage.setItem(keyFor(key), JSON.stringify({ v: version, snapshot }));
+ } catch {
+ /* private mode / quota — self-capture is best-effort */
+ }
+}
+
+/**
+ * Runtime self-capture of skeleton bones (Phase 3 of plan 50).
+ *
+ * After a page's real content has rendered, snapshot the referenced region into
+ * bones and cache them in `localStorage` under `sk-bones:<key>`; on the NEXT load
+ * those cached bones drive a pixel-accurate skeleton. The first-ever visit has no
+ * cache, so `bones` is null and the caller falls back to its composed skeleton —
+ * no regression.
+ *
+ * Usage (the ref must go on the element whose real content should be measured;
+ * `SkeletonBoundary` forwards its ref to that container):
+ *
+ * const { ref, bones } = useSelfCapturedBones('ssl', { ready: !loading && !!data });
+ * <SkeletonBoundary ref={ref} loading={loading} bones={bones} skeleton={composed}>
+ * {data && <Content />}
+ * </SkeletonBoundary>
+ *
+ * @param {string} key Stable cache key (page identifier).
+ * @param {object} [opts]
+ * @param {boolean} [opts.ready] True once real content is on screen (capture gate).
+ * @param {number} [opts.version] Cache version; mismatches are purged.
+ * @returns {{ ref: import('react').RefObject<Element>, bones: object|null }}
+ */
+export function useSelfCapturedBones(key, { ready = false, version = BONES_CACHE_VERSION } = {}) {
+ const ref = useRef(null);
+ // Read once at mount — this load replays whatever was cached last time.
+ const bonesRef = useRef(undefined);
+ if (bonesRef.current === undefined) bonesRef.current = readCache(key, version);
+
+ const captured = useRef(false);
+ useEffect(() => {
+ if (!ready || captured.current || !ref.current) return undefined;
+ // Capture after paint so measurements reflect the settled layout.
+ const raf = requestAnimationFrame(() => {
+ if (!ref.current) return;
+ try {
+ const snapshot = snapshotBones(ref.current, key);
+ if (snapshot?.bones?.length) {
+ writeCache(key, version, snapshot);
+ captured.current = true;
+ }
+ } catch {
+ /* capture is best-effort; never break the page */
+ }
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [ready, key, version]);
+
+ return { ref, bones: bonesRef.current };
+}
+
+export default useSelfCapturedBones;
diff --git a/frontend/src/pages/SSLCertificates.jsx b/frontend/src/pages/SSLCertificates.jsx
index 4b30f80f..74ac62db 100644
--- a/frontend/src/pages/SSLCertificates.jsx
+++ b/frontend/src/pages/SSLCertificates.jsx
@@ -17,6 +17,7 @@ import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Skeleton } from '@/components/Skeleton';
import SkeletonBoundary from '@/components/SkeletonBoundary';
+import { useSelfCapturedBones } from '@/hooks/useSelfCapturedBones';
const SSLCertificates = () => {
const toast = useToast();
@@ -26,6 +27,13 @@ const SSLCertificates = () => {
const [actionLoading, setActionLoading] = useState(false);
const [renewingDomain, setRenewingDomain] = useState(null);
+ // Runtime self-capture: after the real page renders, snapshot its layout so a
+ // later load replays a pixel-accurate skeleton (falls back to sslSkeleton on
+ // first-ever visit). See useSelfCapturedBones / plan 50 phase 3.
+ const { ref: pageRef, bones: capturedBones } = useSelfCapturedBones('ssl', {
+ ready: !loading && !!status,
+ });
+
// Modal states
const [showObtainModal, setShowObtainModal] = useState(false);
const [showUploadModal, setShowUploadModal] = useState(false);
@@ -286,9 +294,11 @@ const SSLCertificates = () => {
return (
<>
<SkeletonBoundary
+ ref={pageRef}
className="sk-tabgroup__inner ssl-page"
loading={loading}
skeleton={sslSkeleton}
+ bones={capturedBones}
>
{(!loading || status) && (<>
{/* Status Cards */}
diff --git a/frontend/src/utils/snapshotBones.js b/frontend/src/utils/snapshotBones.js
new file mode 100644
index 00000000..1bafd841
--- /dev/null
+++ b/frontend/src/utils/snapshotBones.js
@@ -0,0 +1,88 @@
+/**
+ * Browser-side skeleton snapshot — a faithful port of boneyard-js `snapshotBones`
+ * (`packages/boneyard/src/extract.ts`). Walks the children of `el`, emitting a
+ * "bone" for each leaf placeholder (and a lighter container bone for visual
+ * surfaces), and returns a SkeletonResult:
+ *
+ * { name, viewportWidth, width, height, bones: [{x, y, w, h, r, c?}] }
+ *
+ * `x`/`w` are PERCENTAGES of the region width (responsive); `y`/`h` are ABSOLUTE
+ * PIXELS from the region top; `r` is a number (px) or a CSS string ("50%" =
+ * circle); `c: true` marks a background/container bone.
+ *
+ * Pure and fully self-contained (references only browser layout globals), so the
+ * dev-time capture script (`scripts/capture-skeletons.mjs`) can also inject it
+ * into a page via `.toString()`. Requires a live DOM (`getBoundingClientRect`,
+ * `getComputedStyle`) — call it after the real content has rendered.
+ *
+ * @param {Element} el Region root whose subtree becomes bones.
+ * @param {string} [name] Label stored on the result.
+ * @returns {{name:string,viewportWidth:number,width:number,height:number,bones:Array}}
+ */
+export function snapshotBones(el, name = 'component') {
+ const round = (n) => Math.round(n);
+ const round4 = (n) => Math.round(n * 10000) / 10000;
+ const MEDIA = new Set(['IMG', 'SVG', 'VIDEO', 'CANVAS']);
+ const FORM = new Set(['INPUT', 'BUTTON', 'TEXTAREA', 'SELECT']);
+ const LEAF_TAGS = new Set(['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'LI', 'TD', 'TH']);
+ const rootRect = el.getBoundingClientRect();
+ const bones = [];
+ if (rootRect.width < 1 || rootRect.height < 1) {
+ return { name, viewportWidth: round(rootRect.width), width: round(rootRect.width), height: round(rootRect.height), bones };
+ }
+
+ const parseRadius = (cs) => {
+ const r = cs.borderTopLeftRadius;
+ if (!r || r === '0px') return null;
+ const px = parseFloat(r);
+ return Number.isFinite(px) ? px : null;
+ };
+ const isVisible = (node) => {
+ const cs = getComputedStyle(node);
+ return cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0';
+ };
+ const relX = (rect) => round4(((rect.left - rootRect.left) / rootRect.width) * 100);
+ const relW = (rect) => round4((rect.width / rootRect.width) * 100);
+
+ const walk = (node) => {
+ if (!(node instanceof Element) || !isVisible(node)) return;
+ const cs = getComputedStyle(node);
+ const kids = Array.from(node.children).filter((c) => c instanceof Element && isVisible(c));
+ const tag = node.tagName;
+ const isLeaf = kids.length === 0 || MEDIA.has(tag) || FORM.has(tag) || LEAF_TAGS.has(tag);
+
+ if (isLeaf) {
+ const rect = node.getBoundingClientRect();
+ if (rect.width < 1 || rect.height < 1) return;
+ const squarish = MEDIA.has(tag) && Math.abs(rect.width - rect.height) < 4;
+ const r = squarish ? '50%' : (parseRadius(cs) ?? 8);
+ bones.push({ x: relX(rect), y: round(rect.top - rootRect.top), w: relW(rect), h: round(rect.height), r });
+ return;
+ }
+
+ // Non-leaf: emit a lighter container bone for visual surfaces, then recurse.
+ const hasBg = cs.backgroundColor && cs.backgroundColor !== 'rgba(0, 0, 0, 0)' && cs.backgroundColor !== 'transparent';
+ const hasBgImage = cs.backgroundImage && cs.backgroundImage !== 'none';
+ const hasBorder = parseFloat(cs.borderTopWidth) > 0
+ && cs.borderTopColor && cs.borderTopColor !== 'rgba(0, 0, 0, 0)';
+ const hasRadius = parseFloat(cs.borderTopLeftRadius) > 0;
+ if (hasBg || hasBgImage || (hasBorder && hasRadius)) {
+ const rect = node.getBoundingClientRect();
+ if (rect.width >= 1 && rect.height >= 1) {
+ bones.push({ x: relX(rect), y: round(rect.top - rootRect.top), w: relW(rect), h: round(rect.height), r: parseRadius(cs) ?? 8, c: true });
+ }
+ }
+ kids.forEach(walk);
+ };
+
+ Array.from(el.children).forEach(walk);
+ return {
+ name,
+ viewportWidth: round(rootRect.width),
+ width: round(rootRect.width),
+ height: round(rootRect.height),
+ bones,
+ };
+}
+
+export default snapshotBones;