Skip to content

Commit

Permalink
feat: html label supported (#5354)
Browse files Browse the repository at this point in the history
* feat: html label supported

* chore: fix ci

* chore: update screenshot

* docs: add 4 examples for label

* docs: update label document
  • Loading branch information
hustcc authored Jul 28, 2023
1 parent b883e5d commit 64137e1
Show file tree
Hide file tree
Showing 20 changed files with 324 additions and 20 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions __tests__/integration/utils/createNodeGCanvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ export function createNodeGCanvas(width: number, height: number): Canvas {

// Create a renderer, unregister plugin relative to DOM.
const renderer = new Renderer();
// Remove html plugin to ssr.
const htmlRendererPlugin = renderer.getPlugin('html-renderer');
renderer.unregisterPlugin(htmlRendererPlugin);
const domInteractionPlugin = renderer.getPlugin('dom-interaction');
renderer.unregisterPlugin(domInteractionPlugin);
renderer.registerPlugin(
Expand Down
41 changes: 41 additions & 0 deletions __tests__/plots/static/alphabet-interval-html-label.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { G2Spec } from '../../../src';

export function alphabetIntervalHtmlLabel(): G2Spec {
return {
type: 'interval',
transform: [{ type: 'sortX', by: 'y', reverse: true }],
data: {
type: 'fetch',
value: 'data/alphabet.csv',
},
axis: {
y: { labelFormatter: '.0%' },
},
encode: {
x: 'letter',
y: 'frequency',
color: 'steelblue',
},
labels: [
{
text: 'frequency',
transform: [
{
type: 'overlapHide',
},
],
className: 'alphabet-labels',
render: (
_,
datum,
) => `<div style="left:-50%;top:-16px;position:relative;font-size:12px;">
<span style="color: blue">${
datum.letter
}</span>:<span style="color: black">${datum.frequency.toFixed(
2,
)}</span>
</div>`,
},
],
};
}
1 change: 1 addition & 0 deletions __tests__/plots/static/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { alphabetInterval } from './alphabet-interval';
export { alphabetIntervalHtmlLabel } from './alphabet-interval-html-label';
export { alphabetIntervalMaxWidth } from './alphabet-interval-max-width';
export { alphabetIntervalMinWidth } from './alphabet-interval-min-width';
export { alphabetIntervalMaxWidthTransposed } from './alphabet-interval-max-width-transposed';
Expand Down
16 changes: 15 additions & 1 deletion site/docs/spec/label/overview.zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ Label 继承 G Text 所有属性样式配置,此外还有 `position`, `selecto
| backgroundPadding | 背景框内间距 | `number[]` | - |
| `background${style}` | 更多背景框样式配置,参考 `RectStyleProps` 属性值 | - | - |

数据标签支持使用 HTML 自定义标签,具体配置为:

| 参数 | 说明 | 类型 | 默认值 |
| -------------------- | ------------------------------------------------ | ---------- | ------ |
| render | 返回 HTML string 或者 HTMElement,使用 HTML 自定义复杂标签 | `RenderFunc` | - |

```ts
type RenderFunc = (text: string, datum: object, index: number) => String | HTMLElement;
```

## FAQ

### 支持哪些 position?
Expand Down Expand Up @@ -131,6 +141,10 @@ selector 选择器可以对系列数据进行过滤索引。
}
```

### 支持哪些 transform
### 支持哪些 transform?

所有的 transform 有单独具体的文档,具体参考 [Label.transform](/spec/overview#label)

### 怎么使用 HTML 自定义数据标签?

使用 label 配置手册中的 `render` 即可,具体使用可以参考 [DEMO](/examples/component/label/#htmlLabel)
32 changes: 32 additions & 0 deletions site/examples/component/label/demo/contrastReverse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Chart } from '@antv/g2';

const chart = new Chart({
container: 'container',
theme: 'classic',
autoFit: true,
});

chart
.interval()
.data({
type: 'fetch',
value: 'https://assets.antv.antgroup.com/g2/alphabet.json',
})
.encode('x', 'letter')
.encode('y', 'frequency')
.encode('color', 'letter')
.label({
text: 'frequency',
position: 'inside',
formatter: '.0%',
fill: '#000',
transform: [
{
type: 'contrastReverse',
threshold: 21,
palette: ['#000', '#fff'], // Use full color string to avoid screenshot error.
},
],
});

chart.render();
39 changes: 39 additions & 0 deletions site/examples/component/label/demo/htmlLabel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Chart } from '@antv/g2';

const chart = new Chart({
container: 'container',
theme: 'classic',
autoFit: true,
});

const data = [
{ repo: 'G', star: 918 },
{ repo: 'G2', star: 11688 },
{ repo: 'G6', star: 10045 },
{ repo: 'L7', star: 3125 },
{ repo: 'F2', star: 7820 },
{ repo: 'S2', star: 1231 },
{ repo: 'X6', star: 4755 },
];

chart
.interval()
.data(data)
.encode('x', 'repo')
.encode('y', 'star')
.encode('color', 'repo')
.label({
text: 'star',
render: (text, datum) => {
return `
<div style="left:-50%;top:-20px;position:relative;font-size:14px;">
<span>${datum.repo}</span>
:
<a href="https://github.com/antvis/${datum.repo}" target="_blank">${datum.star}</a>
</div>
`;
},
})
.legend(false);

chart.render();
40 changes: 40 additions & 0 deletions site/examples/component/label/demo/meta.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"title": {
"zh": "中文分类",
"en": "Category"
},
"demos": [
{
"filename": "overlapHide.ts",
"title": {
"zh": "数据标签碰撞隐藏",
"en": "Overlap Hide"
},
"screenshot": "https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*clZ2SbxuHloAAAAAAAAAAAAADmJ7AQ/original"
},
{
"filename": "overflowHide.ts",
"title": {
"zh": "数据标签超出隐藏",
"en": "Overflow Hide"
},
"screenshot": "https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*EMy1RqEBmm4AAAAAAAAAAAAADmJ7AQ/original"
},
{
"filename": "contrastReverse.ts",
"title": {
"zh": "数据标签颜色反转",
"en": "Contrast Reverse"
},
"screenshot": "https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*CUyIT4Bxx9wAAAAAAAAAAAAADmJ7AQ/original"
},
{
"filename": "htmlLabel.ts",
"title": {
"zh": "HTML 标签",
"en": "HTML Label"
},
"screenshot": "https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*rUexRKH7czsAAAAAAAAAAAAADmJ7AQ/original"
}
]
}
27 changes: 27 additions & 0 deletions site/examples/component/label/demo/overflowHide.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Chart } from '@antv/g2';

const chart = new Chart({
container: 'container',
theme: 'classic',
width: 800,
autoFit: false,
});

chart
.interval()
.data({
type: 'fetch',
value: 'https://assets.antv.antgroup.com/g2/alphabet.json',
})
.encode('x', 'letter')
.encode('y', 'frequency')
.encode('color', 'steelblue')
.axis('y', { labelFormatter: '.0%' })
.label({
text: 'frequency',
position: 'inside',
formatter: '.0%',
transform: [{ type: 'overflowHide' }],
});

chart.render();
26 changes: 26 additions & 0 deletions site/examples/component/label/demo/overlapHide.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { Chart } from '@antv/g2';

const chart = new Chart({
container: 'container',
theme: 'classic',
autoFit: true,
});

chart
.line()
.data({
type: 'fetch',
value: 'https://assets.antv.antgroup.com/g2/aapl.json',
})
.encode('x', (d) => new Date(d.date))
.encode('y', 'close')
.label({
text: 'close',
transform: [
{
type: 'overlapHide',
},
],
});

chart.render();
4 changes: 4 additions & 0 deletions site/examples/component/label/index.en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
title: Label
order: 3
---
4 changes: 4 additions & 0 deletions site/examples/component/label/index.zh.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
title: 数据标签
order: 3
---
9 changes: 7 additions & 2 deletions src/runtime/plot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1189,6 +1189,7 @@ function createLabelShapeFunction(
formatter = (d) => `${d}`,
transform,
style: abstractStyle,
render,
...abstractOptions
} = options;
const visualOptions = mapObject(
Expand All @@ -1197,10 +1198,14 @@ function createLabelShapeFunction(
);
const { shape = defaultLabelShape, text, ...style } = visualOptions;
const f = typeof formatter === 'string' ? format(formatter) : formatter;
const value = { ...style, text: f(text, datum, index, abstractData) };
const value = {
...style,
text: f(text, datum, index, abstractData),
datum,
};

// Params for create shape.
const shapeOptions = { type: `label.${shape}`, ...style };
const shapeOptions = { type: `label.${shape}`, render, ...style };
const shapeFunction = useShape(shapeOptions, shapeContext);
const defaults = getDefaultsStyle(theme, 'label', shape, 'label');

Expand Down
1 change: 1 addition & 0 deletions src/runtime/types/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ type ComponentTheme = {
legendContinuous?: any;
label?: LabelStyleProps;
innerLabel?: LabelStyleProps;
htmlLabel?: any;
slider?: any;
scrollbar?: any;
title?: any; // @todo
Expand Down
23 changes: 21 additions & 2 deletions src/shape/label/label.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ import { Advance } from '../text/advance';
import { LabelPosition } from './position/default';
import * as PositionProcessor from './position';

export type LabelOptions = Record<string, any>;
export type LabelOptions = {
/**
* Customize label with html string or element.
*/
render: (text: string, datum: any, index: number) => string | HTMLElement;
[key: string]: any;
};

function inferPosition(position: LabelPosition, coordinate: Coordinate) {
if (position !== undefined) return position;
Expand All @@ -27,8 +33,14 @@ function getDefaultStyle(
// For non-series mark, calc position for label based on
// position and the bounds of shape.
const { position } = value;
const { render } = options;
const p = inferPosition(position, coordinate);
const t = theme[p === 'inside' ? 'innerLabel' : 'label'];
const labelType = render
? 'htmlLabel'
: p === 'inside'
? 'innerLabel'
: 'label';
const t = theme[labelType];
const v = Object.assign({}, t, value);
const processor = PositionProcessor[camelCase(p)];
if (!processor) {
Expand All @@ -46,13 +58,15 @@ function getDefaultStyle(
*/
export const Label: SC<LabelOptions> = (options, context) => {
const { coordinate, theme } = context;
const { render } = options;
return (points, value) => {
const {
text,
x,
y,
transform: specifiedTS = '',
transformOrigin,
className = '',
...overrideStyle
} = value;
const {
Expand All @@ -64,6 +78,11 @@ export const Label: SC<LabelOptions> = (options, context) => {
return select(new Advance())
.call(applyStyle, defaultStyle)
.style('text', `${text}`)
.style('className', `${className} g2-label`)
.style(
'innerHTML',
render ? render(text, value.datum, value.index) : undefined,
)
.style(
'labelTransform',
`${transform} rotate(${+rotate}) ${specifiedTS}`.trim(),
Expand Down
Loading

0 comments on commit 64137e1

Please sign in to comment.