Skip to content

Commit

Permalink
improve: allow adding class names to words
Browse files Browse the repository at this point in the history
This commit adds new prop `wordClassNames`, which allows to define
custom class name(s) for each word separately. This expands the ability
to customize words presentation at call-site.
  • Loading branch information
uson1x committed Jul 9, 2024
1 parent b7a35e3 commit 999e859
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ for more detailed props, please refer to below:
| padding | The padding accessor function, which indicates the numerical padding for each word. | `number \| (d) => number` | | `1` |
| random | The internal random number generator, used for selecting the initial position of each word, and the clockwise/counterclockwise direction of the spiral for each word. This should return a number in the range `[0, 1)`. | `(d) => number` | | `Math.random` |
| fill | The fill accessor function, which indicates the color for each word. | `(d, i) => string` | | `(d, i) => schemeCategory10ScaleOrdinal(i)` |
| wordClassNames | The classNames accessor function, which indicates the `class` for each word. | `(d, i) => string` | | `() => ''` |
| onWordClick | The function will be called when `click` event is triggered on a word | `(event, d) => {}` | | null |
| onWordMouseOver | The function will be called when `mouseover` event is triggered on a word | `(event, d) => {}` | | null |
| onWordMouseOut | The function will be called when `mouseout` event is triggered on a word | `(event, d) => {}` | | null |
Expand Down
3 changes: 3 additions & 0 deletions src/WordCloud.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ type WordCloudProps = {
padding?: number | ((word: Word, index: number) => number);
random?: () => number;
fill?: ValueFn<SVGTextElement, Word, string>;
wordClassNames?: ValueFn<SVGTextElement, Word, string>;
onWordClick?: (this: BaseType, event: any, d: Word) => void;
onWordMouseOver?: (this: BaseType, event: any, d: Word) => void;
onWordMouseOut?: (this: BaseType, event: any, d: Word) => void;
Expand All @@ -58,6 +59,7 @@ function WordCloud({
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore The ordinal function should accept number
fill = (_, i) => defaultScaleOrdinal(i),
wordClassNames = () => '',
onWordClick,
onWordMouseOver,
onWordMouseOut,
Expand Down Expand Up @@ -115,6 +117,7 @@ function WordCloud({
((d) => `${d.size}px`) as ValueFn<SVGTextElement, Word, string>
)
.style('fill', fill)
.attr('class', (d, i, nodes) => wordClassNames.call(nodes[i], d, i, nodes))
.attr('text-anchor', 'middle')
.attr('transform', (d) => `translate(${[d.x, d.y]})rotate(${d.rotate})`)
.text((d) => d.text);
Expand Down

0 comments on commit 999e859

Please sign in to comment.