Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions assets/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,27 @@ html {
.code-with-filename .code-with-filename-label {
background-color: var(--color-blue-200);
padding: 0.4rem 1.1428571em;
display: flex;
align-items: center;
gap: 1rem;
}

.prose .code-shinylive-link {
margin-left: auto;
display: inline-flex;
align-items: center;
gap: 0.35rem;
font-size: 0.875rem;
font-weight: 500;
text-decoration: none;
}

.prose .code-shinylive-link:hover {
text-decoration: underline;
}

.code-shinylive-link svg {
fill: currentColor;
}

.code-with-filename div.highlight,
Expand Down
1 change: 1 addition & 0 deletions content/blog/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Every post must have:
| `description` | 1-2 sentences; shown in card listings, under the post hero, and in social previews |
| `image` | Thumbnail/hero image filename; 1920×1080 PNG or JPG recommended (16:9); GIF is supported and animation will play |
| `image-alt` | Alt text for the image — describe what it shows, not just "screenshot" |
| `image-video` | Optional hero video filename (mp4). On the post page the hero plays it as a muted loop with `image` as the poster; `image` is still what the listing card and social previews show |
| `topics` | Fixed set — see below |
| `software` | Projects the post is about; use folder names from `content/software/` |
| `languages` | Programming languages (R, Python, etc.) |
Expand Down
43 changes: 43 additions & 0 deletions content/blog/shinywidgets-1-0/_feature-src/capture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""Regenerate the post's featured image from feature.html.

Writes featured.jpg (1920x1080) to the post directory (the parent of this
folder). The screenshot tiles in img/ come from the shinywidgets website's
landing page and the gallery apps.

Usage:

uv run --with playwright python capture.py
"""

import pathlib

from playwright.sync_api import sync_playwright

HERE = pathlib.Path(__file__).parent
POST_DIR = HERE.parent
SRC = (HERE / "feature.html").as_uri()

WIDTH, HEIGHT = 1200, 675 # 16:9; 1.6x device scale gives 1920x1080

with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(
viewport={"width": WIDTH, "height": HEIGHT},
device_scale_factor=1.6,
)
page.goto(SRC)
# Fail loudly if the site fonts or tiles did not load; fallbacks look wrong.
page.evaluate("() => document.fonts.ready")
for spec in ('700 16px "Open Sans"', '500 16px "Source Code Pro"'):
if not page.evaluate(f"() => document.fonts.check('{spec}')"):
raise SystemExit(f"font not loaded: {spec}")
broken = page.evaluate(
"[...document.images].filter(i => !i.naturalWidth).map(i => i.src)"
)
if broken:
raise SystemExit(f"images not loaded: {broken}")
page.wait_for_timeout(300)
page.screenshot(path=str(POST_DIR / "featured.jpg"), type="jpeg", quality=85)
browser.close()

print("featured.jpg written (1920x1080)")
138 changes: 138 additions & 0 deletions content/blog/shinywidgets-1-0/_feature-src/capture_gallery_hover.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
"""Record the gallery "stage" on the shinywidgets.org landing page.

The stage auto-plays each of the six featured apps (a ~7s gesture animation,
then it advances). This script drives it deterministically: a scripted cursor
glides onto each app in the picker list, a JS click restarts that app's
animation just as the cursor arrives, and it plays start-to-finish before the
cursor moves on. Clicks are timed ~100ms before autoplay would advance so the
auto-advance never fires mid-recording.

Playwright's video doesn't render an OS cursor, so we inject an SVG cursor
that follows the (scripted) mouse via mousemove events.

Usage:

uv run --with playwright python capture_gallery_hover.py

Writes gallery-hover.mp4 next to this script (2320x1182 h264). Playwright's
video captures at CSS-pixel size even with a device scale factor, so for a
hi-res recording we zoom the page 2x inside a 2560x1600 viewport and crop to
the stage. The injected cursor lives outside the zoomed body (mouse events
report viewport coordinates regardless of zoom) and is drawn 2x to match.
"""

import pathlib
import subprocess
import tempfile
import time

from playwright.sync_api import sync_playwright

HERE = pathlib.Path(__file__).parent
OUT = HERE.parent / "gallery-hover.mp4"
URL = "https://shinywidgets.org/"

WIDTH, HEIGHT = 2560, 1600
ZOOM = 2
# landing.js: each showcase plays for DUR ms, then autoplay advances.
DUR_MS = 7000
# Click the next app this long after the previous click: the full gesture
# (done by 5600ms) plus most of the progress bar, but before autoplay fires.
ITEM_MS = DUR_MS - 100
N_ITEMS = 6

CURSOR_JS = """
() => {
const c = document.createElement('div');
c.style.cssText = 'position:fixed;z-index:999999;pointer-events:none;left:0;top:0;margin:0';
c.innerHTML = `<svg width="40" height="40" viewBox="0 0 24 24">
<path d="M4 2 L20 12 L12.5 13.5 L9 22 Z" fill="white" stroke="black" stroke-width="1.5"/>
</svg>`;
document.documentElement.appendChild(c);
addEventListener('mousemove', e => {
c.style.transform = `translate(${e.clientX}px, ${e.clientY}px)`;
});
}
"""

PRELOAD_JS = """
async () => {
const imgs = SHOWCASES.flatMap(s => [0, 1].map(i => {
const img = new Image();
img.src = `assets/landing/img/show-${s.id}-${i}.webp`;
return img.decode().catch(() => {});
}));
await Promise.all(imgs);
return SHOWCASES.map(s => s.id);
}
"""


def main() -> None:
with sync_playwright() as p, tempfile.TemporaryDirectory() as vdir:
browser = p.chromium.launch()
context = browser.new_context(
viewport={"width": WIDTH, "height": HEIGHT},
record_video_dir=vdir,
record_video_size={"width": WIDTH, "height": HEIGHT},
)
page = context.new_page()
t0 = time.monotonic() # video starts recording with the page
page.goto(URL, wait_until="networkidle")
page.evaluate(f"() => {{ document.body.style.zoom = {ZOOM} }}")
ids = page.evaluate(PRELOAD_JS)
assert len(ids) == N_ITEMS, ids
page.evaluate(CURSOR_JS)

# Frame just the stage (the app picker + animated browser, not the
# section title/subtitle); scrolling it into view starts the autoplay.
page.evaluate(
"() => scrollTo(0, document.getElementById('stage')"
".getBoundingClientRect().top + scrollY - 12)"
)
page.wait_for_timeout(800)
# trim the pre-scroll page top off the head of the video, keeping a
# short lead-in before the cursor starts moving
head = max(0.0, time.monotonic() - t0 - 0.3)
stage_box = page.locator("#stage").bounding_box()
# h264/yuv420p needs even dimensions
crop = [
2 * int(stage_box["x"] // 2),
2 * int(stage_box["y"] // 2),
2 * int(stage_box["width"] // 2),
2 * int(stage_box["height"] // 2),
]

items = page.locator("#picker li")
centers = []
for i in range(N_ITEMS):
box = items.nth(i).bounding_box()
centers.append((box["x"] + box["width"] / 2, box["y"] + box["height"] / 2))

# Park the cursor above the first item, then glide in.
page.mouse.move(centers[0][0], centers[0][1] - 140 * ZOOM)
for i, (x, y) in enumerate(centers):
page.mouse.move(x, y, steps=25) # ~GLIDE_MS of mousemove events
items.nth(i).evaluate("(el) => el.click()")
# Don't outwait the last item's DUR or autoplay loops to item 0
page.wait_for_timeout(ITEM_MS if i < N_ITEMS - 1 else DUR_MS - 400)

context.close() # finalizes the .webm
browser.close()

webm = next(pathlib.Path(vdir).glob("*.webm"))
subprocess.run(
[
"ffmpeg", "-y", "-ss", f"{head:.2f}", "-i", str(webm),
"-vf", f"crop={crop[2]}:{crop[3]}:{crop[0]}:{crop[1]}",
"-an", "-c:v", "libx264", "-pix_fmt", "yuv420p",
"-crf", "21", "-preset", "slow", "-movflags", "+faststart",
str(OUT),
],
check=True,
)
print(f"wrote {OUT}")


if __name__ == "__main__":
main()
86 changes: 86 additions & 0 deletions content/blog/shinywidgets-1-0/_feature-src/capture_video.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""Record an animated version of feature.html for the post's hero video.

Writes PNG frames to /tmp/feature-frames/ at 2400x1350 (1200x675 @ 2x), then
prints the ffmpeg command to encode featured.mp4 with a seamless-loop
crossfade. The static featured.jpg comes from capture.py; this script injects
the tile drift at runtime so feature.html itself stays static.

Playwright's video recording caps at 800px and resizes the window in ways that
break this fixed-size card, so instead we seek the CSS animations to
deterministic timestamps and screenshot each frame.

Usage:

uv run --with playwright python capture_video.py
"""

import pathlib

from playwright.sync_api import sync_playwright

HERE = pathlib.Path(__file__).parent
SRC = (HERE / "feature.html").as_uri()
FRAMES = pathlib.Path("/tmp/feature-frames")

WIDTH, HEIGHT = 1200, 675
FPS = 24
# All columns share one drift period (phase-shifted for variety), so capturing
# exactly one period gives a pixel-perfect loop with no crossfade. 40s at
# 830px/period is a slow ~21px/s drift.
SECONDS = 40 # must equal the animation period passed to the page
OFFSET_MS = 0
# One set of 5 tiles + 5 gaps in feature.html's .col (5*150 + 5*16)
DRIFT_PX = 830

FRAMES.mkdir(exist_ok=True)

with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(
viewport={"width": WIDTH, "height": HEIGHT},
device_scale_factor=2,
)
page.goto(SRC)
page.evaluate("() => document.fonts.ready")
broken = page.evaluate(
"[...document.images].filter(i => !i.naturalWidth).map(i => i.src)"
)
if broken:
raise SystemExit(f"images not loaded: {broken}")

page.evaluate(
"""([driftPx, periodSeconds]) => {
const style = document.createElement('style');
style.textContent = `@keyframes sw-drift {
from { transform: translateY(0); }
to { transform: translateY(-${driftPx}px); }
}`;
document.head.appendChild(style);
document.querySelectorAll('.wall .col').forEach((col, i) => {
col.innerHTML += col.innerHTML; // repeat the set so the drift loops
col.style.animation = `sw-drift ${periodSeconds}s linear infinite`;
col.style.animationDelay = `-${(periodSeconds * i) / 3}s`;
if (i === 1) col.style.animationDirection = 'reverse';
});
document.getAnimations().forEach(a => a.pause());
}""",
[DRIFT_PX, SECONDS],
)

total = FPS * SECONDS
for i in range(total):
page.evaluate(
"(t) => document.getAnimations().forEach(a => { a.currentTime = t })",
OFFSET_MS + i * 1000 // FPS,
)
page.screenshot(path=str(FRAMES / f"{i:04d}.png"))
if (i + 1) % 100 == 0:
print(f"{i + 1}/{total}")
browser.close()

print(f"frames in {FRAMES}")
# 1280px is plenty for the hero banner (at most 384px tall, cropped), and keeps
# the 40s loop near 2 MB instead of ~7 MB at 1920px.
print("encode: ffmpeg -y -framerate 24 -i /tmp/feature-frames/%04d.png "
"-vf scale=1280:720:flags=lanczos -an -c:v libx264 -pix_fmt yuv420p "
"-crf 28 -preset slow -movflags +faststart featured.mp4")
Loading
Loading