AgentiaPT/vela-slides / skills/vela-slides
vela-slides
UnverifiedCreate presentation decks using the Vela engine. Compact DSL format — never verbose JSON. Also loads, extracts, and edits existing decks.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 6.5 KB |
| app/vela.jsx | other | 2.3 MB |
| examples/vela-demo.json | config | 87.0 KB |
| references/block-schema.md | markdown | 25.6 KB |
| references/design-patterns.md | markdown | 20.5 KB |
| references/formats.md | markdown | 4.6 KB |
| references/themes.md | markdown | 4.5 KB |
| scripts/_safe_term.py | script | 10.2 KB |
| scripts/assemble.py | script | 9.3 KB |
| scripts/validate.py | script | 16.7 KB |
| scripts/vela.py | script | 115.0 KB |
scripts/validate.py
View on GitHub#!/usr/bin/env python3
# © 2025-present Rui Quintino. Vela Slides — licensed under ELv2. See LICENSE.
"""
Vela Deck Validator
Checks deck JSON for common quality issues before assembly.
Usage:
python3 validate.py <deck.vela>
"""
import sys, json, os, re
# ── Terminal-output funnel ──────────────────────────────────────────────
# COMPLETE MEDIATION: every human-readable byte this script writes leaves
# through emit(), which applies the canonical encoder in _safe_term.py (read
# that module's header for the threat and the policy). Encoding at the SINK
# rather than at each call site is what makes the mediation total: a new print
# site cannot be added without either routing through emit() or failing the
# lint gate (tools/vela-dev/scripts/lint.py, check_terminal_sink_gate).
#
# NOT applied to file writes, and never to deck data on its way back into a
# deck — `deck extract-text` → `patch-text` is a round-trip edit that must stay
# lossless, so the encoder belongs on the display path only.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from _safe_term import term_text # noqa: E402
_write = print # the only builtin-print reference; everything else uses emit()
def emit(*parts, **kwargs):
"""Write to the terminal with deck-supplied control sequences neutralized."""
_write(*(term_text(p) if isinstance(p, str) else p for p in parts), **kwargs)
REQUIRED_SLIDE_KEYS = {"blocks", "duration"}
VALID_BLOCK_TYPES = {
"heading", "text", "bullets", "image", "code", "grid", "callout",
"metric", "quote", "badge", "icon", "icon-row", "flow", "table",
"progress", "steps", "tag-group", "timeline", "svg", "spacer", "divider",
"comparison", "funnel", "cycle", "number-row", "matrix", "checklist"
}
SIZE_TOKENS = {"xs", "sm", "md", "lg", "xl", "2xl", "3xl", "4xl"}
# Numeric slide-level layout fields: key -> (min, max, must_be_int).
# Mirrors SLIDE_NUMERIC_BOUNDS in src/parts/part-imports.jsx — the app coerces
# and clamps these at load, so flag bad values here rather than let a deck render
# with a value the author never wrote.
# imageCols - column count for a run of adjacent image blocks
# gap / splitGap - px gap between blocks / between columns
# contentFlex/imageFlex - flex-grow ratio of the two columns
SLIDE_NUMERIC_BOUNDS = {
"imageCols": (1, 6, True),
"gap": (0, 200, False),
"splitGap": (0, 200, False),
"contentFlex": (0.1, 20, False),
"imageFlex": (0.1, 20, False),
}
def check_slide_numerics(slide, loc, errors):
"""Type/range-check the numeric slide layout fields (see SLIDE_NUMERIC_BOUNDS)."""
for key, (lo, hi, must_int) in SLIDE_NUMERIC_BOUNDS.items():
if key not in slide:
continue
v = slide[key]
# bool is an int subclass in Python — reject it explicitly.
if isinstance(v, bool) or not isinstance(v, (int, float)):
errors.append(f"{loc}: '{key}' must be a number (got {type(v).__name__})")
continue
if must_int and isinstance(v, float) and not v.is_integer():
errors.append(f"{loc}: '{key}' must be a whole number (got {v})")
continue
if not (lo <= v <= hi):
errors.append(f"{loc}: '{key}' out of range — must be {lo}..{hi} (got {v})")
# Solid-color-only background fields. The app renders each of these through
# cssColor() (src/parts/part-imports.jsx), a fail-closed solid-color allowlist:
# a gradient value there is dropped and the element falls back to its default
# color. Only the slide has a gradient field (`bgGradient`, via cssGradient()).
# Flag the mistake here so the author sees it before the deck renders wrong.
SOLID_BG_KEYS = ("bg", "iconBg", "headerBg")
_GRADIENT_TOKEN = re.compile(r"gradient\s*\(", re.I)
def _is_gradient(v):
return isinstance(v, str) and bool(_GRADIENT_TOKEN.search(v))
def check_block_gradients(node, loc, errors, path=""):
"""Report a gradient in any solid-color-only bg field of a block tree."""
if isinstance(node, list):
for i, child in enumerate(node):
check_block_gradients(child, loc, errors, f"{path}[{i}]")
elif isinstance(node, dict):
for key, val in node.items():
here = f"{path}.{key}" if path else key
if key in SOLID_BG_KEYS and _is_gradient(val):
errors.append(
f"{loc}: '{here}' contains a CSS gradient — this field is "
f"solid-color only and the gradient is dropped (default "
f"color shows). Use a solid color here; put slide "
f"gradients in the slide's 'bgGradient'")
elif isinstance(val, (dict, list)):
check_block_gradients(val, loc, errors, here)
# Optional deck-level `session` { start, end } (epoch ms). Same rule as the app's
# sanitizeSession (part-imports.jsx): integers only (no bool/float/string),
# 2000-01-01 <= start, end <= 2100-01-01, 1 min <= end - start <= 24 h. A bad
# value is a WARNING, not an error: the app drops it fail-closed on load, and an
# error would block `ship`.
SESSION_EPOCH_MIN = 946684800000
SESSION_EPOCH_MAX = 4102444800000
def _check_session(deck, warnings):
if "session" not in deck:
return
v = deck["session"]
reason = None
if not isinstance(v, dict):
reason = "must be an object {start, end}"
elif type(v.get("start")) is not int or type(v.get("end")) is not int:
reason = "start and end must be whole-number epoch milliseconds"
elif not all(SESSION_EPOCH_MIN <= v[k] <= SESSION_EPOCH_MAX for k in ("start", "end")):
reason = "start or end out of range (years 2000-2100)"
elif v["end"] <= v["start"]:
reason = "end must be after start"
elif not (60000 <= v["end"] - v["start"] <= 86400000):
reason = "length must be 1 min to 24 h"
if reason:
warnings.append(f"session ignored by the app: {reason}")
def validate(path):
with open(path, 'r', encoding="utf-8") as f:
deck = json.load(f)
# Auto-expand compact/turbo format to full format before validating
if "S" in deck or isinstance(deck, list):
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, script_dir)
from vela import _load_full
deck = _load_full(path)
# Save expanded version back so assembly works
real_path = os.path.realpath(path)
if real_path != os.path.abspath(path):
emit(f"WARNING: refusing to write through symlink: {path}", file=sys.stderr)
else:
with open(real_path, 'w', encoding="utf-8") as f:
json.dump(deck, f, ensure_ascii=False)
except ImportError as e:
emit(f"WARNING: could not expand compact/turbo deck ({e}); "
f"validating the un-expanded form", file=sys.stderr)
errors = []
warnings = []
stats = {"slides": 0, "blocks": 0, "duration": 0, "block_types": {}}
if not deck.get("deckTitle"):
errors.append("Missing 'deckTitle' — every deck needs a title")
if isinstance(deck, dict):
_check_session(deck, warnings)
lanes = deck.get("lanes", [])
if not lanes:
errors.append("No lanes found in deck")
return errors, warnings, stats
for li, lane in enumerate(lanes):
for ii, item in enumerate(lane.get("items", [])):
slides = item.get("slides", [])
if not slides:
warnings.append(f"Lane '{lane.get('title','?')}' → Item '{item.get('title','?')}' has no slides")
for si, slide in enumerate(slides):
loc = f"L{li+1}/I{ii+1}/S{si+1}"
stats["slides"] += 1
# Duration check
dur = slide.get("duration")
if dur is None:
errors.append(f"{loc}: Missing 'duration'")
else:
stats["duration"] += dur
if dur < 10:
warnings.append(f"{loc}: Duration {dur}s seems too short")
if dur > 300:
warnings.append(f"{loc}: Duration {dur}s seems too long")
# Background check
if not slide.get("bg") and not slide.get("bgGradient"):
errors.append(f"{loc}: Missing 'bg' or 'bgGradient'")
if _is_gradient(slide.get("bg")):
errors.append(
f"{loc}: 'bg' contains a CSS gradient — 'bg' is "
f"solid-color only, so the slide shows the default "
f"background. Move the gradient to 'bgGradient'")
# Color check + contrast auto-fix
if not slide.get("color"):
warnings.append(f"{loc}: No 'color' set — will use default")
else:
# Auto-fix low contrast: light text on light bg or dark text on dark bg
bg_hex = slide.get("bg", "#0A0F1C")
color_hex = slide.get("color", "#E6F1FF")
if bg_hex and color_hex and bg_hex.startswith("#") and color_hex.startswith("#"):
try:
bg_r, bg_g, bg_b = [int(bg_hex.lstrip("#")[i:i+2], 16) for i in (0,2,4)]
fg_r, fg_g, fg_b = [int(color_hex.lstrip("#")[i:i+2], 16) for i in (0,2,4)]
bg_lum = 0.2126*(bg_r/255) + 0.7152*(bg_g/255) + 0.0722*(bg_b/255)
fg_lum = 0.2126*(fg_r/255) + 0.7152*(fg_g/255) + 0.0722*(fg_b/255)
# Both light or both dark = low contrast
if bg_lum > 0.5 and fg_lum > 0.5:
slide["color"] = "#1E293B"
warnings.append(f"{loc}: Auto-fixed light-on-light contrast (was {color_hex} on {bg_hex})")
elif bg_lum < 0.15 and fg_lum < 0.15:
slide["color"] = "#E6F1FF"
warnings.append(f"{loc}: Auto-fixed dark-on-dark contrast (was {color_hex} on {bg_hex})")
except (ValueError, IndexError):
pass
# Numeric layout fields (imageCols, gap, splitGap, flex ratios)
check_slide_numerics(slide, loc, errors)
# studyNotes (offline student content) check
sn = slide.get("studyNotes")
if sn is not None:
if not isinstance(sn, dict):
errors.append(f"{loc}: studyNotes must be an object")
else:
text = sn.get("text")
if not text or not isinstance(text, str):
errors.append(f"{loc}: studyNotes.text is required (non-empty string)")
elif len(text) > 4000:
errors.append(f"{loc}: studyNotes.text exceeds 4000 chars ({len(text)})")
elif len(text) > 2000:
warnings.append(f"{loc}: studyNotes.text > 2000 chars (consider trimming)")
if "diagram" in sn:
if not isinstance(sn["diagram"], str):
errors.append(f"{loc}: studyNotes.diagram must be a string")
elif len(sn["diagram"]) > 8000:
warnings.append(f"{loc}: studyNotes.diagram exceeds 8000 chars — will be truncated at sanitize")
if "questions" in sn:
if not isinstance(sn["questions"], list):
errors.append(f"{loc}: studyNotes.questions must be an array")
elif len(sn["questions"]) > 6:
warnings.append(f"{loc}: studyNotes.questions > 6 (will be truncated at render)")
if "glossary" in sn and not isinstance(sn["glossary"], dict):
errors.append(f"{loc}: studyNotes.glossary must be an object")
# Block checks
blocks = slide.get("blocks", [])
has_cols_content = slide.get("layout") == "cols" and (bool(slide.get("L")) or bool(slide.get("R")))
if not blocks and not has_cols_content:
warnings.append(f"{loc}: Empty blocks array")
# A run of adjacent image blocks renders as ONE grid, so it
# counts as one block for the overflow hint.
eff_blocks = 0
prev_img = False
for _b in blocks:
is_img = isinstance(_b, dict) and _b.get("type") == "image"
if not (is_img and prev_img):
eff_blocks += 1
prev_img = is_img
if eff_blocks > 7:
warnings.append(f"{loc}: {len(blocks)} blocks — may overflow (max 7 recommended)")
# story (present the slide's images one by one) — strict boolean
if "story" in slide and not isinstance(slide["story"], bool):
errors.append(f"{loc}: story must be a boolean (true or false)")
for bi, block in enumerate(blocks):
check_block_gradients(block, f"{loc}/B{bi+1}", errors)
stats["blocks"] += 1
bt = block.get("type", "unknown")
stats["block_types"][bt] = stats["block_types"].get(bt, 0) + 1
if bt not in VALID_BLOCK_TYPES:
errors.append(f"{loc}/B{bi+1}: Unknown block type '{bt}'. Valid: {', '.join(sorted(VALID_BLOCK_TYPES))}")
# Check grid items have blocks
if bt == "grid":
for gi, gitem in enumerate(block.get("items", [])):
if not gitem.get("blocks"):
errors.append(f"{loc}/B{bi+1}/Grid{gi+1}: Grid cell missing 'blocks'")
# Check checklist item labels (custom status text)
if bt == "checklist":
for ci, citem in enumerate(block.get("items", [])):
lb = citem.get("label") if isinstance(citem, dict) else None
if lb is not None and not isinstance(lb, str):
errors.append(f"{loc}/B{bi+1}/Item{ci+1}: checklist label must be a string")
elif isinstance(lb, str) and len(lb) > 200:
errors.append(f"{loc}/B{bi+1}/Item{ci+1}: checklist label exceeds 200 chars ({len(lb)})")
# Check flow items
if bt == "flow":
items = block.get("items", [])
if len(items) > 6:
warnings.append(f"{loc}/B{bi+1}: Flow has {len(items)} items — max 5-6 recommended")
# L/R blocks (cols layout)
for col_key in ("L", "R"):
for bi, block in enumerate(slide.get(col_key, [])):
check_block_gradients(block, f"{loc}/{col_key}{bi+1}", errors)
stats["blocks"] += 1
bt = block.get("type", "unknown")
stats["block_types"][bt] = stats["block_types"].get(bt, 0) + 1
if bt not in VALID_BLOCK_TYPES:
errors.append(f"{loc}/{col_key}{bi+1}: Unknown block type '{bt}'. Valid: {', '.join(sorted(VALID_BLOCK_TYPES))}")
# Quality audit
type_count = len(stats["block_types"])
if type_count < 4 and stats["slides"] > 5:
warnings.append(f"Low visual variety: only {type_count} block types used across {stats['slides']} slides")
bullet_heavy = stats["block_types"].get("bullets", 0)
if bullet_heavy > stats["slides"] * 0.5:
warnings.append(f"Bullet-heavy deck: {bullet_heavy} bullet blocks across {stats['slides']} slides")
return errors, warnings, stats
if __name__ == "__main__":
if len(sys.argv) < 2:
emit("Usage: python3 validate.py <deck.vela>", file=sys.stderr)
sys.exit(1)
errors, warnings, stats = validate(sys.argv[1])
emit(f"📊 Deck Stats: {stats['slides']} slides | {stats['blocks']} blocks | {stats['duration']//60}m {stats['duration']%60}s")
emit(f" Block types: {', '.join(f'{k}({v})' for k,v in sorted(stats['block_types'].items(), key=lambda x: -x[1]))}")
if warnings:
emit(f"\n⚠️ {len(warnings)} warnings:")
for w in warnings:
emit(f" • {w}")
if errors:
emit(f"\n❌ {len(errors)} errors:")
for e in errors:
emit(f" • {e}")
sys.exit(1)
else:
emit(f"\n✅ Deck is valid")
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| canvas-designanthropics/skillsCreate beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| docxanthropics/skillsUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include: any mention of 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| pdfanthropics/skillsUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| pptxanthropics/skillsUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |