-
Notifications
You must be signed in to change notification settings - Fork 134
fix(chart): Enhance Canvas based text measurement to account for various font features #2798
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
awahab07
wants to merge
15
commits into
elastic:main
Choose a base branch
from
awahab07:249382-Monospace-fonts-for-Lens
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 3 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
137f5b6
Add story to confirm/assert canvas based text measure takes into acco…
awahab07 52b33aa
Use in-Dom canvas, rendered within .echChart, instead of off-screen c…
awahab07 bd9e537
Optimize font assignment calls to Canvas context.
awahab07 e2a95a3
Merge remote-tracking branch 'upstream/main' into 249382-Monospace-fo…
awahab07 3351db7
Merge remote-tracking branch 'upstream/main' into 249382-Monospace-fo…
awahab07 f866fff
Add 'Elastic UI Numeric' font assets and helpers.
awahab07 3edae98
Enhance font measurement story.
awahab07 3d1292f
Add support for a custom font family for bullet charts.
awahab07 5503545
Add 'Elastic UI Numeric' font to bullet graph story.
awahab07 6a036fc
Font measurement story test.
awahab07 36aff19
Merge remote-tracking branch 'upstream/main' into 249382-Monospace-fo…
awahab07 63fd67a
Merge remote-tracking branch 'upstream/main' into 249382-Monospace-fo…
awahab07 ca2286d
Fix linting.
awahab07 a88e2ac
Use `valueFontSize: 'fit'` for Metric chart.
awahab07 9c7470d
test(vrt): update screenshots [skip ci]
elastic-datavis[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0 and the Server Side Public License, v 1; you may not use this file except | ||
| * in compliance with, at your election, the Elastic License 2.0 or the Server | ||
| * Side Public License, v 1. | ||
| */ | ||
|
|
||
| import React from 'react'; | ||
|
|
||
| import { registerMeasureCanvas, unregisterMeasureCanvas } from '../utils/bbox/canvas_text_bbox_calculator'; | ||
|
|
||
| const canvasStyle: React.CSSProperties = { position: 'absolute', width: 0, height: 0, overflow: 'hidden' }; | ||
|
|
||
| /** | ||
| * Hidden canvas element that lives in the Chart DOM tree to inherit computed | ||
| * CSS font properties (e.g. font-feature-settings, font-variant-numeric) | ||
| * from ancestors. Used by {@link withTextMeasure} for accurate text measurement. | ||
| * @internal | ||
| */ | ||
| export class ChartMeasureCanvas extends React.Component { | ||
| private canvasRef = React.createRef<HTMLCanvasElement>(); | ||
|
|
||
| componentDidMount() { | ||
| if (this.canvasRef.current) registerMeasureCanvas(this.canvasRef.current); | ||
| } | ||
|
|
||
| componentWillUnmount() { | ||
| if (this.canvasRef.current) unregisterMeasureCanvas(this.canvasRef.current); | ||
| } | ||
|
|
||
| shouldComponentUpdate() { | ||
| return false; | ||
| } | ||
|
|
||
| render() { | ||
| return <canvas ref={this.canvasRef} width={0} height={0} aria-hidden style={canvasStyle} />; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
169 changes: 169 additions & 0 deletions
169
storybook/stories/test_cases/34_font_measurement.story.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| /* | ||
| * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
| * or more contributor license agreements. Licensed under the Elastic License | ||
| * 2.0 and the Server Side Public License, v 1; you may not use this file except | ||
| * in compliance with, at your election, the Elastic License 2.0 or the Server | ||
| * Side Public License, v 1. | ||
| */ | ||
|
|
||
| import { select, number, boolean } from '@storybook/addon-knobs'; | ||
| import React from 'react'; | ||
|
|
||
| import type { PartialTheme } from '@elastic/charts'; | ||
| import { | ||
| Axis, | ||
| BarSeries, | ||
| Chart, | ||
| LabelOverflowConstraint, | ||
| Metric, | ||
| Position, | ||
| ScaleType, | ||
| Settings, | ||
| } from '@elastic/charts'; | ||
|
|
||
| import type { ChartsStory } from '../../types'; | ||
| import { useBaseTheme } from '../../use_base_theme'; | ||
|
|
||
| const barData = [ | ||
| { x: '2021', y: 1234567.89 }, | ||
| { x: '2022', y: 2345678.9 }, | ||
| { x: '2023', y: 3456789.01 }, | ||
| { x: '2024', y: 4567890.12 }, | ||
| { x: '2025', y: 5678901.23 }, | ||
| ]; | ||
|
|
||
| const metricData = [ | ||
| [ | ||
| { | ||
| color: '#3c3c3c', | ||
| title: 'Revenue 2025', | ||
| subtitle: 'Total Revenue', | ||
| value: 5678901.23, | ||
| valueFormatter: (v: number) => `$${v.toFixed(2)}`, | ||
| }, | ||
| ], | ||
| ]; | ||
|
|
||
| export const Example: ChartsStory = (_, { description }) => { | ||
| // ── Layout ─────────────────────────────────────────────────────────────── | ||
| const chartWidth = number('Chart width (px)', 300, { min: 100, max: 1200, step: 1 }); | ||
|
|
||
| // ── Font ───────────────────────────────────────────────────────────────── | ||
| const fontFamily = select( | ||
| 'Font: family', | ||
| { Inter: 'Inter', Arial: 'Arial', 'Times New Roman': 'Times New Roman', Courier: 'Courier' }, | ||
| 'Inter', | ||
| ); | ||
| const fontSize = number('Font: size (px)', 20, { range: true, min: 8, max: 48, step: 1 }); | ||
|
|
||
| // ── font-feature-settings ───────────────────────────────────────────────── | ||
| const tnum = boolean("font-feature-settings: 'tnum' — tabular digits", true); | ||
| const zero = boolean("font-feature-settings: 'zero' — slashed zero", true); | ||
| const ss01 = boolean("font-feature-settings: 'ss01' — open digits", true); | ||
| const ss07 = boolean("font-feature-settings: 'ss07' — squared punctuation", true); | ||
|
|
||
| // ── font-variant-numeric ────────────────────────────────────────────────── | ||
| const tabularNums = boolean('font-variant-numeric: tabular-nums', true); | ||
| const slashedZero = boolean('font-variant-numeric: slashed-zero', true); | ||
|
|
||
| const fontFeatureParts: string[] = []; | ||
| if (tnum) fontFeatureParts.push("'tnum'"); | ||
| if (zero) fontFeatureParts.push("'zero'"); | ||
| if (ss01) fontFeatureParts.push("'ss01'"); | ||
| if (ss07) fontFeatureParts.push("'ss07'"); | ||
|
|
||
| const fontVariantNumericParts: string[] = []; | ||
| if (tabularNums) fontVariantNumericParts.push('tabular-nums'); | ||
| if (slashedZero) fontVariantNumericParts.push('slashed-zero'); | ||
|
|
||
| const containerStyle: React.CSSProperties = { | ||
| ...(fontFeatureParts.length > 0 ? { fontFeatureSettings: fontFeatureParts.join(', ') } : {}), | ||
| ...(fontVariantNumericParts.length > 0 ? { fontVariantNumeric: fontVariantNumericParts.join(' ') } : {}), | ||
| }; | ||
|
|
||
| const theme: PartialTheme = { | ||
| barSeriesStyle: { | ||
| displayValue: { | ||
| fontSize: fontSize + 2, | ||
| fontFamily, | ||
| fill: '#000', | ||
| }, | ||
| }, | ||
| axes: { | ||
| tickLabel: { | ||
| fontSize, | ||
| fontFamily, | ||
| fill: '#000', | ||
| }, | ||
| }, | ||
| }; | ||
|
|
||
| const anyFeaturesActive = fontFeatureParts.length > 0 || fontVariantNumericParts.length > 0; | ||
|
|
||
| return ( | ||
| <div style={{ display: 'flex', flexDirection: 'column', gap: '24px', ...containerStyle }}> | ||
| <div style={{ height: '200px', width: `${chartWidth}px` }}> | ||
| <Chart title="Metric Chart" description={description}> | ||
| <Settings baseTheme={useBaseTheme()} /> | ||
| <Metric id="metric1" data={metricData} /> | ||
| </Chart> | ||
| </div> | ||
|
|
||
| <div style={{ height: '300px', width: `${chartWidth}px` }}> | ||
| <Chart> | ||
| <Settings theme={theme} baseTheme={useBaseTheme()} /> | ||
| <Axis id="bottom" position={Position.Bottom} title="Year" showOverlappingTicks /> | ||
| <Axis | ||
| id="left" | ||
| title="Revenue ($)" | ||
| position={Position.Left} | ||
| tickFormat={(d: number) => `$${(d / 1_000_000).toFixed(1)}M`} | ||
| /> | ||
| <BarSeries | ||
| id="bars" | ||
| displayValueSettings={{ | ||
| showValueLabel: true, | ||
| overflowConstraints: [LabelOverflowConstraint.ChartEdges, LabelOverflowConstraint.BarGeometry], | ||
| }} | ||
| xScaleType={ScaleType.Ordinal} | ||
| yScaleType={ScaleType.Linear} | ||
| xAccessor="x" | ||
| yAccessors={['y']} | ||
| data={barData} | ||
| /> | ||
| </Chart> | ||
| </div> | ||
|
|
||
| {anyFeaturesActive && ( | ||
| <div | ||
| style={{ | ||
| padding: '12px 16px', | ||
| background: '#fff3cd', | ||
| border: '1px solid #ffc107', | ||
| borderRadius: '4px', | ||
| fontSize: '13px', | ||
| }} | ||
| > | ||
| <strong>Active features:</strong>{' '} | ||
| {[ | ||
| ...(fontFeatureParts.length > 0 ? [`font-feature-settings: ${fontFeatureParts.join(', ')}`] : []), | ||
| ...(fontVariantNumericParts.length > 0 | ||
| ? [`font-variant-numeric: ${fontVariantNumericParts.join(' ')}`] | ||
| : []), | ||
| ].join(' | ')} | ||
| <div style={{ marginTop: '8px', fontSize: '20px', fontFamily }}>0123456789 · $1,234,567.89 · 100.00%</div> | ||
| </div> | ||
| )} | ||
|
|
||
| <p style={{ margin: 0, fontSize: '12px', color: '#888' }}> | ||
| Tests whether canvas text measurement respects rendered text when font variants (e.g. OpenType features) are | ||
| applied via CSS inheritance. Text measurement should account for all computed font properties that affect | ||
| rendered dimensions, ensuring text is neither clipped nor overlapping. | ||
| </p> | ||
| </div> | ||
| ); | ||
| }; | ||
|
|
||
| Example.parameters = { | ||
| resize: false, | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is to save on performance cost as performance trail shows
ctx.fontassignment is the most expensive call when measuring text (it's even expensive thanctx.measureText()).