mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-09-03 04:38:33 +00:00
refactor(studio): simplify hooks, split contexts, remove dead code (#1416)
* fix(studio): guard Zustand no-op setters and fix useConsoleErrorCapture memory leak - Guard setIsPlaying to skip set() when value unchanged (eliminates 60 notifications/sec during reverse playback) - Guard caption store selectGroup to bail before set() when group missing (prevents empty Zustand notifications) - Guard clearSelection to skip when already empty - Fix useConsoleErrorCapture: restore original console.error, remove error event listener, and delete __hfErrorCapture flag on cleanup * fix(studio): delete dead files and unused exports Remove 7 dead files (audioBeatDetection, keyframeSnapping, timelineInspector, DopesheetStrip, StaggerControls, TimelineLayerPanel, TimelineEditorNotice) and their test companions. Delete unused computeFitToChildrenSize export from propertyPanelHelpers. Fix re-export indirection: useDomEditCommits and studioMotionOps.test now import patch builders directly from manualEditsDomPatches instead of the re-export passthrough in manualEditsDom. * fix(studio): eliminate effect-chain state mirroring for lint findings, hover, and GSAP fetch Move lint findingsByElement sync from App.tsx into useLintModal where the value is produced, removing the mirroring useEffect. Consolidate 4 hover-clearing effects in useDomSelection into 2 (one unconditional on context change, one conditional combining caption mode, selection match, and disconnected element checks). Fold the GSAP retry effect into the fetch effect in useGsapTweenCache, scheduling a single retry via setTimeout when the initial fetch returns 0 animations. Eliminates 3 unnecessary render cycles from effect chains. * fix(studio): memoize renderQueue, toolbar, and canvas rect to prevent re-render cascade - Wrap renderQueue object in useMemo so StudioContext consumers don't re-render on every App render - Memoize timelineToolbar JSX so NLELayout memo isn't defeated - Move canvasRect getBoundingClientRect() from render-time IIFE to a useLayoutEffect-backed ref, eliminating layout thrashing - Track and clear setTimeout handles in refreshPreviewDocumentVersion to prevent stale timer accumulation on rapid calls and unmount * refactor(studio): consolidate GSAP shared primitives — defaults, iframe access, keyframe parsing Extract duplicated PROPERTY_DEFAULTS, IframeGsap interface, iframe accessors (getIframeGsap, queryIframeElement), percentage keyframe parsing, and toAbsoluteTime into a single gsapShared.ts module. Removes ~120 lines of copy-pasted logic across 8 hook files, reducing drift risk between the duplicate implementations. * fix(studio): remove dead store fields, dead file, duplicate helper, and unsafe assertions * refactor(studio): deduplicate selector helpers, rounding utils, percentage computation, and iframe access * fix(studio): split StudioContext into Shell + Playback to prevent cascade re-renders * refactor(studio): decompose useGsapScriptCommits into focused mutation hooks * refactor(studio): decompose useFileManager into focused file operation hooks Extract useFileTree (tree loading, refresh, derived assets/compositions) and useEditorSave (debounced save with history tracking) from the 508-LOC useFileManager. The parent hook composes both and retains file I/O, click-to-source, upload/import, and CRUD — preserving the same public interface so no consumers change. * refactor(studio): decompose useDomEditCommits into focused commit hooks Extract geometry (path offset, box size, rotation) and element lifecycle (delete, z-index reorder) into useDomGeometryCommits and useElementLifecycleOps. Parent keeps persistDomEditOperations as core and composes all sub-hooks — public interface unchanged. * refactor(studio): simplify useAppHotkeys with declarative command table * refactor(studio): simplify useAppHotkeys with declarative command table Replace 15 individual useRef callback refs with a single cbRef object. Extract keydown dispatch into pure dispatchModifierKey/dispatchPlainKey functions. Merge duplicate undo/redo logic into shared applyHistory. Extract cross-origin listener boilerplate into safeAddListener/safeRemoveListener. Hook body: 204 LOC (down from 445). Public API unchanged. * fix(studio): remove unused getDomEditTargetKey import * refactor(studio): decompose useDomEditSession into focused editing hooks Extract GSAP-aware geometry intercepts (move/resize/rotation) and animated property commit into useGsapAwareEditing, and selection wiring, GSAP cache management, preview sync, and selection handlers into useDomEditWiring. The parent remains a pure composition shell. * style(studio): fix formatting in 5 files * fix(studio): trim App.tsx to 598 lines (under 600 limit) --------- Co-authored-by: Miguel Ángel <miguel07alm@protonmail.com>
This commit is contained in:
co-authored by
Miguel Ángel
parent
6f677292ae
commit
7bff49ecf0
@@ -1,58 +0,0 @@
|
||||
const WINDOW_SIZE = 1024;
|
||||
const HOP_SIZE = 512;
|
||||
|
||||
// fallow-ignore-next-line complexity
|
||||
export async function detectBeats(audioBuffer: AudioBuffer): Promise<number[]> {
|
||||
const channelData = audioBuffer.getChannelData(0);
|
||||
const sampleRate = audioBuffer.sampleRate;
|
||||
|
||||
const energies: number[] = [];
|
||||
for (let i = 0; i < channelData.length - WINDOW_SIZE; i += HOP_SIZE) {
|
||||
let sum = 0;
|
||||
for (let j = 0; j < WINDOW_SIZE; j++) {
|
||||
const sample = channelData[i + j]!;
|
||||
sum += sample * sample;
|
||||
}
|
||||
energies.push(sum / WINDOW_SIZE);
|
||||
}
|
||||
|
||||
const beats: number[] = [];
|
||||
const localWindowSize = 20;
|
||||
|
||||
for (let i = localWindowSize; i < energies.length - localWindowSize; i++) {
|
||||
let localMean = 0;
|
||||
for (let j = i - localWindowSize; j < i + localWindowSize; j++) {
|
||||
localMean += energies[j]!;
|
||||
}
|
||||
localMean /= localWindowSize * 2;
|
||||
|
||||
const threshold = localMean * 1.5;
|
||||
const current = energies[i]!;
|
||||
|
||||
if (
|
||||
current > threshold &&
|
||||
current > (energies[i - 1] ?? 0) &&
|
||||
current > (energies[i + 1] ?? 0)
|
||||
) {
|
||||
const timeInSeconds = (i * HOP_SIZE) / sampleRate;
|
||||
if (beats.length === 0 || timeInSeconds - beats[beats.length - 1]! > 0.1) {
|
||||
beats.push(Math.round(timeInSeconds * 1000) / 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return beats;
|
||||
}
|
||||
|
||||
// fallow-ignore-next-line complexity
|
||||
export async function detectBeatsFromUrl(url: string): Promise<number[]> {
|
||||
const audioContext = new AudioContext();
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
|
||||
return detectBeats(audioBuffer);
|
||||
} finally {
|
||||
await audioContext.close();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { COMPOSITION_ROOT_OPEN_TAG_RE } from "./studioHelpers";
|
||||
|
||||
const CLIPBOARD_MARKER = "hyperframes-clipboard:v1";
|
||||
|
||||
export interface ClipboardPayload {
|
||||
@@ -99,8 +101,7 @@ export function insertAsSibling(
|
||||
}
|
||||
|
||||
// Fallback: insert after composition root opening tag (same as timeline clips)
|
||||
const rootOpenTag = /<[^>]*data-composition-id="[^"]+"[^>]*>/i;
|
||||
const rootMatch = rootOpenTag.exec(source);
|
||||
const rootMatch = COMPOSITION_ROOT_OPEN_TAG_RE.exec(source);
|
||||
if (rootMatch && rootMatch.index != null) {
|
||||
const insertAt = rootMatch.index + rootMatch[0].length;
|
||||
return source.slice(0, insertAt) + newHtml + source.slice(insertAt);
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { computeSnapThreshold, snapKeyframe } from "./keyframeSnapping";
|
||||
|
||||
describe("snapKeyframe", () => {
|
||||
test("snaps to frame boundary", () => {
|
||||
const result = snapKeyframe(0.34, { fps: 30, keyframeTimes: [], threshold: 0.05 });
|
||||
expect(result.snapType).toBe("frame");
|
||||
expect(Math.abs(result.snappedTime - 1 / 3)).toBeLessThan(0.01);
|
||||
});
|
||||
|
||||
test("snaps to cross-element keyframe when closest", () => {
|
||||
const result = snapKeyframe(1.005, { fps: 30, keyframeTimes: [1.0], threshold: 0.05 });
|
||||
expect(result.snapType).toBe("keyframe");
|
||||
expect(result.snappedTime).toBe(1.0);
|
||||
});
|
||||
|
||||
test("keyframe snap wins tie with frame at same position", () => {
|
||||
const result = snapKeyframe(1.0, { fps: 30, keyframeTimes: [1.0], threshold: 0.05 });
|
||||
expect(result.snapType).toBe("keyframe");
|
||||
expect(result.snappedTime).toBe(1.0);
|
||||
});
|
||||
|
||||
test("snaps to beat marker when closer than frame", () => {
|
||||
const result = snapKeyframe(2.49, {
|
||||
fps: 30,
|
||||
keyframeTimes: [],
|
||||
beatTimes: [2.5],
|
||||
threshold: 0.05,
|
||||
});
|
||||
expect(result.snapType).toBe("beat");
|
||||
expect(result.snappedTime).toBe(2.5);
|
||||
});
|
||||
|
||||
test("disabled returns raw time", () => {
|
||||
const result = snapKeyframe(1.5, {
|
||||
fps: 30,
|
||||
keyframeTimes: [1.5],
|
||||
threshold: 0.05,
|
||||
disabled: true,
|
||||
});
|
||||
expect(result.snapType).toBeNull();
|
||||
expect(result.snappedTime).toBe(1.5);
|
||||
});
|
||||
|
||||
test("no snap when outside threshold", () => {
|
||||
const result = snapKeyframe(1.5, {
|
||||
fps: 30,
|
||||
keyframeTimes: [0.5],
|
||||
threshold: 0.05,
|
||||
});
|
||||
expect(result.snapType).toBe("frame");
|
||||
});
|
||||
|
||||
test("empty beat times is graceful", () => {
|
||||
const result = snapKeyframe(0.5, {
|
||||
fps: 30,
|
||||
keyframeTimes: [],
|
||||
beatTimes: [],
|
||||
threshold: 0.05,
|
||||
});
|
||||
expect(result.snapType).toBe("frame");
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeSnapThreshold", () => {
|
||||
test("returns threshold based on pixels per second", () => {
|
||||
const threshold = computeSnapThreshold(100, 5);
|
||||
expect(threshold).toBe(0.05);
|
||||
});
|
||||
|
||||
test("fallback for zero pixels per second", () => {
|
||||
expect(computeSnapThreshold(0)).toBe(0.1);
|
||||
});
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
export type SnapType = "frame" | "keyframe" | "beat" | null;
|
||||
|
||||
export interface SnapResult {
|
||||
snappedTime: number;
|
||||
snapType: SnapType;
|
||||
}
|
||||
|
||||
export function snapKeyframe(
|
||||
time: number,
|
||||
options: {
|
||||
fps: number;
|
||||
keyframeTimes: number[];
|
||||
beatTimes?: number[];
|
||||
threshold: number;
|
||||
disabled?: boolean;
|
||||
},
|
||||
): SnapResult {
|
||||
if (options.disabled) return { snappedTime: time, snapType: null };
|
||||
|
||||
const { fps, keyframeTimes, beatTimes = [], threshold } = options;
|
||||
|
||||
let bestDist = threshold;
|
||||
let bestTime = time;
|
||||
let bestType: SnapType = null;
|
||||
|
||||
// Priority: cross-element keyframes > beat markers > frame boundaries
|
||||
// Higher priority snaps use strict < so they win on equal distance
|
||||
if (fps > 0) {
|
||||
const frameDuration = 1 / fps;
|
||||
const nearestFrame = Math.round(time / frameDuration) * frameDuration;
|
||||
const dist = Math.abs(time - nearestFrame);
|
||||
if (dist < bestDist) {
|
||||
bestDist = dist;
|
||||
bestTime = nearestFrame;
|
||||
bestType = "frame";
|
||||
}
|
||||
}
|
||||
|
||||
for (const bt of beatTimes) {
|
||||
const dist = Math.abs(time - bt);
|
||||
if (dist <= bestDist) {
|
||||
bestDist = dist;
|
||||
bestTime = bt;
|
||||
bestType = "beat";
|
||||
}
|
||||
}
|
||||
|
||||
for (const kt of keyframeTimes) {
|
||||
const dist = Math.abs(time - kt);
|
||||
if (dist <= bestDist) {
|
||||
bestDist = dist;
|
||||
bestTime = kt;
|
||||
bestType = "keyframe";
|
||||
}
|
||||
}
|
||||
|
||||
return { snappedTime: bestTime, snapType: bestType };
|
||||
}
|
||||
|
||||
export function computeSnapThreshold(pixelsPerSecond: number, baseThresholdPx: number = 5): number {
|
||||
if (pixelsPerSecond <= 0) return 0.1;
|
||||
return baseThresholdPx / pixelsPerSecond;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Round to 3 decimal places (millisecond precision for GSAP values). */
|
||||
export function roundTo3(val: number): number {
|
||||
return Math.round(val * 1000) / 1000;
|
||||
}
|
||||
|
||||
/** Round to 2 decimal places (centisecond precision for timeline values). */
|
||||
export function roundToCenti(val: number): number {
|
||||
return Math.round(val * 100) / 100;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { TimelineElement } from "../player";
|
||||
import type { DomEditSelection } from "../components/editor/domEditing";
|
||||
import type { TimelineAssetKind } from "./timelineAssetDrop";
|
||||
import { roundToCenti } from "./rounding";
|
||||
|
||||
export interface EditingFile {
|
||||
path: string;
|
||||
@@ -171,6 +172,9 @@ export function clampNumber(value: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(value, min), max);
|
||||
}
|
||||
|
||||
/** Matches the opening tag of a composition root element (`data-composition-id`). */
|
||||
export const COMPOSITION_ROOT_OPEN_TAG_RE = /<[^>]*data-composition-id="[^"]+"[^>]*>/i;
|
||||
|
||||
export function collectHtmlIds(source: string): string[] {
|
||||
return Array.from(source.matchAll(/\bid="([^"]+)"/g), (match) => match[1] ?? "");
|
||||
}
|
||||
@@ -205,7 +209,7 @@ export async function resolveDroppedAssetDuration(
|
||||
const raw = Number(media.duration);
|
||||
finalize(
|
||||
Number.isFinite(raw) && raw > 0
|
||||
? Math.round(raw * 100) / 100
|
||||
? roundToCenti(raw)
|
||||
: DEFAULT_TIMELINE_ASSET_DURATION[kind],
|
||||
);
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { RightPanelTab } from "./studioHelpers";
|
||||
import { buildProjectHash, parseProjectHashRoute } from "./projectRouting";
|
||||
import { STUDIO_INSPECTOR_PANELS_ENABLED } from "../components/editor/manualEditingAvailability";
|
||||
import { roundTo3 } from "./rounding";
|
||||
|
||||
export interface StudioUrlSelectionState {
|
||||
sourceFile?: string;
|
||||
@@ -111,7 +112,7 @@ export function buildStudioHash(projectId: string, state: StudioUrlState): strin
|
||||
params.set("v", "1");
|
||||
if (state.activeCompPath) params.set("comp", state.activeCompPath);
|
||||
if (state.currentTime != null && Number.isFinite(state.currentTime)) {
|
||||
params.set("t", String(Math.max(0, Math.round(state.currentTime * 1000) / 1000)));
|
||||
params.set("t", String(Math.max(0, roundTo3(state.currentTime))));
|
||||
}
|
||||
if (state.rightPanelTab) params.set("tab", state.rightPanelTab);
|
||||
if (state.rightCollapsed != null) params.set("rc", state.rightCollapsed ? "1" : "0");
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { AUDIO_EXT, IMAGE_EXT, VIDEO_EXT } from "./mediaTypes";
|
||||
import { roundToCenti } from "./rounding";
|
||||
import { COMPOSITION_ROOT_OPEN_TAG_RE } from "./studioHelpers";
|
||||
|
||||
export const TIMELINE_ASSET_MIME = "application/x-hyperframes-asset";
|
||||
export const TIMELINE_BLOCK_MIME = "application/x-hyperframes-block";
|
||||
@@ -51,13 +53,13 @@ export function buildTimelineFileDropPlacements(
|
||||
durations: number[],
|
||||
occupiedClips: Array<{ start: number; duration: number; track: number }> = [],
|
||||
): Array<{ start: number; track: number }> {
|
||||
let nextStart = Math.round(Math.max(0, placement.start) * 100) / 100;
|
||||
let nextStart = roundToCenti(Math.max(0, placement.start));
|
||||
const sequenceStart = nextStart;
|
||||
const resolvedDurations = durations.map((duration) =>
|
||||
Number.isFinite(duration) && duration > 0 ? duration : FALLBACK_TIMELINE_FILE_DROP_DURATION,
|
||||
);
|
||||
const sequenceEnd = resolvedDurations.reduce(
|
||||
(end, duration) => Math.round((end + duration) * 100) / 100,
|
||||
(end, duration) => roundToCenti(end + duration),
|
||||
sequenceStart,
|
||||
);
|
||||
const overlapsDropTrack = occupiedClips.some((clip) => {
|
||||
@@ -72,7 +74,7 @@ export function buildTimelineFileDropPlacements(
|
||||
|
||||
return resolvedDurations.map((duration) => {
|
||||
const start = nextStart;
|
||||
nextStart = Math.round((nextStart + duration) * 100) / 100;
|
||||
nextStart = roundToCenti(nextStart + duration);
|
||||
return { start, track };
|
||||
});
|
||||
}
|
||||
@@ -120,8 +122,7 @@ export function buildTimelineAssetInsertHtml(input: {
|
||||
}
|
||||
|
||||
export function insertTimelineAssetIntoSource(source: string, assetHtml: string): string {
|
||||
const rootOpenTag = /<[^>]*data-composition-id="[^"]+"[^>]*>/i;
|
||||
const match = rootOpenTag.exec(source);
|
||||
const match = COMPOSITION_ROOT_OPEN_TAG_RE.exec(source);
|
||||
if (!match || match.index == null) {
|
||||
throw new Error("No composition root found in target source");
|
||||
}
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Window } from "happy-dom";
|
||||
import {
|
||||
canInspectTimelineElement,
|
||||
getTimelineLayerVisibilityInPreview,
|
||||
getTimelineElementKey,
|
||||
isAudioTimelineElement,
|
||||
isTimelineElementActiveAtTime,
|
||||
isTimelineLayerVisibleInPreview,
|
||||
shouldShowTimelineInspectorBounds,
|
||||
} from "./timelineInspector";
|
||||
|
||||
function createDocument(markup: string): Document {
|
||||
const window = new Window();
|
||||
window.document.body.innerHTML = markup;
|
||||
return window.document;
|
||||
}
|
||||
|
||||
function attachVisibleBox(element: HTMLElement) {
|
||||
Object.defineProperty(element, "getBoundingClientRect", {
|
||||
configurable: true,
|
||||
value: () => ({
|
||||
bottom: 34,
|
||||
height: 24,
|
||||
left: 10,
|
||||
right: 90,
|
||||
top: 10,
|
||||
width: 80,
|
||||
x: 10,
|
||||
y: 10,
|
||||
toJSON: () => ({}),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
describe("timeline inspector", () => {
|
||||
it("keeps visual clips inspectable and audio-only clips out of the visual panel", () => {
|
||||
expect(canInspectTimelineElement({ tag: "section" })).toBe(true);
|
||||
expect(canInspectTimelineElement({ tag: "video", src: "assets/demo.mp4" })).toBe(true);
|
||||
expect(canInspectTimelineElement({ tag: "audio" })).toBe(false);
|
||||
expect(canInspectTimelineElement({ tag: "div", src: "assets/narration.mp3" })).toBe(false);
|
||||
expect(isAudioTimelineElement({ tag: "sfx" })).toBe(true);
|
||||
});
|
||||
|
||||
it("uses stable timeline keys and only shows bounds at clip edges", () => {
|
||||
expect(getTimelineElementKey({ id: "card", key: "index.html#card" })).toBe("index.html#card");
|
||||
expect(shouldShowTimelineInspectorBounds(2, { start: 2, duration: 4 })).toBe(true);
|
||||
expect(shouldShowTimelineInspectorBounds(6, { start: 2, duration: 4 })).toBe(true);
|
||||
expect(shouldShowTimelineInspectorBounds(4, { start: 2, duration: 4 })).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps selected layer bounds visible only while the clip is active", () => {
|
||||
expect(isTimelineElementActiveAtTime(1.99, { start: 2, duration: 4 }, 0)).toBe(false);
|
||||
expect(isTimelineElementActiveAtTime(2, { start: 2, duration: 4 }, 0)).toBe(true);
|
||||
expect(isTimelineElementActiveAtTime(4, { start: 2, duration: 4 }, 0)).toBe(true);
|
||||
expect(isTimelineElementActiveAtTime(6, { start: 2, duration: 4 }, 0)).toBe(true);
|
||||
expect(isTimelineElementActiveAtTime(6.01, { start: 2, duration: 4 }, 0)).toBe(false);
|
||||
});
|
||||
|
||||
it("uses composite visibility for nested layers", () => {
|
||||
const hiddenDoc = createDocument(`<div style="opacity: 0"><span id="label">Label</span></div>`);
|
||||
const hiddenLabel = hiddenDoc.getElementById("label") as HTMLElement;
|
||||
attachVisibleBox(hiddenLabel);
|
||||
expect(isTimelineLayerVisibleInPreview(hiddenLabel)).toBe(false);
|
||||
|
||||
const visibleDoc = createDocument(
|
||||
`<div style="opacity: 1"><span id="label">Label</span></div>`,
|
||||
);
|
||||
const visibleLabel = visibleDoc.getElementById("label") as HTMLElement;
|
||||
attachVisibleBox(visibleLabel);
|
||||
expect(isTimelineLayerVisibleInPreview(visibleLabel)).toBe(true);
|
||||
expect(getTimelineLayerVisibilityInPreview(visibleLabel)).toMatchObject({
|
||||
compositeOpacity: 1,
|
||||
hasBox: true,
|
||||
inViewport: true,
|
||||
visible: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,116 +0,0 @@
|
||||
import type { TimelineElement } from "../player";
|
||||
|
||||
const TIMELINE_INSPECTOR_BOUNDARY_EPSILON_SECONDS = 0.08;
|
||||
|
||||
const AUDIO_TIMELINE_TAGS = new Set(["audio", "music", "sfx", "sound", "narration"]);
|
||||
const AUDIO_SOURCE_EXT_RE = /\.(aac|flac|m4a|mp3|ogg|opus|wav)(?:[?#].*)?$/i;
|
||||
|
||||
export function getTimelineElementKey(
|
||||
element: Pick<TimelineElement, "id" | "key"> | null | undefined,
|
||||
): string | null {
|
||||
if (!element) return null;
|
||||
return element.key ?? element.id;
|
||||
}
|
||||
|
||||
export function isAudioTimelineElement(
|
||||
element: Pick<TimelineElement, "tag" | "src"> | null | undefined,
|
||||
): boolean {
|
||||
if (!element) return false;
|
||||
const tag = element.tag.trim().toLowerCase();
|
||||
if (AUDIO_TIMELINE_TAGS.has(tag)) return true;
|
||||
return Boolean(element.src && AUDIO_SOURCE_EXT_RE.test(element.src));
|
||||
}
|
||||
|
||||
export function canInspectTimelineElement(
|
||||
element: Pick<TimelineElement, "tag" | "src"> | null | undefined,
|
||||
): boolean {
|
||||
return !isAudioTimelineElement(element);
|
||||
}
|
||||
|
||||
export function shouldShowTimelineInspectorBounds(
|
||||
currentTime: number,
|
||||
element: Pick<TimelineElement, "start" | "duration"> | null | undefined,
|
||||
epsilonSeconds = TIMELINE_INSPECTOR_BOUNDARY_EPSILON_SECONDS,
|
||||
): boolean {
|
||||
if (!element) return false;
|
||||
if (!Number.isFinite(currentTime)) return false;
|
||||
if (!Number.isFinite(element.start) || !Number.isFinite(element.duration)) return false;
|
||||
const start = Math.max(0, element.start);
|
||||
const end = Math.max(start, start + Math.max(0, element.duration));
|
||||
const epsilon = Math.max(0, epsilonSeconds);
|
||||
return Math.abs(currentTime - start) <= epsilon || Math.abs(currentTime - end) <= epsilon;
|
||||
}
|
||||
|
||||
export function isTimelineElementActiveAtTime(
|
||||
currentTime: number,
|
||||
element: Pick<TimelineElement, "start" | "duration"> | null | undefined,
|
||||
epsilonSeconds = TIMELINE_INSPECTOR_BOUNDARY_EPSILON_SECONDS,
|
||||
): boolean {
|
||||
if (!element) return false;
|
||||
if (!Number.isFinite(currentTime)) return false;
|
||||
if (!Number.isFinite(element.start) || !Number.isFinite(element.duration)) return false;
|
||||
const start = Math.max(0, element.start);
|
||||
const end = Math.max(start, start + Math.max(0, element.duration));
|
||||
const epsilon = Math.max(0, epsilonSeconds);
|
||||
return currentTime >= start - epsilon && currentTime <= end + epsilon;
|
||||
}
|
||||
|
||||
export interface TimelineLayerVisibility {
|
||||
visible: boolean;
|
||||
compositeOpacity: number;
|
||||
hasBox: boolean;
|
||||
inViewport: boolean;
|
||||
}
|
||||
|
||||
export function getTimelineLayerVisibilityInPreview(
|
||||
element: HTMLElement,
|
||||
options: { minCompositeOpacity?: number } = {},
|
||||
): TimelineLayerVisibility {
|
||||
const hidden: TimelineLayerVisibility = {
|
||||
visible: false,
|
||||
compositeOpacity: 0,
|
||||
hasBox: false,
|
||||
inViewport: false,
|
||||
};
|
||||
if (!element.isConnected) return hidden;
|
||||
const doc = element.ownerDocument;
|
||||
const win = doc.defaultView;
|
||||
if (!win) return hidden;
|
||||
|
||||
const minCompositeOpacity = options.minCompositeOpacity ?? 0.01;
|
||||
let compositeOpacity = 1;
|
||||
let current: HTMLElement | null = element;
|
||||
while (current && current !== doc.body && current !== doc.documentElement) {
|
||||
const style = win.getComputedStyle(current);
|
||||
if (style.display === "none" || style.visibility === "hidden") {
|
||||
return { ...hidden, compositeOpacity };
|
||||
}
|
||||
compositeOpacity *= Number.parseFloat(style.opacity || "1");
|
||||
if (compositeOpacity <= minCompositeOpacity) {
|
||||
return { ...hidden, compositeOpacity };
|
||||
}
|
||||
current = current.parentElement;
|
||||
}
|
||||
|
||||
const rect = element.getBoundingClientRect();
|
||||
const hasBox = rect.width > 0.5 && rect.height > 0.5;
|
||||
if (!hasBox) return { visible: false, compositeOpacity, hasBox, inViewport: false };
|
||||
|
||||
const viewportWidth = win.innerWidth || doc.documentElement.clientWidth;
|
||||
const viewportHeight = win.innerHeight || doc.documentElement.clientHeight;
|
||||
const inViewport =
|
||||
rect.right > 0 && rect.bottom > 0 && rect.left < viewportWidth && rect.top < viewportHeight;
|
||||
return {
|
||||
visible: inViewport,
|
||||
compositeOpacity,
|
||||
hasBox,
|
||||
inViewport,
|
||||
};
|
||||
}
|
||||
|
||||
export function isTimelineLayerVisibleInPreview(
|
||||
element: HTMLElement,
|
||||
options: { minCompositeOpacity?: number } = {},
|
||||
): boolean {
|
||||
return getTimelineLayerVisibilityInPreview(element, options).visible;
|
||||
}
|
||||
Reference in New Issue
Block a user