mirror of
https://github.com/nexu-io/openmotion.git
synced 2026-12-02 08:49:51 +08:00
* Prepare versioned project edits locally and skip recursive preview mounts * Preserve validation details on locally prepared composition drops * Prepare Studio edits from one ordered local working copy * Chain editable media references to their preceding Studio writes --------- Co-authored-by: lefarcen <935902669@qq.com>
82 lines
5.8 KiB
TypeScript
82 lines
5.8 KiB
TypeScript
import type { parseHTML } from 'linkedom';
|
|
|
|
export const canvasPresets = [
|
|
{ ratio: '16:9', width: 1920, height: 1080 },
|
|
{ ratio: '9:16', width: 1080, height: 1920 },
|
|
{ ratio: '1:1', width: 1080, height: 1080 },
|
|
{ ratio: '4:3', width: 1440, height: 1080 },
|
|
{ ratio: '3:4', width: 1080, height: 1440 },
|
|
] as const;
|
|
export type CanvasRatio = typeof canvasPresets[number]['ratio'];
|
|
export type CanvasFit = 'contain' | 'cover';
|
|
export type CanvasSettings = { width: number; height: number; ratio: string; fit: CanvasFit };
|
|
export function canvasFrameTransform(sourceWidth: number, sourceHeight: number, width: number, height: number, fit: CanvasFit) {
|
|
const scale = Math[fit === 'cover' ? 'max' : 'min'](width / sourceWidth, height / sourceHeight);
|
|
return `translate(${(width - sourceWidth * scale) / 2}px,${(height - sourceHeight * scale) / 2}px) scale(${scale})`;
|
|
}
|
|
export function canvasRatio(width: number, height: number): string {
|
|
return canvasPresets.find(item => Math.abs(item.width / item.height - width / height) < 0.001)?.ratio || `${width}:${height}`;
|
|
}
|
|
|
|
type Span = { start: { offset: number }; end: { offset: number } };
|
|
type CanvasCssParser = {
|
|
parse(source: string, options: { positions: boolean }): unknown;
|
|
walk(ast: unknown, visitor: { visit: string; enter(node: { loc: Span; name: { name: string; loc: Span } }): void }): void;
|
|
ident: { decode(name: string): string };
|
|
};
|
|
|
|
export function canvasStyleRewriter(css: CanvasCssParser) {
|
|
return (source: string, aliases: Map<string, string>) => {
|
|
const edits: { start: number; end: number; text: string }[] = [];
|
|
css.walk(css.parse(source, { positions: true }), { visit: 'AttributeSelector', enter(node) {
|
|
const alias = aliases.get(css.ident.decode(node.name.name).toLowerCase());
|
|
if (!alias) return;
|
|
const start = node.loc.start.offset, end = node.loc.end.offset;
|
|
const selector = source.slice(start, end);
|
|
const authored = source.slice(start, node.name.loc.start.offset) + alias + source.slice(node.name.loc.end.offset, end);
|
|
// Also retain nested composition matches, with the original specificity.
|
|
edits.push({ start, end, text: `:is(${authored},${selector}:not(:where([data-canvas-fit])))` });
|
|
} });
|
|
for (const edit of edits.reverse()) source = source.slice(0, edit.start) + edit.text + source.slice(edit.end);
|
|
return source;
|
|
};
|
|
}
|
|
|
|
/** Native source owns framing. Preview and export consume these same dimensions and transforms. */
|
|
export function compositionCanvasSource(html: string, parsers: { parseHTML: typeof parseHTML; rewriteStyles: (source: string, aliases: Map<string, string>) => string }, change?: { ratio: CanvasRatio; fit: CanvasFit }) {
|
|
const { document } = parsers.parseHTML(html);
|
|
let root = document.querySelector('[data-composition-id]');
|
|
if (!root || root.tagName !== 'DIV') throw new Error('Choose a native composition with a div root');
|
|
const width = Number(root.getAttribute('data-width')), height = Number(root.getAttribute('data-height'));
|
|
if (![width, height].every(value => Number.isFinite(value) && value > 0)) throw new Error('Composition requires explicit canvas dimensions');
|
|
if (!change) return { content: html, canvas: { width, height, ratio: canvasRatio(width, height), fit: root.getAttribute('data-canvas-fit') === 'cover' ? 'cover' : 'contain' } as CanvasSettings };
|
|
const preset = canvasPresets.find(item => item.ratio === change.ratio);
|
|
if (!preset || !['contain', 'cover'].includes(change.fit)) throw new Error('Choose a supported aspect ratio and content fit');
|
|
let frame = [...root.children].find(node => node.hasAttribute('data-canvas-frame')) as HTMLElement | undefined;
|
|
if (!frame) {
|
|
// Keep the authored root and its children together: selectors and GSAP targets retain their IDs.
|
|
const outer = document.createElement('div');
|
|
const aliases = new Map<string, string>();
|
|
for (const attr of [...root.attributes]) {
|
|
if (/^data-(?:composition|start$|duration$|width$|height$|fps$|track-index$)/.test(attr.name)) {
|
|
const alias = `data-canvas-authored-${attr.name.slice(5)}`;
|
|
aliases.set(attr.name, alias); root.setAttribute(alias, attr.value);
|
|
outer.setAttribute(attr.name, attr.value); root.removeAttribute(attr.name);
|
|
}
|
|
}
|
|
outer.setAttribute('data-canvas-source-width', String(width));
|
|
outer.setAttribute('data-canvas-source-height', String(height));
|
|
frame = document.createElement('div'); frame.setAttribute('data-canvas-frame', '');
|
|
root.setAttribute('data-canvas-content', '');
|
|
(root as HTMLElement).style.width = `${width}px`; (root as HTMLElement).style.height = `${height}px`;
|
|
root.replaceWith(outer); outer.append(frame); frame.append(root); root = outer;
|
|
for (const style of document.querySelectorAll('style')) style.textContent = parsers.rewriteStyles(style.textContent || '', aliases);
|
|
}
|
|
const sourceWidth = Number(root.getAttribute('data-canvas-source-width')), sourceHeight = Number(root.getAttribute('data-canvas-source-height'));
|
|
if (![sourceWidth, sourceHeight].every(value => Number.isFinite(value) && value > 0)) throw new Error('Canvas framing metadata changed; restore the composition before reframing');
|
|
frame.setAttribute('style', `position:absolute;left:0;top:0;width:${sourceWidth}px;height:${sourceHeight}px;transform-origin:0 0;transform:${canvasFrameTransform(sourceWidth, sourceHeight, preset.width, preset.height, change.fit)}`);
|
|
root.setAttribute('data-width', String(preset.width)); root.setAttribute('data-height', String(preset.height)); root.setAttribute('data-canvas-fit', change.fit);
|
|
root.setAttribute('style', `position:relative;width:${preset.width}px;height:${preset.height}px;overflow:hidden;background:#000`);
|
|
return { content: document.toString(), canvas: { width: preset.width, height: preset.height, ratio: preset.ratio, fit: change.fit } };
|
|
}
|