refactor(bg): dont use math random for pattern id generation closes #2086
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import React, { memo, useMemo, FC } from 'react';
|
import React, { memo, FC, useEffect, useState, useRef } from 'react';
|
||||||
import cc from 'classcat';
|
import cc from 'classcat';
|
||||||
|
|
||||||
import { useStore } from '../../store';
|
import { useStore } from '../../store';
|
||||||
@@ -20,9 +20,16 @@ const Background: FC<BackgroundProps> = ({
|
|||||||
style,
|
style,
|
||||||
className,
|
className,
|
||||||
}) => {
|
}) => {
|
||||||
|
const ref = useRef<SVGSVGElement>(null);
|
||||||
|
const [patternId, setPatternId] = useState<string | null>(null);
|
||||||
const [x, y, scale] = useStore(transformSelector);
|
const [x, y, scale] = useStore(transformSelector);
|
||||||
// when there are multiple flows on a page we need to make sure that every background gets its own pattern.
|
|
||||||
const patternId = useMemo(() => `pattern-${Math.floor(Math.random() * 100000)}`, []);
|
useEffect(() => {
|
||||||
|
// when there are multiple flows on a page we need to make sure that every background gets its own pattern.
|
||||||
|
const bgs = document.querySelectorAll('.react-flow__background');
|
||||||
|
const index = Array.from(bgs).findIndex((bg) => bg === ref.current);
|
||||||
|
setPatternId(`pattern-${index}`);
|
||||||
|
}, []);
|
||||||
|
|
||||||
const bgClasses = cc(['react-flow__background', 'react-flow__container', className]);
|
const bgClasses = cc(['react-flow__background', 'react-flow__container', className]);
|
||||||
const scaledGap = gap * scale;
|
const scaledGap = gap * scale;
|
||||||
@@ -41,18 +48,23 @@ const Background: FC<BackgroundProps> = ({
|
|||||||
width: '100%',
|
width: '100%',
|
||||||
height: '100%',
|
height: '100%',
|
||||||
}}
|
}}
|
||||||
|
ref={ref}
|
||||||
>
|
>
|
||||||
<pattern
|
{patternId && (
|
||||||
id={patternId}
|
<>
|
||||||
x={xOffset}
|
<pattern
|
||||||
y={yOffset}
|
id={patternId}
|
||||||
width={scaledGap}
|
x={xOffset}
|
||||||
height={scaledGap}
|
y={yOffset}
|
||||||
patternUnits="userSpaceOnUse"
|
width={scaledGap}
|
||||||
>
|
height={scaledGap}
|
||||||
{path}
|
patternUnits="userSpaceOnUse"
|
||||||
</pattern>
|
>
|
||||||
<rect x="0" y="0" width="100%" height="100%" fill={`url(#${patternId})`} />
|
{path}
|
||||||
|
</pattern>
|
||||||
|
<rect x="0" y="0" width="100%" height="100%" fill={`url(#${patternId})`} />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</svg>
|
</svg>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user