diff --git a/README.md b/README.md
index d713f48..f679a8c 100644
--- a/README.md
+++ b/README.md
@@ -75,7 +75,8 @@ The component is the default export of `@opencor/plot`, and is also exported as
| Type | Definition | Description |
|---|---|---|
-| `PlotData` | `{ traces, xAxis?, yAxis? }` | The data to plot (see [Data](#data)). |
+| `PlotData` | `{ traces, title?, titlePosition?, xAxis?, yAxis? }` | The data to plot (see [Data](#data)). |
+| `PlotTitlePosition` | `'top' \| 'left' \| 'right' \| 'bottom'` | Where the title of the plot is (see [Data](#data)). |
| `PlotAxis` | `{ title?, range?, grid?, log? }` | An axis of the plot (see [Data](#data)). |
| `PlotTrace` | `{ name, x, y, xValue, yValue, line?, marker?, traceId?, legendRank?, runLabel? }` | A trace to plot (see [Data](#data)). |
| `PlotLineStyle` | `{ type?, color?, thickness? }` | The style of the line of a trace (see [Data](#data)). |
@@ -109,6 +110,8 @@ The component is the default export of `@opencor/plot`, and is also exported as
| Property | Type | Description |
|---|---|---|
| `traces` | [`PlotTrace`](#types)`[]` | The traces to plot. |
+| `title` | `string` | The title of the plot. |
+| `titlePosition` | [`PlotTitlePosition`](#types) | Where the title of the plot is: above the plot (`'top'`, the default) or below it (`'bottom'`), centred on its plotting area, or to its left (`'left'`), centred on its plotting area and reading from bottom to top (like the title of the Y axis), or to its right (`'right'`, i.e. between its plotting area and its legend), centred on its plotting area and reading from top to bottom. |
| `xAxis`, `yAxis` | [`PlotAxis`](#types) | The axes. |
[`PlotAxis`](#types):
@@ -216,7 +219,7 @@ Also set the [`live`](#props) prop while the data is live, so that the last poin
### Several plots
Plots can be shown together (e.g., stacked or side by side) and made to work as one, using a [`PlotGroup`](#types), i.e. a string or a symbol, which all the plots of a group share:
-- **Aligned axes:** the plots of an [`xAxisAlign`](#props) group get the same left and right margins, so that their plotting areas line up when they are stacked, while those of a [`yAxisAlign`](#props) group get the same top and bottom margins, so that their plotting areas line up when they are side by side.
+- **Aligned axes:** the plots of an [`xAxisAlign`](#props) group get the same left and right margins, so that their plotting areas line up when they are stacked, while those of a [`yAxisAlign`](#props) group get the same top and bottom margins, so that their plotting areas line up when they are side by side. This is also the case if some of them have a title and others don't, or if their titles are at different positions. In that case, a plot leaves room for the title of the plots that have one on the left (or right), so that its Y axis title (or legend) lines up with theirs.
- **Synchronised axes:** the plots of an [`xAxisSync`](#props) (or [`yAxisSync`](#props)) group share the range and the scale (i.e. linear or logarithmic) of their X (or Y) axis. Zooming, panning, or resetting the zoom of one of them, or making its axis logarithmic (or not), does the same to the others, be it done by the user or using [`setRanges()`](#methods). Until one of them gets zoomed or panned, their axes fit the data of all of them. With a synchronised X axis, hovering one of them also shows the hover guide and tooltip of the others, at the same X value (or, for a plot that has no point there, at its closest point, as when it is hovered itself).
Aligning and synchronising are independent of each other: plots can be aligned without being synchronised (e.g., when they show different X values), and synchronised without being aligned (e.g., when they are not shown next to each other). A plot can also be in different groups for its X and Y axes, and the groups of X axes are separate from those of Y axes, so the same group can be used for both.
@@ -390,7 +393,7 @@ Set any of these CSS variables on an ancestor of the component. Each has a light
| Variable | Used for |
|---|---|
| `--opencor-plot-background` | The background of the plot. |
-| `--opencor-plot-text-color` | The axis titles, the legend, and the ring around the last point of a live trace. |
+| `--opencor-plot-text-color` | The plot and axis titles, the legend, and the ring around the last point of a live trace. |
| `--opencor-plot-muted-text-color` | Tick labels, the hover guide line, hidden traces in the legend, and secondary text in overlays. |
| `--opencor-plot-primary-color` | The zoom box (and, by default, the keyboard focus ring). |
| `--opencor-plot-grid-color` | Grid lines. |
diff --git a/demo/App.vue b/demo/App.vue
index 4ba8004..9fcbf41 100644
--- a/demo/App.vue
+++ b/demo/App.vue
@@ -148,6 +148,12 @@
Stacked
+
+ Title
+
+ {{ name }}
+
+
Theme
@@ -277,7 +283,8 @@ import OpenCORPlot, {
type PlotMarkerType,
type PlotMemoryUsage,
type PlotRanges,
- type PlotTheme
+ type PlotTheme,
+ type PlotTitlePosition
} from '../index';
import {
BENCHMARK_INTERACTIONS,
@@ -305,6 +312,7 @@ const nbOfInstances = vue.ref(1);
const theme = vue.ref('mixed');
const levelOfDetail = vue.ref(true);
const customContextMenu = vue.ref(false);
+const titlePosition = vue.ref('none'); // Where our plot titles are.
const layout = vue.ref<'grid' | 'stacked'>('grid'); // Whether our instances are in a grid or stacked (in one column).
const alignedXAxes = vue.ref(true); // Whether the X axes of our instances line up (see ALIGN_GROUP).
const linkedXAxes = vue.ref(true); // Whether the X axes of our instances are synchronised (see SYNC_GROUP).
@@ -737,14 +745,25 @@ vue.watch(nbOfInstances, (newNbOfInstances: number) => {
instanceLegends.value = instanceLegends.value.slice(0, newNbOfInstances);
});
-// Our data, as given to our instances, i.e. with our axis, line, and marker options applied to it.
+// Our data, as given to our instances, i.e. with our title, axis, line, and marker options applied to it.
// Note #1: we only create new data objects when our data or our options change, since giving new data to our instances
// makes them update their plot.
// Note #2: with mixed lines (or markers), each of our traces has another type of line (or marker) other than none, so
// that they can be told apart and compared.
// Note #3: with default markers, our traces have no marker style, i.e. they only have markers if they have fewer than
// 20 points, so our other marker options don't apply.
+// Note #4: with mixed titles, each of our instances has its title at another position, so that we can check that their
+// plotting areas still line up.
+const TITLE_POSITIONS: Record = {
+ none: 'None',
+ top: 'Top',
+ left: 'Left',
+ right: 'Right',
+ bottom: 'Bottom',
+ mixed: 'Mixed'
+};
+const MIXED_TITLE_POSITIONS: PlotTitlePosition[] = ['top', 'left', 'right', 'bottom'];
const Y_RANGES: Record = {
auto: undefined,
fromZero: [0, null],
@@ -823,6 +842,13 @@ const plottedDatasets = vue.computed(() => {
return datasets.value.map((data, index) => ({
...data,
+ title: titlePosition.value === 'none' ? undefined : `Plot #${index + 1} `,
+ titlePosition:
+ titlePosition.value === 'none'
+ ? undefined
+ : titlePosition.value === 'mixed'
+ ? MIXED_TITLE_POSITIONS[index % MIXED_TITLE_POSITIONS.length]
+ : titlePosition.value,
xAxis: { ...data.xAxis, ...instanceAxesSettings(index).x },
yAxis: { ...data.yAxis, range, ...instanceAxesSettings(index).y },
traces: data.traces.map((trace, traceIndex) => ({
diff --git a/index.ts b/index.ts
index 043c136..d36cbf3 100644
--- a/index.ts
+++ b/index.ts
@@ -29,6 +29,7 @@ export type {
PlotPointCounts,
PlotRanges,
PlotRangesToSet,
+ PlotTitlePosition,
PlotTrace
} from './src/widgets/PlotWidget.vue';
export { default, default as OpenCORPlot } from './src/widgets/PlotWidget.vue';
diff --git a/package.json b/package.json
index 2062f7b..8bdeb07 100644
--- a/package.json
+++ b/package.json
@@ -32,7 +32,7 @@
],
"type": "module",
"types": "dist/index.d.ts",
- "version": "0.20261204.0",
+ "version": "0.20261204.1",
"exports": {
".": {
"types": "./dist/index.d.ts",
diff --git a/src/common/alignUtils.test.ts b/src/common/alignUtils.test.ts
index 243fdd0..c689fdd 100644
--- a/src/common/alignUtils.test.ts
+++ b/src/common/alignUtils.test.ts
@@ -50,6 +50,15 @@ describe('sameMargins()', () => {
expect(sameMargins({ start: 1, end: 2 }, { start: 1, end: 3 })).toBe(false);
});
+ it('returns whether the outer part of some start margins is the same', () => {
+ expect(sameMargins({ start: 1, end: 2, outerStart: 1 }, { start: 1, end: 2, outerStart: 1 })).toBe(true);
+ expect(sameMargins({ start: 1, end: 2, outerStart: 0 }, { start: 1, end: 2 })).toBe(true);
+ expect(sameMargins({ start: 1, end: 2, outerStart: 1 }, { start: 1, end: 2 })).toBe(false);
+ expect(sameMargins({ start: 1, end: 2, innerEnd: 1 }, { start: 1, end: 2, innerEnd: 1 })).toBe(true);
+ expect(sameMargins({ start: 1, end: 2, innerEnd: 0 }, { start: 1, end: 2 })).toBe(true);
+ expect(sameMargins({ start: 1, end: 2, innerEnd: 1 }, { start: 1, end: 2 })).toBe(false);
+ });
+
it('returns that no margins are only the same as no margins', () => {
expect(sameMargins(undefined, undefined)).toBe(true);
expect(sameMargins({ start: 1, end: 2 }, undefined)).toBe(false);
@@ -102,6 +111,72 @@ describe('MarginsAligner', () => {
expect(plot3.nbOfCalls()).toBe(1);
});
+ it('shares the outer part of the start margins separately from the rest of them', () => {
+ // Our first plot has a wide Y axis, while our second plot has a narrow Y axis and a plot title on the left. So,
+ // both plots must leave room for a plot title on the left and a wide Y axis, so that their Y axis titles line up.
+
+ const group = Symbol('group');
+ const plot1 = testAligner(group, { start: 60, end: 20 });
+ const plot2 = testAligner(group, { start: 50, end: 10, outerStart: 24 });
+
+ for (const plot of [plot1, plot2]) {
+ expect(plot.aligner.sharedMargins()).toEqual({ start: 84, end: 20, outerStart: 24 });
+ }
+
+ // Our second plot no longer has a plot title on the left.
+
+ plot2.aligner.setNaturalMargins({ start: 26, end: 10 });
+
+ for (const plot of [plot1, plot2]) {
+ expect(plot.aligner.sharedMargins()).toEqual({ start: 60, end: 20 });
+ }
+
+ expect(plot1.nbOfCalls()).toBe(3);
+ expect(plot2.nbOfCalls()).toBe(2);
+ });
+
+ it('shares the inner part of the end margins separately from the rest of them', () => {
+ // Our first plot has a wide legend, while our second plot has a narrow legend and a plot title on the right
+ // (between its plotting area and its legend). So, both plots must leave room for a plot title on the right and for
+ // a wide legend, so that their legends line up.
+
+ const group = Symbol('group');
+ const plot1 = testAligner(group, { start: 10, end: 100 });
+ const plot2 = testAligner(group, { start: 10, end: 80, innerEnd: 24 });
+
+ for (const plot of [plot1, plot2]) {
+ expect(plot.aligner.sharedMargins()).toEqual({ start: 10, end: 124, innerEnd: 24 });
+ }
+
+ // Our second plot no longer has a plot title on the right.
+
+ plot2.aligner.setNaturalMargins({ start: 10, end: 56 });
+
+ for (const plot of [plot1, plot2]) {
+ expect(plot.aligner.sharedMargins()).toEqual({ start: 10, end: 100 });
+ }
+
+ expect(plot1.nbOfCalls()).toBe(3);
+ expect(plot2.nbOfCalls()).toBe(2);
+ });
+
+ it('shares the X axis part of the bottom margins separately from the rest of them', () => {
+ // Our first plot has an X axis without a title and a plot title at the bottom (below its X axis), while our second
+ // plot has an X axis with a title. So, both plots must leave room for an X axis with a title and for a plot title
+ // at the bottom, so that their plot titles line up.
+
+ const group = Symbol('group');
+ const plot1 = testAligner(group, { start: 0, end: 44, innerEnd: 20 });
+ const plot2 = testAligner(group, { start: 0, end: 37, innerEnd: 37 });
+
+ for (const plot of [plot1, plot2]) {
+ expect(plot.aligner.sharedMargins()).toEqual({ start: 0, end: 61, innerEnd: 37 });
+ }
+
+ expect(plot1.nbOfCalls()).toBe(2);
+ expect(plot2.nbOfCalls()).toBe(1);
+ });
+
it('only lets its plot know when its shared margins change', () => {
const group = Symbol('group');
const plot1 = testAligner(group, { start: 30, end: 40 });
diff --git a/src/common/alignUtils.ts b/src/common/alignUtils.ts
index 70bb6b1..03bd65c 100644
--- a/src/common/alignUtils.ts
+++ b/src/common/alignUtils.ts
@@ -12,8 +12,9 @@ export type AlignAxis = 'x' | 'y';
/**
* The margins (in pixels) of a plot along an axis, i.e. on either side of its plotting area: its left and right margins
- * along the X axis (i.e. the space taken by its Y axis and its legend), or its top and bottom margins along the Y axis
- * (i.e. the space taken by its X axis).
+ * along the X axis (i.e. the space taken by its plot title, if it is on the left or right, its Y axis, and its legend),
+ * or its top and bottom margins along the Y axis (i.e. the space taken by its plot title, if it is at the top or
+ * bottom, and its X axis).
*/
export interface Margins {
@@ -21,6 +22,19 @@ export interface Margins {
start: number;
/** The margin after the plotting area, i.e. its right margin along the X axis, or its bottom one along the Y axis. */
end: number;
+ /**
+ * The outer part of the margin before the plotting area (0 by default), i.e. the part of it that is furthest from the
+ * plotting area (e.g., the space taken by a plot title on the left). It is shared separately from the rest of the
+ * margin, so that what is in the rest of the margin (e.g., the title of the Y axis) also lines up.
+ */
+ outerStart?: number;
+ /**
+ * The inner part of the margin after the plotting area (0 by default), i.e. the part of it that is closest to the
+ * plotting area (e.g., the space taken by a plot title on the right, or by the X axis). It is shared separately from
+ * the rest of the margin, so that what is in the rest of the margin (e.g., the legend, or a plot title at the bottom)
+ * also lines up.
+ */
+ innerEnd?: number;
}
export const sameMargins = (firstMargins: Margins | undefined, secondMargins: Margins | undefined): boolean => {
@@ -30,7 +44,12 @@ export const sameMargins = (firstMargins: Margins | undefined, secondMargins: Ma
return firstMargins === secondMargins;
}
- return firstMargins.start === secondMargins.start && firstMargins.end === secondMargins.end;
+ return (
+ firstMargins.start === secondMargins.start &&
+ firstMargins.end === secondMargins.end &&
+ (firstMargins.outerStart ?? 0) === (secondMargins.outerStart ?? 0) &&
+ (firstMargins.innerEnd ?? 0) === (secondMargins.innerEnd ?? 0)
+ );
};
// Our groups for each axis, i.e. the aligners (i.e. plots) that are in each of them.
@@ -138,19 +157,38 @@ export class MarginsAligner {
private static updateMembers(members: Set): void {
// Give the biggest natural margins of the given members to all of them, ignoring the members that don't know their
// natural margins yet (e.g., a plot that hasn't been laid out yet), and then tell the members which shared margins
- // have changed about them.
+ // have changed about them. The outer part of our shared start margin is the biggest outer part of the natural start
+ // margins and the rest of it is the biggest rest of them, so that what is in the outer part of the start margin of
+ // one plot (e.g., its plot title) doesn't end up being where something else is in the start margin of another plot
+ // (e.g., its Y axis title). The same goes for the inner part of our shared end margin (e.g., a plot title on the
+ // right, which is between the plotting area and the legend, or the X axis, which is between the plotting area and a
+ // plot title at the bottom).
// Note: we first give all our members their new shared margins and only then tell them about them, in case one of
// them was to straight away join or leave a group, or change its natural margins. Indeed, this would update
// the shared margins of the members of its group, which we would otherwise, for the members that we have yet
// to tell, override with our (now outdated) shared margins.
let margins: Margins | undefined;
+ let innerStart = 0;
+ let outerStart = 0;
+ let innerEnd = 0;
+ let outerEnd = 0;
for (const member of members) {
if (member.natural) {
+ const memberOuterStart = member.natural.outerStart ?? 0;
+ const memberInnerEnd = member.natural.innerEnd ?? 0;
+
+ innerStart = Math.max(innerStart, member.natural.start - memberOuterStart);
+ outerStart = Math.max(outerStart, memberOuterStart);
+ innerEnd = Math.max(innerEnd, memberInnerEnd);
+ outerEnd = Math.max(outerEnd, member.natural.end - memberInnerEnd);
+
margins = {
- start: Math.max(margins?.start ?? 0, member.natural.start),
- end: Math.max(margins?.end ?? 0, member.natural.end)
+ start: innerStart + outerStart,
+ end: innerEnd + outerEnd,
+ ...(outerStart ? { outerStart } : {}),
+ ...(innerEnd ? { innerEnd } : {})
};
}
}
diff --git a/src/widgets/PlotWidget.vue b/src/widgets/PlotWidget.vue
index 323c74a..df77fe3 100644
--- a/src/widgets/PlotWidget.vue
+++ b/src/widgets/PlotWidget.vue
@@ -78,6 +78,7 @@
:style="{
left: `${plotRect.left + 0.5 * plotRect.width}px`,
top: `${plotRect.top + plotRect.height + X_AXIS_SIZE_WITH_TITLE}px`,
+ maxWidth: `${plotRect.width}px`,
fontSize: `${TITLE_FONT_SIZE}px`,
transform: 'translateX(-50%)'
}"
@@ -85,14 +86,19 @@
/>
+
` : '';
};
-const svgHtmlText = (element: HTMLElement | null, origin: DOMRect, vertical: boolean, color: string): string => {
+type TextDirection = 'leftToRight' | 'bottomToTop' | 'topToBottom';
+
+const svgHtmlText = (element: HTMLElement | null, origin: DOMRect, direction: TextDirection, color: string): string => {
// Return the text of the given (rendered) element as SVG text elements (one per text node), positioned relative to
// the given origin, using the given colour (see exportColors()).
// Note: the client rectangle of a text node is the content area of its font, i.e. its alphabetic baseline is the
- // font's ascent below its top. However, if our text is vertical (i.e. our Y axis title, which reads from bottom
- // to top), then its baseline is the font's ascent to the right of its left.
+ // font's ascent below its top. However, if our text reads from bottom to top (e.g., our Y axis title), then its
+ // baseline is the font's ascent to the right of its left, while if it reads from top to bottom (e.g., our plot
+ // title on the right), then its baseline is the font's ascent to the left of its right.
// Make sure that we have a valid element.
@@ -2279,11 +2321,22 @@ const svgHtmlText = (element: HTMLElement | null, origin: DOMRect, vertical: boo
// Add an SVG text element for our text node.
const ascent = fontAscent(`${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`);
- const x = vertical ? rect.left - origin.left + ascent : rect.left - origin.left;
- const y = vertical ? rect.bottom - origin.top : rect.top - origin.top + ascent;
+ const x =
+ direction === 'bottomToTop'
+ ? rect.left - origin.left + ascent
+ : direction === 'topToBottom'
+ ? rect.right - origin.left - ascent
+ : rect.left - origin.left;
+ const y =
+ direction === 'bottomToTop'
+ ? rect.bottom - origin.top
+ : direction === 'topToBottom'
+ ? rect.top - origin.top
+ : rect.top - origin.top + ascent;
+ const rotation = direction === 'bottomToTop' ? -90 : direction === 'topToBottom' ? 90 : 0;
res.push(
- ` {
+const svgTitle = (
+ element: HTMLElement | null,
+ id: string,
+ origin: DOMRect,
+ direction: TextDirection,
+ color: string
+): string => {
+ // Return the given title (i.e. one of our axis titles or our plot title), if any, as an SVG group with the given clip
+ // path id, clipped along its length like on screen (see the axis-title class).
+ // Note: unlike on screen, we don't add an ellipsis to our title if it is truncated, since the ellipsis is not part of
+ // its text (the same goes for the name of our legend items, see svgLegend()).
+
+ // Make sure that we have a title to export.
+
+ if (!element) {
+ return '';
+ }
+
+ // Clip our title along its length, at its padding box like on screen, so that the ink of its first and last glyphs
+ // doesn't get clipped (see the axis-title class).
+
+ const rect = element.getBoundingClientRect();
+ const clipRect =
+ direction === 'leftToRight'
+ ? `x="${svgNumber(rect.left - origin.left)}" y="0" width="${svgNumber(rect.width)}" height="${svgNumber(origin.height)}"`
+ : `x="0" y="${svgNumber(rect.top - origin.top)}" width="${svgNumber(origin.width)}" height="${svgNumber(rect.height)}"`;
+
+ return (
+ ` ` +
+ `${svgHtmlText(element, origin, direction, color)} `
+ );
+};
+
+const svgLegend = (origin: DOMRect, scale: number, colors: ExportColors, idPrefix: string): string => {
// Return our legend, if it is shown, as an SVG group, clipped to what can currently be seen of it (e.g., if it is
- // scrollable).
+ // scrollable), using a clip path whose id starts with the given prefix (see svgDocument()).
// Make sure that we have a legend to export.
@@ -2312,8 +2398,8 @@ const svgLegend = (origin: DOMRect, scale: number, colors: ExportColors): string
const legendRect = legend.getBoundingClientRect();
const res: string[] = [
- ` `,
- ''
+ ` `,
+ ``
];
// Like the browser, we snap the swatch of our legend items to whole (scaled) pixels, so that it is where the browser
@@ -2366,7 +2452,10 @@ const svgLegend = (origin: DOMRect, scale: number, colors: ExportColors): string
// Add the text of our legend item, which is the last child of our legend item element.
- res.push(svgHtmlText(legendItemElement.lastElementChild as HTMLElement | null, origin, false, colors.text), ' ');
+ res.push(
+ svgHtmlText(legendItemElement.lastElementChild as HTMLElement | null, origin, 'leftToRight', colors.text),
+ ' '
+ );
});
res.push('');
@@ -2419,6 +2508,17 @@ const exportColors = (): ExportColors => {
}
};
+const svgIdPrefix = (): string => {
+ // Return a prefix for the ids of the clip paths of an SVG document, unique to that document.
+ // Note: the ids of an SVG document are global to the HTML page in which it is inlined, so if several of our SVG
+ // documents were inlined in the same page and used the same ids, a url(#id) reference in one of them would
+ // resolve to the clip path of the first of them (e.g., a title would get clipped to the length of another
+ // title). So, we prefix our ids with something that is unique to each export rather than to each instance of
+ // our component, since the same plot may be exported several times (e.g., at different sizes).
+
+ return `opencor-plot-${Math.random().toString(36).slice(2, 10)}-`;
+};
+
const svgDocument = (scale: number = 1): SvgDocument => {
// Return our SVG document, which is the size of our container times the given scale.
@@ -2451,9 +2551,10 @@ const svgDocument = (scale: number = 1): SvgDocument => {
const scaledWidth = Math.round(scale * mainDiv.clientWidth);
const scaledHeight = Math.round(scale * mainDiv.clientHeight);
const colors = exportColors();
+ const idPrefix = svgIdPrefix();
const res: string[] = [
``,
- ` `,
+ ` `,
` `
];
@@ -2490,7 +2591,7 @@ const svgDocument = (scale: number = 1): SvgDocument => {
let id = traceClipPaths.get(traceLineWidth);
if (id === undefined) {
- id = `traces${traceClipPaths.size || ''}`;
+ id = `${idPrefix}traces${traceClipPaths.size || ''}`;
traceClipPaths.set(traceLineWidth, id);
@@ -2557,7 +2658,7 @@ const svgDocument = (scale: number = 1): SvgDocument => {
if (markersPaths.length) {
res.push(
- `${markersPaths.join('')} `
+ `${markersPaths.join('')} `
);
}
}
@@ -2578,12 +2679,13 @@ const svgDocument = (scale: number = 1): SvgDocument => {
`${svgTickLabels.join('')} `
);
- // Our axis titles and legend, which we render on top of our plot.
+ // Our axis titles, plot title, and legend, which we render on top of our plot.
res.push(
- svgHtmlText(xAxisTitleRef.value, origin, false, colors.text),
- svgHtmlText(yAxisTitleRef.value, origin, true, colors.text),
- svgLegend(origin, scale, colors),
+ svgTitle(xAxisTitleRef.value, `${idPrefix}xAxisTitle`, origin, 'leftToRight', colors.text),
+ svgTitle(yAxisTitleRef.value, `${idPrefix}yAxisTitle`, origin, 'bottomToTop', colors.text),
+ svgTitle(plotTitleRef.value, `${idPrefix}plotTitle`, origin, plotTitleDirection(), colors.text),
+ svgLegend(origin, scale, colors, idPrefix),
' '
);
@@ -5490,14 +5592,21 @@ const plotDescriptionId = `plot-description-${vue.useId()}`;
const legendDescriptionId = `legend-description-${vue.useId()}`;
const plainText = (html: string | undefined): string => {
- // Return the text of the given HTML (e.g., "IK,r " becomes "IK,r").
- // Note: we parse our HTML in a separate document, so that nothing in it gets loaded or run (e.g., an image).
+ // Return the text of the given HTML, as shown on screen (e.g., "IK,r " becomes "IK,r").
+ // Note #1: we sanitise our HTML first, like when we show it, so that we don't return some text that is never shown
+ // (e.g., that of a script), be it to assistive technologies (see plotLabel), in a tooltip (see
+ // onLegendPointerEnter()), or in a CSV file (see exportToCsv()).
+ // Note #2: we parse our HTML in a separate document, so that nothing in it gets loaded or run (e.g., an image).
- return html ? (new DOMParser().parseFromString(html, 'text/html').body.textContent ?? '').trim() : '';
+ const sanitisedHtml = common.sanitiseHtml(html);
+
+ return sanitisedHtml
+ ? (new DOMParser().parseFromString(sanitisedHtml, 'text/html').body.textContent ?? '').trim()
+ : '';
};
-const plotLabel = vue.computed(() => {
- // Our plot, as described to assistive technologies, i.e. based on the titles of our axes, if any.
+const axesLabel = (): string => {
+ // Return our plot, as described by the titles of our axes, or an empty string if we don't have any.
const xAxisTitle = plainText(props.data.xAxis?.title);
const yAxisTitle = plainText(props.data.yAxis?.title);
@@ -5510,7 +5619,20 @@ const plotLabel = vue.computed(() => {
return `Plot of ${yAxisTitle}`;
}
- return xAxisTitle ? `Plot against ${xAxisTitle}` : 'Plot';
+ return xAxisTitle ? `Plot against ${xAxisTitle}` : '';
+};
+
+const plotLabel = vue.computed(() => {
+ // Our plot, as described to assistive technologies, i.e. based on our plot title and the titles of our axes, if any.
+
+ const title = plainText(props.data.title);
+ const axes = axesLabel();
+
+ if (title) {
+ return axes ? `${title} (${axes})` : title;
+ }
+
+ return axes || 'Plot';
});
const panBy = (axisKey: AxisKey, direction: 1 | -1): void => {
@@ -6026,6 +6148,90 @@ const fontAscent = (font: string): number => {
return measureContext.measureText('0').fontBoundingBoxAscent;
};
+// Our plot title, which takes some space on one side of our plot (see plotTitleSize()), i.e. above our plotting area,
+// below our X axis, to the left of our Y axis, or between our plotting area and our legend.
+
+const PLOT_TITLE_POSITIONS: PlotTitlePosition[] = ['top', 'left', 'right', 'bottom'];
+
+const plotTitlePosition = vue.computed(() => {
+ // Return where our plot title is, if we have one, i.e. at the top of our plot unless we are told otherwise (and
+ // validly so).
+ // Note: a title that has no text once sanitised (e.g., some whitespace or only markup that gets stripped) would show
+ // nothing, so we don't want it to take any space.
+
+ if (!plainText(props.data.title)) {
+ return undefined;
+ }
+
+ const position = props.data.titlePosition;
+
+ return position && PLOT_TITLE_POSITIONS.includes(position) ? position : 'top';
+});
+
+const plotTitleSize = (position: PlotTitlePosition): number => {
+ // Return the size of our plot title, if it is at the given position.
+
+ return plotTitlePosition.value === position ? PLOT_TITLE_SIZE : 0;
+};
+
+const plotTitleDirection = (): TextDirection => {
+ // Return the direction in which our plot title reads, i.e. from bottom to top when it is on the left of our plot
+ // (like our Y axis title) and from top to bottom when it is on the right of our plot.
+
+ return plotTitlePosition.value === 'left'
+ ? 'bottomToTop'
+ : plotTitlePosition.value === 'right'
+ ? 'topToBottom'
+ : 'leftToRight';
+};
+
+const plotTitleStyle = (rect: PlotRect, position: PlotTitlePosition): vue.StyleValue => {
+ // Return the style of our plot title, which is centred on our plotting area. Above our plotting area, below our X
+ // axis, or to the left of our Y axis, it is at the outer edge of the space that it takes, i.e. away from our plotting
+ // area, so that it doesn't get too close to our tick labels. Between our plotting area and our legend, it is in the
+ // middle of the space that it takes.
+ // Note: our plot title can't be longer than our plotting area, so that it doesn't run over our Y axis, our legend, or
+ // a neighbouring plot. If it is too long, then it gets truncated with an ellipsis (see the axis-title class).
+ // The same goes for our axis titles (see our template).
+
+ const fontSize = `${PLOT_TITLE_FONT_SIZE}px`;
+
+ if (position === 'top' || position === 'bottom') {
+ const top =
+ position === 'top'
+ ? rect.top - PLOT_TITLE_SIZE + PLOT_TITLE_GAP
+ : rect.top + rect.height + plotXAxisSpace.value + PLOT_TITLE_SIZE - PLOT_TITLE_GAP - PLOT_TITLE_FONT_SIZE;
+
+ return {
+ left: `${rect.left + 0.5 * rect.width}px`,
+ top: `${top}px`,
+ maxWidth: `${rect.width}px`,
+ fontSize,
+ transform: 'translateX(-50%)'
+ };
+ }
+
+ if (position === 'right') {
+ return {
+ left: `${rect.left + rect.width + 0.5 * (PLOT_TITLE_SIZE - PLOT_TITLE_FONT_SIZE)}px`,
+ top: `${rect.top + 0.5 * rect.height}px`,
+ maxHeight: `${rect.height}px`,
+ fontSize,
+ writingMode: 'vertical-rl',
+ transform: 'translateY(-50%)'
+ };
+ }
+
+ return {
+ left: `${PLOT_TITLE_GAP}px`,
+ top: `${rect.top + 0.5 * rect.height}px`,
+ maxHeight: `${rect.height}px`,
+ fontSize,
+ writingMode: 'vertical-rl',
+ transform: 'translateY(-50%) rotate(180deg)'
+ };
+};
+
// Our Y axis size.
let naturalYAxisSize = 0;
@@ -6052,23 +6258,51 @@ const yAxisSize = (): number => {
const sharedMargins = marginsAligners.x.sharedMargins();
- return sharedMargins ? Math.max(naturalYAxisSize, sharedMargins.start - yAxisTitleSize()) : naturalYAxisSize;
+ return sharedMargins
+ ? Math.max(naturalYAxisSize, sharedMargins.start - yAxisTitleSize() - leftPadding())
+ : naturalYAxisSize;
+};
+
+const leftPadding = (): number => {
+ // Return the space that we need to the left of our Y axis title, i.e. for our plot title, if it is on the left, or
+ // for the plot title of the other plots in our X axis alignment group, if any of them has one on the left, so that
+ // our Y axis titles line up (see MarginsAligner).
+
+ return Math.max(plotTitleSize('left'), marginsAligners.x.sharedMargins()?.outerStart ?? 0);
};
-// Right margin, which we use to make sure that our legend and last X tick label are not cut off.
+// Right margin, which we use to make sure that our plot title (if it is on the right), legend, and last X tick label
+// are not cut off.
+
+const legendSize = (): number => {
+ // Return the room needed by our legend (if any), with a margin on both sides of it (see legendLeft).
-const legendRightMargin = (): number => {
- // Return the right margin needed by our legend (if any), with a margin on both sides of it (see legendLeft).
+ return legendWidth ? Math.ceil(LEGEND_LEFT_MARGIN + legendWidth + LEGEND_RIGHT_MARGIN) : 0;
+};
+
+const naturalRightMargin = (): number => {
+ // Return the right margin needed by our plot title, if it is on the right (and therefore between our plotting area
+ // and our legend), and by our legend (if any).
// Note: this is our natural right margin, i.e. the right margin that we share with the other plots in our X axis
// alignment group, if any (see updateMarginsAsync()).
- return legendWidth ? Math.ceil(LEGEND_LEFT_MARGIN + legendWidth + LEGEND_RIGHT_MARGIN) : 0;
+ return plotTitleSize('right') + legendSize();
+};
+
+const rightTitleSpace = (): number => {
+ // Return the space that we need between our plotting area and our legend, i.e. for our plot title, if it is on the
+ // right, or for the plot title of the other plots in our X axis alignment group, if any of them has one on the right,
+ // so that our legends line up (see MarginsAligner).
+
+ return Math.max(plotTitleSize('right'), marginsAligners.x.sharedMargins()?.innerEnd ?? 0);
};
const rightMargin = (): number => {
// Our right margin must leave room for our legend (or, if we have some shared margins along our X axis, for our
// shared right margin) and for half our last X tick label (since it is centred on its tick), with a margin on its
- // right side.
+ // right side. Our plot title, if it is on the right (or the space that we leave for that of the other plots in our X
+ // axis alignment group, see rightTitleSpace()), is between our plotting area and our legend, so it is part of the
+ // room that our legend needs, but it doesn't affect our last X tick label, which is below it.
// Note #1: our legend is to the right of our plotting area and no taller than it while our last X tick label is below
// our plotting area, so they can't overlap and our right margin only needs to fit the wider of the two. In
// practice, our last X tick label only matters when we don't have a legend (e.g., in the standard view or if
@@ -6080,36 +6314,57 @@ const rightMargin = (): number => {
const lastXValue = tickValues.x[tickValues.x.length - 1];
const sharedMargins = marginsAligners.x.sharedMargins();
- const legendSize = sharedMargins ? Math.max(legendRightMargin(), sharedMargins.end) : legendRightMargin();
+ const titleAndLegendSize = rightTitleSpace() + legendSize();
+ const legendMargin = sharedMargins ? Math.max(titleAndLegendSize, sharedMargins.end) : titleAndLegendSize;
const lastXTickLabelSize = lastXValue ? 0.5 * textWidth(lastXValue, tickFont()) + LEGEND_RIGHT_MARGIN : 0;
- return Math.ceil(Math.max(legendSize, lastXTickLabelSize));
+ return Math.ceil(Math.max(legendMargin, lastXTickLabelSize));
};
-// Top and bottom margins, i.e. the space above our plotting area (none) and below it (taken by our X axis), which we
-// share with the other plots in our Y axis alignment group, if any (see marginsAligners), so that our plotting areas
-// line up when side by side.
+// Top and bottom margins, i.e. the space above our plotting area (taken by our plot title, if it is at the top) and
+// below it (taken by our X axis and by our plot title, if it is at the bottom), which we share with the other plots in
+// our Y axis alignment group, if any (see marginsAligners), so that our plotting areas line up when side by side.
-const naturalBottomMargin = (): number => {
+const xAxisSize = (): number => {
// Return the size of our X axis, including its title, if any (see the X axis in createPlot()).
return props.data.xAxis?.title ? X_AXIS_SIZE_WITH_TITLE + X_AXIS_TITLE_SIZE : X_AXIS_SIZE_WITHOUT_TITLE;
};
+const xAxisSpace = (): number => {
+ // Return the space that we need between our plotting area and our plot title, if it is at the bottom, i.e. for our X
+ // axis, or for the X axis of the other plots in our Y axis alignment group, if any of them has a taller one, so that
+ // our plot titles line up (see MarginsAligner).
+
+ return Math.max(xAxisSize(), marginsAligners.y.sharedMargins()?.innerEnd ?? 0);
+};
+
+const naturalTopMargin = (): number => {
+ // Return the size of our plot title, if it is at the top.
+
+ return plotTitleSize('top');
+};
+
+const naturalBottomMargin = (): number => {
+ // Return the size of our X axis and of our plot title, if it is at the bottom.
+
+ return xAxisSize() + plotTitleSize('bottom');
+};
+
const topPadding = (): number => {
- // Return the space that we need above our plotting area for it to line up with that of the other plots in our Y axis
- // alignment group, if any.
+ // Return the space that we need above our plotting area, i.e. for our plot title, if it is at the top, and for our
+ // plotting area to line up with that of the other plots in our Y axis alignment group, if any.
- return marginsAligners.y.sharedMargins()?.start ?? 0;
+ return Math.max(naturalTopMargin(), marginsAligners.y.sharedMargins()?.start ?? 0);
};
const bottomPadding = (): number => {
- // Return the space that we need below our X axis for our plotting area to line up with that of the other plots in our
- // Y axis alignment group, if any.
+ // Return the space that we need below our X axis, i.e. for our plot title, if it is at the bottom, and for our
+ // plotting area to line up with that of the other plots in our Y axis alignment group, if any.
+ // Note: our plot title is below the space that we leave for our X axis (see xAxisSpace()), which may be taller than
+ // our X axis, so that our plot title lines up with that of the other plots in our group.
- const sharedMargins = marginsAligners.y.sharedMargins();
-
- return sharedMargins ? Math.max(0, sharedMargins.end - naturalBottomMargin()) : 0;
+ return Math.max(xAxisSpace() + plotTitleSize('bottom'), marginsAligners.y.sharedMargins()?.end ?? 0) - xAxisSize();
};
// Update our margins asynchronously, i.e. after our plot has been laid out and we know how much space it needs for its
@@ -6122,9 +6377,10 @@ const bottomPadding = (): number => {
// each other's margins. Our natural left margin depends on our Y tick labels, i.e. on the height of our
// plotting area, which doesn't depend on our shared margins. However, our last X tick label depends on our X
// ticks, i.e. on the width of our plotting area, which does depend on our shared margins. So, our natural
-// right margin only accounts for our legend (see legendRightMargin()) and each plot makes room for its own
-// last X tick label (see rightMargin()). The (unlikely) cost is that a plot which last X tick label needs more
-// room than our shared right margin has a narrower plotting area than the other plots in our group.
+// right margin only accounts for our legend and plot title (see naturalRightMargin()) and each plot makes room
+// for its own last X tick label (see rightMargin()). The (unlikely) cost is that a plot which last X tick
+// label needs more room than our shared right margin has a narrower plotting area than the other plots in our
+// group.
const updateMarginsAsync = (): void => {
// Coalesce multiple margin update requests into a single microtask.
@@ -6148,15 +6404,18 @@ const updateMarginsAsync = (): void => {
}
// Give our natural margins to our margins aligners, which only do something if they have changed.
- // Note: our natural right margin only accounts for our legend (see legendRightMargin()).
+ // Note: our natural right margin only accounts for our legend and plot title (see naturalRightMargin()).
marginsAligners.x.setNaturalMargins({
- start: naturalYAxisSize + yAxisTitleSize(),
- end: legendRightMargin()
+ start: naturalYAxisSize + yAxisTitleSize() + plotTitleSize('left'),
+ end: naturalRightMargin(),
+ outerStart: plotTitleSize('left'),
+ innerEnd: plotTitleSize('right')
});
marginsAligners.y.setNaturalMargins({
- start: 0,
- end: naturalBottomMargin()
+ start: naturalTopMargin(),
+ end: naturalBottomMargin(),
+ innerEnd: xAxisSize()
});
});
};
@@ -8025,7 +8284,7 @@ const createPlot = (width: number, height: number): void => {
mode: 2,
width,
height,
- padding: [topPadding, rightMargin, bottomPadding, 0],
+ padding: [topPadding, rightMargin, bottomPadding, leftPadding],
legend: {
show: false
},
@@ -8222,7 +8481,7 @@ const updatePlot = (): void => {
// Create or update our plot.
// Note: we only (re)create our plot if needed since it is much cheaper to update its data.
- const signature = `${props.data.traces.length}::${titles}::${isDarkMode.value}::${logAxes.value.x}::${logAxes.value.y}`;
+ const signature = `${props.data.traces.length}::${titles}::${plotTitlePosition.value ?? ''}::${isDarkMode.value}::${logAxes.value.x}::${logAxes.value.y}`;
const newLegendWidth = measureLegendWidth();
const legendWidthChanged = newLegendWidth !== legendWidth;
@@ -8402,6 +8661,18 @@ vue.watch(
{ immediate: true }
);
+// Update our plot when our plot title gets shown, hidden, or moved, so that it gets (or stops getting) some space.
+// Note: our data may be mutated rather than replaced (e.g., data.title = 'Foo'), in which case our template would show
+// our plot title right away, but the above watcher wouldn't get triggered, so our plot title would overlap our
+// plotting area or tick labels. Changing the text of our plot title, though, doesn't change the space that it
+// takes (see plotTitleSize()), so there is nothing to do then.
+
+vue.watch(plotTitlePosition, () => {
+ void vue.nextTick().then(() => {
+ updatePlot();
+ });
+});
+
// Make an axis logarithmic (or not) and show (or hide) its grid lines when our data says something else about them than
// it last did (see logAxes and gridAxes), as if the user had done it using our context menu (so that, for a logarithmic
// axis, the plots of the synchronisation group of that axis, if any, do the same).
@@ -8641,9 +8912,30 @@ vue.watch(
white-space: nowrap;
}
+ /**
+ * Note #1: our axis titles and plot title can't be longer than our plotting area (see our template and
+ * plotTitleStyle()), so if one of them is too long, then it gets truncated with an ellipsis.
+ * Note #2: we hide (rather than clip) the overflow of a title on both axes, since some browsers (e.g., Safari) don't
+ * add an ellipsis to a vertical title (e.g., our Y axis title) if its overflow is only clipped along its
+ * length. (We can't hide it along its length and leave it visible across, since it would then be scrollable
+ * across, and we can't clip it along its length and hide it across, since it would then be hidden on both
+ * axes anyway.)
+ * Note #3: a title is hidden at its padding box, so we give it some padding along its length, so that the ink of its
+ * first and last glyphs can stick out of its content box (e.g., the overhang of italic text), and across, so
+ * that the ink of its glyphs can stick out of its line (e.g., the descenders and accents of its glyphs,
+ * since its line height is 1). We cancel the latter padding with a negative margin, so that our titles are
+ * positioned as if they had no padding across. (The export of a title is clipped along its length like on
+ * screen, but not across, see svgTitle().)
+ */
+
.axis-title {
position: absolute;
+ margin-block: -0.5em;
+ padding-block: 0.5em;
+ padding-inline: 3px;
+ overflow: hidden;
line-height: 1;
+ text-overflow: ellipsis;
white-space: nowrap;
pointer-events: none;
user-select: none;