refactor(background): move background to own package, replace example import

This commit is contained in:
Christopher Möller
2022-07-21 13:25:04 +02:00
parent 229c156d79
commit 272d0dfcb4
29 changed files with 384 additions and 275 deletions
+85
View File
@@ -0,0 +1,85 @@
import React, { memo, FC, useEffect, useState, useRef } from 'react';
import cc from 'classcat';
import { useStore, ReactFlowState } from '@react-flow/core';
import { BackgroundProps, BackgroundVariant } from './types';
import { createGridLinesPath, createGridDotsPath } from './utils';
const defaultColors = {
[BackgroundVariant.Dots]: '#81818a',
[BackgroundVariant.Lines]: '#eee',
};
const transformSelector = (s: ReactFlowState) => s.transform;
const Background: FC<BackgroundProps> = ({
variant = BackgroundVariant.Dots,
gap = 15,
size = 0.4,
color,
style,
className,
}) => {
const ref = useRef<SVGSVGElement>(null);
const [patternId, setPatternId] = useState<string | null>(null);
const [tX, tY, tScale] = useStore(transformSelector);
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 scaledGap = gap * tScale || 1;
const xOffset = tX % scaledGap;
const yOffset = tY % scaledGap;
const isLines = variant === BackgroundVariant.Lines;
const bgColor = color ? color : defaultColors[variant];
const path = isLines
? createGridLinesPath(scaledGap, size, bgColor)
: createGridDotsPath(size * tScale, bgColor);
return (
<svg
className={cc([
'react-flow__background',
'react-flow__container',
className,
])}
style={{
...style,
width: '100%',
height: '100%',
}}
ref={ref}
>
{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>
);
};
Background.displayName = 'Background';
export default memo(Background);
+2
View File
@@ -0,0 +1,2 @@
export { default as Background, default } from './Background';
export * from './types';
+13
View File
@@ -0,0 +1,13 @@
import { HTMLAttributes } from 'react';
export enum BackgroundVariant {
Lines = 'lines',
Dots = 'dots',
}
export interface BackgroundProps extends HTMLAttributes<SVGElement> {
variant?: BackgroundVariant;
gap?: number;
color?: string;
size?: number;
}
+9
View File
@@ -0,0 +1,9 @@
import React from 'react';
export const createGridLinesPath = (size: number, strokeWidth: number, stroke: string): React.ReactElement => {
return <path stroke={stroke} strokeWidth={strokeWidth} d={`M${size / 2} 0 V${size} M0 ${size / 2} H${size}`} />;
};
export const createGridDotsPath = (size: number, fill: string): React.ReactElement => {
return <circle cx={size} cy={size} r={size} fill={fill} />;
};