Clone any viral video with AI agents. Not just a script, the whole workflow: swap the face, the words, the B-roll, ship 100 variants in one command, and get your 100M views.
TypeScript agentic-aiaiai-agentsai-videocompilerdslffmpeggenerative-aillmmarkup-languagemonorepoplugin-systemprogramming-languagetext-to-videotypescriptvideovideo-automationvideo-clonevideo-editingvideo-generation
feat(docs): polish interactive demo carousel
rpone4c31693979f9
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.tsindex 207b5836..e47bb6a8 100644--- a/docs/.vitepress/config.ts+++ b/docs/.vitepress/config.ts@@ -3,6 +3,7 @@ import { defineConfig } from "vitepress";export default defineConfig({title: "SVML",description: "Write the story. Compile the video.",+ appearance: "force-dark",cleanUrls: true,markdown: {languageAlias: {diff --git a/docs/.vitepress/theme/components/HeroStatement.vue b/docs/.vitepress/theme/components/HeroStatement.vueindex a612effa..62cfd1fb 100644--- a/docs/.vitepress/theme/components/HeroStatement.vue+++ b/docs/.vitepress/theme/components/HeroStatement.vue@@ -3,16 +3,40 @@ import { onBeforeUnmount, onMounted, ref } from "vue";const statements = [{- en: "A high-level video language for developers.",- zh: "面向开发者的高级视频语言。",+ enBefore: "A ",+ enConcept: "high-level video language",+ enConnector: " for ",+ enAudience: "developers",+ enAfter: ".",+ zhBefore: "面向",+ zhAudience: "开发者",+ zhConnector: "的",+ zhConcept: "高级视频语言",+ zhAfter: "。",},{- en: "An editing-free production system for creative teams.",- zh: "面向创意团队的免剪辑制作系统。",+ enBefore: "An ",+ enConcept: "editing-free production system",+ enConnector: " for ",+ enAudience: "creative teams",+ enAfter: ".",+ zhBefore: "面向",+ zhAudience: "创意团队",+ zhConnector: "的",+ zhConcept: "免剪辑制作系统",+ zhAfter: "。",},{- en: "A scalable marketing video engine for brands.",- zh: "面向品牌的可规模化营销视频引擎。",+ enBefore: "A ",+ enConcept: "scalable marketing video engine",+ enConnector: " for ",+ enAudience: "brands",+ enAfter: ".",+ zhBefore: "面向",+ zhAudience: "品牌",+ zhConnector: "的",+ zhConcept: "可规模化营销视频引擎",+ zhAfter: "。",},];@@ -37,7 +61,7 @@ onBeforeUnmount(() => {<div class="hero-statement-viewport hero-statement-viewport-en"><Transition name="hero-statement-swap"><p :key="activeIndex" class="hero-statement-en">- {{ statements[activeIndex].en }}+ <span class="hero-statement-line">{{ statements[activeIndex].enBefore }}{{ statements[activeIndex].enConcept }}{{ statements[activeIndex].enConnector }}<br><span class="hero-statement-accent">{{ statements[activeIndex].enAudience }}</span>{{ statements[activeIndex].enAfter }}</span></p></Transition></div>@@ -45,7 +69,7 @@ onBeforeUnmount(() => {<div class="hero-statement-viewport hero-statement-viewport-zh"><Transition name="hero-statement-swap"><p :key="activeIndex" class="hero-statement-zh">- {{ statements[activeIndex].zh }}+ <span class="hero-statement-line">{{ statements[activeIndex].zhBefore }}<span class="hero-statement-accent">{{ statements[activeIndex].zhAudience }}</span>{{ statements[activeIndex].zhConnector }}{{ statements[activeIndex].zhConcept }}{{ statements[activeIndex].zhAfter }}</span></p></Transition></div>diff --git a/docs/.vitepress/theme/components/SemanticVideoDemo.vue b/docs/.vitepress/theme/components/SemanticVideoDemo.vueindex fcbef4c5..5d1c98b5 100644--- a/docs/.vitepress/theme/components/SemanticVideoDemo.vue+++ b/docs/.vitepress/theme/components/SemanticVideoDemo.vue@@ -1,5 +1,6 @@<script setup lang="ts">import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";+import { goodBetterBestMedia, resolveDemoMedia } from "./demo-media";import {semanticVideoDemos,type DemoId,@@ -7,8 +8,17 @@ import {type DemoSourceLine,type WordCue,} from "./semantic-video-demos";--const props = defineProps<{ demo: DemoId }>();+import {+ buildFoldedSourceView,+ buildFullSourceView,+ type SourceDisplayEntry,+} from "./source-display";++const props = withDefaults(defineProps<{ demo: DemoId; active?: boolean; showHeading?: boolean }>(), {+ active: true,+ showHeading: true,+});+const emit = defineEmits<{ ended: [] }>();const config = semanticVideoDemos[props.demo];const sourceLines = config.lines;const sceneSelections = config.selections.filter((selection) => selection.layer === "scene");@@ -21,12 +31,7 @@ type RangeBounds = {depth: number;};-type DisplayLine = {- key: string;- kind: "line" | "fold" | "spacer";- index: number | null;- line: DemoSourceLine | null;-};+type DisplayLine = SourceDisplayEntry<DemoSourceLine>;const rawBounds = config.selections.map((selection) => ({id: selection.id,@@ -74,7 +79,10 @@ const activeSceneSelection = ref(sceneSelections[0]);const activeOverlaySelection = ref<DemoSelection | null>(null);const visibleLogoCount = ref(0);const audioEnabled = ref(false);+const sourceViewportRows = ref(27);+const sourceLineRows = ref<number[]>(sourceLines.map(() => 1));const codeScrollElement = ref<HTMLElement | null>(null);+const sourceMeasureElement = ref<HTMLElement | null>(null);const playheadElement = ref<HTMLElement | null>(null);const rangeCanvas = ref({ width: 0, height: 0 });const rangeGeometry = ref<Record<string, { path: string; depth: number }>>({});@@ -86,6 +94,7 @@ let previousTimestamp = 0;let programTime = 0;let playbackSceneIndex = -1;let playbackOverlayId: string | null = null;+let completedPass = false;function setBaseVideo(element: unknown, index: number) {if (element && typeof element === "object" && "currentTime" in element) {@@ -149,44 +158,25 @@ const bindingLine = computed(() => {return Math.min(sourceLines.length - 1, scriptEnd + 2);});-function windowAround(start: number, end: number, size: number) {- let first = Math.max(0, start - 2);- let last = Math.min(sourceLines.length - 1, end + 2);- while (last - first + 1 < size && (first > 0 || last < sourceLines.length - 1)) {- if (first > 0) first -= 1;- if (last - first + 1 < size && last < sourceLines.length - 1) last += 1;- }- if (last - first + 1 > size) {- const center = Math.max(start, Math.min(end, sourceWordLine.value));- first = Math.max(0, Math.min(sourceLines.length - size, center - Math.floor(size / 2)));- last = first + size - 1;- }- return Array.from({ length: last - first + 1 }, (_, offset) => first + offset);-}-const displayedLines = computed<DisplayLine[]>(() => {if (!sourceFollowEnabled.value) {- return sourceLines.map((line, index) => ({ key: `line-${index}`, kind: "line", index, line }));+ return buildFullSourceView(sourceLines);}- const outerBounds = rangeBounds.find((range) => range.id === activeSceneSelection.value.id);- const top = windowAround(outerBounds?.start ?? sourceWordLine.value, outerBounds?.end ?? sourceWordLine.value, 13);- const bottom = windowAround(bindingLine.value, bindingLine.value, 13);- const toDisplay = (indices: number[]) => indices.map((index) => ({- key: `line-${index}`,- kind: "line" as const,- index,- line: sourceLines[index],- }));- const topRows = toDisplay(top);- const bottomRows = toDisplay(bottom);- while (topRows.length < 13) topRows.unshift({ key: `top-space-${topRows.length}`, kind: "spacer", index: null, line: null });- while (bottomRows.length < 13) bottomRows.push({ key: `bottom-space-${bottomRows.length}`, kind: "spacer", index: null, line: null });- return [- ...topRows,- { key: `fold-${top.at(-1)}-${bottom[0]}`, kind: "fold", index: null, line: null },- ...bottomRows,- ];+ const sideRows = Math.max(3, Math.floor((sourceViewportRows.value - 1) / 2));+ const activeRanges = sourceSelections.value+ .map((selection) => rangeBounds.find((range) => range.id === selection.id))+ .filter((range): range is RangeBounds => range !== undefined)+ .sort((left, right) => left.depth - right.depth);++ return buildFoldedSourceView({+ lines: sourceLines,+ rowSpans: sourceLineRows.value,+ rowBudget: sideRows,+ topRanges: activeRanges,+ topFocus: sourceWordLine.value,+ bottomLine: bindingLine.value,+ });});function renderedLineHtml(index: number) {@@ -253,13 +243,13 @@ function updateRangeGeometry() {const offsetX = container.scrollLeft - containerRect.left;const offsetY = container.scrollTop - containerRect.top;const lineHeight = Number.parseFloat(getComputedStyle(startLine).lineHeight) || 26;- const blockPadding = 4;+ const blockPadding = 0;const startCenter = (startRect.top + startRect.bottom) / 2 + offsetY;const endCenter = (endRect.top + endRect.bottom) / 2 + offsetY;- const inlinePadding = 4;- const edgeOverhang = 4;- const startX = Math.max(4, Math.min(width - 4, startRect.left + offsetX - inlinePadding));- const endX = Math.max(4, Math.min(width - 4, endRect.right + offsetX + inlinePadding));+ const inlinePadding = 3;+ const edgeOverhang = 3;+ const startX = Math.max(3, Math.min(width - 3, startRect.left + offsetX - inlinePadding));+ const endX = Math.max(3, Math.min(width - 3, endRect.right + offsetX + inlinePadding));const left = 44 - edgeOverhang;const right = width - 12 + edgeOverhang;const top = startCenter - lineHeight / 2 - blockPadding;@@ -329,7 +319,7 @@ function syncBaseVideos(force = false) {return;}if (force || sceneChanged || Math.abs(video.currentTime - localTime) > .2) video.currentTime = localTime;- if (video.paused) void video.play().catch(() => undefined);+ if (props.active && video.paused) void video.play().catch(() => undefined);});playbackSceneIndex = activeIndex;}@@ -346,7 +336,7 @@ function syncOverlayVideos(force = false) {}const localTime = Math.max(0, programTime - selection.start);if (force || playbackOverlayId !== selection.id || Math.abs(video.currentTime - localTime) > .2) video.currentTime = localTime;- if (video.paused) void video.play().catch(() => undefined);+ if (props.active && video.paused) void video.play().catch(() => undefined);});playbackOverlayId = activeOverlaySelection.value?.id ?? null;}@@ -401,8 +391,26 @@ function clearInspection() {pinnedLoopSelection.value = null;}-function stopSourceFollow() {+function stopSourceFollow(event?: MouseEvent) {+ if (!sourceFollowEnabled.value) return;+ const container = codeScrollElement.value;+ const hoveredLine = event?.target instanceof Element && container+ ? event.target.closest<HTMLElement>("[data-source-line]")+ : null;+ const lineIndex = Number(hoveredLine?.dataset.sourceLine);+ const lineOffset = event && hoveredLine ? event.clientY - hoveredLine.getBoundingClientRect().top : 0;+ const targetTop = event && hoveredLine ? event.clientY - lineOffset : null;sourceFollowEnabled.value = false;+ if (!container || !Number.isInteger(lineIndex) || targetTop === null) return;+ void nextTick().then(() => {+ const expandedLine = container.querySelector<HTMLElement>(`[data-source-line="${lineIndex}"]`);+ if (!expandedLine) return;+ const previousBehavior = container.style.scrollBehavior;+ container.style.scrollBehavior = "auto";+ container.scrollTop += expandedLine.getBoundingClientRect().top - targetTop;+ container.style.scrollBehavior = previousBehavior;+ updateRangeGeometry();+ });}function resumeSourceFollow() {@@ -410,7 +418,34 @@ function resumeSourceFollow() {sourceFollowEnabled.value = true;}+function updateSourceViewportRows() {+ const container = codeScrollElement.value;+ if (!container) return;+ let rows = Math.max(7, Math.floor(container.clientHeight / 26));+ if (rows % 2 === 0) rows -= 1;+ if (sourceViewportRows.value !== rows) sourceViewportRows.value = rows;+ const padding = Math.max(0, (container.clientHeight - rows * 26) / 2);+ container.style.setProperty("--source-vertical-padding", `${padding}px`);++ const measuredRows = Array.from(+ sourceMeasureElement.value?.querySelectorAll<HTMLElement>("[data-measure-line]") ?? [],+ ).map((line) => Math.max(1, Math.ceil(line.getBoundingClientRect().height / 26)));+ const measurementChanged = measuredRows.length === sourceLines.length && measuredRows.some(+ (rowSpan, index) => rowSpan !== sourceLineRows.value[index],+ );+ if (measurementChanged) sourceLineRows.value = measuredRows;+}++function updateLayoutGeometry() {+ updateSourceViewportRows();+ updateRangeGeometry();+}+function renderFrame(timestamp: number) {+ if (!props.active) {+ animationFrame = 0;+ return;+ }if (!previousTimestamp) previousTimestamp = timestamp;const delta = Math.min(.05, (timestamp - previousTimestamp) / 1000);previousTimestamp = timestamp;@@ -425,6 +460,10 @@ function renderFrame(timestamp: number) {looped = true;}} else if (nextTime >= config.duration) {+ if (!completedPass) {+ completedPass = true;+ emit("ended");+ }nextTime = 0;looped = true;}@@ -436,43 +475,71 @@ function renderFrame(timestamp: number) {animationFrame = requestAnimationFrame(renderFrame);}+function stopPlayback() {+ cancelAnimationFrame(animationFrame);+ animationFrame = 0;+ previousTimestamp = 0;+ baseVideos.forEach((video) => video?.pause());+ overlayVideos.forEach((video) => video?.pause());+}++function startPlayback() {+ stopPlayback();+ programTime = 0;+ playbackSceneIndex = -1;+ playbackOverlayId = null;+ completedPass = false;+ pinnedSelection.value = null;+ pinnedLoopSelection.value = null;+ syncState(programTime, true);+ syncBaseVideos(true);+ syncOverlayVideos(true);+ animationFrame = requestAnimationFrame(renderFrame);+}+watch([() => displayedLines.value.map((entry) => entry.key).join("|"), sourceFollowEnabled, sourceSelections],- () => void nextTick().then(updateRangeGeometry),+ () => void nextTick().then(updateLayoutGeometry),+ { flush: "post" },+);++watch(+ () => props.active,+ (active) => {+ if (active) void nextTick().then(startPlayback);+ else stopPlayback();+ },{ flush: "post" },);onMounted(() => {window.addEventListener("pointerdown", enableAudio, { capture: true, once: true });window.addEventListener("keydown", enableAudio, { capture: true, once: true });- window.addEventListener("resize", updateRangeGeometry);+ window.addEventListener("resize", updateLayoutGeometry);if (navigator.userActivation?.hasBeenActive) enableAudio();void nextTick().then(() => {syncState(0, true);- syncBaseVideos(true);- updateRangeGeometry();+ if (props.active) startPlayback();+ updateLayoutGeometry();if (codeScrollElement.value) {- resizeObserver = new ResizeObserver(updateRangeGeometry);+ resizeObserver = new ResizeObserver(updateLayoutGeometry);resizeObserver.observe(codeScrollElement.value);}});- animationFrame = requestAnimationFrame(renderFrame);});onBeforeUnmount(() => {- cancelAnimationFrame(animationFrame);+ stopPlayback();window.removeEventListener("pointerdown", enableAudio, true);window.removeEventListener("keydown", enableAudio, true);- window.removeEventListener("resize", updateRangeGeometry);+ window.removeEventListener("resize", updateLayoutGeometry);resizeObserver?.disconnect();- baseVideos.forEach((video) => video?.pause());- overlayVideos.forEach((video) => video?.pause());});</script><template><section class="svml-demo semantic-video-demo" aria-label="SVML 交互式实时渲染预览">- <header class="demo-heading">+ <header v-if="props.showHeading" class="demo-heading"><h2>悬停标记范围,查看对应画面</h2></header>@@ -480,12 +547,22 @@ onBeforeUnmount(() => {<divclass="source-panel":class="{ 'source-following': sourceFollowEnabled }"- @pointerenter="stopSourceFollow"@pointermove="stopSourceFollow"@pointerdown="stopSourceFollow"@wheel="stopSourceFollow"@pointerleave="resumeSourceFollow"- >+ >+ <div ref="sourceMeasureElement" class="source-measure" aria-hidden="true">+ <div+ v-for="(html, index) in decoratedLines"+ :key="index"+ class="code-line"+ :data-measure-line="index"+ >+ <span class="line-number">{{ index + 1 }}</span>+ <code v-html="html || ' '" />+ </div>+ </div><div class="source-follow-hint">{{ sourceFollowEnabled ? "移入查看所有源码" : "移出查看精简视图" }}</div>@@ -506,11 +583,16 @@ onBeforeUnmount(() => {/></svg><template v-for="entry in displayedLines" :key="entry.key">- <div v-if="entry.kind === 'fold'" class="code-line code-fold" aria-hidden="true"><code>···</code></div>- <div v-else-if="entry.kind === 'spacer'" class="code-line code-spacer" aria-hidden="true"></div>+ <div+ v-if="entry.kind === 'fold'"+ class="code-line code-fold"+ :data-source-line="entry.index"+ aria-hidden="true"+ ><code>···</code></div><divv-else-if="entry.line"class="code-line"+ :data-source-line="entry.index":class="{'binding-active': bindingDepth(entry.line) >= 0,'binding-depth-1': bindingDepth(entry.line) === 1,@@ -538,10 +620,10 @@ onBeforeUnmount(() => {:key="scene.src":ref="(element) => setBaseVideo(element, index)":class="{ active: currentSceneIndex === index }"- :src="scene.src"+ :src="resolveDemoMedia(scene.src)":muted="!audioEnabled || currentSceneIndex !== index"playsinline- preload="metadata"+ preload="auto"@loadedmetadata="syncBaseVideos(true)"/></div>@@ -553,10 +635,10 @@ onBeforeUnmount(() => {:ref="(element) => setOverlayVideo(element, index)"class="street-broll":class="{ active: activeOverlaySelection?.id === selection.id }"- :src="selection.asset"+ :src="resolveDemoMedia(selection.asset!)"mutedplaysinline- preload="metadata"+ preload="auto"/><div class="visual-outline street-scene-outline"></div><div v-if="activeOverlaySelection" class="visual-outline street-broll-outline"></div>@@ -566,15 +648,15 @@ onBeforeUnmount(() => {<div class="gbb-header"><divv-for="(item, index) in [- { id: 'good', label: 'GOOD', src: '/good-better-best/logo-chatgpt.png' },- { id: 'better', label: 'BETTER', src: '/good-better-best/logo-looksmax.png' },- { id: 'best', label: 'BEST', src: '/good-better-best/logo-areum.png' },+ { id: 'good', label: 'GOOD', src: goodBetterBestMedia.logos[0] },+ { id: 'better', label: 'BETTER', src: goodBetterBestMedia.logos[1] },+ { id: 'best', label: 'BEST', src: goodBetterBestMedia.logos[2] },]":key="item.id"class="gbb-slot":class="[{ visible: visibleLogoCount > index, selected: sourceSelections.some((selection) => selection.id === item.id) }, `slot-${item.id}`]">- <img :src="item.src" alt="">+ <img :src="resolveDemoMedia(item.src)" alt=""><strong>{{ item.label }}</strong></div></div>@@ -582,7 +664,7 @@ onBeforeUnmount(() => {v-if="activeOverlaySelection"class="gbb-deck":class="{ selected: sourceSelections.some((selection) => selection.id === activeOverlaySelection?.id) }"- :src="activeOverlaySelection.asset"+ :src="resolveDemoMedia(activeOverlaySelection.asset!)"alt=""></template>@@ -611,7 +693,13 @@ onBeforeUnmount(() => {<div class="real-semantic-controls"><div class="semantic-timeline"><div class="timeline-track demo-progress-track">- <span class="segment"></span>+ <span+ v-for="selection in sceneSelections"+ :key="selection.id"+ class="segment"+ :class="{ active: activeSceneSelection.id === selection.id }"+ :style="{ flexGrow: selection.end - selection.start }"+ ></span><i ref="playheadElement" class="playhead"></i></div></div>@@ -646,8 +734,9 @@ onBeforeUnmount(() => {.caption-good-better-best { top: 65%; }.demo-caption span { display: inline-block; transition: color .08s linear, transform .08s linear; }.demo-caption span.active { color: #ffd34d; transform: scale(1.08); }-.demo-progress-track { display: block; background: #303731; }-.demo-progress-track .segment { display: block; width: 100%; height: 100%; background: #ec4899; opacity: .5; }+.demo-progress-track { display: flex; grid-template-columns: none; gap: 2px; background: transparent; }+.demo-progress-track .segment { min-width: 0; height: 100%; flex-basis: 0; border-radius: 2px; background: rgba(236,72,153,.32); transition: background-color .2s ease; }+.demo-progress-track .segment.active { background: rgba(236,72,153,.76); }@media (max-width: 900px) {.semantic-live-stage { height: 520px; }diff --git a/docs/.vitepress/theme/components/SvmlDemoCarousel.vue b/docs/.vitepress/theme/components/SvmlDemoCarousel.vueindex e43720be..d63485e3 100644--- a/docs/.vitepress/theme/components/SvmlDemoCarousel.vue+++ b/docs/.vitepress/theme/components/SvmlDemoCarousel.vue@@ -1,27 +1,161 @@<script setup lang="ts">-import { computed, ref } from "vue";+import { computed, onBeforeUnmount, onMounted, ref } from "vue";+import {+ demoMediaManifests,+ preloadDemoMedia,+ type DemoMediaManifest,+} from "./demo-media";import SemanticVideoDemo from "./SemanticVideoDemo.vue";import SvmlPlayground from "./SvmlPlayground.vue";-const activeIndex = ref(0);-const demos = [SvmlPlayground, SemanticVideoDemo, SemanticVideoDemo];-const props = [undefined, { demo: "street" as const }, { demo: "good-better-best" as const }];-const activeComponent = computed(() => demos[activeIndex.value]);-const activeProps = computed(() => props[activeIndex.value]);+const cards = [+ { component: SvmlPlayground, props: undefined, label: "AI 图片应用排名" },+ { component: SemanticVideoDemo, props: { demo: "street" as const }, label: "街头采访" },+ { component: SemanticVideoDemo, props: { demo: "good-better-best" as const }, label: "Good Better Best" },+];+const selectedIndex = ref(0);+const playingIndex = ref<number | null>(null);+const loadedIndices = ref<Set<number>>(new Set());+const manifestPromises = new Map<number, Promise<void>>();+let activationId = 0;+let backgroundPreloadStarted = false;++const isLoading = computed(() => !loadedIndices.value.has(selectedIndex.value));++function loadManifest(manifest: DemoMediaManifest) {+ const assets = [+ ...manifest.images.map((source) => preloadDemoMedia(source, "image")),+ ...manifest.videos.map((source) => preloadDemoMedia(source, "video")),+ ];++ return Promise.allSettled(assets).then((results) => {+ const failures = results.filter((result) => result.status === "rejected");+ if (failures.length) {+ console.warn(`SVML demo mounted with ${failures.length} media preload failure(s).`, failures);+ }+ });+}++function preloadDemo(index: number) {+ const existing = manifestPromises.get(index);+ if (existing) return existing;++ const promise = loadManifest(demoMediaManifests[index]).then(() => {+ loadedIndices.value = new Set([...loadedIndices.value, index]);+ });+ manifestPromises.set(index, promise);+ return promise;+}++async function preloadRemainingDemos(initialIndex: number) {+ for (let offset = 1; offset < cards.length; offset += 1) {+ await preloadDemo((initialIndex + offset) % cards.length);+ }+}++function transitionDelay(immediate: boolean) {+ if (immediate || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {+ return Promise.resolve();+ }+ return new Promise<void>((resolve) => window.setTimeout(resolve, 850));+}++async function activateDemo(index: number, immediate = false) {+ if (!immediate && index === selectedIndex.value && playingIndex.value === index) return;++ selectedIndex.value = index;+ playingIndex.value = null;+ const currentActivation = ++activationId;++ await Promise.all([preloadDemo(index), transitionDelay(immediate)]);+ if (currentActivation !== activationId) return;++ playingIndex.value = index;+ if (!backgroundPreloadStarted) {+ backgroundPreloadStarted = true;+ window.setTimeout(() => void preloadRemainingDemos(index), 0);+ }+}++function cardPosition(index: number) {+ const offset = (index - selectedIndex.value + cards.length) % cards.length;+ if (offset === 0) return "is-center";+ if (offset === 1) return "is-right";+ return "is-left";+}function move(direction: number) {- activeIndex.value = (activeIndex.value + direction + demos.length) % demos.length;+ const nextIndex = (selectedIndex.value + direction + cards.length) % cards.length;+ void activateDemo(nextIndex);+}++function handleEnded(index: number) {+ if (playingIndex.value !== index) return;+ move(1);}++onMounted(() => void activateDemo(0, true));+onBeforeUnmount(() => { activationId += 1; });</script><template>- <div class="svml-demo-carousel">- <component :is="activeComponent" :key="activeIndex" v-bind="activeProps" />+ <div class="svml-demo-carousel" :aria-busy="isLoading">+ <header class="demo-heading carousel-heading">+ <h2>悬停标记范围,查看对应画面</h2>+ </header>++ <div class="demo-carousel-stage">+ <article+ v-for="(card, index) in cards"+ :key="card.label"+ class="demo-card"+ :class="cardPosition(index)"+ :aria-hidden="index !== selectedIndex"+ >+ <button+ v-if="index !== selectedIndex"+ class="demo-card-select"+ type="button"+ :aria-label="`查看${card.label}演示`"+ @click="activateDemo(index)"+ ></button>++ <div v-if="!loadedIndices.has(index)" class="demo-loading" role="status" aria-live="polite">+ <span class="demo-loading-spinner" aria-hidden="true"></span>+ <span>加载演示素材…</span>+ </div>+ <div+ v-else+ class="demo-card-content"+ :inert="index !== selectedIndex ? '' : undefined"+ >+ <component+ :is="card.component"+ v-bind="card.props"+ :active="playingIndex === index"+ :show-heading="false"+ @ended="handleEnded(index)"+ />+ </div>+ </article>+ </div>+<nav class="demo-carousel-controls" aria-label="切换示例">- <button type="button" aria-label="上一个示例" @click="move(-1)">+ <button class="arrow-button" type="button" aria-label="上一个示例" @click="move(-1)"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M14.7 5.3 8 12l6.7 6.7 1.4-1.4-5.3-5.3 5.3-5.3z"/></svg></button>- <button type="button" aria-label="下一个示例" @click="move(1)">+ <div class="demo-carousel-dots" aria-label="选择示例">+ <button+ v-for="(card, index) in cards"+ :key="card.label"+ type="button"+ :class="{ active: index === selectedIndex }"+ :aria-label="`查看${card.label}演示`"+ :aria-current="index === selectedIndex ? 'true' : undefined"+ @click="activateDemo(index)"+ ></button>+ </div>+ <button class="arrow-button" type="button" aria-label="下一个示例" @click="move(1)"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="m9.3 5.3-1.4 1.4 5.3 5.3-5.3 5.3 1.4 1.4L16 12z"/></svg></button></nav>@@ -29,9 +163,46 @@ function move(direction: number) {</template><style scoped>-.demo-carousel-controls { display: flex; justify-content: center; gap: 14px; padding: 20px 0 2px; }-.demo-carousel-controls button { display: grid; place-items: center; width: 42px; height: 42px; padding: 0; border: 1px solid #262626; border-radius: 50%; background: #111; color: #f5f5f5; cursor: pointer; transition: border-color .18s ease, background-color .18s ease, transform .18s ease; }-.demo-carousel-controls button:hover { border-color: rgba(236,72,153,.72); background: #262626; transform: translateY(-1px); }+.svml-demo-carousel { width: 100%; }+.demo-carousel-stage { display: grid; width: 100%; overflow: hidden; perspective: 1600px; }+.carousel-heading { width: calc(100% - 64px); margin-inline: auto; }+.demo-card { position: relative; grid-area: 1 / 1; justify-self: center; width: calc(100% - 64px); overflow: hidden; border-radius: 16px; transform-origin: center center; will-change: transform, opacity, filter; transition: transform 850ms cubic-bezier(.16,1,.3,1), opacity 650ms cubic-bezier(.16,1,.3,1), filter 650ms cubic-bezier(.16,1,.3,1); }+.demo-card.is-center { z-index: 3; opacity: 1; filter: brightness(1); transform: translateX(0) scale(1); }+.demo-card.is-left { z-index: 1; opacity: .56; filter: brightness(.58) saturate(.75); transform: translateX(calc(-100% + 58px)) scale(.955); }+.demo-card.is-right { z-index: 1; opacity: .56; filter: brightness(.58) saturate(.75); transform: translateX(calc(100% - 58px)) scale(.955); }+.demo-card-select { position: absolute; z-index: 10; inset: 0; width: 100%; height: 100%; border: 0; background: transparent; cursor: pointer; }+.demo-card-select:focus-visible { outline: 2px solid #ec4899; outline-offset: -5px; border-radius: 16px; }+.demo-card-content { min-width: 0; }+.demo-card-content :deep(.svml-demo) { margin-top: 0; }+.demo-card-content :deep(.demo-shell) { box-shadow: 0 28px 70px rgba(0,0,0,.34); }+.demo-loading { display: grid; place-content: center; justify-items: center; gap: 14px; min-height: 720px; border: 1px solid #262626; border-radius: 16px; background: #0a0a0a; color: #a3a3a3; font-family: var(--vp-font-family-mono); font-size: 12px; letter-spacing: .02em; }+.demo-loading-spinner { width: 30px; height: 30px; border: 2px solid rgba(255,255,255,.14); border-top-color: #ec4899; border-radius: 50%; animation: demo-loading-spin .7s linear infinite; }+.demo-carousel-controls { display: flex; align-items: center; justify-content: center; gap: 16px; padding: 22px 0 2px; }+.demo-carousel-controls button { padding: 0; cursor: pointer; }+.arrow-button { display: grid; place-items: center; width: 42px; height: 42px; border: 1px solid #262626; border-radius: 50%; background: #111; color: #f5f5f5; transition: border-color .18s ease, background-color .18s ease, transform .18s ease; }+.arrow-button:hover { border-color: rgba(236,72,153,.72); background: #262626; transform: translateY(-1px); }.demo-carousel-controls button:focus-visible { outline: 2px solid #ec4899; outline-offset: 3px; }-.demo-carousel-controls svg { width: 21px; height: 21px; fill: currentColor; }+.arrow-button svg { width: 21px; height: 21px; fill: currentColor; }+.demo-carousel-dots { display: flex; align-items: center; gap: 8px; }+.demo-carousel-dots button { width: 7px; height: 7px; border: 0; border-radius: 999px; background: #4a4a4a; transition: width 450ms cubic-bezier(.16,1,.3,1), background-color 250ms ease; }+.demo-carousel-dots button.active { width: 24px; background: #ec4899; }++@keyframes demo-loading-spin { to { transform: rotate(360deg); } }++@media (max-width: 900px) {+ .carousel-heading, .demo-card { width: calc(100% - 40px); }+ .demo-card.is-left { transform: translateX(calc(-100% + 34px)) scale(.97); }+ .demo-card.is-right { transform: translateX(calc(100% - 34px)) scale(.97); }+ .demo-loading { min-height: 990px; }+}++@media (max-width: 520px) {+ .carousel-heading, .demo-card { width: calc(100% - 20px); }+ .demo-card.is-left { transform: translateX(calc(-100% + 20px)) scale(.98); }+ .demo-card.is-right { transform: translateX(calc(100% - 20px)) scale(.98); }+}++@media (prefers-reduced-motion: reduce) {+ .demo-card { transition-duration: .01ms; }+}</style>diff --git a/docs/.vitepress/theme/components/SvmlPlayground.vue b/docs/.vitepress/theme/components/SvmlPlayground.vueindex 3656db25..29ee53a1 100644--- a/docs/.vitepress/theme/components/SvmlPlayground.vue+++ b/docs/.vitepress/theme/components/SvmlPlayground.vue@@ -1,6 +1,18 @@<script setup lang="ts">import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";+import { rankingMedia, resolveDemoMedia } from "./demo-media";import { wordCues, type WordCue } from "./regen-ranking-cues";+import {+ buildFoldedSourceView,+ buildFullSourceView,+ type SourceDisplayEntry,+} from "./source-display";++const props = withDefaults(defineProps<{ active?: boolean; showHeading?: boolean }>(), {+ active: true,+ showHeading: true,+});+const emit = defineEmits<{ ended: [] }>();type RankingSelectionId = "photoshop" | "facetune" | "remini" | "chatgpt" | "regen";type BrollSelectionId = "handsome-1" | "handsome-2" | "dating-photo" | "linkedin-headshot" | "instagram-post";@@ -45,37 +57,32 @@ type SourceLine = {tokens?: readonly [number, number];};-type DisplayedSourceLine = {- key: string;- kind: "line" | "fold" | "spacer";- index: number | null;- line: SourceLine | null;-};+type DisplayedSourceLine = SourceDisplayEntry<SourceLine>;const TOTAL_DURATION = 36.1;const ENTER_DURATION = .45;const MOVE_DURATION = .55;const selections: RankingSelection[] = [- { id: "photoshop", label: "Photoshop", rank: 5, start: .08, end: 6.4, color: "#31add0", icon: "/regen-ranking/ranking-icon-5.jpg" },- { id: "facetune", label: "Facetune", rank: 4, start: 6.4, end: 12, color: "rgb(132, 198, 84)", icon: "/regen-ranking/ranking-icon-4.jpg" },- { id: "remini", label: "Remini", rank: 3, start: 12.043333333333333, end: 18.184444444444445, color: "rgb(234, 220, 42)", icon: "/regen-ranking/ranking-icon-3.jpg" },- { id: "chatgpt", label: "ChatGPT", rank: 2, start: 18.184444444444445, end: 24.066666666666666, color: "rgb(255, 167, 45)", icon: "/regen-ranking/ranking-icon-2.jpg" },- { id: "regen", label: "ReGen", rank: 1, start: 24.076666666666668, end: 36.06666666666666, color: "#ff3f56", icon: "/regen-ranking/ranking-icon-1.jpg" },+ { id: "photoshop", label: "Photoshop", rank: 5, start: .08, end: 6.4, color: "#31add0", icon: rankingMedia.icons[4] },+ { id: "facetune", label: "Facetune", rank: 4, start: 6.4, end: 12, color: "rgb(132, 198, 84)", icon: rankingMedia.icons[3] },+ { id: "remini", label: "Remini", rank: 3, start: 12.043333333333333, end: 18.184444444444445, color: "rgb(234, 220, 42)", icon: rankingMedia.icons[2] },+ { id: "chatgpt", label: "ChatGPT", rank: 2, start: 18.184444444444445, end: 24.066666666666666, color: "rgb(255, 167, 45)", icon: rankingMedia.icons[1] },+ { id: "regen", label: "ReGen", rank: 1, start: 24.076666666666668, end: 36.06666666666666, color: "#ff3f56", icon: rankingMedia.icons[0] },];const baseScenes: BaseScene[] = [- { src: "/regen-ranking/avatar-1.mp4", start: 0, end: 12.033333333333333 },- { src: "/regen-ranking/avatar-2.mp4", start: 12.033333333333333, end: 24.066666666666666 },- { src: "/regen-ranking/avatar-3.mp4", start: 24.066666666666666, end: 36.1 },+ { src: rankingMedia.avatars[0], start: 0, end: 12.033333333333333 },+ { src: rankingMedia.avatars[1], start: 12.033333333333333, end: 24.066666666666666 },+ { src: rankingMedia.avatars[2], start: 24.066666666666666, end: 36.1 },];const brollItems: BrollItem[] = [- { id: "handsome-1", src: "/regen-ranking/broll-5.png", start: 791 / 30, end: 831 / 30, zoom: 1.02 },- { id: "handsome-2", src: "/regen-ranking/broll-4.png", start: 831 / 30, end: 888 / 30, zoom: 1.03 },- { id: "dating-photo", src: "/regen-ranking/broll-3.png", start: 925 / 30, end: 952 / 30, zoom: 1.02 },- { id: "linkedin-headshot", src: "/regen-ranking/broll-2.png", start: 952 / 30, end: 977 / 30, zoom: 1.03 },- { id: "instagram-post", src: "/regen-ranking/broll-1.png", start: 977 / 30, end: 1009 / 30, zoom: 1.02 },+ { id: "handsome-1", src: rankingMedia.broll[4], start: 791 / 30, end: 831 / 30, zoom: 1.02 },+ { id: "handsome-2", src: rankingMedia.broll[3], start: 831 / 30, end: 888 / 30, zoom: 1.03 },+ { id: "dating-photo", src: rankingMedia.broll[2], start: 925 / 30, end: 952 / 30, zoom: 1.02 },+ { id: "linkedin-headshot", src: rankingMedia.broll[1], start: 952 / 30, end: 977 / 30, zoom: 1.03 },+ { id: "instagram-post", src: rankingMedia.broll[0], start: 977 / 30, end: 1009 / 30, zoom: 1.02 },];const semanticSelections: TimelineSelection[] = [...selections, ...brollItems];@@ -207,6 +214,7 @@ let animationFrame = 0;let previousTimestamp = 0;let programTime = 0;let playbackSceneIndex = -1;+let completedPass = false;const automaticScriptLineIndex = computed(() => {const wordIndex = activeWord.value?.index;@@ -232,83 +240,23 @@ const automaticBindingLineIndex = computed(() => {const displayedLines = computed<DisplayedSourceLine[]>(() => {if (!sourceFollowEnabled.value) {- return lines.map((line, index) => ({ key: `line-${index}`, kind: "line", index, line }));+ return buildFullSourceView(lines);}- const outerRange = semanticRangeBounds.find((range) => range.id === activeRankingSelection.value.id);const sideRows = Math.max(3, Math.floor((sourceViewportRows.value - 1) / 2));- const rangeStart = outerRange?.start ?? automaticScriptLineIndex.value;- const rangeEnd = outerRange?.end ?? automaticScriptLineIndex.value;- const rowSpan = (index: number) => sourceLineRows.value[index] ?? 1;- const spanOf = (indices: number[]) => indices.reduce((sum, index) => sum + rowSpan(index), 0);-- const bottomIndices = [automaticBindingLineIndex.value];- let bottomBefore = automaticBindingLineIndex.value - 1;- let bottomAfter = automaticBindingLineIndex.value + 1;- for (let context = 0; context < 3 && bottomBefore >= 0; context += 1) {- if (spanOf(bottomIndices) + rowSpan(bottomBefore) > sideRows) break;- bottomIndices.unshift(bottomBefore);- bottomBefore -= 1;- }- while (spanOf(bottomIndices) < sideRows && (bottomAfter < lines.length || bottomBefore >= 0)) {- if (bottomAfter < lines.length && spanOf(bottomIndices) + rowSpan(bottomAfter) <= sideRows) {- bottomIndices.push(bottomAfter);- bottomAfter += 1;- continue;- }- if (bottomBefore >= 0 && spanOf(bottomIndices) + rowSpan(bottomBefore) <= sideRows) {- bottomIndices.unshift(bottomBefore);- bottomBefore -= 1;- continue;- }- break;- }-- const maximumTopIndex = Math.max(rangeEnd, (bottomIndices[0] ?? lines.length) - 2);- const topIndices = Array.from({ length: rangeEnd - rangeStart + 1 }, (_, offset) => rangeStart + offset);- let topBefore = rangeStart - 1;- let topAfter = rangeEnd + 1;- for (let context = 0; context < 3 && topAfter <= maximumTopIndex; context += 1) {- if (spanOf(topIndices) + rowSpan(topAfter) > sideRows) break;- topIndices.push(topAfter);- topAfter += 1;- }- while (spanOf(topIndices) < sideRows && (topBefore >= 0 || topAfter <= maximumTopIndex)) {- if (topBefore >= 0 && spanOf(topIndices) + rowSpan(topBefore) <= sideRows) {- topIndices.unshift(topBefore);- topBefore -= 1;- continue;- }- if (topAfter <= maximumTopIndex && spanOf(topIndices) + rowSpan(topAfter) <= sideRows) {- topIndices.push(topAfter);- topAfter += 1;- continue;- }- break;- }-- const topSpacerRows = Math.max(0, sideRows - spanOf(topIndices));- const bottomSpacerRows = Math.max(0, sideRows - spanOf(bottomIndices));- const topSpacers = Array.from({ length: topSpacerRows }, (_, index) => ({- key: `top-spacer-${index}`,- kind: "spacer" as const,- index: null,- line: null,- }));- const bottomSpacers = Array.from({ length: bottomSpacerRows }, (_, index) => ({- key: `bottom-spacer-${index}`,- kind: "spacer" as const,- index: null,- line: null,- }));-- return [- ...topSpacers,- ...topIndices.map((index) => ({ key: `line-${index}`, kind: "line" as const, index, line: lines[index] })),- { key: `fold-${topIndices.at(-1)}-${bottomIndices[0]}`, kind: "fold", index: null, line: null },- ...bottomIndices.map((index) => ({ key: `line-${index}`, kind: "line" as const, index, line: lines[index] })),- ...bottomSpacers,- ];+ const activeRanges = activeSourceSelections.value+ .map((selection) => semanticRangeBounds.find((range) => range.id === selection.id))+ .filter((range): range is SemanticRangeBounds => range !== undefined)+ .sort((left, right) => left.depth - right.depth);++ return buildFoldedSourceView({+ lines,+ rowSpans: sourceLineRows.value,+ rowBudget: sideRows,+ topRanges: activeRanges,+ topFocus: automaticScriptLineIndex.value,+ bottomLine: automaticBindingLineIndex.value,+ });});function wordAt(time: number): WordCue | null {@@ -404,14 +352,14 @@ function updateRangeGeometry() {const endRect = endMarker.getBoundingClientRect();const offsetX = container.scrollLeft - containerRect.left;const offsetY = container.scrollTop - containerRect.top;- const inlinePadding = 4;- const edgeOverhang = 4;+ const inlinePadding = 3;+ const edgeOverhang = 3;const left = 44 - edgeOverhang;const right = width - 12 + edgeOverhang;- const startX = Math.max(4, Math.min(width - 4, startRect.left + offsetX - inlinePadding));- const endX = Math.max(4, Math.min(width - 4, endRect.right + offsetX + inlinePadding));+ const startX = Math.max(3, Math.min(width - 3, startRect.left + offsetX - inlinePadding));+ const endX = Math.max(3, Math.min(width - 3, endRect.right + offsetX + inlinePadding));const lineHeight = Number.parseFloat(getComputedStyle(startLine).lineHeight) || 26;- const blockPadding = 4;+ const blockPadding = 0;const startCenter = (startRect.top + startRect.bottom) / 2 + offsetY;const endCenter = (endRect.top + endRect.bottom) / 2 + offsetY;const top = startCenter - lineHeight / 2 - blockPadding;@@ -616,7 +564,7 @@ function syncBaseVideos(force = false) {return;}if (force || sceneChanged) video.currentTime = localTime;- if (video.paused) void video.play().catch(() => undefined);+ if (props.active && video.paused) void video.play().catch(() => undefined);});playbackSceneIndex = activeIndex;}@@ -684,9 +632,26 @@ function clearInspection() {pinnedLoopSelection.value = null;}-function stopSourceFollow() {+function stopSourceFollow(event?: MouseEvent) {if (!sourceFollowEnabled.value) return;+ const container = codeScrollElement.value;+ const hoveredLine = event?.target instanceof Element && container+ ? event.target.closest<HTMLElement>("[data-source-line]")+ : null;+ const lineIndex = Number(hoveredLine?.dataset.sourceLine);+ const lineOffset = event && hoveredLine ? event.clientY - hoveredLine.getBoundingClientRect().top : 0;+ const targetTop = event && hoveredLine ? event.clientY - lineOffset : null;sourceFollowEnabled.value = false;+ if (!container || !Number.isInteger(lineIndex) || targetTop === null) return;+ void nextTick().then(() => {+ const expandedLine = container.querySelector<HTMLElement>(`[data-source-line="${lineIndex}"]`);+ if (!expandedLine) return;+ const previousBehavior = container.style.scrollBehavior;+ container.style.scrollBehavior = "auto";+ container.scrollTop += expandedLine.getBoundingClientRect().top - targetTop;+ container.style.scrollBehavior = previousBehavior;+ updateRangeGeometry();+ });}function resumeSourceFollow() {@@ -700,6 +665,10 @@ function handleDemoPointerMove(event: PointerEvent) {}function renderFrame(timestamp: number) {+ if (!props.active) {+ animationFrame = 0;+ return;+ }if (!previousTimestamp) previousTimestamp = timestamp;const delta = Math.min(.05, (timestamp - previousTimestamp) / 1000);previousTimestamp = timestamp;@@ -716,6 +685,10 @@ function renderFrame(timestamp: number) {looped = true;}} else if (nextTime >= TOTAL_DURATION) {+ if (!completedPass) {+ completedPass = true;+ emit("ended");+ }nextTime = 0;looped = true;}@@ -726,6 +699,26 @@ function renderFrame(timestamp: number) {animationFrame = requestAnimationFrame(renderFrame);}+function stopPlayback() {+ cancelAnimationFrame(animationFrame);+ animationFrame = 0;+ previousTimestamp = 0;+ baseVideos.forEach((video) => video?.pause());+}++function startPlayback() {+ stopPlayback();+ programTime = 0;+ playbackSceneIndex = -1;+ completedPass = false;+ pinnedSelection.value = null;+ pinnedLoopSelection.value = null;+ syncDiscreteState(programTime, true);+ syncBaseVideos(true);+ updateContinuousVisuals(programTime);+ animationFrame = requestAnimationFrame(renderFrame);+}+function updateSourceViewportRows() {const container = codeScrollElement.value;if (!container) return;@@ -761,6 +754,15 @@ watch({ flush: "post" },);+watch(+ () => props.active,+ (active) => {+ if (active) void nextTick().then(startPlayback);+ else stopPlayback();+ },+ { flush: "post" },+);+onMounted(() => {window.addEventListener("pointerdown", enableAudio, { capture: true, once: true });window.addEventListener("keydown", enableAudio, { capture: true, once: true });@@ -768,28 +770,26 @@ onMounted(() => {void nextTick().then(() => {updateLayoutGeometry();syncDiscreteState(programTime, true);- syncBaseVideos(true);+ if (props.active) startPlayback();if (codeScrollElement.value) {rangeResizeObserver = new ResizeObserver(updateLayoutGeometry);rangeResizeObserver.observe(codeScrollElement.value);}});window.addEventListener("resize", updateLayoutGeometry);- animationFrame = requestAnimationFrame(renderFrame);});onBeforeUnmount(() => {- cancelAnimationFrame(animationFrame);+ stopPlayback();window.removeEventListener("pointerdown", enableAudio, true);window.removeEventListener("keydown", enableAudio, true);window.removeEventListener("resize", updateLayoutGeometry);rangeResizeObserver?.disconnect();- baseVideos.forEach((video) => video?.pause());});</script><template><section class="svml-demo" aria-label="SVML 交互式实时渲染预览">- <header class="demo-heading">+ <header v-if="props.showHeading" class="demo-heading"><h2>悬停标记范围,查看对应画面</h2></header>@@ -801,7 +801,6 @@ onBeforeUnmount(() => {<divclass="source-panel":class="{ 'source-following': sourceFollowEnabled }"- @pointerenter="stopSourceFollow"@pointermove="stopSourceFollow"@pointerdown="stopSourceFollow"@wheel="stopSourceFollow"@@ -838,10 +837,14 @@ onBeforeUnmount(() => {/></svg><template v-for="entry in displayedLines" :key="entry.key">- <div v-if="entry.kind === 'fold'" class="code-line code-fold" aria-hidden="true">+ <div+ v-if="entry.kind === 'fold'"+ class="code-line code-fold"+ :data-source-line="entry.index"+ aria-hidden="true"+ ><code>···</code></div>- <div v-else-if="entry.kind === 'spacer'" class="code-line code-spacer" aria-hidden="true"></div><divv-else-if="entry.line"class="code-line"@@ -875,7 +878,7 @@ onBeforeUnmount(() => {:key="scene.src":ref="(element) => setBaseVideo(element, index)":class="{ active: currentSceneIndex === index }"- :src="scene.src"+ :src="resolveDemoMedia(scene.src)":muted="!audioEnabled || currentSceneIndex !== index"playsinlinepreload="auto"@@ -891,7 +894,7 @@ onBeforeUnmount(() => {<span :ref="(element) => setRankCell(element, rank)"><imgv-if="settledIds.has(runtimeItems[5 - rank].id)"- :src="runtimeItems[5 - rank].icon"+ :src="resolveDemoMedia(runtimeItems[5 - rank].icon)":alt="runtimeItems[5 - rank].label"></span>@@ -899,14 +902,14 @@ onBeforeUnmount(() => {</div><div v-if="activeRuntimeItem" ref="activeIconElement" class="live-active-icon">- <img :src="activeRuntimeItem.icon" :alt="activeRuntimeItem.label">+ <img :src="resolveDemoMedia(activeRuntimeItem.icon)" :alt="activeRuntimeItem.label"><i></i></div><imgv-if="activeBroll"class="live-broll"- :src="activeBroll.src"+ :src="resolveDemoMedia(activeBroll.src)"alt="":style="{ transform: `scale(${activeBroll.zoom})` }">diff --git a/docs/.vitepress/theme/components/demo-media.ts b/docs/.vitepress/theme/components/demo-media.tsnew file mode 100644index 00000000..3212ab33--- /dev/null+++ b/docs/.vitepress/theme/components/demo-media.ts@@ -0,0 +1,157 @@+export type DemoMediaManifest = {+ images: readonly string[];+ videos: readonly string[];+};++type DemoMediaKind = "image" | "video";++const resolvedMedia = new Map<string, string>();+const preloadPromises = new Map<string, Promise<void>>();++export function publicAsset(relativePath: string) {+ return `${import.meta.env.BASE_URL}${relativePath.replace(/^\/+/, "")}`;+}++export function resolveDemoMedia(source: string) {+ return resolvedMedia.get(source) ?? source;+}++function decodeImage(source: string) {+ return new Promise<void>((resolve, reject) => {+ const image = new Image();+ image.onload = async () => {+ try {+ await image.decode();+ resolve();+ } catch (error) {+ reject(error);+ }+ };+ image.onerror = () => reject(new Error(`Unable to decode image: ${source}`));+ image.src = source;+ });+}++function decodeVideo(source: string) {+ return new Promise<void>((resolve, reject) => {+ const video = document.createElement("video");+ const finish = (error?: Error) => {+ video.onloadeddata = null;+ video.onerror = null;+ video.removeAttribute("src");+ video.load();+ error ? reject(error) : resolve();+ };++ video.preload = "auto";+ video.muted = true;+ video.playsInline = true;+ video.onloadeddata = () => finish();+ video.onerror = () => finish(new Error(`Unable to decode video: ${source}`));+ video.src = source;+ video.load();+ });+}++export function preloadDemoMedia(source: string, kind: DemoMediaKind) {+ if (resolvedMedia.has(source)) return Promise.resolve();++ const existing = preloadPromises.get(source);+ if (existing) return existing;++ const promise = fetch(source, { cache: "force-cache" })+ .then((response) => {+ if (!response.ok) throw new Error(`Unable to preload ${source}: ${response.status}`);+ return response.blob();+ })+ .then(async (blob) => {+ const objectUrl = URL.createObjectURL(blob);+ try {+ await (kind === "image" ? decodeImage(objectUrl) : decodeVideo(objectUrl));+ resolvedMedia.set(source, objectUrl);+ } catch (error) {+ URL.revokeObjectURL(objectUrl);+ throw error;+ }+ })+ .catch((error) => {+ preloadPromises.delete(source);+ throw error;+ });++ preloadPromises.set(source, promise);+ return promise;+}++export const rankingMedia = {+ avatars: [+ publicAsset("regen-ranking/avatar-1.mp4"),+ publicAsset("regen-ranking/avatar-2.mp4"),+ publicAsset("regen-ranking/avatar-3.mp4"),+ ],+ icons: [+ publicAsset("regen-ranking/ranking-icon-1.jpg"),+ publicAsset("regen-ranking/ranking-icon-2.jpg"),+ publicAsset("regen-ranking/ranking-icon-3.jpg"),+ publicAsset("regen-ranking/ranking-icon-4.jpg"),+ publicAsset("regen-ranking/ranking-icon-5.jpg"),+ ],+ broll: [+ publicAsset("regen-ranking/broll-1.png"),+ publicAsset("regen-ranking/broll-2.png"),+ publicAsset("regen-ranking/broll-3.png"),+ publicAsset("regen-ranking/broll-4.png"),+ publicAsset("regen-ranking/broll-5.png"),+ ],+} as const;++export const streetMedia = {+ scenes: [+ publicAsset("street-interview/scene-1.mp4"),+ publicAsset("street-interview/scene-2.mp4"),+ publicAsset("street-interview/scene-3.mp4"),+ publicAsset("street-interview/scene-4.mp4"),+ ],+ broll: [+ publicAsset("street-interview/broll-2.mp4"),+ publicAsset("street-interview/broll-3.mp4"),+ publicAsset("street-interview/broll-4.mp4"),+ ],+} as const;++export const goodBetterBestMedia = {+ speakers: [+ publicAsset("good-better-best/speaker-hook.mp4"),+ publicAsset("good-better-best/speaker-1.mp4"),+ publicAsset("good-better-best/speaker-good.mp4"),+ publicAsset("good-better-best/speaker-2.mp4"),+ publicAsset("good-better-best/speaker-better.mp4"),+ publicAsset("good-better-best/speaker-3.mp4"),+ publicAsset("good-better-best/speaker-best.mp4"),+ ],+ decks: [+ publicAsset("good-better-best/deck-votes.png"),+ publicAsset("good-better-best/deck-attract.png"),+ publicAsset("good-better-best/deck-features.png"),+ ],+ logos: [+ publicAsset("good-better-best/logo-chatgpt.png"),+ publicAsset("good-better-best/logo-looksmax.png"),+ publicAsset("good-better-best/logo-areum.png"),+ ],+} as const;++export const demoMediaManifests = [+ {+ images: [...rankingMedia.icons, ...rankingMedia.broll],+ videos: rankingMedia.avatars,+ },+ {+ images: [],+ videos: [...streetMedia.scenes, ...streetMedia.broll],+ },+ {+ images: [...goodBetterBestMedia.decks, ...goodBetterBestMedia.logos],+ videos: goodBetterBestMedia.speakers,+ },+] as const satisfies readonly DemoMediaManifest[];diff --git a/docs/.vitepress/theme/components/semantic-video-demos.ts b/docs/.vitepress/theme/components/semantic-video-demos.tsindex e8dcb17e..fb487786 100644--- a/docs/.vitepress/theme/components/semantic-video-demos.ts+++ b/docs/.vitepress/theme/components/semantic-video-demos.ts@@ -1,5 +1,6 @@import streetTranscript from "../../../public/street-interview/transcript.json";import goodBetterBestTranscript from "../../../public/good-better-best/transcript.json";+import { goodBetterBestMedia, streetMedia } from "./demo-media";export type DemoId = "street" | "good-better-best";@@ -146,19 +147,19 @@ export const semanticVideoDemos: Record<DemoId, SemanticVideoDemoConfig> = {duration: 31.1333333333,words: streetWords,scenes: [- { src: "/street-interview/scene-1.mp4", start: 0, end: 5 },- { src: "/street-interview/scene-2.mp4", start: 5, end: 11 },- { src: "/street-interview/scene-3.mp4", start: 11, end: 22 },- { src: "/street-interview/scene-4.mp4", start: 22, end: 31.1333333333 },+ { src: streetMedia.scenes[0], start: 0, end: 5 },+ { src: streetMedia.scenes[1], start: 5, end: 11 },+ { src: streetMedia.scenes[2], start: 11, end: 22 },+ { src: streetMedia.scenes[3], start: 22, end: 31.1333333333 },],selections: [{ id: "hook", start: .04, end: 5.12, layer: "scene" },{ id: "rainbow", start: 5.12, end: 11.12, layer: "scene" },{ id: "fees", start: 11.12, end: 22.2, layer: "scene" },{ id: "loan", start: 22.2, end: 31.13, layer: "scene" },- { id: "seven-bags", start: 7.08, end: 11.12, layer: "overlay", asset: "/street-interview/broll-2.mp4" },- { id: "receipt", start: 18.81, end: 22.2, layer: "overlay", asset: "/street-interview/broll-3.mp4" },- { id: "college", start: 26.22, end: 31.06, layer: "overlay", asset: "/street-interview/broll-4.mp4" },+ { id: "seven-bags", start: 7.08, end: 11.12, layer: "overlay", asset: streetMedia.broll[0] },+ { id: "receipt", start: 18.81, end: 22.2, layer: "overlay", asset: streetMedia.broll[1] },+ { id: "college", start: 26.22, end: 31.06, layer: "overlay", asset: streetMedia.broll[2] },],lines: streetLines,},@@ -167,22 +168,22 @@ export const semanticVideoDemos: Record<DemoId, SemanticVideoDemoConfig> = {duration: 42.0333333333,words: goodBetterBestWords,scenes: [- { src: "/good-better-best/speaker-hook.mp4", start: 0, end: 4 },- { src: "/good-better-best/speaker-1.mp4", start: 4, end: 8 },- { src: "/good-better-best/speaker-good.mp4", start: 8, end: 14 },- { src: "/good-better-best/speaker-2.mp4", start: 14, end: 18.05 },- { src: "/good-better-best/speaker-better.mp4", start: 18.05, end: 23.05 },- { src: "/good-better-best/speaker-3.mp4", start: 23.05, end: 28.05 },- { src: "/good-better-best/speaker-best.mp4", start: 28.05, end: 42.0333333333 },+ { src: goodBetterBestMedia.speakers[0], start: 0, end: 4 },+ { src: goodBetterBestMedia.speakers[1], start: 4, end: 8 },+ { src: goodBetterBestMedia.speakers[2], start: 8, end: 14 },+ { src: goodBetterBestMedia.speakers[3], start: 14, end: 18.05 },+ { src: goodBetterBestMedia.speakers[4], start: 18.05, end: 23.05 },+ { src: goodBetterBestMedia.speakers[5], start: 23.05, end: 28.05 },+ { src: goodBetterBestMedia.speakers[6], start: 28.05, end: 42.0333333333 },],selections: [{ id: "hook", start: .19, end: 4.01, layer: "scene" },{ id: "good", start: 4.01, end: 14.12, layer: "scene" },{ id: "better", start: 14.12, end: 23.12, layer: "scene" },{ id: "best", start: 23.12, end: 41.34, layer: "scene" },- { id: "votes", start: 30.24, end: 33.45, layer: "overlay", asset: "/good-better-best/deck-votes.png" },- { id: "attract", start: 33.49, end: 36, layer: "overlay", asset: "/good-better-best/deck-attract.png" },- { id: "features", start: 36, end: 39.28, layer: "overlay", asset: "/good-better-best/deck-features.png" },+ { id: "votes", start: 30.24, end: 33.45, layer: "overlay", asset: goodBetterBestMedia.decks[0] },+ { id: "attract", start: 33.49, end: 36, layer: "overlay", asset: goodBetterBestMedia.decks[1] },+ { id: "features", start: 36, end: 39.28, layer: "overlay", asset: goodBetterBestMedia.decks[2] },],lines: goodBetterBestLines,},diff --git a/docs/.vitepress/theme/components/source-display.ts b/docs/.vitepress/theme/components/source-display.tsnew file mode 100644index 00000000..0bdf2483--- /dev/null+++ b/docs/.vitepress/theme/components/source-display.ts@@ -0,0 +1,157 @@+export type SourceRange = {+ start: number;+ end: number;+};++export type SourceDisplayEntry<Line> =+ | {+ key: string;+ kind: "line";+ index: number;+ line: Line;+ }+ | {+ key: string;+ kind: "fold";+ index: number;+ line: null;+ };++type SourceWindowOptions = SourceRange & {+ focus: number;+ alignment: "start" | "end";+ rowBudget: number;+ rowSpans: readonly number[];+ totalLines: number;+};++type FoldedSourceViewOptions<Line> = {+ lines: readonly Line[];+ rowSpans: readonly number[];+ rowBudget: number;+ topRanges: readonly SourceRange[];+ topFocus: number;+ bottomLine: number;+};++function sourceRowSpan(rowSpans: readonly number[], index: number) {+ return rowSpans[index] ?? 1;+}++function sourceRowsSpan(rowSpans: readonly number[], indices: readonly number[]) {+ return indices.reduce((sum, index) => sum + sourceRowSpan(rowSpans, index), 0);+}++function fitSourceWindow({+ start,+ end,+ focus,+ alignment,+ rowBudget,+ rowSpans,+ totalLines,+}: SourceWindowOptions) {+ const spanOf = (indices: readonly number[]) => sourceRowsSpan(rowSpans, indices);+ const fillBefore = (indices: number[], minimum: number) => {+ let before = indices[0] - 1;+ while (before >= minimum && spanOf(indices) + sourceRowSpan(rowSpans, before) <= rowBudget) {+ indices.unshift(before);+ before -= 1;+ }+ };+ const fillAfter = (indices: number[], maximum: number) => {+ let after = indices[indices.length - 1] + 1;+ while (after <= maximum && spanOf(indices) + sourceRowSpan(rowSpans, after) <= rowBudget) {+ indices.push(after);+ after += 1;+ }+ };+ const fill = (indices: number[], minimum: number, maximum: number) => {+ if (alignment === "end") {+ fillBefore(indices, minimum);+ fillAfter(indices, maximum);+ } else {+ fillAfter(indices, maximum);+ fillBefore(indices, minimum);+ }+ return indices;+ };+ const fullRange = Array.from({ length: end - start + 1 }, (_, offset) => start + offset);++ if (spanOf(fullRange) <= rowBudget) {+ return fill(fullRange, 0, totalLines - 1);+ }++ const center = Math.max(start, Math.min(end, focus));+ return fill([center], start, end);+}++function pickFittingSourceRange<Range extends SourceRange>(+ ranges: readonly Range[],+ rowSpans: readonly number[],+ rowBudget: number,+) {+ return ranges.find((range) => {+ const indices = Array.from(+ { length: range.end - range.start + 1 },+ (_, offset) => range.start + offset,+ );+ return sourceRowsSpan(rowSpans, indices) <= rowBudget;+ }) ?? ranges.at(-1);+}++export function buildFullSourceView<Line>(lines: readonly Line[]): SourceDisplayEntry<Line>[] {+ return lines.map((line, index) => ({ key: `line-${index}`, kind: "line", index, line }));+}++export function buildFoldedSourceView<Line>({+ lines,+ rowSpans,+ rowBudget,+ topRanges,+ topFocus,+ bottomLine,+}: FoldedSourceViewOptions<Line>): SourceDisplayEntry<Line>[] {+ const selectedRange = pickFittingSourceRange(topRanges, rowSpans, rowBudget);+ const top = fitSourceWindow({+ start: selectedRange?.start ?? topFocus,+ end: selectedRange?.end ?? topFocus,+ focus: topFocus,+ alignment: "end",+ rowBudget,+ rowSpans,+ totalLines: lines.length,+ });+ const bottom = fitSourceWindow({+ start: bottomLine,+ end: bottomLine,+ focus: bottomLine,+ alignment: "start",+ rowBudget,+ rowSpans,+ totalLines: lines.length,+ });+ const lineEntry = (index: number): SourceDisplayEntry<Line> => ({+ key: `line-${index}`,+ kind: "line",+ index,+ line: lines[index],+ });++ const topIndices = new Set(top);+ const remainingBottom = bottom.filter((index) => !topIndices.has(index));+ const lastTop = top.at(-1) ?? -1;+ const firstBottom = remainingBottom[0] ?? lines.length;+ const hasFold = firstBottom > lastTop + 1;++ return [+ ...top.map(lineEntry),+ ...(hasFold ? [{+ key: `fold-${top.at(-1)}-${bottom[0]}`,+ kind: "fold" as const,+ index: Math.floor(((top.at(-1) ?? 0) + (bottom[0] ?? lines.length - 1)) / 2),+ line: null,+ }] : []),+ ...remainingBottom.map(lineEntry),+ ];+}diff --git a/docs/.vitepress/theme/style.css b/docs/.vitepress/theme/style.cssindex e320d8f3..969f443d 100644--- a/docs/.vitepress/theme/style.css+++ b/docs/.vitepress/theme/style.css@@ -36,10 +36,12 @@ body { letter-spacing: -0.012em; }.hero-statement-name { width: fit-content; margin: 0; border: 0; padding: 0; color: #f4f7f0; font-size: clamp(48px,7vw,92px); font-weight: 700; line-height: .98; letter-spacing: -.065em; }.hero-statement-viewport { position: relative; width: min(100%,900px); overflow: hidden; -webkit-mask-image: linear-gradient(to bottom,transparent 0,#000 18px,#000 calc(100% - 18px),transparent 100%); mask-image: linear-gradient(to bottom,transparent 0,#000 18px,#000 calc(100% - 18px),transparent 100%); }.hero-statement-viewport-en { height: clamp(108px,12vw,142px); margin-top: 8px; }-.hero-statement-viewport-zh { height: 68px; margin-top: -12px; }+.hero-statement-viewport-zh { height: 68px; margin-top: -20px; }.hero-statement-en, .hero-statement-zh { position: absolute; inset: 0; display: flex; align-items: center; margin: 0; padding-block: 20px; will-change: transform,filter,opacity; }.hero-statement-en { color: #f4f7f0; font-size: clamp(28px,4vw,52px); font-weight: 700; line-height: 1.04; letter-spacing: -.045em; }.hero-statement-zh { color: var(--vp-c-text-2); font-size: 18px; font-weight: 500; line-height: 1.65; }+.hero-statement-line { display: inline; }+.hero-statement-accent { color: var(--vp-c-brand-1); }.hero-statement-swap-enter-active, .hero-statement-swap-leave-active { transition: transform .9s cubic-bezier(.22,1,.36,1), filter .9s cubic-bezier(.22,1,.36,1), opacity .72s cubic-bezier(.22,1,.36,1); }.hero-statement-swap-enter-from { opacity: 0; filter: blur(12px); transform: translateY(72%); }.hero-statement-swap-leave-to { opacity: 0; filter: blur(12px); transform: translateY(-72%); }@@ -245,7 +247,7 @@ body { letter-spacing: -0.012em; }.VPHero .text { font-size: 29px !important; }.hero-statement-name { font-size: 50px; }.hero-statement-viewport-en { height: 126px; margin-top: 6px; }- .hero-statement-viewport-zh { height: 62px; margin-top: -10px; }+ .hero-statement-viewport-zh { height: 62px; margin-top: -18px; }.hero-statement-en { font-size: 29px; }.hero-statement-zh { font-size: 16px; }.demo-shell { margin-inline: -8px; border-radius: 12px; }