Skip to content

🎥 Make videos programmatically with React

Address halftone linear gradient review

Cursor Agent3567f1d08f85
diff --git a/packages/core/src/sequence-field-schema.ts b/packages/core/src/sequence-field-schema.ts
index f377694a07..23dd26c588 100644
--- a/packages/core/src/sequence-field-schema.ts
+++ b/packages/core/src/sequence-field-schema.ts
@@ -31,6 +31,15 @@ export type TranslateFieldSchema = {
description?: string;
};
+export type UvCoordinateFieldSchema = {
+ type: 'uv-coordinate';
+ min?: number;
+ max?: number;
+ step?: number;
+ default: readonly [number, number] | undefined;
+ description?: string;
+};
+
export type ColorFieldSchema = {
type: 'color';
default: string | undefined;
@@ -49,6 +58,7 @@ export type VisibleFieldSchema =
| BooleanFieldSchema
| RotationFieldSchema
| TranslateFieldSchema
+ | UvCoordinateFieldSchema
| ColorFieldSchema
| EnumFieldSchema;
diff --git a/packages/docs/components/demos/control.tsx b/packages/docs/components/demos/control.tsx
index 9dfc9a960f..caedb67245 100644
--- a/packages/docs/components/demos/control.tsx
+++ b/packages/docs/components/demos/control.tsx
@@ -1,6 +1,6 @@
import React, {useMemo} from 'react';
-import styles from './styles.module.css';
import type {Option} from './types';
+import styles from './styles.module.css';
const left: React.CSSProperties = {
fontFamily: 'GTPlanar',
@@ -26,8 +26,10 @@ export const Control = ({
setValue,
}: {
readonly option: Option;
- readonly value: number | string | boolean;
- readonly setValue: (value: number | string | boolean | null) => void;
+ readonly value: number | string | boolean | readonly [number, number];
+ readonly setValue: (
+ value: number | string | boolean | readonly [number, number] | null,
+ ) => void;
}) => {
const enabled = value !== null;
@@ -56,6 +58,22 @@ export const Control = ({
[],
);
+ const uvValue = useMemo<readonly [number, number] | null>(() => {
+ if (option.type !== 'uv-coordinate') {
+ return null;
+ }
+
+ if (
+ Array.isArray(value) &&
+ value.length === 2 &&
+ value.every((item) => typeof item === 'number')
+ ) {
+ return [value[0], value[1]];
+ }
+
+ return option.default;
+ }, [option, value]);
+
return (
<label style={labelStyle} className={styles.item}>
<div style={left}>
@@ -85,11 +103,46 @@ export const Control = ({
style={inputStyle}
onChange={(e) => setValue(Number(e.target.value))}
/>
+ ) : option.type === 'uv-coordinate' && enabled ? (
+ <>
+ <input
+ type="range"
+ min={option.min}
+ max={option.max}
+ step={option.step}
+ value={(uvValue ?? option.default)[0]}
+ style={inputStyle}
+ onChange={(e) =>
+ setValue([
+ Number(e.target.value),
+ (uvValue ?? option.default)[1],
+ ] as const)
+ }
+ />
+ <input
+ type="range"
+ min={option.min}
+ max={option.max}
+ step={option.step}
+ value={(uvValue ?? option.default)[1]}
+ style={inputStyle}
+ onChange={(e) =>
+ setValue([
+ (uvValue ?? option.default)[0],
+ Number(e.target.value),
+ ] as const)
+ }
+ />
+ </>
) : null}
{option.type === 'numeric' ? (
<div style={right}>
<code>{value}</code>
</div>
+ ) : option.type === 'uv-coordinate' ? (
+ <div style={right}>
+ <code>{`[${(uvValue ?? option.default)[0]}, ${(uvValue ?? option.default)[1]}]`}</code>
+ </div>
) : option.type === 'enum' ? (
<div>
<select
diff --git a/packages/docs/components/demos/index.tsx b/packages/docs/components/demos/index.tsx
index b5bf1e2836..016e115511 100644
--- a/packages/docs/components/demos/index.tsx
+++ b/packages/docs/components/demos/index.tsx
@@ -26,7 +26,7 @@ import {
effectsGlowDemo,
effectsGrayscaleDemo,
effectsHalftoneDemo,
- effectsHalftoneGradientDemo,
+ effectsHalftoneLinearGradientDemo,
effectsHueDemo,
effectsInvertDemo,
effectsLightLeakDemo,
@@ -114,7 +114,7 @@ const demos: DemoType[] = [
effectsChromaticAberrationDemo,
effectsWaveDemo,
effectsHalftoneDemo,
- effectsHalftoneGradientDemo,
+ effectsHalftoneLinearGradientDemo,
effectsStarburstDemo,
effectsLightLeakDemo,
arrowDemo,
diff --git a/packages/docs/components/demos/types.ts b/packages/docs/components/demos/types.ts
index 2a7233f4f1..bd71c8c4c9 100644
--- a/packages/docs/components/demos/types.ts
+++ b/packages/docs/components/demos/types.ts
@@ -7,7 +7,7 @@ import {EffectsContrastPreview} from '../effects/effects-contrast-preview';
import {EffectsDuotonePreview} from '../effects/effects-duotone-preview';
import {EffectsGlowPreview} from '../effects/effects-glow-preview';
import {EffectsGrayscalePreview} from '../effects/effects-grayscale-preview';
-import {EffectsHalftoneGradientPreview} from '../effects/effects-halftone-gradient-preview';
+import {EffectsHalftoneLinearGradientPreview} from '../effects/effects-halftone-linear-gradient-preview';
import {EffectsHalftonePreview} from '../effects/effects-halftone-preview';
import {EffectsHuePreview} from '../effects/effects-hue-preview';
import {EffectsInvertPreview} from '../effects/effects-invert-preview';
@@ -111,6 +111,13 @@ export type Option = {
type: 'color';
default: string;
}
+ | {
+ type: 'uv-coordinate';
+ min: number;
+ default: readonly [number, number];
+ max: number;
+ step: number;
+ }
);
export type DemoType = {
@@ -2165,13 +2172,13 @@ export const effectsHalftoneDemo: DemoType = {
],
};
-export const effectsHalftoneGradientDemo: DemoType = {
- comp: EffectsHalftoneGradientPreview,
+export const effectsHalftoneLinearGradientDemo: DemoType = {
+ comp: EffectsHalftoneLinearGradientPreview,
compHeight: 720,
compWidth: 1280,
durationInFrames: 1,
fps: 30,
- id: 'effects-halftone-gradient',
+ id: 'effects-halftone-linear-gradient',
autoPlay: false,
controls: false,
logLevel: 'info',
@@ -2194,6 +2201,24 @@ export const effectsHalftoneGradientDemo: DemoType = {
default: 40,
optional: 'no',
},
+ {
+ name: 'firstStopPosition',
+ type: 'uv-coordinate',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: [0, 0.5],
+ optional: 'no',
+ },
+ {
+ name: 'secondStopPosition',
+ type: 'uv-coordinate',
+ min: 0,
+ max: 1,
+ step: 0.01,
+ default: [1, 0.5],
+ optional: 'no',
+ },
{
name: 'gridSize',
type: 'numeric',
@@ -2203,15 +2228,6 @@ export const effectsHalftoneGradientDemo: DemoType = {
default: 24,
optional: 'no',
},
- {
- name: 'rotation',
- type: 'numeric',
- min: -180,
- max: 180,
- step: 1,
- default: 0,
- optional: 'no',
- },
{
name: 'colorMode',
type: 'enum',
@@ -2222,7 +2238,7 @@ export const effectsHalftoneGradientDemo: DemoType = {
{
name: 'dotColor',
type: 'color',
- default: '#ffffff',
+ default: '#0b84f3',
optional: 'no',
showIf: {
option: 'colorMode',
diff --git a/packages/docs/components/effects/effects-halftone-gradient-preview.tsx b/packages/docs/components/effects/effects-halftone-linear-gradient-preview.tsx
similarity index 60%
rename from packages/docs/components/effects/effects-halftone-gradient-preview.tsx
rename to packages/docs/components/effects/effects-halftone-linear-gradient-preview.tsx
index e57c3fbc46..be75a151e4 100644
--- a/packages/docs/components/effects/effects-halftone-gradient-preview.tsx
+++ b/packages/docs/components/effects/effects-halftone-linear-gradient-preview.tsx
@@ -1,5 +1,8 @@
-import type {HalftoneGradientColorMode} from '@remotion/effects/halftone-gradient';
-import {halftoneGradient} from '@remotion/effects/halftone-gradient';
+import type {
+ HalftoneLinearGradientColorMode,
+ UvCoordinate,
+} from '@remotion/effects/halftone-linear-gradient';
+import {halftoneLinearGradient} from '@remotion/effects/halftone-linear-gradient';
import React from 'react';
import {CanvasImage} from 'remotion';
import {EFFECTS_PREVIEW_IMAGE_SRC} from './effects-preview-image';
@@ -9,18 +12,20 @@ const fullSize: React.CSSProperties = {
height: '100%',
};
-export const EffectsHalftoneGradientPreview: React.FC<{
+export const EffectsHalftoneLinearGradientPreview: React.FC<{
readonly firstStopDotSize: number;
readonly secondStopDotSize: number;
+ readonly firstStopPosition: UvCoordinate;
+ readonly secondStopPosition: UvCoordinate;
readonly gridSize: number;
- readonly rotation: number;
- readonly colorMode: HalftoneGradientColorMode;
+ readonly colorMode: HalftoneLinearGradientColorMode;
readonly dotColor: string;
}> = ({
firstStopDotSize,
secondStopDotSize,
+ firstStopPosition,
+ secondStopPosition,
gridSize,
- rotation,
colorMode,
dotColor,
}) => {
@@ -37,11 +42,12 @@ export const EffectsHalftoneGradientPreview: React.FC<{
fit="cover"
style={fullSize}
effects={[
- halftoneGradient({
+ halftoneLinearGradient({
firstStopDotSize,
secondStopDotSize,
+ firstStopPosition,
+ secondStopPosition,
gridSize,
- rotation,
...colorParams,
}),
]}
diff --git a/packages/docs/docs/effects/halftone-gradient.mdx b/packages/docs/docs/effects/halftone-linear-gradient.mdx
similarity index 65%
rename from packages/docs/docs/effects/halftone-gradient.mdx
rename to packages/docs/docs/effects/halftone-linear-gradient.mdx
index c5b28b82cd..0cc0ccebc6 100644
--- a/packages/docs/docs/effects/halftone-gradient.mdx
+++ b/packages/docs/docs/effects/halftone-linear-gradient.mdx
@@ -1,12 +1,12 @@
---
-image: /generated/articles-docs-effects-halftone-gradient.png
-slug: /effects/halftone-gradient
-title: halftoneGradient()
-sidebar_label: halftoneGradient()
+image: /generated/articles-docs-effects-halftone-linear-gradient.png
+slug: /effects/halftone-linear-gradient
+title: halftoneLinearGradient()
+sidebar_label: halftoneLinearGradient()
crumb: '@remotion/effects'
---
-# halftoneGradient()<AvailableFrom v="4.0.468" />
+# halftoneLinearGradient()<AvailableFrom v="4.0.468" />
_Part of the [`@remotion/effects`](/docs/effects/api) package._
@@ -16,14 +16,14 @@ Use it for dot-pattern wipes, overlays, and backgrounds on canvas-based componen
## Preview
-<Demo type="effects-halftone-gradient" />
+<Demo type="effects-halftone-linear-gradient" />
## Example
```tsx twoslash title="MyComp.tsx"
import {AbsoluteFill} from 'remotion';
import {Video} from '@remotion/media';
-import {halftoneGradient} from '@remotion/effects/halftone-gradient';
+import {halftoneLinearGradient} from '@remotion/effects/halftone-linear-gradient';
export const MyComp: React.FC = () => {
return (
@@ -31,12 +31,13 @@ export const MyComp: React.FC = () => {
<Video
src="https://remotion.media/video.mp4"
effects={[
- halftoneGradient({
+ halftoneLinearGradient({
firstStopDotSize: 0,
secondStopDotSize: 42,
+ firstStopPosition: [0, 0.5],
+ secondStopPosition: [1, 0.5],
gridSize: 24,
- rotation: 20,
- dotColor: '#111111',
+ dotColor: '#0b84f3',
}),
]}
/>
@@ -50,7 +51,7 @@ To use colors from the previous effect in the chain, set `colorMode` to `'source
```tsx twoslash title="MyComp.tsx"
import {AbsoluteFill} from 'remotion';
import {Video} from '@remotion/media';
-import {halftoneGradient} from '@remotion/effects/halftone-gradient';
+import {halftoneLinearGradient} from '@remotion/effects/halftone-linear-gradient';
export const MyComp: React.FC = () => {
return (
@@ -58,11 +59,12 @@ export const MyComp: React.FC = () => {
<Video
src="https://remotion.media/video.mp4"
effects={[
- halftoneGradient({
+ halftoneLinearGradient({
firstStopDotSize: 8,
secondStopDotSize: 44,
+ firstStopPosition: [0.2, 0],
+ secondStopPosition: [0.8, 1],
gridSize: 24,
- rotation: -25,
colorMode: 'source',
}),
]}
@@ -74,7 +76,7 @@ export const MyComp: React.FC = () => {
## API
-Pass an object with the following properties. You can also call `halftoneGradient()` without arguments.
+Pass an object with the following properties. You can also call `halftoneLinearGradient()` without arguments.
### `firstStopDotSize?`
@@ -88,13 +90,21 @@ Dot diameter in pixels on the opposite side of the gradient. Defaults to `40`. M
Set both dot sizes to `0` for no coverage. Set both large enough to overlap neighboring cells for full coverage.
-### `gridSize?`
+### `firstStopPosition?`
-Distance between adjacent dot centers in pixels. Defaults to `24`. Must be greater than `0`.
+UV coordinate where `firstStopDotSize` is reached. Defaults to `[0, 0.5]`.
+
+Pass a `[number, number]` tuple.
+
+### `secondStopPosition?`
-### `rotation?`
+UV coordinate where `secondStopDotSize` is reached. Defaults to `[1, 0.5]`.
-Rotation of the dot grid and linear gradient in degrees. Defaults to `0`.
+Pass a `[number, number]` tuple.
+
+### `gridSize?`
+
+Distance between adjacent dot centers in pixels. Defaults to `24`. Must be greater than `0`.
### `colorMode?`
@@ -116,11 +126,11 @@ When `true`, the effect is skipped. Defaults to `false`.
## Requirements
-`halftoneGradient()` uses a WebGL2 backend. During renders, enable WebGL via [`Config.setChromiumOpenGlRenderer()`](/docs/config#setchromiumopenglrenderer) (for example `'angle'`). See [Using WebGL during renders](/docs/remotion/html-in-canvas#using-webgl-during-renders).
+`halftoneLinearGradient()` uses a WebGL2 backend. During renders, enable WebGL via [`Config.setChromiumOpenGlRenderer()`](/docs/config#setchromiumopenglrenderer) (for example `'angle'`). See [Using WebGL during renders](/docs/remotion/html-in-canvas#using-webgl-during-renders).
## See also
- [`@remotion/effects`](/docs/effects/api)
- [`halftone()`](/docs/effects/halftone)
- [HTML-in-canvas guide](/docs/html-in-canvas)
-- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/halftone-gradient.ts)
+- [Source code for this effect](https://github.com/remotion-dev/remotion/blob/main/packages/effects/src/halftone-linear-gradient.ts)
diff --git a/packages/docs/docs/effects/table-of-contents.tsx b/packages/docs/docs/effects/table-of-contents.tsx
index fc9f72a7d2..18bcec83b5 100644
--- a/packages/docs/docs/effects/table-of-contents.tsx
+++ b/packages/docs/docs/effects/table-of-contents.tsx
@@ -166,10 +166,10 @@ const categories: {
description: 'Halftone dot grid effect',
},
{
- link: '/docs/effects/halftone-gradient',
- preview: '/img/effects-halftone-gradient-preview.jpg',
- alt: 'halftone gradient effect preview',
- name: 'halftoneGradient()',
+ link: '/docs/effects/halftone-linear-gradient',
+ preview: '/img/effects-halftone-linear-gradient-preview.jpg',
+ alt: 'halftone linear gradient effect preview',
+ name: 'halftoneLinearGradient()',
description: 'Linear dot size gradient',
},
{
diff --git a/packages/docs/sidebars.ts b/packages/docs/sidebars.ts
index 053bf8313f..deb96480d7 100644
--- a/packages/docs/sidebars.ts
+++ b/packages/docs/sidebars.ts
@@ -277,7 +277,7 @@ const sidebars: SidebarsConfig = {
'effects/glow',
'effects/grayscale',
'effects/halftone',
- 'effects/halftone-gradient',
+ 'effects/halftone-linear-gradient',
'effects/hue',
'effects/invert',
'effects/mirror',
diff --git a/packages/docs/src/data/articles.ts b/packages/docs/src/data/articles.ts
index 290370cbef..b70054e8a0 100644
--- a/packages/docs/src/data/articles.ts
+++ b/packages/docs/src/data/articles.ts
@@ -1791,13 +1791,13 @@ export const articles = [
slug: 'effects/grayscale',
},
{
- id: 'effects/halftone-gradient',
- title: 'halftoneGradient()',
- relativePath: 'docs/effects/halftone-gradient.mdx',
- compId: 'articles-docs-effects-halftone-gradient',
+ id: 'effects/halftone-linear-gradient',
+ title: 'halftoneLinearGradient()',
+ relativePath: 'docs/effects/halftone-linear-gradient.mdx',
+ compId: 'articles-docs-effects-halftone-linear-gradient',
crumb: '@remotion/effects',
noAi: false,
- slug: 'effects/halftone-gradient',
+ slug: 'effects/halftone-linear-gradient',
},
{
id: 'effects/halftone',
diff --git a/packages/docs/static/generated/articles-docs-effects-halftone-gradient.png b/packages/docs/static/generated/articles-docs-effects-halftone-gradient.png
deleted file mode 100644
index 8ce257eb9a..0000000000
Binary files a/packages/docs/static/generated/articles-docs-effects-halftone-gradient.png and /dev/null differ
diff --git a/packages/docs/static/generated/articles-docs-effects-halftone-linear-gradient.png b/packages/docs/static/generated/articles-docs-effects-halftone-linear-gradient.png
new file mode 100644
index 0000000000..d1549c61e2
Binary files /dev/null and b/packages/docs/static/generated/articles-docs-effects-halftone-linear-gradient.png differ
diff --git a/packages/docs/static/img/effects-halftone-gradient-preview.jpg b/packages/docs/static/img/effects-halftone-gradient-preview.jpg
deleted file mode 100644
index 054ab0205e..0000000000
Binary files a/packages/docs/static/img/effects-halftone-gradient-preview.jpg and /dev/null differ
diff --git a/packages/docs/static/img/effects-halftone-linear-gradient-preview.jpg b/packages/docs/static/img/effects-halftone-linear-gradient-preview.jpg
new file mode 100644
index 0000000000..6b21e53501
Binary files /dev/null and b/packages/docs/static/img/effects-halftone-linear-gradient-preview.jpg differ
diff --git a/packages/effects/bundle.ts b/packages/effects/bundle.ts
index 8a1f223f5f..563c42ba31 100644
--- a/packages/effects/bundle.ts
+++ b/packages/effects/bundle.ts
@@ -15,7 +15,7 @@ const effectEntrypoints = [
'src/duotone.ts',
'src/glow.ts',
'src/grayscale.ts',
- 'src/halftone-gradient.ts',
+ 'src/halftone-linear-gradient.ts',
'src/halftone.ts',
'src/hue.ts',
'src/invert.ts',
diff --git a/packages/effects/package.json b/packages/effects/package.json
index 6e44882bc0..b26e244f79 100644
--- a/packages/effects/package.json
+++ b/packages/effects/package.json
@@ -72,10 +72,10 @@
"module": "./dist/esm/halftone.mjs",
"import": "./dist/esm/halftone.mjs"
},
- "./halftone-gradient": {
- "types": "./dist/halftone-gradient.d.ts",
- "module": "./dist/esm/halftone-gradient.mjs",
- "import": "./dist/esm/halftone-gradient.mjs"
+ "./halftone-linear-gradient": {
+ "types": "./dist/halftone-linear-gradient.d.ts",
+ "module": "./dist/esm/halftone-linear-gradient.mjs",
+ "import": "./dist/esm/halftone-linear-gradient.mjs"
},
"./grayscale": {
"types": "./dist/grayscale.d.ts",
@@ -160,8 +160,8 @@
"halftone": [
"dist/halftone.d.ts"
],
- "halftone-gradient": [
- "dist/halftone-gradient.d.ts"
+ "halftone-linear-gradient": [
+ "dist/halftone-linear-gradient.d.ts"
],
"grayscale": [
"dist/grayscale.d.ts"
diff --git a/packages/effects/src/halftone-gradient.ts b/packages/effects/src/halftone-linear-gradient.ts
similarity index 70%
rename from packages/effects/src/halftone-gradient.ts
rename to packages/effects/src/halftone-linear-gradient.ts
index ee0611ddfa..bf4c497bf2 100644
--- a/packages/effects/src/halftone-gradient.ts
+++ b/packages/effects/src/halftone-linear-gradient.ts
@@ -12,15 +12,16 @@ import {
const {createEffect, createWebGL2ContextError} = Internals;
-const HALFTONE_GRADIENT_COLOR_MODES = ['solid', 'source'] as const;
+const HALFTONE_LINEAR_GRADIENT_COLOR_MODES = ['solid', 'source'] as const;
const DEFAULT_FIRST_STOP_DOT_SIZE = 0;
const DEFAULT_SECOND_STOP_DOT_SIZE = 40;
+const DEFAULT_FIRST_STOP_POSITION = [0, 0.5] as const;
+const DEFAULT_SECOND_STOP_POSITION = [1, 0.5] as const;
const DEFAULT_GRID_SIZE = 24;
-const DEFAULT_ROTATION = 0;
const DEFAULT_DOT_COLOR = 'black';
-export const halftoneGradientSchema = {
+export const halftoneLinearGradientSchema = {
firstStopDotSize: {
type: 'number',
min: 0,
@@ -37,6 +38,22 @@ export const halftoneGradientSchema = {
default: DEFAULT_SECOND_STOP_DOT_SIZE,
description: 'Second stop dot size',
},
+ firstStopPosition: {
+ type: 'uv-coordinate',
+ min: -1,
+ max: 2,
+ step: 0.01,
+ default: DEFAULT_FIRST_STOP_POSITION,
+ description: 'First stop position',
+ },
+ secondStopPosition: {
+ type: 'uv-coordinate',
+ min: -1,
+ max: 2,
+ step: 0.01,
+ default: DEFAULT_SECOND_STOP_POSITION,
+ description: 'Second stop position',
+ },
gridSize: {
type: 'number',
min: 1,
@@ -45,14 +62,6 @@ export const halftoneGradientSchema = {
default: DEFAULT_GRID_SIZE,
description: 'Grid size',
},
- rotation: {
- type: 'number',
- min: -180,
- max: 180,
- step: 1,
- default: DEFAULT_ROTATION,
- description: 'Rotation',
- },
colorMode: {
type: 'enum',
default: 'solid' as const,
@@ -70,10 +79,12 @@ export const halftoneGradientSchema = {
},
} as const satisfies SequenceSchema;
-export type HalftoneGradientColorMode =
- (typeof HALFTONE_GRADIENT_COLOR_MODES)[number];
+export type HalftoneLinearGradientColorMode =
+ (typeof HALFTONE_LINEAR_GRADIENT_COLOR_MODES)[number];
+
+export type UvCoordinate = readonly [number, number];
-type HalftoneGradientCommonParams = {
+type HalftoneLinearGradientCommonParams = {
/**
* Dot diameter at the first side of the gradient.
*/
@@ -83,16 +94,20 @@ type HalftoneGradientCommonParams = {
*/
readonly secondStopDotSize?: number;
/**
- * Distance between adjacent dot centers.
+ * UV coordinate where the first dot size is reached.
*/
- readonly gridSize?: number;
+ readonly firstStopPosition?: UvCoordinate;
/**
- * Rotation of the dot grid and the linear gradient in degrees.
+ * UV coordinate where the second dot size is reached.
*/
- readonly rotation?: number;
+ readonly secondStopPosition?: UvCoordinate;
+ /**
+ * Distance between adjacent dot centers.
+ */
+ readonly gridSize?: number;
};
-export type HalftoneGradientParams = HalftoneGradientCommonParams &
+export type HalftoneLinearGradientParams = HalftoneLinearGradientCommonParams &
(
| {
readonly colorMode?: 'solid';
@@ -104,12 +119,13 @@ export type HalftoneGradientParams = HalftoneGradientCommonParams &
}
);
-type HalftoneGradientResolved = {
+type HalftoneLinearGradientResolved = {
firstStopDotSize: number;
secondStopDotSize: number;
+ firstStopPosition: UvCoordinate;
+ secondStopPosition: UvCoordinate;
gridSize: number;
- rotation: number;
- colorMode: HalftoneGradientColorMode;
+ colorMode: HalftoneLinearGradientColorMode;
dotColor: string;
};
@@ -138,11 +154,18 @@ const assertOptionalEnum = <T extends string>(
}
};
-const resolve = (p: HalftoneGradientParams): HalftoneGradientResolved => ({
+const resolve = (
+ p: HalftoneLinearGradientParams,
+): HalftoneLinearGradientResolved => ({
firstStopDotSize: p.firstStopDotSize ?? DEFAULT_FIRST_STOP_DOT_SIZE,
secondStopDotSize: p.secondStopDotSize ?? DEFAULT_SECOND_STOP_DOT_SIZE,
+ firstStopPosition: [
+ ...(p.firstStopPosition ?? DEFAULT_FIRST_STOP_POSITION),
+ ] as UvCoordinate,
+ secondStopPosition: [
+ ...(p.secondStopPosition ?? DEFAULT_SECOND_STOP_POSITION),
+ ] as UvCoordinate,
gridSize: p.gridSize ?? DEFAULT_GRID_SIZE,
- rotation: p.rotation ?? DEFAULT_ROTATION,
colorMode: p.colorMode ?? 'solid',
dotColor:
'dotColor' in p ? (p.dotColor ?? DEFAULT_DOT_COLOR) : DEFAULT_DOT_COLOR,
@@ -164,18 +187,33 @@ const validatePositive = (value: number, name: string): void => {
}
};
-const validateHalftoneGradientParams = (
- params: HalftoneGradientParams,
+const assertOptionalUvCoordinate = (value: unknown, name: string): void => {
+ if (value === undefined) {
+ return;
+ }
+
+ if (
+ !Array.isArray(value) ||
+ value.length !== 2 ||
+ value.some((item) => typeof item !== 'number' || !Number.isFinite(item))
+ ) {
+ throw new TypeError(`"${name}" must be a [number, number] tuple`);
+ }
+};
+
+const validateHalftoneLinearGradientParams = (
+ params: HalftoneLinearGradientParams,
): void => {
- assertEffectParamsObject(params, 'Halftone gradient');
+ assertEffectParamsObject(params, 'Halftone linear gradient');
assertOptionalFiniteNumber(params.firstStopDotSize, 'firstStopDotSize');
assertOptionalFiniteNumber(params.secondStopDotSize, 'secondStopDotSize');
+ assertOptionalUvCoordinate(params.firstStopPosition, 'firstStopPosition');
+ assertOptionalUvCoordinate(params.secondStopPosition, 'secondStopPosition');
assertOptionalFiniteNumber(params.gridSize, 'gridSize');
- assertOptionalFiniteNumber(params.rotation, 'rotation');
assertOptionalEnum(
params.colorMode,
'colorMode',
- HALFTONE_GRADIENT_COLOR_MODES,
+ HALFTONE_LINEAR_GRADIENT_COLOR_MODES,
);
if (params.colorMode === 'source' && 'dotColor' in params) {
@@ -202,7 +240,7 @@ const validateHalftoneGradientParams = (
}
};
-const HALFTONE_GRADIENT_VS = /* glsl */ `#version 300 es
+const HALFTONE_LINEAR_GRADIENT_VS = /* glsl */ `#version 300 es
in vec2 aPos;
in vec2 aUv;
out vec2 vUv;
@@ -212,7 +250,7 @@ void main() {
}
`;
-const HALFTONE_GRADIENT_FS = /* glsl */ `#version 300 es
+const HALFTONE_LINEAR_GRADIENT_FS = /* glsl */ `#version 300 es
precision highp float;
in vec2 vUv;
@@ -222,51 +260,34 @@ uniform sampler2D uSource;
uniform vec2 uResolution;
uniform float uFirstStopDotSize;
uniform float uSecondStopDotSize;
+uniform vec2 uFirstStopPosition;
+uniform vec2 uSecondStopPosition;
uniform float uGridSize;
-uniform float uRotation;
uniform vec4 uColor;
uniform bool uUseSourceColor;
-vec2 rotatePoint(vec2 point, float angle) {
- float cosR = cos(angle);
- float sinR = sin(angle);
- return vec2(
- point.x * cosR + point.y * sinR,
- -point.x * sinR + point.y * cosR
- );
-}
-
-vec2 unrotatePoint(vec2 point, float angle) {
- float cosR = cos(angle);
- float sinR = sin(angle);
- return vec2(
- point.x * cosR - point.y * sinR,
- point.x * sinR + point.y * cosR
- );
-}
-
-float gradientProgress(vec2 point, vec2 direction) {
- float halfExtent = dot(abs(direction), uResolution * 0.5);
- if (halfExtent <= 0.0) {
+float gradientProgress(vec2 uv) {
+ vec2 stopVector = uSecondStopPosition - uFirstStopPosition;
+ float stopDistance = dot(stopVector, stopVector);
+ if (stopDistance <= 0.0) {
return 0.0;
}
- return clamp(dot(point, direction) / (halfExtent * 2.0) + 0.5, 0.0, 1.0);
+ return clamp(dot(uv - uFirstStopPosition, stopVector) / stopDistance, 0.0, 1.0);
}
void main() {
vec2 fragPos = vUv * uResolution;
vec2 center = uResolution * 0.5;
- vec2 relative = fragPos - center;
+ vec2 gridPos = fragPos - center;
- vec2 gridPos = rotatePoint(relative, uRotation);
float gridSize = max(uGridSize, 0.001);
vec2 cellIndex = floor(gridPos / gridSize + 0.5);
vec2 gridCenter = cellIndex * gridSize;
- vec2 canvasCenter = center + unrotatePoint(gridCenter, uRotation);
+ vec2 canvasCenter = center + gridCenter;
- vec2 direction = vec2(cos(uRotation), sin(uRotation));
- float progress = gradientProgress(canvasCenter - center, direction);
+ vec2 centerUv = canvasCenter / uResolution;
+ float progress = gradientProgress(centerUv);
float dotSize = mix(uFirstStopDotSize, uSecondStopDotSize, progress);
if (dotSize <= 0.01) {
@@ -278,13 +299,13 @@ void main() {
float radius = dotSize * 0.5;
float coverage = 1.0 - smoothstep(radius - 0.75, radius + 0.75, length(diff));
- vec2 sampleUv = clamp(canvasCenter / uResolution, vec2(0.0), vec2(1.0));
+ vec2 sampleUv = clamp(centerUv, vec2(0.0), vec2(1.0));
vec4 texColor = texture(uSource, sampleUv);
fragColor = (uUseSourceColor ? texColor : uColor) * coverage;
}
`;
-type HalftoneGradientState = {
+type HalftoneLinearGradientState = {
gl: WebGL2RenderingContext;
program: WebGLProgram;
vao: WebGLVertexArrayObject;
@@ -294,8 +315,9 @@ type HalftoneGradientState = {
uResolution: WebGLUniformLocation | null;
uFirstStopDotSize: WebGLUniformLocation | null;
uSecondStopDotSize: WebGLUniformLocation | null;
+ uFirstStopPosition: WebGLUniformLocation | null;
+ uSecondStopPosition: WebGLUniformLocation | null;
uGridSize: WebGLUniformLocation | null;
- uRotation: WebGLUniformLocation | null;
uColor: WebGLUniformLocation | null;
uUseSourceColor: WebGLUniformLocation | null;
colorCtx: CanvasRenderingContext2D;
@@ -319,7 +341,7 @@ const compileShader = (
const log = gl.getShaderInfoLog(shader);
gl.deleteShader(shader);
throw new Error(
- `Halftone gradient shader compile failed: ${log ?? '(no log)'}`,
+ `Halftone linear gradient shader compile failed: ${log ?? '(no log)'}`,
);
}
@@ -343,24 +365,25 @@ const linkProgram = (
const log = gl.getProgramInfoLog(program);
gl.deleteProgram(program);
throw new Error(
- `Halftone gradient program link failed: ${log ?? '(no log)'}`,
+ `Halftone linear gradient program link failed: ${log ?? '(no log)'}`,
);
}
return program;
};
-export const halftoneGradient = createEffect<
- HalftoneGradientParams,
- HalftoneGradientState
+export const halftoneLinearGradient = createEffect<
+ HalftoneLinearGradientParams,
+ HalftoneLinearGradientState
>({
- type: 'remotion/halftone-gradient',
- label: 'halftoneGradient()',
- documentationLink: 'https://www.remotion.dev/docs/effects/halftone-gradient',
+ type: 'remotion/halftone-linear-gradient',
+ label: 'halftoneLinearGradient()',
+ documentationLink:
+ 'https://www.remotion.dev/docs/effects/halftone-linear-gradient',
backend: 'webgl2',
calculateKey: (params) => {
const r = resolve(params);
- return `halftone-gradient-${r.firstStopDotSize}-${r.secondStopDotSize}-${r.gridSize}-${r.rotation}-${r.colorMode}-${r.dotColor}`;
+ return `halftone-linear-gradient-${r.firstStopDotSize}-${r.secondStopDotSize}-${r.firstStopPosition.join(':')}-${r.secondStopPosition.join(':')}-${r.gridSize}-${r.colorMode}-${r.dotColor}`;
},
setup: (target) => {
const gl = target.getContext('webgl2', {
@@ -369,13 +392,17 @@ export const halftoneGradient = createEffect<
preserveDrawingBuffer: true,
});
if (!gl) {
- throw createWebGL2ContextError('halftone gradient effect');
+ throw createWebGL2ContextError('halftone linear gradient effect');
}
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
- const vs = compileShader(gl, gl.VERTEX_SHADER, HALFTONE_GRADIENT_VS);
- const fs = compileShader(gl, gl.FRAGMENT_SHADER, HALFTONE_GRADIENT_FS);
+ const vs = compileShader(gl, gl.VERTEX_SHADER, HALFTONE_LINEAR_GRADIENT_VS);
+ const fs = compileShader(
+ gl,
+ gl.FRAGMENT_SHADER,
+ HALFTONE_LINEAR_GRADIENT_FS,
+ );
const program = linkProgram(gl, vs, fs);
gl.deleteShader(vs);
gl.deleteShader(fs);
@@ -438,8 +465,12 @@ export const halftoneGradient = createEffect<
uResolution: gl.getUniformLocation(program, 'uResolution'),
uFirstStopDotSize: gl.getUniformLocation(program, 'uFirstStopDotSize'),
uSecondStopDotSize: gl.getUniformLocation(program, 'uSecondStopDotSize'),
+ uFirstStopPosition: gl.getUniformLocation(program, 'uFirstStopPosition'),
+ uSecondStopPosition: gl.getUniformLocation(
+ program,
+ 'uSecondStopPosition',
+ ),
uGridSize: gl.getUniformLocation(program, 'uGridSize'),
- uRotation: gl.getUniformLocation(program, 'uRotation'),
uColor: gl.getUniformLocation(program, 'uColor'),
uUseSourceColor: gl.getUniformLocation(program, 'uUseSourceColor'),
colorCtx,
@@ -484,9 +515,19 @@ export const halftoneGradient = createEffect<
gl.uniform1f(state.uFirstStopDotSize, r.firstStopDotSize);
if (state.uSecondStopDotSize)
gl.uniform1f(state.uSecondStopDotSize, r.secondStopDotSize);
+ if (state.uFirstStopPosition)
+ gl.uniform2f(
+ state.uFirstStopPosition,
+ r.firstStopPosition[0],
+ r.firstStopPosition[1],
+ );
+ if (state.uSecondStopPosition)
+ gl.uniform2f(
+ state.uSecondStopPosition,
+ r.secondStopPosition[0],
+ r.secondStopPosition[1],
+ );
if (state.uGridSize) gl.uniform1f(state.uGridSize, r.gridSize);
- if (state.uRotation)
- gl.uniform1f(state.uRotation, (r.rotation * Math.PI) / 180);
if (state.uColor)
gl.uniform4f(
state.uColor,
@@ -510,6 +551,6 @@ export const halftoneGradient = createEffect<
gl.deleteVertexArray(vao);
gl.deleteTexture(texture);
},
- schema: halftoneGradientSchema,
- validateParams: validateHalftoneGradientParams,
+ schema: halftoneLinearGradientSchema,
+ validateParams: validateHalftoneLinearGradientParams,
});
diff --git a/packages/effects/src/test/effect-params.test.ts b/packages/effects/src/test/effect-params.test.ts
index fe81fcde64..6afb7cfafd 100644
--- a/packages/effects/src/test/effect-params.test.ts
+++ b/packages/effects/src/test/effect-params.test.ts
@@ -7,7 +7,7 @@ import {contrast} from '../contrast.js';
import {duotone} from '../duotone.js';
import {glow} from '../glow/index.js';
import {grayscale} from '../grayscale.js';
-import {halftoneGradient} from '../halftone-gradient.js';
+import {halftoneLinearGradient} from '../halftone-linear-gradient.js';
import {halftone} from '../halftone.js';
import {hue} from '../hue.js';
import {invert} from '../invert.js';
@@ -48,8 +48,8 @@ test('@remotion/effects expose documentation links', () => {
expect(halftone().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/halftone',
);
- expect(halftoneGradient().definition.documentationLink).toBe(
- 'https://www.remotion.dev/docs/effects/halftone-gradient',
+ expect(halftoneLinearGradient().definition.documentationLink).toBe(
+ 'https://www.remotion.dev/docs/effects/halftone-linear-gradient',
);
expect(hue().definition.documentationLink).toBe(
'https://www.remotion.dev/docs/effects/hue',
@@ -95,7 +95,9 @@ test('@remotion/effects expose API names as Studio labels', () => {
expect(duotone().definition.label).toBe('duotone()');
expect(grayscale().definition.label).toBe('grayscale()');
expect(halftone().definition.label).toBe('halftone()');
- expect(halftoneGradient().definition.label).toBe('halftoneGradient()');
+ expect(halftoneLinearGradient().definition.label).toBe(
+ 'halftoneLinearGradient()',
+ );
expect(hue().definition.label).toBe('hue()');
expect(invert().definition.label).toBe('invert()');
expect(mirror().definition.label).toBe('mirror()');
@@ -621,67 +623,85 @@ test('halftone() rejects dotColor for source color mode', () => {
).toThrow('"dotColor" can only be set when "colorMode" is "solid"');
});
-test('halftoneGradient() accepts default params', () => {
- expect(() => halftoneGradient()).not.toThrow();
+test('halftoneLinearGradient() accepts default params', () => {
+ expect(() => halftoneLinearGradient()).not.toThrow();
});
-test('halftoneGradient() rejects first stop dot size below range', () => {
- expect(() => halftoneGradient({firstStopDotSize: -1})).toThrow(
+test('halftoneLinearGradient() rejects first stop dot size below range', () => {
+ expect(() => halftoneLinearGradient({firstStopDotSize: -1})).toThrow(
'"firstStopDotSize" must be >= 0',
);
});
-test('halftoneGradient() rejects second stop dot size below range', () => {
- expect(() => halftoneGradient({secondStopDotSize: -1})).toThrow(
+test('halftoneLinearGradient() rejects second stop dot size below range', () => {
+ expect(() => halftoneLinearGradient({secondStopDotSize: -1})).toThrow(
'"secondStopDotSize" must be >= 0',
);
});
-test('halftoneGradient() rejects non-positive grid size', () => {
- expect(() => halftoneGradient({gridSize: 0})).toThrow(
+test('halftoneLinearGradient() rejects first stop position outside the tuple shape', () => {
+ expect(() =>
+ halftoneLinearGradient({
+ firstStopPosition: [0, 0.5, 1] as unknown as [number, number],
+ }),
+ ).toThrow('"firstStopPosition" must be a [number, number] tuple');
+});
+
+test('halftoneLinearGradient() rejects second stop position outside the tuple shape', () => {
+ expect(() =>
+ halftoneLinearGradient({
+ secondStopPosition: [0, Number.NaN],
+ }),
+ ).toThrow('"secondStopPosition" must be a [number, number] tuple');
+});
+
+test('halftoneLinearGradient() rejects non-positive grid size', () => {
+ expect(() => halftoneLinearGradient({gridSize: 0})).toThrow(
'"gridSize" must be greater than 0',
);
});
-test('halftoneGradient() rejects color outside the enum', () => {
+test('halftoneLinearGradient() rejects color outside the enum', () => {
expect(() =>
- halftoneGradient({
+ halftoneLinearGradient({
colorMode: 'cmyk' as Exclude<
- Parameters<typeof halftoneGradient>[0],
+ Parameters<typeof halftoneLinearGradient>[0],
undefined
>['colorMode'],
}),
).toThrow('"colorMode" must be "solid" or "source"');
});
-test('halftoneGradient() rejects empty dotColor strings', () => {
- expect(() => halftoneGradient({dotColor: ''})).toThrow(
+test('halftoneLinearGradient() rejects empty dotColor strings', () => {
+ expect(() => halftoneLinearGradient({dotColor: ''})).toThrow(
'"dotColor" must be a non-empty string, but got ""',
);
});
-test('halftoneGradient() rejects dotColor for source color mode', () => {
+test('halftoneLinearGradient() rejects dotColor for source color mode', () => {
expect(() =>
- halftoneGradient({
+ halftoneLinearGradient({
colorMode: 'source',
dotColor: 'black',
- } as Parameters<typeof halftoneGradient>[0]),
+ } as Parameters<typeof halftoneLinearGradient>[0]),
).toThrow('"dotColor" can only be set when "colorMode" is "solid"');
});
-test('halftoneGradient() parameters produce distinct effect keys', () => {
- const defaultGradient = halftoneGradient();
- const shiftedFirstStop = halftoneGradient({firstStopDotSize: 8});
- const shiftedSecondStop = halftoneGradient({secondStopDotSize: 20});
- const rotated = halftoneGradient({rotation: 45});
- const sourceColor = halftoneGradient({colorMode: 'source'});
+test('halftoneLinearGradient() parameters produce distinct effect keys', () => {
+ const defaultGradient = halftoneLinearGradient();
+ const shiftedFirstStop = halftoneLinearGradient({firstStopDotSize: 8});
+ const shiftedSecondStop = halftoneLinearGradient({secondStopDotSize: 20});
+ const shiftedFirstPosition = halftoneLinearGradient({
+ firstStopPosition: [0.2, 0.5],
+ });
+ const sourceColor = halftoneLinearGradient({colorMode: 'source'});
expect(
new Set([
defaultGradient.effectKey,
shiftedFirstStop.effectKey,
shiftedSecondStop.effectKey,
- rotated.effectKey,
+ shiftedFirstPosition.effectKey,
sourceColor.effectKey,
]).size,
).toBe(5);
diff --git a/packages/studio-server/src/test/update-effect-props.test.ts b/packages/studio-server/src/test/update-effect-props.test.ts
index 54123765e4..3689772795 100644
--- a/packages/studio-server/src/test/update-effect-props.test.ts
+++ b/packages/studio-server/src/test/update-effect-props.test.ts
@@ -15,6 +15,10 @@ const tintSchema = {
type: 'number',
default: 1,
},
+ position: {
+ type: 'uv-coordinate',
+ default: [0, 0.5],
+ },
} as const;
const buildInput = (
@@ -60,6 +64,19 @@ test('updateEffectProps adds a missing prop', () => {
expect(serialized).toContain('color: "red"');
});
+test('updateEffectProps writes uv-coordinate tuples', () => {
+ const input = buildInput('[tint({color: "red"})]');
+ const {serialized} = updateEffectPropsAst({
+ input,
+ sequenceNodePath: lineColumnToNodePath(input, 6),
+ effectIndex: 0,
+ update: {key: 'position', value: [0.25, 0.75], defaultValue: null},
+ schema: tintSchema,
+ });
+
+ expect(serialized).toContain('position: [0.25,0.75]');
+});
+
test('updateEffectProps removes a prop equal to default', () => {
const input = buildInput('[tint({color: "red", opacity: 0.5})]');
const {serialized} = updateEffectPropsAst({
diff --git a/packages/studio-shared/src/schema-field-info.ts b/packages/studio-shared/src/schema-field-info.ts
index 1b901fe32b..68156e8fe0 100644
--- a/packages/studio-shared/src/schema-field-info.ts
+++ b/packages/studio-shared/src/schema-field-info.ts
@@ -43,6 +43,7 @@ const SUPPORTED_SCHEMA_TYPES = [
'boolean',
'rotation',
'translate',
+ 'uv-coordinate',
'color',
'enum',
'hidden',
diff --git a/packages/studio-shared/src/test/schema-field-info.test.ts b/packages/studio-shared/src/test/schema-field-info.test.ts
index 3882a81c68..1b5a907e7e 100644
--- a/packages/studio-shared/src/test/schema-field-info.test.ts
+++ b/packages/studio-shared/src/test/schema-field-info.test.ts
@@ -30,6 +30,11 @@ const effect = {
source: {},
},
},
+ position: {
+ type: 'uv-coordinate',
+ default: [0, 0.5] as const,
+ description: 'Position',
+ },
},
} satisfies EffectDefinition<unknown>;
@@ -64,7 +69,7 @@ test('getEffectFieldsToShow uses the active enum variant', () => {
getEffectDragOverrides: () => ({}),
});
- expect(fields.map((field) => field.key)).toEqual(['colorMode']);
+ expect(fields.map((field) => field.key)).toEqual(['colorMode', 'position']);
});
test('getEffectFieldsToShow uses default enum variant if no code value exists', () => {
@@ -76,5 +81,9 @@ test('getEffectFieldsToShow uses default enum variant if no code value exists',
getEffectDragOverrides: () => ({}),
});
- expect(fields.map((field) => field.key)).toEqual(['colorMode', 'dotColor']);
+ expect(fields.map((field) => field.key)).toEqual([
+ 'colorMode',
+ 'dotColor',
+ 'position',
+ ]);
});
diff --git a/packages/studio/src/components/Timeline/TimelineSchemaField.tsx b/packages/studio/src/components/Timeline/TimelineSchemaField.tsx
index 8a5b2dd813..17cadf2831 100644
--- a/packages/studio/src/components/Timeline/TimelineSchemaField.tsx
+++ b/packages/studio/src/components/Timeline/TimelineSchemaField.tsx
@@ -15,6 +15,7 @@ import {TimelineEnumField} from './TimelineEnumField';
import {TimelineNumberField} from './TimelineNumberField';
import {TimelineRotationField} from './TimelineRotationField';
import {TimelineTranslateField} from './TimelineTranslateField';
+import {TimelineUvCoordinateField} from './TimelineUvCoordinateField';
const unsupportedLabel: React.CSSProperties = {
color: 'rgba(255, 255, 255, 0.4)',
@@ -116,6 +117,21 @@ export const TimelineFieldValue: React.FC<{
);
}
+ if (field.typeName === 'uv-coordinate') {
+ return (
+ <span style={wrapperStyle}>
+ <TimelineUvCoordinateField
+ field={field}
+ effectiveValue={effectiveValue}
+ propStatus={propStatus}
+ onSave={onSave}
+ onDragValueChange={onDragValueChange}
+ onDragEnd={onDragEnd}
+ />
+ </span>
+ );
+ }
+
if (field.typeName === 'boolean') {
return (
<span style={wrapperStyle}>
diff --git a/packages/studio/src/components/Timeline/TimelineUvCoordinateField.tsx b/packages/studio/src/components/Timeline/TimelineUvCoordinateField.tsx
new file mode 100644
index 0000000000..156a61fc93
--- /dev/null
+++ b/packages/studio/src/components/Timeline/TimelineUvCoordinateField.tsx
@@ -0,0 +1,232 @@
+import React, {useCallback, useMemo, useState} from 'react';
+import type {CanUpdateSequencePropStatus} from 'remotion';
+import type {
+ SchemaFieldInfo,
+ TimelineFieldOnDragValueChange,
+ TimelineFieldOnSave,
+} from '../../helpers/timeline-layout';
+import {InputDragger} from '../NewComposition/InputDragger';
+import {getDecimalPlaces} from './timeline-field-utils';
+
+const leftDraggerStyle: React.CSSProperties = {
+ paddingLeft: 0,
+};
+
+const rightDraggerStyle: React.CSSProperties = {
+ paddingRight: 0,
+};
+
+const containerStyle: React.CSSProperties = {
+ display: 'flex',
+ gap: 4,
+};
+
+const parseUvCoordinate = (value: unknown): [number, number] => {
+ if (
+ Array.isArray(value) &&
+ value.length === 2 &&
+ value.every((item) => typeof item === 'number' && Number.isFinite(item))
+ ) {
+ return [value[0], value[1]];
+ }
+
+ return [0, 0];
+};
+
+const tuplesEqual = (
+ left: unknown,
+ right: readonly [number, number],
+): boolean => {
+ if (!Array.isArray(left) || left.length !== 2) {
+ return false;
+ }
+
+ return left[0] === right[0] && left[1] === right[1];
+};
+
+export const TimelineUvCoordinateField: React.FC<{
+ readonly field: SchemaFieldInfo;
+ readonly propStatus: CanUpdateSequencePropStatus;
+ readonly effectiveValue: unknown;
+ readonly onSave: TimelineFieldOnSave;
+ readonly onDragValueChange: TimelineFieldOnDragValueChange;
+ readonly onDragEnd: () => void;
+}> = ({
+ field,
+ propStatus,
+ effectiveValue,
+ onSave,
+ onDragValueChange,
+ onDragEnd,
+}) => {
+ const [dragX, setDragX] = useState<number | null>(null);
+ const [dragY, setDragY] = useState<number | null>(null);
+
+ const [codeX, codeY] = useMemo(
+ () => parseUvCoordinate(effectiveValue),
+ [effectiveValue],
+ );
+
+ const makeTuple = useCallback(
+ (x: number, y: number): [number, number] => [x, y],
+ [],
+ );
+
+ const step =
+ field.fieldSchema.type === 'uv-coordinate'
+ ? (field.fieldSchema.step ?? 0.01)
+ : 0.01;
+
+ const min =
+ field.fieldSchema.type === 'uv-coordinate'
+ ? (field.fieldSchema.min ?? -Infinity)
+ : -Infinity;
+
+ const max =
+ field.fieldSchema.type === 'uv-coordinate'
+ ? (field.fieldSchema.max ?? Infinity)
+ : Infinity;
+
+ const stepDecimals = useMemo(() => getDecimalPlaces(step), [step]);
+
+ const formatter = useCallback(
+ (v: number | string) => {
+ const num = Number(v);
+ const digits = Math.max(stepDecimals, getDecimalPlaces(num));
+ return digits === 0 ? String(num) : num.toFixed(digits);
+ },
+ [stepDecimals],
+ );
+
+ const onXChange = useCallback(
+ (newVal: number) => {
+ setDragX(newVal);
+ const currentY = dragY ?? codeY;
+ onDragValueChange(makeTuple(newVal, currentY));
+ },
+ [onDragValueChange, dragY, codeY, makeTuple],
+ );
+
+ const onXChangeEnd = useCallback(
+ (newVal: number) => {
+ const currentY = dragY ?? codeY;
+ const newTuple = makeTuple(newVal, currentY);
+ if (
+ propStatus.canUpdate &&
+ !tuplesEqual(propStatus.codeValue, newTuple)
+ ) {
+ onSave(newTuple).finally(() => {
+ setDragX(null);
+ onDragEnd();
+ });
+ } else {
+ setDragX(null);
+ onDragEnd();
+ }
+ },
+ [dragY, codeY, makeTuple, propStatus, onSave, onDragEnd],
+ );
+
+ const onXTextChange = useCallback(
+ (newVal: string) => {
+ if (propStatus.canUpdate) {
+ const parsed = Number(newVal);
+ if (!Number.isNaN(parsed)) {
+ const currentY = dragY ?? codeY;
+ const newTuple = makeTuple(parsed, currentY);
+ if (!tuplesEqual(propStatus.codeValue, newTuple)) {
+ setDragX(parsed);
+ onSave(newTuple).finally(() => {
+ setDragX(null);
+ });
+ }
+ }
+ }
+ },
+ [propStatus, dragY, codeY, makeTuple, onSave],
+ );
+
+ const onYChange = useCallback(
+ (newVal: number) => {
+ setDragY(newVal);
+ const currentX = dragX ?? codeX;
+ onDragValueChange(makeTuple(currentX, newVal));
+ },
+ [onDragValueChange, dragX, codeX, makeTuple],
+ );
+
+ const onYChangeEnd = useCallback(
+ (newVal: number) => {
+ const currentX = dragX ?? codeX;
+ const newTuple = makeTuple(currentX, newVal);
+ if (
+ propStatus.canUpdate &&
+ !tuplesEqual(propStatus.codeValue, newTuple)
+ ) {
+ onSave(newTuple).finally(() => {
+ setDragY(null);
+ onDragEnd();
+ });
+ } else {
+ setDragY(null);
+ onDragEnd();
+ }
+ },
+ [dragX, codeX, makeTuple, propStatus, onSave, onDragEnd],
+ );
+
+ const onYTextChange = useCallback(
+ (newVal: string) => {
+ if (propStatus.canUpdate) {
+ const parsed = Number(newVal);
+ if (!Number.isNaN(parsed)) {
+ const currentX = dragX ?? codeX;
+ const newTuple = makeTuple(currentX, parsed);
+ if (!tuplesEqual(propStatus.codeValue, newTuple)) {
+ setDragY(parsed);
+ onSave(newTuple).finally(() => {
+ setDragY(null);
+ });
+ }
+ }
+ }
+ },
+ [propStatus, onSave, dragX, codeX, makeTuple],
+ );
+
+ return (
+ <span style={containerStyle}>
+ <InputDragger
+ type="number"
+ value={dragX ?? codeX}
+ style={leftDraggerStyle}
+ status="ok"
+ small
+ onValueChange={onXChange}
+ onValueChangeEnd={onXChangeEnd}
+ onTextChange={onXTextChange}
+ min={min}
+ max={max}
+ step={step}
+ formatter={formatter}
+ rightAlign={false}
+ />
+ <div style={{marginLeft: -6, marginRight: -6}} />
+ <InputDragger
+ type="number"
+ value={dragY ?? codeY}
+ style={rightDraggerStyle}
+ status="ok"
+ small
+ onValueChange={onYChange}
+ onValueChangeEnd={onYChangeEnd}
+ onTextChange={onYTextChange}
+ min={min}
+ max={max}
+ step={step}
+ formatter={formatter}
+ rightAlign={false}
+ />
+ </span>
+ );
+};