Skip to content

Commit

Permalink
docs: add brush tooltip show (#5919)
Browse files Browse the repository at this point in the history
Co-authored-by: wb-xcf804241 <[email protected]>
  • Loading branch information
ai-qing-hai and wb-xcf804241 authored Dec 12, 2023
1 parent 08153e6 commit 04e673b
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
71 changes: 70 additions & 1 deletion site/examples/interaction/brush/demo/brush.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import { Chart } from '@antv/g2';
import { Chart, MASK_CLASS_NAME } from '@antv/g2';

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

const [render, remove] = useTip({
container: document.getElementById('container'),
onRemove: () => chart.emit('brush:remove', {}),
});

chart
.point()
.data({
Expand All @@ -28,4 +33,68 @@ chart
})
.interaction('brushHighlight', true);

chart.on('brush:start', onStart);
chart.on('brush:end', onUpdate);
chart.on('brush:remove', onRemove);

chart.render();

function onStart() {
chart.emit('tooltip:disable');
remove();
}

async function onUpdate(e) {
const data = await fetch(
'https://gw.alipayobjects.com/os/antvdemo/assets/data/scatter.json',
).then((res) => res.json());

const { canvas } = chart.getContext();
const [mask] = canvas.document.getElementsByClassName(MASK_CLASS_NAME);
const bounds = mask.getBounds();
const x = bounds.max[0];
const y = bounds.center[1];
const [X, Y] = e.data.selection;

const filtered = data.filter(({ weight, height }) => {
return weight >= X[0] && weight <= X[1] && height >= Y[0] && height <= Y[1];
});

render(filtered, [x, y]);
}

function onRemove(e) {
const { nativeEvent } = e;
if (nativeEvent) remove();
chart.emit('tooltip:enable');
}

function useTip({ container, onRemove = () => {}, offsetX = 20, offsetY = 0 }) {
let div;

const render = (data, [x, y]) => {
if (div) remove();
div = document.createElement('div');
div.innerHTML = `
Select a node:
<ul>${data.map((d) => `<li>x:${d.weight},y:${d.height}</li>`).join('')}</ul>
`;
div.style.position = 'absolute';
div.style.background = '#eee';
div.style.padding = '0.5em';
div.style.left = x + offsetX + 'px';
div.style.top = y + offsetY + 'px';
div.onclick = () => {
remove();
onRemove();
};
container.append(div);
};

const remove = () => {
if (div) div.remove();
div = null;
};

return [render, remove];
}
2 changes: 1 addition & 1 deletion site/examples/interaction/brush/demo/meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"zh": "刷选",
"en": "Brush"
},
"screenshot": "https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*XbQtTrYgA88AAAAAAAAAAAAADmJ7AQ/original"
"screenshot": "https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*ESblSJqW3zYAAAAAAAAAAAAADmJ7AQ/original"
},
{
"filename": "brush-emit.ts",
Expand Down

0 comments on commit 04e673b

Please sign in to comment.