Skip to content

Instantly share code, notes, and snippets.

@dagda1 dagda1/text.ts
Created Apr 10, 2019

Embed
What would you like to do?
import React, { useState, useEffect, useRef } from 'react';
import { LabelProps, LabelPosition } from '../../types';
import cs from 'classnames';
import { Text } from '@vx/text';
const styles = require('./LabelCompressed.scss');
export interface LabelPositioningProps {
angle: number;
dy: number;
dx: number;
}
export interface LabelPositioning {
[LabelPosition.root]: LabelPositioningProps;
[LabelPosition.horizontal]: LabelPositioningProps;
[LabelPosition.diagonal]: LabelPositioningProps;
}
export const LabelPositions: LabelPositioning = {
root: {
angle: 0,
dy: 30,
dx: 0
},
diagonal: {
angle: -60,
dy: -15,
dx: 12
},
horizontal: {
angle: 0,
dy: 0,
dx: 12
}
};
export const LabelCompressed: React.FunctionComponent<LabelProps> = ({
node,
active,
isRoot,
position = LabelPosition.diagonal
}) => {
// with --fix enabled positioning will be added to the deps array
// causing endless thrashing.
const [positioning, setSetPositioning] = useState<LabelPositioningProps>(LabelPositions[position]);
const textRef = useRef<SVGTextElement>(null);
useEffect(() => {
if (position !== LabelPosition.root) {
return;
}
const width = -textRef.current!.getBBox().width;
setSetPositioning({ ...positioning, dx: width / 2 });
}, [position, positioning]);
return (
<Text
className={cs(styles.item__name, {
[styles.active]: active,
[styles.root]: isRoot
})}
// @vx/text still uses old school refs
// eslint-disable-next-line
innerRef={textRef as any}
width={1000}
style={{ pointerEvents: 'none' }}
{...positioning}
>
{node.data.name}
</Text>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.