@remotion/web-renderer 4.0.424 → 4.0.425

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/add-sample.js +20 -0
  2. package/dist/artifact.js +56 -0
  3. package/dist/audio.js +42 -0
  4. package/dist/can-use-webfs-target.js +19 -0
  5. package/dist/compose.js +85 -0
  6. package/dist/create-scaffold.js +104 -0
  7. package/dist/drawing/border-radius.js +151 -0
  8. package/dist/drawing/calculate-object-fit.js +208 -0
  9. package/dist/drawing/calculate-transforms.js +127 -0
  10. package/dist/drawing/clamp-rect-to-parent-bounds.js +18 -0
  11. package/dist/drawing/do-rects-intersect.js +6 -0
  12. package/dist/drawing/draw-background.js +62 -0
  13. package/dist/drawing/draw-border.js +353 -0
  14. package/dist/drawing/draw-box-shadow.js +103 -0
  15. package/dist/drawing/draw-dom-element.js +85 -0
  16. package/dist/drawing/draw-element.js +84 -0
  17. package/dist/drawing/draw-outline.js +93 -0
  18. package/dist/drawing/draw-rounded.js +34 -0
  19. package/dist/drawing/drawn-fn.js +1 -0
  20. package/dist/drawing/fit-svg-into-its-dimensions.js +35 -0
  21. package/dist/drawing/get-clipped-background.d.ts +8 -0
  22. package/dist/drawing/get-clipped-background.js +14 -0
  23. package/dist/drawing/get-padding-box.js +30 -0
  24. package/dist/drawing/get-pretransform-rect.js +49 -0
  25. package/dist/drawing/handle-3d-transform.js +26 -0
  26. package/dist/drawing/handle-mask.js +21 -0
  27. package/dist/drawing/has-transform.js +14 -0
  28. package/dist/drawing/mask-image.js +14 -0
  29. package/dist/drawing/opacity.js +7 -0
  30. package/dist/drawing/overflow.js +14 -0
  31. package/dist/drawing/parse-linear-gradient.js +260 -0
  32. package/dist/drawing/parse-transform-origin.js +7 -0
  33. package/dist/drawing/precompose.d.ts +11 -0
  34. package/dist/drawing/precompose.js +14 -0
  35. package/dist/drawing/process-node.js +122 -0
  36. package/dist/drawing/round-to-expand-rect.js +7 -0
  37. package/dist/drawing/text/apply-text-transform.js +12 -0
  38. package/dist/drawing/text/draw-text.js +53 -0
  39. package/dist/drawing/text/find-line-breaks.text.js +118 -0
  40. package/dist/drawing/text/get-collapsed-text.d.ts +1 -0
  41. package/dist/drawing/text/get-collapsed-text.js +46 -0
  42. package/dist/drawing/text/handle-text-node.js +24 -0
  43. package/dist/drawing/transform-in-3d.js +177 -0
  44. package/dist/drawing/transform-rect-with-matrix.js +19 -0
  45. package/dist/drawing/transform.js +10 -0
  46. package/dist/drawing/turn-svg-into-drawable.js +41 -0
  47. package/dist/frame-range.js +15 -0
  48. package/dist/get-audio-encoding-config.js +18 -0
  49. package/dist/get-biggest-bounding-client-rect.js +43 -0
  50. package/dist/index.js +2 -0
  51. package/dist/internal-state.js +36 -0
  52. package/dist/mediabunny-mappings.js +63 -0
  53. package/dist/output-target.js +1 -0
  54. package/dist/props-if-has-props.js +1 -0
  55. package/dist/render-media-on-web.js +304 -0
  56. package/dist/render-operations-queue.js +3 -0
  57. package/dist/render-still-on-web.js +110 -0
  58. package/dist/send-telemetry-event.js +22 -0
  59. package/dist/take-screenshot.js +30 -0
  60. package/dist/throttle-progress.js +43 -0
  61. package/dist/tree-walker-cleanup-after-children.js +33 -0
  62. package/dist/update-time.js +17 -0
  63. package/dist/validate-video-frame.js +34 -0
  64. package/dist/wait-for-ready.js +39 -0
  65. package/dist/walk-tree.js +14 -0
  66. package/dist/web-fs-target.js +41 -0
  67. package/dist/with-resolvers.js +9 -0
  68. package/package.json +9 -9
@@ -0,0 +1,20 @@
1
+ import { AudioSample, VideoSample } from 'mediabunny';
2
+ export const addVideoSampleAndCloseFrame = async (frameToEncode, videoSampleSource) => {
3
+ const sample = new VideoSample(frameToEncode);
4
+ try {
5
+ await videoSampleSource.add(sample);
6
+ }
7
+ finally {
8
+ sample.close();
9
+ frameToEncode.close();
10
+ }
11
+ };
12
+ export const addAudioSample = async (audio, audioSampleSource) => {
13
+ const sample = new AudioSample(audio);
14
+ try {
15
+ await audioSampleSource.add(sample);
16
+ }
17
+ finally {
18
+ sample.close();
19
+ }
20
+ };
@@ -0,0 +1,56 @@
1
+ import { NoReactInternals } from 'remotion/no-react';
2
+ export const onlyArtifact = async ({ assets, frameBuffer, }) => {
3
+ const artifacts = assets.filter((asset) => asset.type === 'artifact');
4
+ let frameBufferUint8 = null;
5
+ const result = [];
6
+ for (const artifact of artifacts) {
7
+ if (artifact.contentType === 'binary' || artifact.contentType === 'text') {
8
+ result.push({
9
+ frame: artifact.frame,
10
+ content: artifact.content,
11
+ filename: artifact.filename,
12
+ downloadBehavior: artifact.downloadBehavior,
13
+ });
14
+ continue;
15
+ }
16
+ if (artifact.contentType === 'thumbnail') {
17
+ if (frameBuffer === null) {
18
+ // A thumbnail artifact was defined to be emitted, but the output was not a video.
19
+ // Also, in Lambda, there are extra frames which are not video frames.
20
+ // This could happen if a thumbnail is unconditionally emitted.
21
+ continue;
22
+ }
23
+ const ab = frameBuffer instanceof Blob
24
+ ? await frameBuffer.arrayBuffer()
25
+ : new Uint8Array(await (await frameBuffer.convertToBlob({ type: 'image/png' })).arrayBuffer());
26
+ frameBufferUint8 = new Uint8Array(ab);
27
+ result.push({
28
+ frame: artifact.frame,
29
+ content: frameBufferUint8,
30
+ filename: artifact.filename,
31
+ downloadBehavior: artifact.downloadBehavior,
32
+ });
33
+ continue;
34
+ }
35
+ throw new Error('Unknown artifact type: ' + artifact);
36
+ }
37
+ return result.filter(NoReactInternals.truthy);
38
+ };
39
+ export const handleArtifacts = () => {
40
+ const previousArtifacts = [];
41
+ const handle = async ({ imageData, frame, assets: artifactAssets, onArtifact, }) => {
42
+ const artifacts = await onlyArtifact({
43
+ assets: artifactAssets,
44
+ frameBuffer: imageData,
45
+ });
46
+ for (const artifact of artifacts) {
47
+ const previousArtifact = previousArtifacts.find((a) => a.filename === artifact.filename);
48
+ if (previousArtifact) {
49
+ throw new Error(`An artifact with output "${artifact.filename}" was already registered at frame ${previousArtifact.frame}, but now registered again at frame ${frame}. Artifacts must have unique names. https://remotion.dev/docs/artifacts`);
50
+ }
51
+ onArtifact(artifact);
52
+ previousArtifacts.push({ frame, filename: artifact.filename });
53
+ }
54
+ };
55
+ return { handle };
56
+ };
package/dist/audio.js ADDED
@@ -0,0 +1,42 @@
1
+ const TARGET_NUMBER_OF_CHANNELS = 2;
2
+ const TARGET_SAMPLE_RATE = 48000;
3
+ function mixAudio(waves, length) {
4
+ if (waves.length === 1 && waves[0].length === length) {
5
+ return waves[0];
6
+ }
7
+ const mixed = new Int16Array(length);
8
+ if (waves.length === 1) {
9
+ mixed.set(waves[0].subarray(0, length));
10
+ return mixed;
11
+ }
12
+ for (let i = 0; i < length; i++) {
13
+ const sum = waves.reduce((acc, wave) => {
14
+ var _a;
15
+ return acc + ((_a = wave[i]) !== null && _a !== void 0 ? _a : 0);
16
+ }, 0);
17
+ // Clamp to Int16 range
18
+ mixed[i] = Math.max(-32768, Math.min(32767, sum));
19
+ }
20
+ return mixed;
21
+ }
22
+ export const onlyInlineAudio = ({ assets, fps, frame, }) => {
23
+ const inlineAudio = assets.filter((asset) => asset.type === 'inline-audio');
24
+ if (inlineAudio.length === 0) {
25
+ return null;
26
+ }
27
+ const expectedLength = Math.round((TARGET_NUMBER_OF_CHANNELS * TARGET_SAMPLE_RATE) / fps);
28
+ for (const asset of inlineAudio) {
29
+ if (asset.toneFrequency !== 1) {
30
+ throw new Error('Setting the toneFrequency is not supported yet in web rendering.');
31
+ }
32
+ }
33
+ const mixedAudio = mixAudio(inlineAudio.map((asset) => asset.audio), expectedLength);
34
+ return new AudioData({
35
+ data: mixedAudio,
36
+ format: 's16',
37
+ numberOfChannels: TARGET_NUMBER_OF_CHANNELS,
38
+ numberOfFrames: expectedLength / TARGET_NUMBER_OF_CHANNELS,
39
+ sampleRate: TARGET_SAMPLE_RATE,
40
+ timestamp: (frame / fps) * 1000000,
41
+ });
42
+ };
@@ -0,0 +1,19 @@
1
+ export const canUseWebFsWriter = async () => {
2
+ if (!('storage' in navigator)) {
3
+ return false;
4
+ }
5
+ if (!('getDirectory' in navigator.storage)) {
6
+ return false;
7
+ }
8
+ try {
9
+ const directoryHandle = await navigator.storage.getDirectory();
10
+ const fileHandle = await directoryHandle.getFileHandle('remotion-probe-web-fs-support', {
11
+ create: true,
12
+ });
13
+ const canUse = fileHandle.createWritable !== undefined;
14
+ return canUse;
15
+ }
16
+ catch (_a) {
17
+ return false;
18
+ }
19
+ };
@@ -0,0 +1,85 @@
1
+ import { drawDomElement } from './drawing/draw-dom-element';
2
+ import { processNode } from './drawing/process-node';
3
+ import { handleTextNode } from './drawing/text/handle-text-node';
4
+ import { createTreeWalkerCleanupAfterChildren } from './tree-walker-cleanup-after-children';
5
+ import { skipToNextNonDescendant } from './walk-tree';
6
+ const walkOverNode = ({ node, context, logLevel, parentRect, internalState, rootElement, onlyBackgroundClip, }) => {
7
+ if (node instanceof HTMLElement || node instanceof SVGElement) {
8
+ return processNode({
9
+ element: node,
10
+ context,
11
+ draw: drawDomElement(node),
12
+ logLevel,
13
+ parentRect,
14
+ internalState,
15
+ rootElement,
16
+ });
17
+ }
18
+ if (node instanceof Text) {
19
+ return handleTextNode({
20
+ node,
21
+ context,
22
+ logLevel,
23
+ parentRect,
24
+ internalState,
25
+ rootElement,
26
+ onlyBackgroundClip,
27
+ });
28
+ }
29
+ throw new Error('Unknown node type');
30
+ };
31
+ const getFilterFunction = (node) => {
32
+ if (!(node instanceof Element)) {
33
+ // Must be a text node!
34
+ return NodeFilter.FILTER_ACCEPT;
35
+ }
36
+ // SVG does have children, but we process SVG elements in its
37
+ // entirety
38
+ if (node.parentElement instanceof SVGSVGElement) {
39
+ return NodeFilter.FILTER_REJECT;
40
+ }
41
+ const computedStyle = getComputedStyle(node);
42
+ if (computedStyle.display === 'none') {
43
+ return NodeFilter.FILTER_REJECT;
44
+ }
45
+ return NodeFilter.FILTER_ACCEPT;
46
+ };
47
+ export const compose = async ({ element, context, logLevel, parentRect, internalState, onlyBackgroundClip, }) => {
48
+ const treeWalker = document.createTreeWalker(element, onlyBackgroundClip
49
+ ? NodeFilter.SHOW_TEXT
50
+ : NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, getFilterFunction);
51
+ // Skip to the first text node
52
+ if (onlyBackgroundClip) {
53
+ treeWalker.nextNode();
54
+ if (!treeWalker.currentNode) {
55
+ return;
56
+ }
57
+ }
58
+ const { checkCleanUpAtBeginningOfIteration, addCleanup, cleanupInTheEndOfTheIteration, } = createTreeWalkerCleanupAfterChildren(treeWalker);
59
+ while (true) {
60
+ checkCleanUpAtBeginningOfIteration();
61
+ const val = await walkOverNode({
62
+ node: treeWalker.currentNode,
63
+ context,
64
+ logLevel,
65
+ parentRect,
66
+ internalState,
67
+ rootElement: element,
68
+ onlyBackgroundClip,
69
+ });
70
+ if (val.type === 'skip-children') {
71
+ if (!skipToNextNonDescendant(treeWalker)) {
72
+ break;
73
+ }
74
+ }
75
+ else {
76
+ if (val.cleanupAfterChildren) {
77
+ addCleanup(treeWalker.currentNode, val.cleanupAfterChildren);
78
+ }
79
+ if (!treeWalker.nextNode()) {
80
+ break;
81
+ }
82
+ }
83
+ }
84
+ cleanupInTheEndOfTheIteration();
85
+ };
@@ -0,0 +1,104 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createRef } from 'react';
3
+ import { flushSync } from 'react-dom';
4
+ import ReactDOM from 'react-dom/client';
5
+ import { Internals } from 'remotion';
6
+ import { UpdateTime } from './update-time';
7
+ import { withResolvers } from './with-resolvers';
8
+ export async function createScaffold({ width, height, delayRenderTimeoutInMilliseconds, logLevel, resolvedProps, id, mediaCacheSizeInBytes, durationInFrames, fps, initialFrame, schema, Component, audioEnabled, videoEnabled, defaultCodec, defaultOutName, }) {
9
+ if (!ReactDOM.createRoot) {
10
+ throw new Error('@remotion/web-renderer requires React 18 or higher');
11
+ }
12
+ const div = document.createElement('div');
13
+ // Match same behavior as in portal-node.ts
14
+ div.style.position = 'fixed';
15
+ div.style.display = 'flex';
16
+ div.style.flexDirection = 'column';
17
+ div.style.backgroundColor = 'transparent';
18
+ div.style.width = `${width}px`;
19
+ div.style.height = `${height}px`;
20
+ div.style.zIndex = '-9999';
21
+ div.style.top = '0';
22
+ div.style.left = '0';
23
+ div.style.right = '0';
24
+ div.style.bottom = '0';
25
+ div.style.visibility = 'hidden';
26
+ div.style.pointerEvents = 'none';
27
+ const scaffoldClassName = `remotion-scaffold-${Math.random().toString(36).substring(2, 15)}`;
28
+ div.className = scaffoldClassName;
29
+ const cleanupCSS = Internals.CSSUtils.injectCSS(Internals.CSSUtils.makeDefaultPreviewCSS(`.${scaffoldClassName}`, 'white'));
30
+ document.body.appendChild(div);
31
+ const { promise, resolve, reject } = withResolvers();
32
+ // TODO: This might not work in React 18
33
+ const root = ReactDOM.createRoot(div, {
34
+ onUncaughtError: (err) => {
35
+ reject(err);
36
+ },
37
+ });
38
+ const delayRenderScope = {
39
+ remotion_renderReady: true,
40
+ remotion_delayRenderTimeouts: {},
41
+ remotion_puppeteerTimeout: delayRenderTimeoutInMilliseconds,
42
+ remotion_attempt: 0,
43
+ remotion_delayRenderHandles: [],
44
+ };
45
+ const timeUpdater = createRef();
46
+ const collectAssets = createRef();
47
+ flushSync(() => {
48
+ root.render(_jsx(Internals.MaxMediaCacheSizeContext.Provider, { value: mediaCacheSizeInBytes, children: _jsx(Internals.RemotionEnvironmentContext.Provider, { value: {
49
+ isStudio: false,
50
+ isRendering: true,
51
+ isPlayer: false,
52
+ isReadOnlyStudio: false,
53
+ isClientSideRendering: true,
54
+ }, children: _jsx(Internals.DelayRenderContextType.Provider, { value: delayRenderScope, children: _jsx(Internals.CompositionManager.Provider, { value: {
55
+ compositions: [
56
+ {
57
+ id,
58
+ // @ts-expect-error
59
+ component: Component,
60
+ nonce: 0,
61
+ defaultProps: {},
62
+ folderName: null,
63
+ parentFolderName: null,
64
+ schema: schema !== null && schema !== void 0 ? schema : null,
65
+ calculateMetadata: null,
66
+ durationInFrames,
67
+ fps,
68
+ height,
69
+ width,
70
+ },
71
+ ],
72
+ canvasContent: {
73
+ type: 'composition',
74
+ compositionId: id,
75
+ },
76
+ currentCompositionMetadata: {
77
+ props: resolvedProps,
78
+ durationInFrames,
79
+ fps,
80
+ height,
81
+ width,
82
+ defaultCodec: defaultCodec !== null && defaultCodec !== void 0 ? defaultCodec : null,
83
+ defaultOutName: defaultOutName !== null && defaultOutName !== void 0 ? defaultOutName : null,
84
+ defaultVideoImageFormat: null,
85
+ defaultPixelFormat: null,
86
+ defaultProResProfile: null,
87
+ },
88
+ folders: [],
89
+ }, children: _jsx(Internals.RenderAssetManagerProvider, { collectAssets: collectAssets, children: _jsx(UpdateTime, { audioEnabled: audioEnabled, videoEnabled: videoEnabled, logLevel: logLevel, compId: id, initialFrame: initialFrame, timeUpdater: timeUpdater, children: _jsx(Internals.CanUseRemotionHooks.Provider, { value: true, children: _jsx(Component, { ...resolvedProps }) }) }) }) }) }) }) }));
90
+ });
91
+ resolve();
92
+ await promise;
93
+ return {
94
+ delayRenderScope,
95
+ div,
96
+ cleanupScaffold: () => {
97
+ root.unmount();
98
+ div.remove();
99
+ cleanupCSS();
100
+ },
101
+ timeUpdater,
102
+ collectAssets,
103
+ };
104
+ }
@@ -0,0 +1,151 @@
1
+ import { drawRoundedRectPath } from './draw-rounded';
2
+ import { getBoxBasedOnBackgroundClip } from './get-padding-box';
3
+ function parseValue({ value, reference, }) {
4
+ value = value.trim();
5
+ if (value.endsWith('%')) {
6
+ const percentage = parseFloat(value);
7
+ return (percentage / 100) * reference;
8
+ }
9
+ if (value.endsWith('px')) {
10
+ return parseFloat(value);
11
+ }
12
+ // If no unit, assume pixels
13
+ return parseFloat(value);
14
+ }
15
+ function expandShorthand(values) {
16
+ if (values.length === 1) {
17
+ // All corners the same
18
+ return [values[0], values[0], values[0], values[0]];
19
+ }
20
+ if (values.length === 2) {
21
+ // [0] = top-left & bottom-right, [1] = top-right & bottom-left
22
+ return [values[0], values[1], values[0], values[1]];
23
+ }
24
+ if (values.length === 3) {
25
+ // [0] = top-left, [1] = top-right & bottom-left, [2] = bottom-right
26
+ return [values[0], values[1], values[2], values[1]];
27
+ }
28
+ // 4 values: top-left, top-right, bottom-right, bottom-left
29
+ return [values[0], values[1], values[2], values[3]];
30
+ }
31
+ function clampBorderRadius({ borderRadius, width, height, }) {
32
+ // According to CSS spec, if the sum of border radii on adjacent corners
33
+ // exceeds the length of the edge, they should be proportionally reduced
34
+ const clamped = {
35
+ topLeft: { ...borderRadius.topLeft },
36
+ topRight: { ...borderRadius.topRight },
37
+ bottomRight: { ...borderRadius.bottomRight },
38
+ bottomLeft: { ...borderRadius.bottomLeft },
39
+ };
40
+ // Check top edge
41
+ const topSum = clamped.topLeft.horizontal + clamped.topRight.horizontal;
42
+ if (topSum > width) {
43
+ const factor = width / topSum;
44
+ clamped.topLeft.horizontal *= factor;
45
+ clamped.topRight.horizontal *= factor;
46
+ }
47
+ // Check right edge
48
+ const rightSum = clamped.topRight.vertical + clamped.bottomRight.vertical;
49
+ if (rightSum > height) {
50
+ const factor = height / rightSum;
51
+ clamped.topRight.vertical *= factor;
52
+ clamped.bottomRight.vertical *= factor;
53
+ }
54
+ // Check bottom edge
55
+ const bottomSum = clamped.bottomRight.horizontal + clamped.bottomLeft.horizontal;
56
+ if (bottomSum > width) {
57
+ const factor = width / bottomSum;
58
+ clamped.bottomRight.horizontal *= factor;
59
+ clamped.bottomLeft.horizontal *= factor;
60
+ }
61
+ // Check left edge
62
+ const leftSum = clamped.bottomLeft.vertical + clamped.topLeft.vertical;
63
+ if (leftSum > height) {
64
+ const factor = height / leftSum;
65
+ clamped.bottomLeft.vertical *= factor;
66
+ clamped.topLeft.vertical *= factor;
67
+ }
68
+ return clamped;
69
+ }
70
+ export function parseBorderRadius({ borderRadius, width, height, }) {
71
+ // Split by '/' to separate horizontal and vertical radii
72
+ const parts = borderRadius.split('/').map((part) => part.trim());
73
+ const horizontalPart = parts[0];
74
+ const verticalPart = parts[1];
75
+ // Split each part into individual values
76
+ const horizontalValues = horizontalPart.split(/\s+/).filter((v) => v);
77
+ const verticalValues = verticalPart
78
+ ? verticalPart.split(/\s+/).filter((v) => v)
79
+ : horizontalValues; // If no '/', use horizontal values for vertical
80
+ // Expand shorthand to 4 values
81
+ const [hTopLeft, hTopRight, hBottomRight, hBottomLeft] = expandShorthand(horizontalValues);
82
+ const [vTopLeft, vTopRight, vBottomRight, vBottomLeft] = expandShorthand(verticalValues);
83
+ return clampBorderRadius({
84
+ borderRadius: {
85
+ topLeft: {
86
+ horizontal: parseValue({ value: hTopLeft, reference: width }),
87
+ vertical: parseValue({ value: vTopLeft, reference: height }),
88
+ },
89
+ topRight: {
90
+ horizontal: parseValue({ value: hTopRight, reference: width }),
91
+ vertical: parseValue({ value: vTopRight, reference: height }),
92
+ },
93
+ bottomRight: {
94
+ horizontal: parseValue({ value: hBottomRight, reference: width }),
95
+ vertical: parseValue({ value: vBottomRight, reference: height }),
96
+ },
97
+ bottomLeft: {
98
+ horizontal: parseValue({ value: hBottomLeft, reference: width }),
99
+ vertical: parseValue({ value: vBottomLeft, reference: height }),
100
+ },
101
+ },
102
+ width,
103
+ height,
104
+ });
105
+ }
106
+ export function setBorderRadius({ ctx, rect, borderRadius, forceClipEvenWhenZero = false, computedStyle, backgroundClip, }) {
107
+ if (borderRadius.topLeft.horizontal === 0 &&
108
+ borderRadius.topLeft.vertical === 0 &&
109
+ borderRadius.topRight.horizontal === 0 &&
110
+ borderRadius.topRight.vertical === 0 &&
111
+ borderRadius.bottomRight.horizontal === 0 &&
112
+ borderRadius.bottomRight.vertical === 0 &&
113
+ borderRadius.bottomLeft.horizontal === 0 &&
114
+ borderRadius.bottomLeft.vertical === 0 &&
115
+ !forceClipEvenWhenZero) {
116
+ return () => { };
117
+ }
118
+ ctx.save();
119
+ const boundingRect = getBoxBasedOnBackgroundClip(rect, computedStyle, backgroundClip);
120
+ // See background-clip tests for why this logic matters!
121
+ const actualBorderRadius = {
122
+ topLeft: {
123
+ horizontal: Math.max(0, borderRadius.topLeft.horizontal - (boundingRect.left - rect.left)),
124
+ vertical: Math.max(0, borderRadius.topLeft.vertical - (boundingRect.top - rect.top)),
125
+ },
126
+ topRight: {
127
+ horizontal: Math.max(0, borderRadius.topRight.horizontal - (rect.right - boundingRect.right)),
128
+ vertical: Math.max(0, borderRadius.topRight.vertical - (boundingRect.top - rect.top)),
129
+ },
130
+ bottomRight: {
131
+ horizontal: Math.max(0, borderRadius.bottomRight.horizontal - (rect.right - boundingRect.right)),
132
+ vertical: Math.max(0, borderRadius.bottomRight.vertical - (rect.bottom - boundingRect.bottom)),
133
+ },
134
+ bottomLeft: {
135
+ horizontal: Math.max(0, borderRadius.bottomLeft.horizontal - (boundingRect.left - rect.left)),
136
+ vertical: Math.max(0, borderRadius.bottomLeft.vertical - (rect.bottom - boundingRect.bottom)),
137
+ },
138
+ };
139
+ drawRoundedRectPath({
140
+ ctx,
141
+ x: boundingRect.left,
142
+ y: boundingRect.top,
143
+ width: boundingRect.width,
144
+ height: boundingRect.height,
145
+ borderRadius: actualBorderRadius,
146
+ });
147
+ ctx.clip();
148
+ return () => {
149
+ ctx.restore();
150
+ };
151
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * fill: Stretch the image to fill the container, ignoring aspect ratio
3
+ */
4
+ const calculateFill = ({ containerSize, intrinsicSize, }) => {
5
+ return {
6
+ sourceX: 0,
7
+ sourceY: 0,
8
+ sourceWidth: intrinsicSize.width,
9
+ sourceHeight: intrinsicSize.height,
10
+ destX: containerSize.left,
11
+ destY: containerSize.top,
12
+ destWidth: containerSize.width,
13
+ destHeight: containerSize.height,
14
+ };
15
+ };
16
+ /**
17
+ * contain: Scale the image to fit inside the container while maintaining aspect ratio.
18
+ * This may result in letterboxing (empty space on sides or top/bottom).
19
+ */
20
+ const calculateContain = ({ containerSize, intrinsicSize, }) => {
21
+ const containerAspect = containerSize.width / containerSize.height;
22
+ const imageAspect = intrinsicSize.width / intrinsicSize.height;
23
+ let destWidth;
24
+ let destHeight;
25
+ if (imageAspect > containerAspect) {
26
+ // Image is wider than container (relative to their heights)
27
+ // Fit by width, letterbox top/bottom
28
+ destWidth = containerSize.width;
29
+ destHeight = containerSize.width / imageAspect;
30
+ }
31
+ else {
32
+ // Image is taller than container (relative to their widths)
33
+ // Fit by height, letterbox left/right
34
+ destHeight = containerSize.height;
35
+ destWidth = containerSize.height * imageAspect;
36
+ }
37
+ // Center the image in the container
38
+ const destX = containerSize.left + (containerSize.width - destWidth) / 2;
39
+ const destY = containerSize.top + (containerSize.height - destHeight) / 2;
40
+ return {
41
+ sourceX: 0,
42
+ sourceY: 0,
43
+ sourceWidth: intrinsicSize.width,
44
+ sourceHeight: intrinsicSize.height,
45
+ destX,
46
+ destY,
47
+ destWidth,
48
+ destHeight,
49
+ };
50
+ };
51
+ /**
52
+ * cover: Scale the image to cover the container while maintaining aspect ratio.
53
+ * Parts of the image may be cropped.
54
+ */
55
+ const calculateCover = ({ containerSize, intrinsicSize, }) => {
56
+ // Guard against zero or non-positive heights to avoid division by zero and NaN/Infinity.
57
+ if (containerSize.height <= 0 || intrinsicSize.height <= 0) {
58
+ return {
59
+ sourceX: 0,
60
+ sourceY: 0,
61
+ sourceWidth: 0,
62
+ sourceHeight: 0,
63
+ destX: containerSize.left,
64
+ destY: containerSize.top,
65
+ destWidth: 0,
66
+ destHeight: 0,
67
+ };
68
+ }
69
+ const containerAspect = containerSize.width / containerSize.height;
70
+ const imageAspect = intrinsicSize.width / intrinsicSize.height;
71
+ let sourceX = 0;
72
+ let sourceY = 0;
73
+ let sourceWidth = intrinsicSize.width;
74
+ let sourceHeight = intrinsicSize.height;
75
+ if (imageAspect > containerAspect) {
76
+ // Image is wider than container - crop horizontally
77
+ // Scale by height, then crop width
78
+ sourceWidth = intrinsicSize.height * containerAspect;
79
+ sourceX = (intrinsicSize.width - sourceWidth) / 2;
80
+ }
81
+ else {
82
+ // Image is taller than container - crop vertically
83
+ // Scale by width, then crop height
84
+ sourceHeight = intrinsicSize.width / containerAspect;
85
+ sourceY = (intrinsicSize.height - sourceHeight) / 2;
86
+ }
87
+ return {
88
+ sourceX,
89
+ sourceY,
90
+ sourceWidth,
91
+ sourceHeight,
92
+ destX: containerSize.left,
93
+ destY: containerSize.top,
94
+ destWidth: containerSize.width,
95
+ destHeight: containerSize.height,
96
+ };
97
+ };
98
+ /**
99
+ * none: Draw the image at its natural size, centered in the container.
100
+ * Clips to the container bounds if the image overflows.
101
+ */
102
+ const calculateNone = ({ containerSize, intrinsicSize, }) => {
103
+ // Calculate centered position (can be negative if image is larger than container)
104
+ const centeredX = containerSize.left + (containerSize.width - intrinsicSize.width) / 2;
105
+ const centeredY = containerSize.top + (containerSize.height - intrinsicSize.height) / 2;
106
+ // Calculate clipping bounds
107
+ let sourceX = 0;
108
+ let sourceY = 0;
109
+ let sourceWidth = intrinsicSize.width;
110
+ let sourceHeight = intrinsicSize.height;
111
+ let destX = centeredX;
112
+ let destY = centeredY;
113
+ let destWidth = intrinsicSize.width;
114
+ let destHeight = intrinsicSize.height;
115
+ // Clip left edge
116
+ if (destX < containerSize.left) {
117
+ const clipAmount = containerSize.left - destX;
118
+ sourceX = clipAmount;
119
+ sourceWidth -= clipAmount;
120
+ destX = containerSize.left;
121
+ destWidth -= clipAmount;
122
+ }
123
+ // Clip top edge
124
+ if (destY < containerSize.top) {
125
+ const clipAmount = containerSize.top - destY;
126
+ sourceY = clipAmount;
127
+ sourceHeight -= clipAmount;
128
+ destY = containerSize.top;
129
+ destHeight -= clipAmount;
130
+ }
131
+ // Clip right edge
132
+ const containerRight = containerSize.left + containerSize.width;
133
+ if (destX + destWidth > containerRight) {
134
+ const clipAmount = destX + destWidth - containerRight;
135
+ sourceWidth -= clipAmount;
136
+ destWidth -= clipAmount;
137
+ }
138
+ // Clip bottom edge
139
+ const containerBottom = containerSize.top + containerSize.height;
140
+ if (destY + destHeight > containerBottom) {
141
+ const clipAmount = destY + destHeight - containerBottom;
142
+ sourceHeight -= clipAmount;
143
+ destHeight -= clipAmount;
144
+ }
145
+ return {
146
+ sourceX,
147
+ sourceY,
148
+ sourceWidth,
149
+ sourceHeight,
150
+ destX,
151
+ destY,
152
+ destWidth,
153
+ destHeight,
154
+ };
155
+ };
156
+ /**
157
+ * Calculates how to draw an image based on object-fit CSS property.
158
+ *
159
+ * @param objectFit - The CSS object-fit value
160
+ * @param containerSize - The container dimensions (where the image should be drawn)
161
+ * @param intrinsicSize - The natural/intrinsic size of the image
162
+ * @returns Source and destination rectangles for drawImage
163
+ */
164
+ export const calculateObjectFit = ({ objectFit, containerSize, intrinsicSize, }) => {
165
+ switch (objectFit) {
166
+ case 'fill':
167
+ return calculateFill({ containerSize, intrinsicSize });
168
+ case 'contain':
169
+ return calculateContain({ containerSize, intrinsicSize });
170
+ case 'cover':
171
+ return calculateCover({ containerSize, intrinsicSize });
172
+ case 'none':
173
+ return calculateNone({ containerSize, intrinsicSize });
174
+ case 'scale-down': {
175
+ // scale-down behaves like contain or none, whichever results in a smaller image
176
+ const containResult = calculateContain({ containerSize, intrinsicSize });
177
+ const noneResult = calculateNone({ containerSize, intrinsicSize });
178
+ // Compare the rendered size - use whichever is smaller
179
+ const containArea = containResult.destWidth * containResult.destHeight;
180
+ const noneArea = noneResult.destWidth * noneResult.destHeight;
181
+ return containArea < noneArea ? containResult : noneResult;
182
+ }
183
+ default: {
184
+ const exhaustiveCheck = objectFit;
185
+ throw new Error(`Unknown object-fit value: ${exhaustiveCheck}`);
186
+ }
187
+ }
188
+ };
189
+ /**
190
+ * Parse an object-fit CSS value string into our ObjectFit type.
191
+ * Returns 'fill' as the default if the value is not recognized.
192
+ */
193
+ export const parseObjectFit = (value) => {
194
+ if (!value) {
195
+ return 'fill';
196
+ }
197
+ const normalized = value.trim().toLowerCase();
198
+ switch (normalized) {
199
+ case 'fill':
200
+ case 'contain':
201
+ case 'cover':
202
+ case 'none':
203
+ case 'scale-down':
204
+ return normalized;
205
+ default:
206
+ return 'fill';
207
+ }
208
+ };