refactor(bg): dont use math random for pattern id generation closes #2086

This commit is contained in:
moklick
2022-04-21 23:07:31 +02:00
parent eff243076b
commit 84f1c8ca88
+14 -2
View File
@@ -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);
useEffect(() => {
// when there are multiple flows on a page we need to make sure that every background gets its own pattern. // 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)}`, []); 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,7 +48,10 @@ const Background: FC<BackgroundProps> = ({
width: '100%', width: '100%',
height: '100%', height: '100%',
}} }}
ref={ref}
> >
{patternId && (
<>
<pattern <pattern
id={patternId} id={patternId}
x={xOffset} x={xOffset}
@@ -53,6 +63,8 @@ const Background: FC<BackgroundProps> = ({
{path} {path}
</pattern> </pattern>
<rect x="0" y="0" width="100%" height="100%" fill={`url(#${patternId})`} /> <rect x="0" y="0" width="100%" height="100%" fill={`url(#${patternId})`} />
</>
)}
</svg> </svg>
); );
}; };