@remotion/web-renderer 4.0.422 → 4.0.424

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 (71) hide show
  1. package/dist/create-audio-sample-source.d.ts +1 -1
  2. package/dist/esm/index.mjs +12 -0
  3. package/dist/mediabunny-mappings.d.ts +1 -1
  4. package/package.json +9 -10
  5. package/dist/add-sample.js +0 -20
  6. package/dist/artifact.js +0 -56
  7. package/dist/audio.js +0 -42
  8. package/dist/can-use-webfs-target.js +0 -19
  9. package/dist/compose.js +0 -85
  10. package/dist/create-scaffold.js +0 -104
  11. package/dist/drawing/border-radius.js +0 -151
  12. package/dist/drawing/calculate-object-fit.js +0 -208
  13. package/dist/drawing/calculate-transforms.js +0 -127
  14. package/dist/drawing/clamp-rect-to-parent-bounds.js +0 -18
  15. package/dist/drawing/do-rects-intersect.js +0 -6
  16. package/dist/drawing/draw-background.js +0 -62
  17. package/dist/drawing/draw-border.js +0 -353
  18. package/dist/drawing/draw-box-shadow.js +0 -103
  19. package/dist/drawing/draw-dom-element.js +0 -85
  20. package/dist/drawing/draw-element.js +0 -84
  21. package/dist/drawing/draw-outline.js +0 -93
  22. package/dist/drawing/draw-rounded.js +0 -34
  23. package/dist/drawing/drawn-fn.js +0 -1
  24. package/dist/drawing/fit-svg-into-its-dimensions.js +0 -35
  25. package/dist/drawing/get-clipped-background.d.ts +0 -8
  26. package/dist/drawing/get-clipped-background.js +0 -14
  27. package/dist/drawing/get-padding-box.js +0 -30
  28. package/dist/drawing/get-pretransform-rect.js +0 -49
  29. package/dist/drawing/handle-3d-transform.js +0 -26
  30. package/dist/drawing/handle-mask.js +0 -21
  31. package/dist/drawing/has-transform.js +0 -14
  32. package/dist/drawing/mask-image.js +0 -14
  33. package/dist/drawing/opacity.js +0 -7
  34. package/dist/drawing/overflow.js +0 -14
  35. package/dist/drawing/parse-linear-gradient.js +0 -260
  36. package/dist/drawing/parse-transform-origin.js +0 -7
  37. package/dist/drawing/precompose.d.ts +0 -11
  38. package/dist/drawing/precompose.js +0 -14
  39. package/dist/drawing/process-node.js +0 -122
  40. package/dist/drawing/round-to-expand-rect.js +0 -7
  41. package/dist/drawing/text/apply-text-transform.js +0 -12
  42. package/dist/drawing/text/draw-text.js +0 -53
  43. package/dist/drawing/text/find-line-breaks.text.js +0 -118
  44. package/dist/drawing/text/get-collapsed-text.d.ts +0 -1
  45. package/dist/drawing/text/get-collapsed-text.js +0 -46
  46. package/dist/drawing/text/handle-text-node.js +0 -24
  47. package/dist/drawing/transform-in-3d.js +0 -177
  48. package/dist/drawing/transform-rect-with-matrix.js +0 -19
  49. package/dist/drawing/transform.js +0 -10
  50. package/dist/drawing/turn-svg-into-drawable.js +0 -41
  51. package/dist/frame-range.js +0 -15
  52. package/dist/get-audio-encoding-config.js +0 -18
  53. package/dist/get-biggest-bounding-client-rect.js +0 -43
  54. package/dist/index.js +0 -2
  55. package/dist/internal-state.js +0 -36
  56. package/dist/mediabunny-mappings.js +0 -63
  57. package/dist/output-target.js +0 -1
  58. package/dist/props-if-has-props.js +0 -1
  59. package/dist/render-media-on-web.js +0 -304
  60. package/dist/render-operations-queue.js +0 -3
  61. package/dist/render-still-on-web.js +0 -110
  62. package/dist/send-telemetry-event.js +0 -22
  63. package/dist/take-screenshot.js +0 -30
  64. package/dist/throttle-progress.js +0 -43
  65. package/dist/tree-walker-cleanup-after-children.js +0 -33
  66. package/dist/update-time.js +0 -17
  67. package/dist/validate-video-frame.js +0 -34
  68. package/dist/wait-for-ready.js +0 -39
  69. package/dist/walk-tree.js +0 -14
  70. package/dist/web-fs-target.js +0 -41
  71. package/dist/with-resolvers.js +0 -9
@@ -1,7 +1,7 @@
1
1
  import { AudioSampleSource, type Quality } from 'mediabunny';
2
2
  export declare const createAudioSampleSource: ({ muted, codec, bitrate, }: {
3
3
  muted: boolean;
4
- codec: "aac" | "alaw" | "flac" | "mp3" | "opus" | "pcm-f32" | "pcm-f32be" | "pcm-f64" | "pcm-f64be" | "pcm-s16" | "pcm-s16be" | "pcm-s24" | "pcm-s24be" | "pcm-s32" | "pcm-s32be" | "pcm-s8" | "pcm-u8" | "ulaw" | "vorbis" | null;
4
+ codec: "aac" | "ac3" | "alaw" | "eac3" | "flac" | "mp3" | "opus" | "pcm-f32" | "pcm-f32be" | "pcm-f64" | "pcm-f64be" | "pcm-s16" | "pcm-s16be" | "pcm-s24" | "pcm-s24be" | "pcm-s32" | "pcm-s32be" | "pcm-s8" | "pcm-u8" | "ulaw" | "vorbis" | null;
5
5
  bitrate: number | Quality;
6
6
  }) => {
7
7
  audioSampleSource: AudioSampleSource;
@@ -36,6 +36,14 @@ var __callDispose = (stack, error, hasError) => {
36
36
  return next();
37
37
  };
38
38
 
39
+ // src/symbol-dispose.ts
40
+ if (typeof Symbol.dispose !== "symbol")
41
+ Object.defineProperty(Symbol, "dispose", { value: Symbol.for("dispose") });
42
+ if (typeof Symbol.asyncDispose !== "symbol")
43
+ Object.defineProperty(Symbol, "asyncDispose", {
44
+ value: Symbol.for("asyncDispose")
45
+ });
46
+
39
47
  // src/can-render-media-on-web.ts
40
48
  import { canEncodeVideo } from "mediabunny";
41
49
 
@@ -360,6 +368,7 @@ var getEncodableAudioCodecs = async (container, options) => {
360
368
  // src/render-media-on-web.tsx
361
369
  import { BufferTarget, StreamTarget } from "mediabunny";
362
370
  import { Internals as Internals8 } from "remotion";
371
+ import { VERSION } from "remotion/version";
363
372
 
364
373
  // src/add-sample.ts
365
374
  import { AudioSample, VideoSample } from "mediabunny";
@@ -3805,6 +3814,9 @@ var internalRenderMediaOnWeb = async ({
3805
3814
  format,
3806
3815
  target
3807
3816
  }), 0);
3817
+ outputWithCleanup.output.setMetadataTags({
3818
+ comment: `Made with Remotion ${VERSION}`
3819
+ });
3808
3820
  const throttledProgress = __using(__stack2, createThrottledProgressCallback(onProgress), 0);
3809
3821
  const throttledOnProgress = throttledProgress?.throttled ?? null;
3810
3822
  try {
@@ -12,4 +12,4 @@ export declare const getMimeType: (container: WebRendererContainer) => string;
12
12
  export declare const getDefaultAudioCodecForContainer: (container: WebRendererContainer) => WebRendererAudioCodec;
13
13
  export declare const getSupportedVideoCodecsForContainer: (container: WebRendererContainer) => WebRendererVideoCodec[];
14
14
  export declare const getSupportedAudioCodecsForContainer: (container: WebRendererContainer) => WebRendererAudioCodec[];
15
- export declare const audioCodecToMediabunnyAudioCodec: (audioCodec: WebRendererAudioCodec) => "aac" | "alaw" | "flac" | "mp3" | "opus" | "pcm-f32" | "pcm-f32be" | "pcm-f64" | "pcm-f64be" | "pcm-s16" | "pcm-s16be" | "pcm-s24" | "pcm-s24be" | "pcm-s32" | "pcm-s32be" | "pcm-s8" | "pcm-u8" | "ulaw" | "vorbis";
15
+ export declare const audioCodecToMediabunnyAudioCodec: (audioCodec: WebRendererAudioCodec) => "aac" | "ac3" | "alaw" | "eac3" | "flac" | "mp3" | "opus" | "pcm-f32" | "pcm-f32be" | "pcm-f64" | "pcm-f64be" | "pcm-s16" | "pcm-s16be" | "pcm-s24" | "pcm-s24be" | "pcm-s32" | "pcm-s32be" | "pcm-s8" | "pcm-u8" | "ulaw" | "vorbis";
package/package.json CHANGED
@@ -3,10 +3,9 @@
3
3
  "url": "https://github.com/remotion-dev/remotion/tree/main/packages/web-renderer"
4
4
  },
5
5
  "name": "@remotion/web-renderer",
6
- "version": "4.0.422",
6
+ "version": "4.0.424",
7
7
  "main": "dist/index.js",
8
8
  "type": "module",
9
- "sideEffects": false,
10
9
  "scripts": {
11
10
  "formatting": "prettier --experimental-cli src --check",
12
11
  "lint": "eslint src",
@@ -19,18 +18,18 @@
19
18
  "author": "Remotion <jonny@remotion.dev>",
20
19
  "license": "UNLICENSED",
21
20
  "dependencies": {
22
- "@remotion/licensing": "4.0.422",
23
- "remotion": "4.0.422",
24
- "mediabunny": "1.29.0"
21
+ "@remotion/licensing": "4.0.424",
22
+ "remotion": "4.0.424",
23
+ "mediabunny": "1.34.4"
25
24
  },
26
25
  "devDependencies": {
27
26
  "@react-three/fiber": "9.2.0",
28
- "@remotion/eslint-config-internal": "4.0.422",
29
- "@remotion/player": "4.0.422",
30
- "@remotion/media": "4.0.422",
31
- "@remotion/three": "4.0.422",
27
+ "@remotion/eslint-config-internal": "4.0.424",
28
+ "@remotion/player": "4.0.424",
29
+ "@remotion/media": "4.0.424",
30
+ "@remotion/three": "4.0.424",
32
31
  "@types/three": "0.170.0",
33
- "@typescript/native-preview": "7.0.0-dev.20260105.1",
32
+ "@typescript/native-preview": "7.0.0-dev.20260217.1",
34
33
  "@vitejs/plugin-react": "4.1.0",
35
34
  "@vitest/browser-playwright": "4.0.9",
36
35
  "playwright": "1.55.1",
@@ -1,20 +0,0 @@
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
- };
package/dist/artifact.js DELETED
@@ -1,56 +0,0 @@
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 DELETED
@@ -1,42 +0,0 @@
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
- };
@@ -1,19 +0,0 @@
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
- };
package/dist/compose.js DELETED
@@ -1,85 +0,0 @@
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
- };
@@ -1,104 +0,0 @@
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
- }
@@ -1,151 +0,0 @@
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
- }