🎥 Make videos programmatically with React
`@remotion/maptiler`: Add MapTiler-compatible map components (#10638)
Jonny Burger6bf11d021c3d
diff --git a/packages/example/src/Root.tsx b/packages/example/src/Root.tsxindex de3a507c53..db0d8dc4c8 100644--- a/packages/example/src/Root.tsx+++ b/packages/example/src/Root.tsx@@ -449,22 +449,32 @@ export const Index: React.FC = () => {width={1280}height={720}/>- <Composition- id="switzerland-map"- lazyComponent={() => import('./SwitzerlandMap/SwitzerlandMap')}- durationInFrames={240}- fps={30}- width={1080}- height={1080}- />- <Composition- id="zurich-to-stuttgart-map"- lazyComponent={() => import('./SwitzerlandMap/ZurichToStuttgartMap')}- durationInFrames={270}- fps={30}- width={1080}- height={1080}- />+ <Folder name="maptiler">+ <Composition+ id="switzerland-map"+ lazyComponent={() => import('./SwitzerlandMap/SwitzerlandMap')}+ durationInFrames={240}+ fps={30}+ width={1080}+ height={1080}+ />+ <Composition+ id="zurich-to-stuttgart-map"+ lazyComponent={() => import('./SwitzerlandMap/ZurichToStuttgartMap')}+ durationInFrames={270}+ fps={30}+ width={1080}+ height={1080}+ />+ <Composition+ id="maptiler-heatmap"+ lazyComponent={() => import('./SwitzerlandMap/Heatmap')}+ durationInFrames={150}+ fps={30}+ width={1080}+ height={1080}+ />+ </Folder><Compositionid="captions-tester"component={AnimatedCaptionsComposition}diff --git a/packages/example/src/SwitzerlandMap/Heatmap.tsx b/packages/example/src/SwitzerlandMap/Heatmap.tsxnew file mode 100644index 0000000000..52ea4c6cd5--- /dev/null+++ b/packages/example/src/SwitzerlandMap/Heatmap.tsx@@ -0,0 +1,148 @@+import {+ MapHeatmap,+ MapViewport,+ type MapHeatmapProps,+} from '@remotion/maptiler';+import {Easing, interpolate, useCurrentFrame} from 'remotion';++const zurichActivity = {+ type: 'FeatureCollection',+ features: [+ {+ type: 'Feature',+ properties: {activity: 92},+ geometry: {type: 'Point', coordinates: [8.5417, 47.3769]},+ },+ {+ type: 'Feature',+ properties: {activity: 78},+ geometry: {type: 'Point', coordinates: [8.5352, 47.3782]},+ },+ {+ type: 'Feature',+ properties: {activity: 74},+ geometry: {type: 'Point', coordinates: [8.5482, 47.3763]},+ },+ {+ type: 'Feature',+ properties: {activity: 66},+ geometry: {type: 'Point', coordinates: [8.5203, 47.3731]},+ },+ {+ type: 'Feature',+ properties: {activity: 62},+ geometry: {type: 'Point', coordinates: [8.5581, 47.3708]},+ },+ {+ type: 'Feature',+ properties: {activity: 59},+ geometry: {type: 'Point', coordinates: [8.531, 47.3674]},+ },+ {+ type: 'Feature',+ properties: {activity: 57},+ geometry: {type: 'Point', coordinates: [8.5451, 47.3658]},+ },+ {+ type: 'Feature',+ properties: {activity: 54},+ geometry: {type: 'Point', coordinates: [8.5097, 47.3815]},+ },+ {+ type: 'Feature',+ properties: {activity: 51},+ geometry: {type: 'Point', coordinates: [8.5662, 47.3833]},+ },+ {+ type: 'Feature',+ properties: {activity: 48},+ geometry: {type: 'Point', coordinates: [8.577, 47.3717]},+ },+ {+ type: 'Feature',+ properties: {activity: 45},+ geometry: {type: 'Point', coordinates: [8.5175, 47.3894]},+ },+ {+ type: 'Feature',+ properties: {activity: 42},+ geometry: {type: 'Point', coordinates: [8.5517, 47.3902]},+ },+ {+ type: 'Feature',+ properties: {activity: 39},+ geometry: {type: 'Point', coordinates: [8.5268, 47.3981]},+ },+ {+ type: 'Feature',+ properties: {activity: 36},+ geometry: {type: 'Point', coordinates: [8.5634, 47.397]},+ },+ {+ type: 'Feature',+ properties: {activity: 34},+ geometry: {type: 'Point', coordinates: [8.4914, 47.3912]},+ },+ {+ type: 'Feature',+ properties: {activity: 31},+ geometry: {type: 'Point', coordinates: [8.5847, 47.3888]},+ },+ {+ type: 'Feature',+ properties: {activity: 28},+ geometry: {type: 'Point', coordinates: [8.5013, 47.3635]},+ },+ {+ type: 'Feature',+ properties: {activity: 25},+ geometry: {type: 'Point', coordinates: [8.5688, 47.3569]},+ },+ ],+} satisfies MapHeatmapProps['data'];++export const Heatmap = () => {+ const frame = useCurrentFrame();++ return (+ <MapViewport+ name="Map camera"+ apiKey={process.env.REMOTION_MAPTILER_KEY ?? null}+ centerLongitude={8.54}+ centerLatitude={47.378}+ zoom={11.6}+ bearing={0}+ pitch={0}+ showLabels={false}+ administrativeBorders="none"+ >+ <MapHeatmap+ name="Zurich activity heatmap"+ layerId="zurich-activity"+ data={zurichActivity}+ property="activity"+ weight={[+ {propertyValue: 20, value: 0.2},+ {propertyValue: 100, value: 1},+ ]}+ radius={interpolate(frame, [0, 45], [12, 42], {+ easing: Easing.out(Easing.cubic),+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ })}+ intensity={interpolate(frame, [0, 45], [0.2, 1.4], {+ easing: Easing.out(Easing.cubic),+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ })}+ opacity={interpolate(frame, [0, 30, 120, 150], [0, 0.85, 0.85, 0], {+ extrapolateLeft: 'clamp',+ extrapolateRight: 'clamp',+ })}+ zoomCompensation={false}+ />+ </MapViewport>+ );+};++export default Heatmap;diff --git a/packages/example/src/SwitzerlandMap/SwitzerlandMap.tsx b/packages/example/src/SwitzerlandMap/SwitzerlandMap.tsxindex 41af3a3533..7334c644ce 100644--- a/packages/example/src/SwitzerlandMap/SwitzerlandMap.tsx+++ b/packages/example/src/SwitzerlandMap/SwitzerlandMap.tsx@@ -18,6 +18,8 @@ export const SwitzerlandMap = () => {name="Map camera"from={0}apiKey={process.env.REMOTION_MAPTILER_KEY ?? null}+ showLabels={false}+ administrativeBorders="country-only"centerLongitude={interpolate(frame, [124, 164], [8.2275, 13.3347], {easing: [Easing.bezier(0.65, 0, 0.35, 1)],extrapolateLeft: 'clamp',diff --git a/packages/example/src/SwitzerlandMap/ZurichToStuttgartMap.tsx b/packages/example/src/SwitzerlandMap/ZurichToStuttgartMap.tsxindex 1cd2aa894c..e6646aa24b 100644--- a/packages/example/src/SwitzerlandMap/ZurichToStuttgartMap.tsx+++ b/packages/example/src/SwitzerlandMap/ZurichToStuttgartMap.tsx@@ -1,8 +1,8 @@import {MapOverlay,- MapRoute,+ MapPolyline,MapViewport,- type MapRouteFeature,+ type MapPolylineFeature,} from '@remotion/maptiler';import {Easing, interpolate, staticFile, useCurrentFrame} from 'remotion';import {MapPin} from './MapPin';@@ -24,7 +24,7 @@ const zurichToStuttgart = {[9.1829, 48.7758],],},-} as const satisfies MapRouteFeature;+} as const satisfies MapPolylineFeature;export const ZurichToStuttgartMap = () => {const frame = useCurrentFrame();@@ -34,6 +34,8 @@ export const ZurichToStuttgartMap = () => {name="Map camera"from={0}apiKey={process.env.REMOTION_MAPTILER_KEY ?? null}+ showLabels={false}+ administrativeBorders="country-only"centerLongitude={interpolate(frame,[106, 179],@@ -84,6 +86,7 @@ export const ZurichToStuttgartMap = () => {<MapOverlayname="Zurich marker"from={28}+ anchor="top-left"longitude={8.541071693747302}latitude={47.41728197584036}style={{@@ -92,12 +95,16 @@ export const ZurichToStuttgartMap = () => {><MapPin name="Zurich pin" imageSrc={staticFile('zurich-pin.png')} /></MapOverlay>- <MapRoute+ <MapPolylinename="Zurich to Stuttgart route"from={106}- id="zurich-to-stuttgart"- feature={zurichToStuttgart}- glow={0.7}+ layerId="zurich-to-stuttgart"+ data={zurichToStuttgart}+ outline+ outlineBlur={8}+ outlineColor="#ffffff"+ outlineOpacity={0.7}+ outlineWidth={7}progress={interpolate(frame, [128, 179], [0, 1], {extrapolateLeft: 'clamp',extrapolateRight: 'clamp',@@ -113,12 +120,13 @@ export const ZurichToStuttgartMap = () => {}),],})}- strokeColor={'#ff6700'}- strokeWidth={8}+ lineColor={'#ff6700'}+ lineWidth={8}/><MapOverlayname="Stuttgart marker"from={225}+ anchor="top-left"longitude={9.1829}latitude={48.7758}style={{diff --git a/packages/maptiler/src/MapHeatmap.tsx b/packages/maptiler/src/MapHeatmap.tsxnew file mode 100644index 0000000000..872fa97b39--- /dev/null+++ b/packages/maptiler/src/MapHeatmap.tsx@@ -0,0 +1,211 @@+import {+ helpers,+ type GeoJSONSource,+ type HeatmapLayerOptions,+} from '@maptiler/sdk';+import {useContext, useEffect, useRef} from 'react';+import {+ Sequence,+ type InteractiveBaseProps,+ type SequenceControls,+ useDelayRender,+} from 'remotion';+import {delayMapRender} from './delay-map-render';+import {MapTilerContext} from './MapTilerContext';++export type MapHeatmapProps = InteractiveBaseProps &+ Omit<HeatmapLayerOptions, 'layerId' | 'sourceId'> & {+ readonly controls?: SequenceControls;+ readonly layerId: string;+ readonly sourceId?: string;+ };++type MapHeatmapLayerIds = {+ readonly heatmapLayerId: string;+ readonly heatmapSourceId: string;+};++const MapHeatmapDrawing = ({+ beforeId,+ colorRamp,+ data,+ intensity,+ layerId,+ maxzoom,+ minzoom,+ opacity,+ property,+ radius,+ sourceId = `${layerId}-source`,+ weight,+ zoomCompensation,+}: MapHeatmapProps) => {+ const {map, styleRevision} = useContext(MapTilerContext);+ const {continueRender, delayRender} = useDelayRender();+ const layerIdsRef = useRef<MapHeatmapLayerIds | null>(null);+ const optionsRef = useRef<HeatmapLayerOptions | null>(null);+ const intensityIsDynamic = typeof intensity === 'number';+ const opacityIsDynamic = typeof opacity === 'number';+ const radiusIsDynamic = typeof radius === 'number';+ const structuralKey = JSON.stringify({+ beforeId,+ colorRamp,+ data: typeof data === 'string' ? data : null,+ intensity: intensityIsDynamic ? null : intensity,+ maxzoom,+ minzoom,+ opacity: opacityIsDynamic ? null : opacity,+ property,+ radius: radiusIsDynamic ? null : radius,+ weight,+ zoomCompensation,+ });++ optionsRef.current = {+ ...(beforeId === undefined ? {} : {beforeId}),+ ...(colorRamp === undefined ? {} : {colorRamp}),+ data,+ ...(intensity === undefined ? {} : {intensity}),+ layerId,+ ...(maxzoom === undefined ? {} : {maxzoom}),+ ...(minzoom === undefined ? {} : {minzoom}),+ ...(opacity === undefined ? {} : {opacity}),+ ...(property === undefined ? {} : {property}),+ ...(radius === undefined ? {} : {radius}),+ sourceId,+ ...(weight === undefined ? {} : {weight}),+ ...(zoomCompensation === undefined ? {} : {zoomCompensation}),+ };++ useEffect(() => {+ if (!map || !optionsRef.current) {+ return;+ }++ const loadingHandle = delayRender(`Loading MapTiler heatmap ${layerId}`);+ let hasFinished = false;+ const finish = () => {+ if (hasFinished) {+ return;+ }++ hasFinished = true;+ continueRender(loadingHandle);+ };++ layerIdsRef.current = helpers.addHeatmap(map, optionsRef.current);+ map.once('idle', finish);+ map.triggerRepaint();++ return () => {+ map.off('idle', finish);+ finish();+ const ids = layerIdsRef.current;+ if (!ids) {+ return;+ }++ if (map.getLayer(ids.heatmapLayerId)) {+ map.removeLayer(ids.heatmapLayerId);+ }++ if (map.getSource(ids.heatmapSourceId)) {+ map.removeSource(ids.heatmapSourceId);+ }++ layerIdsRef.current = null;+ map.triggerRepaint();+ };+ }, [continueRender, delayRender, layerId, map, structuralKey, styleRevision]);++ useEffect(() => {+ if (!map || typeof data === 'string') {+ return;+ }++ const ids = layerIdsRef.current;+ if (ids && map.getSource(ids.heatmapSourceId)) {+ (map.getSource(ids.heatmapSourceId) as GeoJSONSource).setData(data);+ return delayMapRender({+ continueRender,+ delayRender,+ label: `Updating MapTiler heatmap source ${layerId}`,+ map,+ });+ }+ }, [continueRender, data, delayRender, layerId, map]);++ useEffect(() => {+ if (!map) {+ return;+ }++ const id = layerIdsRef.current?.heatmapLayerId;+ if (!id || !map.getLayer(id)) {+ return;+ }++ if (intensityIsDynamic) {+ map.setPaintProperty(id, 'heatmap-intensity', intensity);+ }++ if (opacityIsDynamic) {+ map.setPaintProperty(id, 'heatmap-opacity', opacity);+ }++ if (radiusIsDynamic) {+ map.setPaintProperty(id, 'heatmap-radius', radius);+ }++ return delayMapRender({+ continueRender,+ delayRender,+ label: `Drawing MapTiler heatmap ${layerId}`,+ map,+ });+ }, [+ continueRender,+ delayRender,+ intensity,+ intensityIsDynamic,+ layerId,+ map,+ opacity,+ opacityIsDynamic,+ radius,+ radiusIsDynamic,+ structuralKey,+ styleRevision,+ ]);++ return null;+};++export const MapHeatmap = (props: MapHeatmapProps) => {+ const {+ controls,+ durationInFrames,+ freeze,+ from,+ hidden,+ name,+ showInTimeline,+ trimBefore,+ } = props;++ return (+ <Sequence+ layout="none"+ from={from ?? 0}+ trimBefore={trimBefore}+ durationInFrames={durationInFrames ?? Infinity}+ freeze={freeze}+ hidden={hidden}+ name={name ?? '<MapHeatmap>'}+ showInTimeline={showInTimeline ?? true}+ controls={controls}+ >+ <MapHeatmapDrawing {...props} />+ </Sequence>+ );+};diff --git a/packages/maptiler/src/MapLayer.tsx b/packages/maptiler/src/MapLayer.tsxnew file mode 100644index 0000000000..da5bc442bb--- /dev/null+++ b/packages/maptiler/src/MapLayer.tsx@@ -0,0 +1,122 @@+import type {LayerSpecification} from '@maptiler/sdk';+import {useContext, useEffect, useRef} from 'react';+import {useDelayRender} from 'remotion';+import {MapTilerContext} from './MapTilerContext';++export type MapLayerProps = {+ readonly beforeId?: string;+ readonly layer: LayerSpecification;+};++export const MapLayer = ({beforeId, layer}: MapLayerProps) => {+ const {map, styleRevision} = useContext(MapTilerContext);+ const previousLayerRef = useRef<LayerSpecification | null>(null);+ const {continueRender, delayRender} = useDelayRender();++ useEffect(() => {+ if (!map) {+ return;+ }++ const loadingHandle = delayRender(`Drawing MapTiler layer ${layer.id}`);+ let hasFinished = false;+ const finish = () => {+ if (hasFinished) {+ return;+ }++ hasFinished = true;+ continueRender(loadingHandle);+ };++ const previousLayer = previousLayerRef.current;+ const existingLayer = map.getLayer(layer.id);+ const layerWithDefinedProperties = Object.fromEntries(+ Object.entries(layer).filter(([, value]) => value !== undefined),+ ) as LayerSpecification;+ const sourceChanged =+ previousLayer !== null &&+ 'source' in previousLayer &&+ 'source' in layer &&+ (previousLayer.source !== layer.source ||+ previousLayer['source-layer'] !== layer['source-layer']);++ if (existingLayer && (existingLayer.type !== layer.type || sourceChanged)) {+ map.removeLayer(layer.id);+ }++ if (!map.getLayer(layer.id)) {+ map.addLayer(layerWithDefinedProperties, beforeId);+ } else {+ if ('paint' in layer || (previousLayer && 'paint' in previousLayer)) {+ const previousPaint =+ previousLayer && 'paint' in previousLayer+ ? previousLayer.paint+ : undefined;+ const paint = 'paint' in layer ? layer.paint : undefined;+ for (const property of new Set([+ ...Object.keys(previousPaint ?? {}),+ ...Object.keys(paint ?? {}),+ ])) {+ map.setPaintProperty(+ layer.id,+ property,+ (paint as Record<string, unknown> | undefined)?.[property] ?? null,+ );+ }+ }++ if ('layout' in layer || (previousLayer && 'layout' in previousLayer)) {+ const previousLayout =+ previousLayer && 'layout' in previousLayer+ ? previousLayer.layout+ : undefined;+ const layout = 'layout' in layer ? layer.layout : undefined;+ for (const property of new Set([+ ...Object.keys(previousLayout ?? {}),+ ...Object.keys(layout ?? {}),+ ])) {+ map.setLayoutProperty(+ layer.id,+ property,+ (layout as Record<string, unknown> | undefined)?.[property] ?? null,+ );+ }+ }++ if ('filter' in layer) {+ map.setFilter(layer.id, layer.filter ?? null);+ }++ map.setLayerZoomRange(layer.id, layer.minzoom ?? 0, layer.maxzoom ?? 24);++ if (beforeId && map.getLayer(beforeId)) {+ map.moveLayer(layer.id, beforeId);+ }+ }++ previousLayerRef.current = layer;+ map.once('idle', finish);+ map.triggerRepaint();++ return () => {+ map.off('idle', finish);+ finish();+ };+ }, [beforeId, continueRender, delayRender, layer, map, styleRevision]);++ useEffect(() => {+ if (!map) {+ return;+ }++ return () => {+ if (map.getLayer(layer.id)) {+ map.removeLayer(layer.id);+ map.triggerRepaint();+ }+ };+ }, [layer.id, map]);++ return null;+};diff --git a/packages/maptiler/src/MapOverlay.tsx b/packages/maptiler/src/MapOverlay.tsxindex 6d42b57e82..6427d4732a 100644--- a/packages/maptiler/src/MapOverlay.tsx+++ b/packages/maptiler/src/MapOverlay.tsx@@ -16,12 +16,29 @@ import {} from 'remotion';import {MapTilerContext} from './MapTilerContext';-type MapOverlayProps = InteractiveBaseProps &+export type MapOverlayAnchor =+ | 'bottom'+ | 'bottom-left'+ | 'bottom-right'+ | 'center'+ | 'left'+ | 'right'+ | 'top'+ | 'top-left'+ | 'top-right';++export type MapOverlayProps = InteractiveBaseProps &InteractiveTransformProps & {+ readonly anchor?: MapOverlayAnchor;readonly children?: ReactNode;readonly controls?: SequenceControls;readonly latitude: number;readonly longitude: number;+ readonly offsetX?: number;+ readonly offsetY?: number;+ readonly opacity?: number;+ readonly rotation?: number;+ readonly rotationAlignment?: 'map' | 'viewport';};const mapOverlaySchema = {@@ -44,6 +61,46 @@ const mapOverlaySchema = {description: 'Latitude',hiddenFromList: false,},+ offsetX: {+ type: 'number',+ min: -2000,+ max: 2000,+ step: 1,+ default: 0,+ description: 'Horizontal marker offset',+ hiddenFromList: false,+ keyframable: true,+ },+ offsetY: {+ type: 'number',+ min: -2000,+ max: 2000,+ step: 1,+ default: 0,+ description: 'Vertical marker offset',+ hiddenFromList: false,+ keyframable: true,+ },+ opacity: {+ type: 'number',+ min: 0,+ max: 1,+ step: 0.01,+ default: 1,+ description: 'Marker opacity',+ hiddenFromList: false,+ keyframable: true,+ },+ rotation: {+ type: 'number',+ min: -360,+ max: 360,+ step: 1,+ default: 0,+ description: 'Marker rotation',+ hiddenFromList: false,+ keyframable: true,+ },...Interactive.transformSchema,} as const satisfies InteractivitySchema;@@ -52,9 +109,15 @@ const MapOverlayRefForwardingFunction: ForwardRefRenderFunction<MapOverlayProps> = ({+ anchor = 'center',children,latitude,longitude,+ offsetX = 0,+ offsetY = 0,+ opacity = 1,+ rotation = 0,+ rotationAlignment = 'viewport',style,durationInFrames,from,@@ -70,6 +133,16 @@ const MapOverlayRefForwardingFunction: ForwardRefRenderFunction<const {map} = useContext(MapTilerContext);const refForOutline = useRef<HTMLDivElement>(null);const point = map?.project([longitude, latitude]);+ const horizontalAnchor = anchor.includes('left')+ ? 0+ : anchor.includes('right')+ ? -100+ : -50;+ const verticalAnchor = anchor.includes('top')+ ? 0+ : anchor.includes('bottom')+ ? -100+ : -50;useImperativeHandle(ref, () => refForOutline.current as HTMLDivElement, []);@@ -89,10 +162,13 @@ const MapOverlayRefForwardingFunction: ForwardRefRenderFunction<<divref={refForOutline}style={{- left: point?.x ?? 0,+ left: (point?.x ?? 0) + offsetX,+ opacity,pointerEvents: 'none',position: 'absolute',- top: point?.y ?? 0,+ rotate: `${rotation + (rotationAlignment === 'map' ? (map?.getBearing() ?? 0) : 0)}deg`,+ top: (point?.y ?? 0) + offsetY,+ translate: `${horizontalAnchor}% ${verticalAnchor}%`,zIndex: 1,...style,}}@@ -112,3 +188,5 @@ export const MapOverlay = Interactive.withSchema({schema: mapOverlaySchema,supportsEffects: false,});++export const MapMarker = MapOverlay;diff --git a/packages/maptiler/src/MapPoint.tsx b/packages/maptiler/src/MapPoint.tsxnew file mode 100644index 0000000000..aa56310c39--- /dev/null+++ b/packages/maptiler/src/MapPoint.tsx@@ -0,0 +1,285 @@+import {+ helpers,+ type GeoJSONSource,+ type PointLayerOptions,+} from '@maptiler/sdk';+import {useContext, useEffect, useRef} from 'react';+import {+ Sequence,+ type InteractiveBaseProps,+ type SequenceControls,+ useDelayRender,+} from 'remotion';+import {delayMapRender} from './delay-map-render';+import {MapTilerContext} from './MapTilerContext';++export type MapPointProps = InteractiveBaseProps &+ Omit<PointLayerOptions, 'layerId' | 'sourceId'> & {+ readonly controls?: SequenceControls;+ readonly layerId: string;+ readonly sourceId?: string;+ };++type MapPointLayerIds = {+ readonly clusterLayerId: string;+ readonly labelLayerId: string;+ readonly pointLayerId: string;+ readonly pointSourceId: string;+};++const MapPointDrawing = ({+ alignOnViewport,+ beforeId,+ cluster,+ data,+ labelColor,+ labelSize,+ layerId,+ maxPointRadius,+ maxzoom,+ minPointRadius,+ minzoom,+ outline,+ outlineColor,+ outlineOpacity,+ outlineWidth,+ pointColor,+ pointOpacity,+ pointRadius,+ property,+ showLabel,+ sourceId = `${layerId}-source`,+ zoomCompensation,+}: MapPointProps) => {+ const {map, styleRevision} = useContext(MapTilerContext);+ const {continueRender, delayRender} = useDelayRender();+ const layerIdsRef = useRef<MapPointLayerIds | null>(null);+ const optionsRef = useRef<PointLayerOptions | null>(null);+ const outlineColorIsDynamic = typeof outlineColor === 'string';+ const outlineOpacityIsDynamic = typeof outlineOpacity === 'number';+ const outlineWidthIsDynamic = typeof outlineWidth === 'number';+ const pointColorIsDynamic = typeof pointColor === 'string';+ const pointOpacityIsDynamic = typeof pointOpacity === 'number';+ const pointRadiusIsDynamic = typeof pointRadius === 'number';+ const structuralKey = JSON.stringify({+ alignOnViewport,+ beforeId,+ cluster,+ data: typeof data === 'string' ? data : null,+ maxPointRadius,+ maxzoom,+ minPointRadius,+ minzoom,+ outline,+ outlineColor: outlineColorIsDynamic ? null : outlineColor,+ outlineOpacity: outlineOpacityIsDynamic ? null : outlineOpacity,+ outlineWidth: outlineWidthIsDynamic ? null : outlineWidth,+ pointColor: pointColorIsDynamic ? null : pointColor,+ pointOpacity: pointOpacityIsDynamic ? null : pointOpacity,+ pointRadius: pointRadiusIsDynamic ? null : pointRadius,+ property,+ showLabel,+ zoomCompensation,+ });++ optionsRef.current = {+ ...(alignOnViewport === undefined ? {} : {alignOnViewport}),+ ...(beforeId === undefined ? {} : {beforeId}),+ ...(cluster === undefined ? {} : {cluster}),+ data,+ ...(labelColor === undefined ? {} : {labelColor}),+ ...(labelSize === undefined ? {} : {labelSize}),+ layerId,+ ...(maxPointRadius === undefined ? {} : {maxPointRadius}),+ ...(maxzoom === undefined ? {} : {maxzoom}),+ ...(minPointRadius === undefined ? {} : {minPointRadius}),+ ...(minzoom === undefined ? {} : {minzoom}),+ ...(outline === undefined ? {} : {outline}),+ ...(outlineColor === undefined ? {} : {outlineColor}),+ ...(outlineOpacity === undefined ? {} : {outlineOpacity}),+ ...(outlineWidth === undefined ? {} : {outlineWidth}),+ ...(pointColor === undefined ? {} : {pointColor}),+ ...(pointOpacity === undefined ? {} : {pointOpacity}),+ ...(pointRadius === undefined ? {} : {pointRadius}),+ ...(property === undefined ? {} : {property}),+ ...(showLabel === undefined ? {} : {showLabel}),+ sourceId,+ ...(zoomCompensation === undefined ? {} : {zoomCompensation}),+ };++ useEffect(() => {+ if (!map || !optionsRef.current) {+ return;+ }++ const loadingHandle = delayRender(+ `Loading MapTiler point layer ${layerId}`,+ );+ let hasFinished = false;+ const finish = () => {+ if (hasFinished) {+ return;+ }++ hasFinished = true;+ continueRender(loadingHandle);+ };++ layerIdsRef.current = helpers.addPoint(map, optionsRef.current);+ map.once('idle', finish);+ map.triggerRepaint();++ return () => {+ map.off('idle', finish);+ finish();+ const ids = layerIdsRef.current;+ if (!ids) {+ return;+ }++ for (const id of [+ ids.labelLayerId,+ ids.clusterLayerId,+ ids.pointLayerId,+ ]) {+ if (id && map.getLayer(id)) {+ map.removeLayer(id);+ }+ }++ if (map.getSource(ids.pointSourceId)) {+ map.removeSource(ids.pointSourceId);+ }++ layerIdsRef.current = null;+ map.triggerRepaint();+ };+ }, [continueRender, delayRender, layerId, map, structuralKey, styleRevision]);++ useEffect(() => {+ if (!map || typeof data === 'string') {+ return;+ }++ const ids = layerIdsRef.current;+ if (ids && map.getSource(ids.pointSourceId)) {+ (map.getSource(ids.pointSourceId) as GeoJSONSource).setData(data);+ return delayMapRender({+ continueRender,+ delayRender,+ label: `Updating MapTiler point source ${layerId}`,+ map,+ });+ }+ }, [continueRender, data, delayRender, layerId, map]);++ useEffect(() => {+ if (!map) {+ return;+ }++ const ids = layerIdsRef.current;+ if (!ids) {+ return;+ }++ for (const id of [ids.pointLayerId, ids.clusterLayerId]) {+ if (!id || !map.getLayer(id)) {+ continue;+ }++ if (pointColorIsDynamic) {+ map.setPaintProperty(id, 'circle-color', pointColor);+ }++ if (pointOpacityIsDynamic) {+ map.setPaintProperty(id, 'circle-opacity', pointOpacity);+ }++ if (pointRadiusIsDynamic) {+ map.setPaintProperty(id, 'circle-radius', pointRadius);+ }++ if (outlineColorIsDynamic) {+ map.setPaintProperty(id, 'circle-stroke-color', outlineColor);+ }++ if (outlineOpacityIsDynamic) {+ map.setPaintProperty(id, 'circle-stroke-opacity', outlineOpacity);+ }++ if (outlineWidthIsDynamic) {+ map.setPaintProperty(id, 'circle-stroke-width', outlineWidth);+ }+ }++ if (ids.labelLayerId && map.getLayer(ids.labelLayerId)) {+ if (labelColor !== undefined) {+ map.setPaintProperty(ids.labelLayerId, 'text-color', labelColor);+ }++ if (labelSize !== undefined) {+ map.setLayoutProperty(ids.labelLayerId, 'text-size', labelSize);+ }+ }++ return delayMapRender({+ continueRender,+ delayRender,+ label: `Drawing MapTiler point layer ${layerId}`,+ map,+ });+ }, [+ continueRender,+ delayRender,+ labelColor,+ labelSize,+ layerId,+ map,+ outlineColor,+ outlineColorIsDynamic,+ outlineOpacity,+ outlineOpacityIsDynamic,+ outlineWidth,+ outlineWidthIsDynamic,+ pointColor,+ pointColorIsDynamic,+ pointOpacity,+ pointOpacityIsDynamic,+ pointRadius,+ pointRadiusIsDynamic,+ structuralKey,+ styleRevision,+ ]);++ return null;+};++export const MapPoint = (props: MapPointProps) => {+ const {+ controls,+ durationInFrames,+ freeze,+ from,+ hidden,+ name,+ showInTimeline,+ trimBefore,+ } = props;++ return (+ <Sequence+ layout="none"+ from={from ?? 0}+ trimBefore={trimBefore}+ durationInFrames={durationInFrames ?? Infinity}+ freeze={freeze}+ hidden={hidden}+ name={name ?? '<MapPoint>'}+ showInTimeline={showInTimeline ?? true}+ controls={controls}+ >+ <MapPointDrawing {...props} />+ </Sequence>+ );+};diff --git a/packages/maptiler/src/MapPolygon.tsx b/packages/maptiler/src/MapPolygon.tsxnew file mode 100644index 0000000000..29a938afc6--- /dev/null+++ b/packages/maptiler/src/MapPolygon.tsx@@ -0,0 +1,375 @@+import {+ helpers,+ type GeoJSONSource,+ type PolygonLayerOptions,+} from '@maptiler/sdk';+import {useContext, useEffect, useMemo, useRef} from 'react';+import {+ Sequence,+ type InteractiveBaseProps,+ type SequenceControls,+ useDelayRender,+} from 'remotion';+import {delayMapRender} from './delay-map-render';+import {+ MapPolyline,+ type MapPolylineData,+ type MapPolylineFeature,+} from './MapPolyline';+import {MapTilerContext} from './MapTilerContext';++export type MapPolygonFeature = {+ readonly geometry:+ | {readonly coordinates: number[][][]; readonly type: 'Polygon'}+ | {readonly coordinates: number[][][][]; readonly type: 'MultiPolygon'};+ readonly properties: Record<string, unknown> | null;+ readonly type: 'Feature';+};++export type MapPolygonData = MapPolygonFeature | PolygonLayerOptions['data'];++export type MapPolygonProps = InteractiveBaseProps &+ Omit<+ PolygonLayerOptions,+ 'data' | 'fillOpacity' | 'layerId' | 'outlinePosition' | 'sourceId'+ > & {+ readonly controls?: SequenceControls;+ readonly data: MapPolygonData;+ readonly fillOpacity?: number | PolygonLayerOptions['fillOpacity'];+ readonly layerId: string;+ readonly outlinePosition?: PolygonLayerOptions['outlinePosition'];+ readonly progress?: number;+ readonly sourceId?: string;+ };++type MapPolygonLayerIds = {+ readonly polygonLayerId: string;+ readonly polygonOutlineLayerId: string;+ readonly polygonSourceId: string;+};++const normalizeData = (data: MapPolygonData): PolygonLayerOptions['data'] => {+ if (typeof data === 'string' || data.type === 'FeatureCollection') {+ return data;+ }++ return {features: [data], type: 'FeatureCollection'};+};++const getOutlineData = (data: MapPolygonData): MapPolylineData | null => {+ if (typeof data === 'string') {+ return null;+ }++ const normalizedData = normalizeData(data);+ if (typeof normalizedData === 'string') {+ return null;+ }++ const features: MapPolylineFeature[] = [];+ for (const feature of normalizedData.features) {+ if (feature.geometry.type === 'Polygon') {+ for (const coordinates of feature.geometry.coordinates) {+ features.push({+ geometry: {coordinates, type: 'LineString'},+ properties: feature.properties,+ type: 'Feature',+ });+ }+ }++ if (feature.geometry.type === 'MultiPolygon') {+ for (const polygon of feature.geometry.coordinates) {+ for (const coordinates of polygon) {+ features.push({+ geometry: {coordinates, type: 'LineString'},+ properties: feature.properties,+ type: 'Feature',+ });+ }+ }+ }+ }++ return {features, type: 'FeatureCollection'};+};++const MapPolygonDrawing = ({+ beforeId,+ data,+ fillColor,+ fillOpacity,+ layerId,+ maxzoom,+ minzoom,+ outline,+ outlineBlur,+ outlineCap,+ outlineColor,+ outlineDashArray,+ outlineJoin,+ outlineOpacity,+ outlinePosition,+ outlineWidth,+ pattern,+ progress,+ sourceId = `${layerId}-source`,+}: MapPolygonProps) => {+ const {map, styleRevision} = useContext(MapTilerContext);+ const {continueRender, delayRender} = useDelayRender();+ const layerIdsRef = useRef<MapPolygonLayerIds | null>(null);+ const optionsRef = useRef<PolygonLayerOptions | null>(null);+ const fillColorIsDynamic = typeof fillColor === 'string';+ const fillOpacityIsDynamic = typeof fillOpacity === 'number';+ const outlineBlurIsDynamic = typeof outlineBlur === 'number';+ const outlineColorIsDynamic = typeof outlineColor === 'string';+ const outlineOpacityIsDynamic = typeof outlineOpacity === 'number';+ const outlineWidthIsDynamic = typeof outlineWidth === 'number';+ const shouldAnimateOutline = progress !== undefined;+ const outlineData = useMemo(+ () => (shouldAnimateOutline ? getOutlineData(data) : null),+ [data, shouldAnimateOutline],+ );+ const hasAnimatedOutline = outlineData !== null && outline !== false;+ const structuralKey = JSON.stringify({+ beforeId,+ data: typeof data === 'string' ? data : null,+ fillColor: fillColorIsDynamic ? null : fillColor,+ fillOpacity: fillOpacityIsDynamic ? null : fillOpacity,+ maxzoom,+ minzoom,+ outline,+ outlineBlur: outlineBlurIsDynamic ? null : outlineBlur,+ outlineCap,+ outlineColor: outlineColorIsDynamic ? null : outlineColor,+ outlineDashArray,+ outlineJoin,+ outlineOpacity: outlineOpacityIsDynamic ? null : outlineOpacity,+ outlinePosition,+ outlineWidth: outlineWidthIsDynamic ? null : outlineWidth,+ pattern,+ hasAnimatedOutline,+ });++ optionsRef.current = {+ ...(beforeId === undefined ? {} : {beforeId}),+ data: normalizeData(data),+ ...(fillColor === undefined ? {} : {fillColor}),+ ...(fillOpacity === undefined || typeof fillOpacity === 'number'+ ? {}+ : {fillOpacity}),+ layerId,+ ...(maxzoom === undefined ? {} : {maxzoom}),+ ...(minzoom === undefined ? {} : {minzoom}),+ ...(hasAnimatedOutline+ ? {outline: false}+ : outline === undefined+ ? {}+ : {outline}),+ ...(outlineBlur === undefined ? {} : {outlineBlur}),+ ...(outlineCap === undefined ? {} : {outlineCap}),+ ...(outlineColor === undefined ? {} : {outlineColor}),+ ...(outlineDashArray === undefined ? {} : {outlineDashArray}),+ ...(outlineJoin === undefined ? {} : {outlineJoin}),+ ...(outlineOpacity === undefined ? {} : {outlineOpacity}),+ outlinePosition: outlinePosition ?? 'center',+ ...(outlineWidth === undefined ? {} : {outlineWidth}),+ ...(pattern === undefined ? {} : {pattern}),+ sourceId,+ };++ useEffect(() => {+ if (!map || !optionsRef.current) {+ return;+ }++ const loadingHandle = delayRender(`Loading MapTiler polygon ${layerId}`);+ let hasFinished = false;+ const finish = () => {+ if (hasFinished) {+ return;+ }++ hasFinished = true;+ continueRender(loadingHandle);+ };++ layerIdsRef.current = helpers.addPolygon(map, optionsRef.current);+ map.once('idle', finish);+ map.triggerRepaint();++ return () => {+ map.off('idle', finish);+ finish();+ const ids = layerIdsRef.current;+ if (!ids) {+ return;+ }++ for (const id of [ids.polygonOutlineLayerId, ids.polygonLayerId]) {+ if (id && map.getLayer(id)) {+ map.removeLayer(id);+ }+ }++ if (map.getSource(ids.polygonSourceId)) {+ map.removeSource(ids.polygonSourceId);+ }++ layerIdsRef.current = null;+ map.triggerRepaint();+ };+ }, [continueRender, delayRender, layerId, map, structuralKey, styleRevision]);++ useEffect(() => {+ if (!map || typeof data === 'string') {+ return;+ }++ const ids = layerIdsRef.current;+ if (ids && map.getSource(ids.polygonSourceId)) {+ (map.getSource(ids.polygonSourceId) as GeoJSONSource).setData(+ normalizeData(data),+ );+ return delayMapRender({+ continueRender,+ delayRender,+ label: `Updating MapTiler polygon source ${layerId}`,+ map,+ });+ }+ }, [continueRender, data, delayRender, layerId, map]);++ useEffect(() => {+ if (!map) {+ return;+ }++ const ids = layerIdsRef.current;+ if (!ids || !map.getLayer(ids.polygonLayerId)) {+ return;+ }++ if (fillColorIsDynamic) {+ map.setPaintProperty(ids.polygonLayerId, 'fill-color', fillColor);+ }++ if (fillOpacityIsDynamic) {+ map.setPaintProperty(ids.polygonLayerId, 'fill-opacity', fillOpacity);+ }++ if (ids.polygonOutlineLayerId && map.getLayer(ids.polygonOutlineLayerId)) {+ if (outlineBlurIsDynamic) {+ map.setPaintProperty(+ ids.polygonOutlineLayerId,+ 'line-blur',+ outlineBlur,+ );+ }++ if (outlineColorIsDynamic) {+ map.setPaintProperty(+ ids.polygonOutlineLayerId,+ 'line-color',+ outlineColor,+ );+ }++ if (outlineOpacityIsDynamic) {+ map.setPaintProperty(+ ids.polygonOutlineLayerId,+ 'line-opacity',+ outlineOpacity,+ );+ }++ if (outlineWidthIsDynamic) {+ map.setPaintProperty(+ ids.polygonOutlineLayerId,+ 'line-width',+ outlineWidth,+ );+ }+ }++ return delayMapRender({+ continueRender,+ delayRender,+ label: `Drawing MapTiler polygon ${layerId}`,+ map,+ });+ }, [+ continueRender,+ delayRender,+ fillColor,+ fillColorIsDynamic,+ fillOpacity,+ fillOpacityIsDynamic,+ layerId,+ map,+ outlineBlur,+ outlineBlurIsDynamic,+ outlineColor,+ outlineColorIsDynamic,+ outlineOpacity,+ outlineOpacityIsDynamic,+ outlineWidth,+ outlineWidthIsDynamic,+ structuralKey,+ styleRevision,+ ]);++ if (!hasAnimatedOutline) {+ return null;+ }++ return (+ <MapPolyline+ beforeId={beforeId}+ data={outlineData}+ layerId={`${layerId}-outline`}+ lineBlur={outlineBlur}+ lineCap={outlineCap}+ lineColor={outlineColor ?? '#ffffff'}+ lineDashArray={outlineDashArray}+ lineJoin={outlineJoin}+ lineOpacity={outlineOpacity}+ lineWidth={outlineWidth}+ maxzoom={maxzoom}+ minzoom={minzoom}+ name="Map polygon outline"+ progress={progress}+ showInTimeline={false}+ sourceId={`${sourceId}-outline`}+ />+ );+};++export const MapPolygon = (props: MapPolygonProps) => {+ const {+ controls,+ durationInFrames,+ freeze,+ from,+ hidden,+ name,+ showInTimeline,+ trimBefore,+ } = props;++ return (+ <Sequence+ layout="none"+ from={from ?? 0}+ trimBefore={trimBefore}+ durationInFrames={durationInFrames ?? Infinity}+ freeze={freeze}+ hidden={hidden}+ name={name ?? '<MapPolygon>'}+ showInTimeline={showInTimeline ?? true}+ controls={controls}+ >+ <MapPolygonDrawing {...props} />+ </Sequence>+ );+};diff --git a/packages/maptiler/src/MapPolyline.tsx b/packages/maptiler/src/MapPolyline.tsxnew file mode 100644index 0000000000..b6cfaf76d5--- /dev/null+++ b/packages/maptiler/src/MapPolyline.tsx@@ -0,0 +1,452 @@+import {+ helpers,+ type GeoJSONSource,+ type PolylineLayerOptions,+} from '@maptiler/sdk';+import {length as getLineLength, lineSliceAlong, lineString} from '@turf/turf';+import {useContext, useEffect, useRef, useState} from 'react';+import {+ Sequence,+ type InteractiveBaseProps,+ type SequenceControls,+ useDelayRender,+} from 'remotion';+import {delayMapRender} from './delay-map-render';+import {MapTilerContext} from './MapTilerContext';++export type MapPolylineFeature = {+ readonly geometry:+ | {readonly coordinates: number[][]; readonly type: 'LineString'}+ | {readonly coordinates: number[][][]; readonly type: 'MultiLineString'};+ readonly properties: Record<string, unknown> | null;+ readonly type: 'Feature';+};++export type MapPolylineData = MapPolylineFeature | PolylineLayerOptions['data'];++export type MapPolylineProps = InteractiveBaseProps &+ Omit<PolylineLayerOptions, 'data' | 'layerId' | 'sourceId'> & {+ readonly controls?: SequenceControls;+ readonly data: MapPolylineData;+ readonly layerId: string;+ readonly progress?: number;+ readonly sourceId?: string;+ };++type MapPolylineLayerIds = {+ readonly polylineLayerId: string;+ readonly polylineOutlineLayerId: string;+ readonly polylineSourceId: string;+};++const normalizeData = (data: MapPolylineData): PolylineLayerOptions['data'] => {+ if (typeof data === 'string' || data.type === 'FeatureCollection') {+ return data;+ }++ return {features: [data], type: 'FeatureCollection'};+};++const revealData = (+ data: MapPolylineData,+ progress: number,+): PolylineLayerOptions['data'] => {+ if (typeof data === 'string') {+ return data;+ }++ const normalizedData = normalizeData(data);+ if (typeof normalizedData === 'string') {+ return normalizedData;+ }++ const lineCoordinates = normalizedData.features.flatMap((feature) => {+ if (feature.geometry.type === 'LineString') {+ return [feature.geometry.coordinates];+ }++ if (feature.geometry.type === 'MultiLineString') {+ return feature.geometry.coordinates;+ }++ return [];+ });+ const lines = lineCoordinates.map((coordinates) => lineString(coordinates));+ const lineLengths = lines.map((line) => getLineLength(line));+ let remainingLength =+ lineLengths.reduce((sum, lineLength) => sum + lineLength, 0) *+ Math.min(1, Math.max(0, progress));+ let lineIndex = 0;++ return {+ ...normalizedData,+ features: normalizedData.features.map((feature) => {+ if (+ feature.geometry.type !== 'LineString' &&+ feature.geometry.type !== 'MultiLineString'+ ) {+ return feature;+ }++ const featureLines =+ feature.geometry.type === 'LineString'+ ? [feature.geometry.coordinates]+ : feature.geometry.coordinates;+ const revealedLines = featureLines.map(() => {+ const line = lines[lineIndex];+ const lineLength = lineLengths[lineIndex];+ lineIndex++;+ const revealedLength = Math.min(lineLength, remainingLength);+ remainingLength = Math.max(0, remainingLength - lineLength);+ return lineSliceAlong(line, 0, Math.max(0.001, revealedLength)).geometry+ .coordinates;+ });++ return {+ ...feature,+ geometry:+ feature.geometry.type === 'LineString'+ ? {coordinates: revealedLines[0], type: 'LineString' as const}+ : {+ coordinates: revealedLines,+ type: 'MultiLineString' as const,+ },+ };+ }),+ };+};++const MapPolylineDrawing = ({+ beforeId,+ data,+ layerId,+ lineBlur,+ lineCap,+ lineColor,+ lineDashArray,+ lineGapWidth,+ lineJoin,+ lineOpacity,+ lineWidth,+ maxzoom,+ minzoom,+ outline,+ outlineBlur,+ outlineColor,+ outlineOpacity,+ outlineWidth,+ progress = 1,+ sourceId = `${layerId}-source`,+}: MapPolylineProps) => {+ const {map, styleRevision} = useContext(MapTilerContext);+ const {cancelRender, continueRender, delayRender} = useDelayRender();+ const layerIdsRef = useRef<MapPolylineLayerIds | null>(null);+ const optionsRef = useRef<PolylineLayerOptions | null>(null);+ const [layerRevision, setLayerRevision] = useState(0);+ const lineBlurIsDynamic = typeof lineBlur === 'number';+ const lineColorIsDynamic = typeof lineColor === 'string';+ const lineGapWidthIsDynamic = typeof lineGapWidth === 'number';+ const lineOpacityIsDynamic = typeof lineOpacity === 'number';+ const lineWidthIsDynamic = typeof lineWidth === 'number';+ const outlineBlurIsDynamic = typeof outlineBlur === 'number';+ const outlineColorIsDynamic = typeof outlineColor === 'string';+ const outlineOpacityIsDynamic = typeof outlineOpacity === 'number';+ const outlineWidthIsDynamic = typeof outlineWidth === 'number';+ const structuralKey = JSON.stringify({+ beforeId,+ data: typeof data === 'string' ? data : null,+ lineBlur: lineBlurIsDynamic ? null : lineBlur,+ lineCap,+ lineColor: lineColorIsDynamic ? null : lineColor,+ lineDashArray,+ lineGapWidth: lineGapWidthIsDynamic ? null : lineGapWidth,+ lineJoin,+ lineOpacity: lineOpacityIsDynamic ? null : lineOpacity,+ lineWidth: lineWidthIsDynamic ? null : lineWidth,+ maxzoom,+ minzoom,+ outline,+ outlineBlur: outlineBlurIsDynamic ? null : outlineBlur,+ outlineColor: outlineColorIsDynamic ? null : outlineColor,+ outlineOpacity: outlineOpacityIsDynamic ? null : outlineOpacity,+ outlineWidth: outlineWidthIsDynamic ? null : outlineWidth,+ });++ optionsRef.current = {+ ...(beforeId === undefined ? {} : {beforeId}),+ data: revealData(data, progress),+ layerId,+ ...(lineBlur === undefined ? {} : {lineBlur}),+ ...(lineCap === undefined ? {} : {lineCap}),+ ...(lineColor === undefined ? {} : {lineColor}),+ ...(lineDashArray === undefined ? {} : {lineDashArray}),+ ...(lineGapWidth === undefined ? {} : {lineGapWidth}),+ ...(lineJoin === undefined ? {} : {lineJoin}),+ ...(lineOpacity === undefined ? {} : {lineOpacity}),+ ...(lineWidth === undefined ? {} : {lineWidth}),+ ...(maxzoom === undefined ? {} : {maxzoom}),+ ...(minzoom === undefined ? {} : {minzoom}),+ ...(outline === undefined ? {} : {outline}),+ ...(outlineBlur === undefined ? {} : {outlineBlur}),+ ...(outlineColor === undefined ? {} : {outlineColor}),+ ...(outlineOpacity === undefined ? {} : {outlineOpacity}),+ ...(outlineWidth === undefined ? {} : {outlineWidth}),+ sourceId,+ };++ useEffect(() => {+ if (!map || !optionsRef.current) {+ return;+ }++ const loadingHandle = delayRender(`Loading MapTiler polyline ${layerId}`);+ let hasFinished = false;+ let hasCancelled = false;+ const finish = () => {+ if (hasFinished) {+ return;+ }++ hasFinished = true;+ continueRender(loadingHandle);+ };++ const removeLayers = (ids: MapPolylineLayerIds) => {+ for (const id of [ids.polylineLayerId, ids.polylineOutlineLayerId]) {+ if (id && map.getLayer(id)) {+ map.removeLayer(id);+ }+ }++ if (map.getSource(ids.polylineSourceId)) {+ map.removeSource(ids.polylineSourceId);+ }+ };++ helpers+ .addPolyline(map, optionsRef.current)+ .then((ids) => {+ if (hasCancelled) {+ removeLayers(ids);+ finish();+ return;+ }++ layerIdsRef.current = ids;+ setLayerRevision((revision) => revision + 1);+ map.once('idle', finish);+ map.triggerRepaint();+ })+ .catch((error) => {+ finish();+ if (!hasCancelled) {+ cancelRender(error);+ }+ });++ return () => {+ hasCancelled = true;+ map.off('idle', finish);+ finish();+ const ids = layerIdsRef.current;+ if (ids) {+ removeLayers(ids);+ layerIdsRef.current = null;+ map.triggerRepaint();+ }+ };+ }, [+ cancelRender,+ continueRender,+ delayRender,+ layerId,+ map,+ structuralKey,+ styleRevision,+ ]);++ useEffect(() => {+ if (!map || typeof data === 'string') {+ return;+ }++ const ids = layerIdsRef.current;+ if (ids && map.getSource(ids.polylineSourceId)) {+ (map.getSource(ids.polylineSourceId) as GeoJSONSource).setData(+ revealData(data, progress),+ );+ return delayMapRender({+ continueRender,+ delayRender,+ label: `Drawing MapTiler polyline ${layerId}`,+ map,+ });+ }+ }, [+ continueRender,+ data,+ delayRender,+ layerId,+ layerRevision,+ map,+ progress,+ ]);++ useEffect(() => {+ if (!map) {+ return;+ }++ const ids = layerIdsRef.current;+ if (!ids || !map.getLayer(ids.polylineLayerId)) {+ return;+ }++ if (lineBlurIsDynamic) {+ map.setPaintProperty(ids.polylineLayerId, 'line-blur', lineBlur);+ }++ if (lineColorIsDynamic) {+ map.setPaintProperty(ids.polylineLayerId, 'line-color', lineColor);+ }++ if (lineGapWidthIsDynamic) {+ map.setPaintProperty(ids.polylineLayerId, 'line-gap-width', lineGapWidth);+ }++ if (lineOpacityIsDynamic) {+ map.setPaintProperty(ids.polylineLayerId, 'line-opacity', lineOpacity);+ }++ if (lineWidthIsDynamic) {+ map.setPaintProperty(ids.polylineLayerId, 'line-width', lineWidth);+ }++ if (+ ids.polylineOutlineLayerId &&+ map.getLayer(ids.polylineOutlineLayerId)+ ) {+ if (outlineBlurIsDynamic) {+ map.setPaintProperty(+ ids.polylineOutlineLayerId,+ 'line-blur',+ outlineBlur,+ );+ }++ if (outlineColorIsDynamic) {+ map.setPaintProperty(+ ids.polylineOutlineLayerId,+ 'line-color',+ outlineColor,+ );+ }++ if (outlineOpacityIsDynamic) {+ map.setPaintProperty(+ ids.polylineOutlineLayerId,+ 'line-opacity',+ outlineOpacity,+ );+ }++ if (outlineWidthIsDynamic || lineWidthIsDynamic) {+ const actualLineWidth = lineWidth ?? 3;+ const actualOutlineWidth = outlineWidth ?? 1;+ const combinedOutlineWidth =+ typeof actualLineWidth === 'number'+ ? typeof actualOutlineWidth === 'number'+ ? actualLineWidth + actualOutlineWidth * 2+ : [+ 'interpolate',+ ['linear'],+ ['zoom'],+ ...actualOutlineWidth.flatMap(({value, zoom}) => [+ zoom,+ actualLineWidth + value * 2,+ ]),+ ]+ : [+ 'interpolate',+ ['linear'],+ ['zoom'],+ ...actualLineWidth.flatMap(({value, zoom}) => [+ zoom,+ value ++ (typeof actualOutlineWidth === 'number'+ ? actualOutlineWidth+ : 1) *+ 2,+ ]),+ ];+ map.setPaintProperty(+ ids.polylineOutlineLayerId,+ 'line-width',+ combinedOutlineWidth,+ );+ }+ }++ return delayMapRender({+ continueRender,+ delayRender,+ label: `Styling MapTiler polyline ${layerId}`,+ map,+ });+ }, [+ continueRender,+ delayRender,+ lineBlur,+ lineBlurIsDynamic,+ lineColor,+ lineColorIsDynamic,+ lineGapWidth,+ lineGapWidthIsDynamic,+ lineOpacity,+ lineOpacityIsDynamic,+ lineWidth,+ lineWidthIsDynamic,+ layerId,+ layerRevision,+ map,+ outlineBlur,+ outlineBlurIsDynamic,+ outlineColor,+ outlineColorIsDynamic,+ outlineOpacity,+ outlineOpacityIsDynamic,+ outlineWidth,+ outlineWidthIsDynamic,+ ]);++ return null;+};++export const MapPolyline = (props: MapPolylineProps) => {+ const {+ controls,+ durationInFrames,+ freeze,+ from,+ hidden,+ name,+ showInTimeline,+ trimBefore,+ } = props;++ return (+ <Sequence+ layout="none"+ from={from ?? 0}+ trimBefore={trimBefore}+ durationInFrames={durationInFrames ?? Infinity}+ freeze={freeze}+ hidden={hidden}+ name={name ?? '<MapPolyline>'}+ showInTimeline={showInTimeline ?? true}+ controls={controls}+ >+ <MapPolylineDrawing {...props} />+ </Sequence>+ );+};diff --git a/packages/maptiler/src/MapSource.tsx b/packages/maptiler/src/MapSource.tsxnew file mode 100644index 0000000000..8bd0355f64--- /dev/null+++ b/packages/maptiler/src/MapSource.tsx@@ -0,0 +1,88 @@+import type {+ GeoJSONSource,+ GeoJSONSourceSpecification,+ SourceSpecification,+} from '@maptiler/sdk';+import {useContext, useEffect, useRef, type ReactNode} from 'react';+import {useDelayRender} from 'remotion';+import {delayMapRender} from './delay-map-render';+import {MapTilerContext} from './MapTilerContext';++export type MapSourceProps = {+ readonly children?: ReactNode;+ readonly id: string;+ readonly source: SourceSpecification;+};++export const MapSource = ({children, id, source}: MapSourceProps) => {+ const {map, styleRevision} = useContext(MapTilerContext);+ const sourceRef = useRef(source);+ const {continueRender, delayRender} = useDelayRender();+ sourceRef.current = source;++ useEffect(() => {+ if (!map) {+ return;+ }++ const loadingHandle = delayRender(`Loading MapTiler source ${id}`);+ let hasFinished = false;+ const finish = () => {+ if (hasFinished) {+ return;+ }++ hasFinished = true;+ continueRender(loadingHandle);+ };++ if (!map.getSource(id)) {+ map.addSource(id, sourceRef.current);+ }++ map.once('idle', finish);+ map.triggerRepaint();++ return () => {+ map.off('idle', finish);+ finish();++ for (const layer of map.getStyle().layers ?? []) {+ if (+ 'source' in layer &&+ layer.source === id &&+ map.getLayer(layer.id)+ ) {+ map.removeLayer(layer.id);+ }+ }++ if (map.getSource(id)) {+ map.removeSource(id);+ }++ map.triggerRepaint();+ };+ }, [continueRender, delayRender, id, map, styleRevision]);++ useEffect(() => {+ if (!map || source.type !== 'geojson') {+ return;+ }++ const existingSource = map.getSource(id) as GeoJSONSource | undefined;+ if (!existingSource) {+ return;+ }++ existingSource.setData((source as GeoJSONSourceSpecification).data);+ return delayMapRender({+ continueRender,+ delayRender,+ label: `Updating MapTiler source ${id}`,+ map,+ });+ }, [continueRender, delayRender, id, map, source]);++ return children;+};diff --git a/packages/maptiler/src/MapTilerContext.ts b/packages/maptiler/src/MapTilerContext.tsindex 0d09c45546..3477814443 100644--- a/packages/maptiler/src/MapTilerContext.ts+++ b/packages/maptiler/src/MapTilerContext.ts@@ -1,12 +1,18 @@import type {Map as MapTilerMap} from '@maptiler/sdk';-import {createContext} from 'react';+import {createContext, useContext} from 'react';export type MapTilerContextValue = {readonly cameraRevision: number;readonly map: MapTilerMap | null;+ readonly styleRevision: number;};export const MapTilerContext = createContext<MapTilerContextValue>({cameraRevision: 0,map: null,+ styleRevision: 0,});++export const useMapTiler = (): MapTilerContextValue => {+ return useContext(MapTilerContext);+};diff --git a/packages/maptiler/src/MapViewport.tsx b/packages/maptiler/src/MapViewport.tsxindex 9e431d76d3..c8f4cc8809 100644--- a/packages/maptiler/src/MapViewport.tsx+++ b/packages/maptiler/src/MapViewport.tsx@@ -1,6 +1,6 @@-import {Map as MapTilerMap, MapStyle} from '@maptiler/sdk';+import {Map as MapTilerMap, MapStyle, type MapOptions} from '@maptiler/sdk';import '@maptiler/sdk/style.css';-import type {ForwardRefRenderFunction, ReactNode} from 'react';+import type {ComponentType, ForwardRefRenderFunction, ReactNode} from 'react';import {forwardRef,useEffect,@@ -19,7 +19,27 @@ import {} from 'remotion';import {MapTilerContext} from './MapTilerContext';-type MapViewportProps = InteractiveBaseProps & {+export type MapViewportMapOptions = Omit<+ MapOptions,+ | 'apiKey'+ | 'bearing'+ | 'center'+ | 'container'+ | 'fadeDuration'+ | 'interactive'+ | 'language'+ | 'padding'+ | 'pitch'+ | 'projection'+ | 'style'+ | 'terrain'+ | 'terrainExaggeration'+ | 'zoom'+>;++export type MapAdministrativeBorders = 'all' | 'country-only' | 'none';++export type MapViewportProps = InteractiveBaseProps & {readonly apiKey: string | null;readonly backgroundColor?: string;readonly bearing?: number;@@ -27,9 +47,45 @@ type MapViewportProps = InteractiveBaseProps & {readonly centerLongitude?: number;readonly children?: ReactNode;readonly controls?: SequenceControls;+ readonly language?: MapOptions['language'];+ readonly mapOptions?: MapViewportMapOptions;+ readonly mapStyle?: MapOptions['style'];+ readonly onMapReady?: (map: MapTilerMap) => void;+ readonly paddingBottom?: number;+ readonly paddingLeft?: number;+ readonly paddingRight?: number;+ readonly paddingTop?: number;+ readonly pitch?: number;+ readonly projection?: MapOptions['projection'];+ readonly showLabels?: boolean;+ readonly administrativeBorders?: MapAdministrativeBorders;+ readonly terrain?: boolean;+ readonly terrainExaggeration?: number;readonly zoom?: number;};+const stripStyleLayers = ({+ administrativeBorders,+ map,+ showLabels,+}: {+ readonly administrativeBorders: MapAdministrativeBorders;+ readonly map: MapTilerMap;+ readonly showLabels: boolean;+}) => {+ for (const layer of [...(map.getStyle().layers ?? [])]) {+ const shouldRemoveLabel = !showLabels && layer.type === 'symbol';+ const shouldRemoveAdministrativeBorder =+ administrativeBorders === 'none'+ ? /border/i.test(layer.id)+ : administrativeBorders === 'country-only' &&+ /other border/i.test(layer.id);+ if (shouldRemoveLabel || shouldRemoveAdministrativeBorder) {+ map.removeLayer(layer.id);+ }+ }+};+const mapViewportSchema = {...Interactive.baseSchema,centerLongitude: {@@ -72,6 +128,56 @@ const mapViewportSchema = {hiddenFromList: false,keyframable: true,},+ pitch: {+ type: 'number',+ min: 0,+ max: 85,+ step: 1,+ default: 0,+ description: 'Pitch',+ hiddenFromList: false,+ keyframable: true,+ },+ paddingTop: {+ type: 'number',+ min: 0,+ max: 2000,+ step: 1,+ default: 0,+ description: 'Top camera padding',+ hiddenFromList: false,+ keyframable: true,+ },+ paddingRight: {+ type: 'number',+ min: 0,+ max: 2000,+ step: 1,+ default: 0,+ description: 'Right camera padding',+ hiddenFromList: false,+ keyframable: true,+ },+ paddingBottom: {+ type: 'number',+ min: 0,+ max: 2000,+ step: 1,+ default: 0,+ description: 'Bottom camera padding',+ hiddenFromList: false,+ keyframable: true,+ },+ paddingLeft: {+ type: 'number',+ min: 0,+ max: 2000,+ step: 1,+ default: 0,+ description: 'Left camera padding',+ hiddenFromList: false,+ keyframable: true,+ },backgroundColor: {type: 'color',default: '#dfe7e2',@@ -114,6 +220,20 @@ const MapViewportRefForwardingFunction: ForwardRefRenderFunction<centerLatitude = 0,centerLongitude = 0,children,+ language,+ mapOptions,+ mapStyle = MapStyle.BASIC,+ onMapReady,+ paddingBottom = 0,+ paddingLeft = 0,+ paddingRight = 0,+ paddingTop = 0,+ pitch = 0,+ projection,+ showLabels = true,+ administrativeBorders = 'all',+ terrain = false,+ terrainExaggeration = 1,durationInFrames,from,trimBefore,@@ -133,15 +253,38 @@ const MapViewportRefForwardingFunction: ForwardRefRenderFunction<bearing,centerLatitude,centerLongitude,+ paddingBottom,+ paddingLeft,+ paddingRight,+ paddingTop,+ pitch,zoom,});+ const initialMapOptionsRef = useRef({+ administrativeBorders,+ language,+ mapOptions,+ mapStyle,+ projection,+ showLabels,+ terrain,+ terrainExaggeration,+ });+ const lastMapStyleRef = useRef(mapStyle);+ const lastLayerVisibilityRef = useRef({+ administrativeBorders,+ showLabels,+ });+ const onMapReadyRef = useRef(onMapReady);+ onMapReadyRef.current = onMapReady;const {continueRender, delayRender} = useDelayRender();const [map, setMap] = useState<MapTilerMap | null>(null);const [cameraRevision, setCameraRevision] = useState(0);+ const [styleRevision, setStyleRevision] = useState(0);const [loadingHandle] = useState(() => delayRender('Loading MapTiler map'));const contextValue = useMemo(- () => ({cameraRevision, map}),- [cameraRevision, map],+ () => ({cameraRevision, map, styleRevision}),+ [cameraRevision, map, styleRevision],);useImperativeHandle(ref, () => viewportRef.current as HTMLDivElement, []);@@ -157,35 +300,52 @@ const MapViewportRefForwardingFunction: ForwardRefRenderFunction<}const initialCamera = initialCameraRef.current;+ const initialOptions = initialMapOptionsRef.current;// Keep MapTiler's logo and attribution visible:// https://docs.maptiler.com/guides/map-design/attribution/remove-attribution/const mapInstance = new MapTilerMap({+ fullscreenControl: false,+ geolocateControl: false,+ navigationControl: false,+ scaleControl: false,+ terrainControl: false,+ ...initialOptions.mapOptions,apiKey,bearing: initialCamera.bearing,- canvasContextAttributes: {preserveDrawingBuffer: true},+ canvasContextAttributes: {+ ...initialOptions.mapOptions?.canvasContextAttributes,+ preserveDrawingBuffer: true,+ },center: [initialCamera.centerLongitude, initialCamera.centerLatitude],container: mapContainerRef.current,fadeDuration: 0,- fullscreenControl: false,- geolocateControl: false,interactive: false,- navigationControl: false,- scaleControl: false,- style: MapStyle.BASIC,- terrainControl: false,+ language: initialOptions.language,+ pitch: initialCamera.pitch,+ projection: initialOptions.projection,+ style: initialOptions.mapStyle,+ terrain: initialOptions.terrain,+ terrainExaggeration: initialOptions.terrainExaggeration,zoom: initialCamera.zoom,});+ mapInstance.setPadding({+ bottom: initialCamera.paddingBottom,+ left: initialCamera.paddingLeft,+ right: initialCamera.paddingRight,+ top: initialCamera.paddingTop,+ });mapRef.current = mapInstance;mapInstance.on('load', () => {- for (const layer of [...(mapInstance.getStyle().layers ?? [])]) {- if (layer.type === 'symbol' || /other border/i.test(layer.id)) {- mapInstance.removeLayer(layer.id);- }- }+ stripStyleLayers({+ administrativeBorders: initialOptions.administrativeBorders,+ map: mapInstance,+ showLabels: initialOptions.showLabels,+ });mapInstance.once('idle', () => {setMap(mapInstance);+ onMapReadyRef.current?.(mapInstance);continueRender(loadingHandle);});mapInstance.triggerRepaint();@@ -203,11 +363,17 @@ const MapViewportRefForwardingFunction: ForwardRefRenderFunction<}const currentCenter = map.getCenter();+ const currentPadding = map.getPadding();const cameraIsCurrent =Math.abs(currentCenter.lng - centerLongitude) < 0.0000001 &&Math.abs(currentCenter.lat - centerLatitude) < 0.0000001 &&Math.abs(map.getZoom() - zoom) < 0.0000001 &&- Math.abs(map.getBearing() - bearing) < 0.0000001;+ Math.abs(map.getBearing() - bearing) < 0.0000001 &&+ Math.abs(map.getPitch() - pitch) < 0.0000001 &&+ Math.abs((currentPadding.top ?? 0) - paddingTop) < 0.0000001 &&+ Math.abs((currentPadding.right ?? 0) - paddingRight) < 0.0000001 &&+ Math.abs((currentPadding.bottom ?? 0) - paddingBottom) < 0.0000001 &&+ Math.abs((currentPadding.left ?? 0) - paddingLeft) < 0.0000001;if (cameraIsCurrent) {return;@@ -230,6 +396,13 @@ const MapViewportRefForwardingFunction: ForwardRefRenderFunction<map.jumpTo({bearing,center: [centerLongitude, centerLatitude],+ padding: {+ bottom: paddingBottom,+ left: paddingLeft,+ right: paddingRight,+ top: paddingTop,+ },+ pitch,zoom,});setCameraRevision((revision) => revision + 1);@@ -246,9 +419,94 @@ const MapViewportRefForwardingFunction: ForwardRefRenderFunction<continueRender,delayRender,map,+ paddingBottom,+ paddingLeft,+ paddingRight,+ paddingTop,+ pitch,zoom,]);+ useEffect(() => {+ if (+ !map ||+ (lastMapStyleRef.current === mapStyle &&+ lastLayerVisibilityRef.current.showLabels === showLabels &&+ lastLayerVisibilityRef.current.administrativeBorders ===+ administrativeBorders)+ ) {+ return;+ }++ const styleHandle = delayRender('Updating MapTiler style');+ let hasFinished = false;+ const finish = () => {+ if (hasFinished) {+ return;+ }++ hasFinished = true;+ lastMapStyleRef.current = mapStyle;+ lastLayerVisibilityRef.current = {+ administrativeBorders,+ showLabels,+ };+ setStyleRevision((revision) => revision + 1);+ continueRender(styleHandle);+ };++ const onStyleLoad = () => {+ stripStyleLayers({administrativeBorders, map, showLabels});+ map.once('idle', finish);+ map.triggerRepaint();+ };++ map.once('style.load', onStyleLoad);+ map.setStyle(mapStyle ?? null);+ map.triggerRepaint();++ return () => {+ map.off('style.load', onStyleLoad);+ map.off('idle', finish);+ finish();+ };+ }, [+ administrativeBorders,+ continueRender,+ delayRender,+ map,+ mapStyle,+ showLabels,+ ]);++ useEffect(() => {+ if (map && language) {+ map.setLanguage(language);+ map.triggerRepaint();+ }+ }, [language, map]);++ useEffect(() => {+ if (!map) {+ return;+ }++ if (terrain) {+ map.enableTerrain(terrainExaggeration);+ } else {+ map.disableTerrain();+ }++ map.triggerRepaint();+ }, [map, terrain, terrainExaggeration]);++ useEffect(() => {+ if (map && projection) {+ map.setProjection(projection, {persist: true});+ map.triggerRepaint();+ }+ }, [map, projection]);+return (<Sequencelayout="none"@@ -293,10 +551,11 @@ const MapViewportRefForwardingFunction: ForwardRefRenderFunction<const MapViewportInner = forwardRef(MapViewportRefForwardingFunction);-export const MapViewport = Interactive.withSchema({- Component: MapViewportInner,- componentName: '<MapViewport>',- componentIdentity: null,- schema: mapViewportSchema,- supportsEffects: false,-});+export const MapViewport: ComponentType<MapViewportProps> =+ Interactive.withSchema({+ Component: MapViewportInner,+ componentName: '<MapViewport>',+ componentIdentity: null,+ schema: mapViewportSchema,+ supportsEffects: false,+ });diff --git a/packages/maptiler/src/delay-map-render.ts b/packages/maptiler/src/delay-map-render.tsnew file mode 100644index 0000000000..0168effb9e--- /dev/null+++ b/packages/maptiler/src/delay-map-render.ts@@ -0,0 +1,32 @@+import type {Map as MapTilerMap} from '@maptiler/sdk';++export const delayMapRender = ({+ continueRender,+ delayRender,+ label,+ map,+}: {+ readonly continueRender: (handle: number) => void;+ readonly delayRender: (label?: string) => number;+ readonly label: string;+ readonly map: MapTilerMap;+}) => {+ const handle = delayRender(label);+ let hasFinished = false;+ const finish = () => {+ if (hasFinished) {+ return;+ }++ hasFinished = true;+ continueRender(handle);+ };++ map.once('idle', finish);+ map.triggerRepaint();++ return () => {+ map.off('idle', finish);+ finish();+ };+};diff --git a/packages/maptiler/src/index.ts b/packages/maptiler/src/index.tsindex 5609c9b88b..8cbf382cca 100644--- a/packages/maptiler/src/index.ts+++ b/packages/maptiler/src/index.ts@@ -1,4 +1,31 @@-export {MapOverlay} from './MapOverlay';+export {MapHeatmap, type MapHeatmapProps} from './MapHeatmap';+export {MapLayer, type MapLayerProps} from './MapLayer';+export {+ MapMarker,+ MapOverlay,+ type MapOverlayAnchor,+ type MapOverlayProps,+} from './MapOverlay';+export {MapPoint, type MapPointProps} from './MapPoint';+export {+ MapPolygon,+ type MapPolygonData,+ type MapPolygonFeature,+ type MapPolygonProps,+} from './MapPolygon';+export {+ MapPolyline,+ type MapPolylineData,+ type MapPolylineFeature,+ type MapPolylineProps,+} from './MapPolyline';export {MapRegion, type MapRegionFeature} from './MapRegion';export {MapRoute, type MapRouteFeature} from './MapRoute';-export {MapViewport} from './MapViewport';+export {MapSource, type MapSourceProps} from './MapSource';+export {useMapTiler, type MapTilerContextValue} from './MapTilerContext';+export {+ MapViewport,+ type MapAdministrativeBorders,+ type MapViewportMapOptions,+ type MapViewportProps,+} from './MapViewport';