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 { useStore } from '../../store';
|
||||
@@ -20,9 +20,16 @@ const Background: FC<BackgroundProps> = ({
|
||||
style,
|
||||
className,
|
||||
}) => {
|
||||
const ref = useRef<SVGSVGElement>(null);
|
||||
const [patternId, setPatternId] = useState<string | null>(null);
|
||||
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 scaledGap = gap * scale;
|
||||
@@ -41,18 +48,23 @@ const Background: FC<BackgroundProps> = ({
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
}}
|
||||
ref={ref}
|
||||
>
|
||||
<pattern
|
||||
id={patternId}
|
||||
x={xOffset}
|
||||
y={yOffset}
|
||||
width={scaledGap}
|
||||
height={scaledGap}
|
||||
patternUnits="userSpaceOnUse"
|
||||
>
|
||||
{path}
|
||||
</pattern>
|
||||
<rect x="0" y="0" width="100%" height="100%" fill={`url(#${patternId})`} />
|
||||
{patternId && (
|
||||
<>
|
||||
<pattern
|
||||
id={patternId}
|
||||
x={xOffset}
|
||||
y={yOffset}
|
||||
width={scaledGap}
|
||||
height={scaledGap}
|
||||
patternUnits="userSpaceOnUse"
|
||||
>
|
||||
{path}
|
||||
</pattern>
|
||||
<rect x="0" y="0" width="100%" height="100%" fill={`url(#${patternId})`} />
|
||||
</>
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user