Pr comments and merge remote-tracking branch 'origin/main' into shahanneda/add-wordcloud-2

This commit is contained in:
Shahan Nedadahandeh 2022-08-02 20:05:23 -07:00
commit d2f9946fcc
Signed by: snedadah
GPG Key ID: 8638C7F917385B01
11 changed files with 489 additions and 60 deletions

View File

@ -2,6 +2,7 @@
"typescript.tsdk": "node_modules/typescript/lib", "typescript.tsdk": "node_modules/typescript/lib",
"eslint.format.enable": true, "eslint.format.enable": true,
"eslint.codeActionsOnSave.mode": "all", "eslint.codeActionsOnSave.mode": "all",
"css.format.spaceAroundSelectorSeparator": true,
"[css]": { "[css]": {
"editor.suggest.insertMode": "replace", "editor.suggest.insertMode": "replace",
"gitlens.codeLens.scopes": ["document"], "gitlens.codeLens.scopes": ["document"],

View File

@ -0,0 +1,36 @@
.barBackground {
fill: var(--card-background);
}
.bar {
fill: var(--primary-accent-light);
}
.barText {
visibility: hidden;
font-family: "Inconsolata", monospace;
font-weight: 800;
fill: var(--label);
}
.barGroup:hover .bar {
fill: var(--primary-accent);
filter: drop-shadow(0 0 calc(4rem / 16) var(--primary-accent));
}
.barGroup:hover .barText {
visibility: visible;
}
.tickLabel {
font-family: "Inconsolata", monospace;
font-weight: 800;
fill: var(--label);
}
.axisLabel {
font-family: "Inconsolata", monospace;
font-weight: 800;
fill: var(--label);
}

353
components/BarGraph.tsx Normal file
View File

@ -0,0 +1,353 @@
import { AxisBottom, AxisLeft } from "@visx/axis";
import { bottomTickLabelProps } from "@visx/axis/lib/axis/AxisBottom";
import { leftTickLabelProps } from "@visx/axis/lib/axis/AxisLeft";
import { GridColumns, GridRows } from "@visx/grid";
import { Group } from "@visx/group";
import { scaleBand, scaleLinear } from "@visx/scale";
import { Bar } from "@visx/shape";
import { Text } from "@visx/text";
import React from "react";
import { Color } from "utils/Color";
import styles from "./BarGraph.module.css";
interface BarGraphProps {
data: BarGraphData[];
/** Width of the entire graph, in pixels. */
width: number;
/** Height of the entire graph, in pixels. */
height: number;
/** Distance between the edge of the graph and the area where the bars are drawn, in pixels. */
margin: {
top: number;
bottom: number;
left: number;
right: number;
};
className?: string;
/** Font size of the category tick labels, in pixels. Default is 16px. */
categoryTickLabelSize?: number;
/** Font size of the value tick labels, in pixels. Default is 16px. */
valueTickLabelSize?: number;
/** Font size of the value that appears when hovering over a bar, in pixels. */
hoverLabelSize?: number;
/** Label text for the category axis. */
categoryAxisLabel?: string;
/** Font size of the label for the cateogry axis, in pixels. */
categoryAxisLabelSize?: number;
/** Controls the distance between the category axis label and the category axis. */
categoryAxisLabelOffset?: number;
/** Label text for the value axis. */
valueAxisLabel?: string;
/** Font size of the label for the value axis, in pixels. */
valueAxisLabelSize?: number;
/** Controls the distance between the value axis label and the value axis. */
valueAxisLabelOffset?: number;
}
interface BarGraphData {
category: string;
value: number;
}
const DEFAULT_LABEL_SIZE = 16;
export function BarGraphHorizontal(props: BarGraphProps) {
const {
width,
height,
margin,
data,
className,
categoryTickLabelSize = DEFAULT_LABEL_SIZE,
valueTickLabelSize = DEFAULT_LABEL_SIZE,
hoverLabelSize,
categoryAxisLabel,
categoryAxisLabelSize = DEFAULT_LABEL_SIZE,
categoryAxisLabelOffset = 0,
valueAxisLabel,
valueAxisLabelSize = DEFAULT_LABEL_SIZE,
valueAxisLabelOffset = 0,
} = props;
const barPadding = 0.4;
const categoryMax = height - margin.top - margin.bottom;
const valueMax = width - margin.left - margin.right;
const getCategory = (d: BarGraphData) => d.category;
const getValue = (d: BarGraphData) => d.value;
const categoryScale = scaleBand({
range: [0, categoryMax],
domain: data.map(getCategory),
padding: barPadding,
});
const valueScale = scaleLinear({
range: [0, valueMax],
nice: true,
domain: [0, Math.max(...data.map(getValue))],
});
const categoryPoint = (d: BarGraphData) => categoryScale(getCategory(d));
const valuePoint = (d: BarGraphData) => valueScale(getValue(d));
return (
<svg className={className} width={width} height={height}>
<Group top={margin.top} left={margin.left}>
<Group>
{data.map((d, idx) => {
const barName = `${getCategory(d)}-${idx}`;
const barWidth = categoryScale.bandwidth();
const backgroundBarWidth = barWidth / (1 - barPadding);
return idx % 2 === 0 ? (
<Bar
className={styles.barBackground}
key={`bar-${barName}-background`}
x={0}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
y={categoryPoint(d)! - (backgroundBarWidth - barWidth) / 2}
width={valueMax}
height={backgroundBarWidth}
/>
) : null;
})}
</Group>
<GridColumns
scale={valueScale}
height={categoryMax}
numTicks={5}
stroke={Color.label}
strokeWidth={4}
strokeDasharray="10"
strokeLinecap="round"
/>
<Group>
{data.map((d, idx) => {
const barName = `${getCategory(d)}-${idx}`;
const barLength = valuePoint(d);
const barWidth = categoryScale.bandwidth();
return (
<Group className={styles.barGroup} key={`bar-${barName}`}>
<Bar
className={styles.bar}
x={0}
y={categoryPoint(d)}
width={barLength}
height={barWidth}
/>
<Text
className={styles.barText}
x={valuePoint(d) - 12}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
y={categoryPoint(d)! + barWidth / 2}
fontSize={hoverLabelSize ?? barWidth * 0.75}
textAnchor="end"
verticalAnchor="middle"
>
{getValue(d)}
</Text>
</Group>
);
})}
</Group>
</Group>
<AxisLeft
scale={categoryScale}
top={margin.top}
left={margin.left}
hideAxisLine
hideTicks
tickLabelProps={() => {
return {
...leftTickLabelProps(),
className: styles.tickLabel,
dx: "-0.5rem",
dy: "0.25rem",
fontSize: `${categoryTickLabelSize / 16}rem`,
};
}}
label={categoryAxisLabel}
labelClassName={styles.axisLabel}
labelOffset={categoryAxisLabelOffset}
labelProps={{
fontSize: `${categoryAxisLabelSize / 16}rem`,
}}
/>
<AxisBottom
scale={valueScale}
top={margin.top + categoryMax}
left={margin.left}
hideAxisLine
hideTicks
numTicks={5}
tickLabelProps={() => {
return {
...bottomTickLabelProps(),
className: styles.tickLabel,
dy: "0.25rem",
fontSize: `${valueTickLabelSize / 16}rem`,
};
}}
label={valueAxisLabel}
labelClassName={styles.axisLabel}
labelOffset={valueAxisLabelOffset}
labelProps={{
fontSize: `${valueAxisLabelSize / 16}rem`,
}}
/>
</svg>
);
}
export function BarGraphVertical(props: BarGraphProps) {
const {
width,
height,
margin,
data,
className,
categoryTickLabelSize = DEFAULT_LABEL_SIZE,
valueTickLabelSize = DEFAULT_LABEL_SIZE,
hoverLabelSize,
categoryAxisLabel,
categoryAxisLabelSize = DEFAULT_LABEL_SIZE,
categoryAxisLabelOffset = 0,
valueAxisLabel,
valueAxisLabelSize = DEFAULT_LABEL_SIZE,
valueAxisLabelOffset = 0,
} = props;
const barPadding = 0.4;
const categoryMax = width - margin.left - margin.right;
const valueMax = height - margin.top - margin.bottom;
const getCategory = (d: BarGraphData) => d.category;
const getValue = (d: BarGraphData) => d.value;
const categoryScale = scaleBand({
range: [0, categoryMax],
domain: data.map(getCategory),
padding: barPadding,
});
const valueScale = scaleLinear({
range: [valueMax, 0],
nice: true,
domain: [0, Math.max(...data.map(getValue))],
});
const categoryPoint = (d: BarGraphData) => categoryScale(getCategory(d));
const valuePoint = (d: BarGraphData) => valueScale(getValue(d));
return (
<svg className={className} width={width} height={height}>
<Group top={margin.top} left={margin.left}>
<Group>
{data.map((d, idx) => {
const barName = `${getCategory(d)}-${idx}`;
const barWidth = categoryScale.bandwidth();
const backgroundBarWidth = barWidth / (1 - barPadding);
return idx % 2 === 0 ? (
<Bar
className={styles.barBackground}
key={`bar-${barName}-background`}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
x={categoryPoint(d)! - (backgroundBarWidth - barWidth) / 2}
y={0}
width={backgroundBarWidth}
height={valueMax}
/>
) : null;
})}
</Group>
<GridRows
scale={valueScale}
width={categoryMax}
numTicks={5}
stroke={Color.label}
strokeWidth={4}
strokeDasharray="10"
strokeLinecap="round"
/>
<Group>
{data.map((d, idx) => {
const barName = `${getCategory(d)}-${idx}`;
const barHeight = valueMax - valuePoint(d);
const barWidth = categoryScale.bandwidth();
return (
<Group className={styles.barGroup} key={`bar-${barName}`}>
<Bar
className={styles.bar}
x={categoryPoint(d)}
y={valueMax - barHeight}
width={barWidth}
height={barHeight}
/>
<Text
className={styles.barText}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
x={categoryPoint(d)! + barWidth / 2}
y={valueMax - barHeight + 12}
fontSize={hoverLabelSize ?? barWidth * 0.5}
textAnchor="middle"
verticalAnchor="start"
>
{getValue(d)}
</Text>
</Group>
);
})}
</Group>
</Group>
<AxisBottom
scale={categoryScale}
top={valueMax + margin.top}
left={margin.left}
hideAxisLine
hideTicks
tickLabelProps={() => {
return {
...bottomTickLabelProps(),
className: styles.tickLabel,
dy: "-0.25rem",
fontSize: `${categoryTickLabelSize / 16}rem`,
width: categoryScale.bandwidth(),
verticalAnchor: "start",
};
}}
label={categoryAxisLabel}
labelClassName={styles.axisLabel}
labelOffset={categoryAxisLabelOffset}
labelProps={{
fontSize: `${categoryAxisLabelSize / 16}rem`,
}}
/>
<AxisLeft
scale={valueScale}
top={margin.top}
left={margin.left}
hideAxisLine
hideTicks
numTicks={5}
tickLabelProps={() => {
return {
...leftTickLabelProps(),
className: styles.tickLabel,
dx: "-0.5rem",
dy: "0.25rem",
fontSize: `${valueTickLabelSize / 16}rem`,
};
}}
label={valueAxisLabel}
labelClassName={styles.axisLabel}
labelOffset={valueAxisLabelOffset}
labelProps={{
fontSize: `${valueAxisLabelSize / 16}rem`,
}}
/>
</svg>
);
}

View File

@ -1,6 +1,7 @@
.word:hover { .word:hover {
text-shadow: var(--primary-accent) 0 0 calc(20rem / 16); text-shadow: var(--primary-accent) 0 0 calc(20rem / 16);
text-anchor: "middle"; text-anchor: "middle";
cursor: default;
} }
.tooltip { .tooltip {
@ -9,9 +10,9 @@
top: 0; top: 0;
left: 0; left: 0;
position: absolute; position: absolute;
background-color: white; background-color: var(--label);
color: var(--navy); color: var(--primary-background);
box-shadow: var(--card-background) 0px calc(1rem / 16) calc(2rem / 16); box-shadow: 0px calc(1rem / 16) calc(2rem / 16) var(--card-background);
pointer-events: none; pointer-events: none;
padding: calc(10rem / 16); padding: calc(10rem / 16);
font-size: calc(18rem / 16); font-size: calc(18rem / 16);

View File

@ -23,10 +23,12 @@ interface WordCloudProps {
minFontSize?: number; minFontSize?: number;
/** The desired font size of the largest word, in px. */ /** The desired font size of the largest word, in px. */
maxFontSize?: number; maxFontSize?: number;
/** A random seed used for placing the words, change this value to get an alternate placement of words */ /** A random seed in the range [0, 1) used for placing the words, change this value to get an alternate placement of words */
randomSeed?: number; randomSeed?: number;
/** Type of spiral used for rendering the words, either rectangular or archimedean*/
spiral?: "rectangular" | "archimedean";
/** ClassName of the wrapper of the wordcloud */ /** ClassName of the wrapper of the wordcloud */
wrapperClassName?: string; className?: string;
} }
interface WordData { interface WordData {
@ -40,14 +42,15 @@ const TOOLTIP_HORIZONTAL_SHIFT_SCALER = 12.0;
export const WordCloud = withTooltip( export const WordCloud = withTooltip(
({ ({
data, data,
width = 1000, width,
height = 500, height,
wordPadding = 30, wordPadding,
fontWeight = 500, fontWeight,
minFontSize = 20, minFontSize,
maxFontSize = 150, maxFontSize,
randomSeed = 0.5, randomSeed,
wrapperClassName, spiral,
className,
}: WordCloudProps) => { }: WordCloudProps) => {
const { const {
tooltipData, tooltipData,
@ -59,7 +62,7 @@ export const WordCloud = withTooltip(
} = useTooltip<WordData>(); } = useTooltip<WordData>();
return ( return (
<div className={wrapperClassName}> <div className={className}>
<WordCloudWordsMemoized <WordCloudWordsMemoized
width={width} width={width}
height={height} height={height}
@ -79,6 +82,7 @@ export const WordCloud = withTooltip(
tooltipLeft={tooltipLeft} tooltipLeft={tooltipLeft}
tooltipTop={tooltipTop} tooltipTop={tooltipTop}
randomSeed={randomSeed} randomSeed={randomSeed}
spiral={spiral}
/> />
{tooltipOpen && tooltipData ? ( {tooltipOpen && tooltipData ? (
@ -99,36 +103,28 @@ export const WordCloud = withTooltip(
} }
); );
/** The internal wordcloud component that actually lays out the word needs to be seperate from the tooltip to prevent extra rerendering. */ /** The internal wordcloud component that actually lays out the word needs to be separate from the tooltip to prevent extra rerendering. */
type WordCloudWordsProps = WordCloudProps & { type WordCloudWordsProps = Omit<WordCloudProps, "className"> & {
data: Array<WordData>;
width: number;
height: number;
wordPadding: number;
fontWeight: number;
minFontSize: number;
maxFontSize: number;
randomSeed: number;
showTooltip: ( showTooltip: (
data: WordData, data: WordData,
tooltipLeft: number, tooltipLeft: number,
tooltipTop: number tooltipTop: number
) => void; ) => void;
hideTooltip: () => void; hideTooltip: () => void;
// These next props are just used to stop the component from updating when it doesnt need to, // tooltipLeft and tooltipTop are used for preventing unnessary renders
// but they are not needed to render the component
tooltipLeft?: number; tooltipLeft?: number;
tooltipTop?: number; tooltipTop?: number;
}; };
const WordCloudWords: React.FC<WordCloudWordsProps> = ({ const WordCloudWords: React.FC<WordCloudWordsProps> = ({
width,
height,
data, data,
wordPadding, width = 1000,
fontWeight, height = 500,
minFontSize, wordPadding = 30,
maxFontSize, fontWeight = 500,
randomSeed, minFontSize = 20,
maxFontSize = 150,
randomSeed = 0.5,
spiral = "rectangular",
showTooltip, showTooltip,
hideTooltip, hideTooltip,
}) => { }) => {
@ -149,19 +145,19 @@ const WordCloudWords: React.FC<WordCloudWordsProps> = ({
fontSize={fontSizeSetter} fontSize={fontSizeSetter}
font="Inconsolata, monospace" font="Inconsolata, monospace"
padding={wordPadding} padding={wordPadding}
spiral={"rectangular"} spiral={spiral}
rotate={0} rotate={0}
random={fixedValueGenerator} random={fixedValueGenerator}
> >
{(cloudWords) => {(cloudWords) =>
cloudWords.map((w, i) => { cloudWords.map((word, i) => {
return ( return (
<Text <Text
key={`wordcloud-word-${w.text ?? ""}`} key={`wordcloud-word-${word.text ?? ""}`}
fill={wordColors[i % wordColors.length]} fill={wordColors[i % wordColors.length]}
transform={`translate(${w.x ?? 0}, ${w.y ?? 0})`} transform={`translate(${word.x ?? 0}, ${word.y ?? 0})`}
fontSize={w.size} fontSize={word.size}
fontFamily={w.font} fontFamily={word.font}
fontWeight={fontWeight} fontWeight={fontWeight}
className={styles.word} className={styles.word}
textAnchor="middle" textAnchor="middle"
@ -175,11 +171,11 @@ const WordCloudWords: React.FC<WordCloudWordsProps> = ({
e e
) as Point; ) as Point;
if (w.text) { if (word.text) {
showTooltip( showTooltip(
{ text: w.text, value: data[i].value }, { text: word.text, value: data[i].value },
eventSvgCoords.x - eventSvgCoords.x -
w.text.length * TOOLTIP_HORIZONTAL_SHIFT_SCALER, word.text.length * TOOLTIP_HORIZONTAL_SHIFT_SCALER,
eventSvgCoords.y eventSvgCoords.y
); );
} }
@ -188,7 +184,7 @@ const WordCloudWords: React.FC<WordCloudWordsProps> = ({
} }
onMouseLeave={(_) => hideTooltip()} onMouseLeave={(_) => hideTooltip()}
> >
{w.text} {word.text}
</Text> </Text>
); );
}) })

View File

@ -3,35 +3,35 @@
*/ */
export const mockCategoricalData = [ export const mockCategoricalData = [
{ {
key: "Roboto", category: "Roboto",
value: 88, value: 88,
}, },
{ {
key: "Open Sans", category: "Open Sans",
value: 16, value: 16,
}, },
{ {
key: "Lato", category: "Lato",
value: 14, value: 14,
}, },
{ {
key: "Montserrat", category: "Montserrat",
value: 73, value: 73,
}, },
{ {
key: "Oswald", category: "Oswald",
value: 14, value: 14,
}, },
{ {
key: "Source Sans Pro", category: "Source Sans Pro",
value: 8, value: 8,
}, },
{ {
key: "Slabo 27px", category: "Slabo 27px",
value: 41, value: 41,
}, },
{ {
key: "Raleway", category: "Raleway",
value: 29, value: 29,
}, },
]; ];

3
package-lock.json generated
View File

@ -11,9 +11,12 @@
"@visx/axis": "^2.10.0", "@visx/axis": "^2.10.0",
"@visx/event": "^2.6.0", "@visx/event": "^2.6.0",
"@visx/grid": "^2.10.0", "@visx/grid": "^2.10.0",
"@visx/group": "^2.10.0",
"@visx/scale": "^2.2.2",
"@visx/shape": "^2.10.0", "@visx/shape": "^2.10.0",
"@visx/tooltip": "^2.10.0", "@visx/tooltip": "^2.10.0",
"@visx/wordcloud": "^2.10.0", "@visx/wordcloud": "^2.10.0",
"@visx/text": "^2.10.0",
"next": "12.1.6", "next": "12.1.6",
"react": "18.1.0", "react": "18.1.0",
"react-dom": "18.1.0" "react-dom": "18.1.0"

View File

@ -18,9 +18,12 @@
"@visx/axis": "^2.10.0", "@visx/axis": "^2.10.0",
"@visx/event": "^2.6.0", "@visx/event": "^2.6.0",
"@visx/grid": "^2.10.0", "@visx/grid": "^2.10.0",
"@visx/group": "^2.10.0",
"@visx/scale": "^2.2.2",
"@visx/shape": "^2.10.0", "@visx/shape": "^2.10.0",
"@visx/tooltip": "^2.10.0", "@visx/tooltip": "^2.10.0",
"@visx/wordcloud": "^2.10.0", "@visx/wordcloud": "^2.10.0",
"@visx/text": "^2.10.0",
"next": "12.1.6", "next": "12.1.6",
"react": "18.1.0", "react": "18.1.0",
"react-dom": "18.1.0" "react-dom": "18.1.0"

View File

@ -64,7 +64,7 @@ body {
background-color: var(--primary-background); background-color: var(--primary-background);
color: var(--primary-text); color: var(--primary-text);
font-family: "Inconsolata", "monospace"; font-family: "Inconsolata", monospace;
margin: 0; margin: 0;
} }

View File

@ -0,0 +1,7 @@
.page {
padding: calc(8rem / 16);
}
.barGraphDemo {
border: calc(1rem / 16) solid black;
}

View File

@ -1,24 +1,53 @@
import { moreMockCategoricalData } from "data/mocks"; import { BarGraphHorizontal, BarGraphVertical } from "components/BarGraph";
import { mockCategoricalData, moreMockCategoricalData } from "data/mocks";
import React from "react"; import React from "react";
import { ColorPalette } from "../components/ColorPalette"; import { ColorPalette } from "../components/ColorPalette";
import { WordCloud } from "../components/WordCloud"; import { WordCloud } from "../components/WordCloud";
import styles from "./playground.module.css";
export default function Home() { export default function Home() {
return ( return (
<div> <div className={styles.page}>
<h1>Playground</h1> <h1>Playground</h1>
<p>Show off your components here!</p> <p>Show off your components here!</p>
<ColorPalette /> <ColorPalette />
<h2> <h2>
<code>{"<WordCloud />"}</code> <code>{"<BarGraphHorizontal />"}</code>
</h2> </h2>
<WordCloud <BarGraphHorizontal
data={moreMockCategoricalData.map((word) => ({ className={styles.barGraphDemo}
text: word.key, data={mockCategoricalData}
value: word.value, width={800}
}))} height={500}
margin={{
top: 20,
bottom: 40,
left: 150,
right: 20,
}}
/>
<h2>
<code>{"<BarGraphVertical />"}</code>
</h2>
<p>
<code>{"<BarGraphVertical />"}</code> takes the same props as{" "}
<code>{"<BarGraphHorizontal />"}</code>.
</p>
<BarGraphVertical
className={styles.barGraphDemo}
data={mockCategoricalData}
width={800}
height={500}
margin={{
top: 20,
bottom: 80,
left: 60,
right: 20,
}}
/> />
</div> </div>
); );