diff --git a/docs/design/canvas-net-vega-lite.md b/docs/design/canvas-net-vega-lite.md index 1e95a23fc..eb67152bf 100644 --- a/docs/design/canvas-net-vega-lite.md +++ b/docs/design/canvas-net-vega-lite.md @@ -517,7 +517,9 @@ input: and the parameter names from the tree; `FeatureCatalog.Visit` lists the recognized-but-unsupported constructs (the functions, view state, and operators that the compiled expressions collected among them). The parse warnings and the catalog reports are merged once, sorted by line and column (stable), and kept as the - document's reports. + document's reports. A render with a caller's `Config` visits the catalog again with the effective configuration + (`VegaLiteDocument.ReportsFor`), so that the reports that depend on the configuration (the overlays of a path mark, + which say whether the points or the line of an area draw a channel) are those of what is drawn. 5. **Output**: an immutable `VegaLiteDocument`, safe to share between threads. **Measure and render path (`Measure`, `Render(options)`):** @@ -1214,8 +1216,12 @@ The following decisions differ from, or are stricter than, the Vega-Lite referen 51. **Overlays (P9-D6)**: the `point` overlay of a line, area, trail, or rule and the `line` overlay of an area follow the overlay mark definitions of Vega-Lite (`true`, an object, `"transparent"` for invisible points, and the configuration of the mark; an area with an overlay and without an opacity gets the opacity 0.7), with these - differences: an `encoding.shape` does **not** switch the point overlay on (the channel stays reported as not drawn - by the mark), a `size` channel is applied to the overlay points through the scale of the base mark (for a line that + differences: an `encoding.shape` **switches the point overlay on** when the mark has no `point` and the configuration + does not decide (Vega-Lite's `getPointOverlay`; the shape is then drawn by the overlay points and is not reported), + the overlay marks draw the channels of their mark that the path does not (the points a `shape`, `angle`, `strokeDash`, + and `size`, the line overlay of an area its `strokeDash` and its `size` as the width; the legend of a line with + points shows filled symbols), a `size` channel is applied to the overlay points through the scale of the base mark + (for a line that is its range of stroke widths read as the area of a symbol), the overlay line of an area groups as a line, and an `{"expr": ...}` inside an overlay object is not evaluated (`vl-expr-ref`). 52. **Impute (P9-D7, P9-D8)**: the `impute` of `x` or `y` runs the impute engine after the aggregate and before the diff --git a/docs/design/canvas-net-vega-lite/guides/legend-builder.md b/docs/design/canvas-net-vega-lite/guides/legend-builder.md index f61a0a1c2..13347fd8d 100644 --- a/docs/design/canvas-net-vega-lite/guides/legend-builder.md +++ b/docs/design/canvas-net-vega-lite/guides/legend-builder.md @@ -37,7 +37,11 @@ unit's behavior is specified by the `CanvasNetVegaLite-Guides-LegendBuilder-*` r - `LegendMarkFacts` - what the symbols stand for: whether the mark is filled (a **trail is never filled for its legend**, see the paragraph on the path, area, arc, and text marks below), its fixed fill and stroke (the same rules the marks use), the opacity (0.7 for point-like marks, or the constant opacity channel), the fixed shape, the stroke - width, dash, fill and stroke opacity, and whether a field drives the fill or the stroke. + width, dash, fill and stroke opacity, and whether a field drives the fill or the stroke. For a path mark with a **point + overlay** (`SpecNormalizer.PointOverlayDefinition`) the facts are those of the overlay mark, a filled `point` with an + opacity of 1 (whatever the overlay object replaces): Vega-Lite normalizes the mark into the path and a filled point + layer, and the merge of the legends prefers the circle of the points to the stroke of the path (`mergeSymbolType`), so + the legend of a line with points shows filled symbols (the color is their fill), not the hollow symbols of the line. - `LegendSettings` - property lookup: the `legend` objects of the members (the first member that has a property wins, which is Vega-Lite's explicit-over-implicit and first-channel rule), then `config.legend` with the Vega-Lite and Vega defaults, then the `guide-label` and `guide-title` styles. diff --git a/docs/design/canvas-net-vega-lite/marks/mark-builder.md b/docs/design/canvas-net-vega-lite/marks/mark-builder.md index b31c741ea..754182fd8 100644 --- a/docs/design/canvas-net-vega-lite/marks/mark-builder.md +++ b/docs/design/canvas-net-vega-lite/marks/mark-builder.md @@ -231,7 +231,15 @@ opacity of 0); the line overlay is a `line` mark with the `clip`, `interpolate`, run has no `x2` and `y2` (the line is drawn at the edge of the area), reads the stacked end of a stacked channel, skips a channel that has a field but no scale (a channel that the overlaid mark does not draw), and groups its rows as a line does. An `area` that has an overlay and names no `opacity`, `fillOpacity`, or configured opacity has the opacity 0.7. -Every overlay item is charged like the items of any run (a line overlay as a path, each point as an item). +The overlay definitions are built by `SpecNormalizer.PointOverlayDefinition` and `LineOverlayDefinition`, which the scale +resolver and the legend planner share. The point overlay is also enabled by an **encoding with a `shape` channel** when +the mark has no `point` property and `config..point` is not truthy (Vega-Lite's `getPointOverlay`; `point: false` +or null keeps it off). The base run never reads the `shape` (nor an `angle`, or a `strokeDash` of an area or trail: +`ScaleResolver.ChannelIsDrawn` of the mark type is false, as Vega-Lite drops the shape from the path layer), so the shape +does not group the paths. The overlay runs read every channel that has a scale, so the scales that the resolver builds +for the overlays give the points their shapes, rotations, dashes, and sizes (a `shape`, an `angle`, a `strokeDash`, the +`size` of an area), and the line overlay of an area its dash and its width (the `size`, with the range of the stroke +widths). Every overlay item is charged like the items of any run (a line overlay as a path, each point as an item). **Draw order** (`MarkBuilder.Order.cs`). The `order` channel decides the drawing order of `bar`, `rect`, `tick`, `rule`, `point`, `circle`, `square`, `text`, and `arc` (Vega-Lite sorts the marks by it) when the encoding is **not stacked**: @@ -337,9 +345,11 @@ reports the exhausted evaluation steps, and the text limits name `VegaLiteLimits **Documented deviations from Vega-Lite and the plan** (each pinned by a test or reported by the feature catalog): -1. **No `shape` overlay trigger**: Vega-Lite enables the point overlay for an encoding with a `shape` channel; here the - `shape` channel of a line is not drawn and the overlay is not enabled by it. A `size` channel of the overlaid mark is - applied through the scale of that mark to the overlay points as well. +1. **Overlay differences** (the point overlay otherwise follows Vega-Lite's `getPointOverlay`, including the **`shape` + trigger**: an `encoding.shape` enables the overlay when `point` is missing and the configuration does not decide, see + `SpecNormalizer.HasPointOverlay`): the overlay is a second run of this builder and not a layer, so the `size` channel + of a line is applied through the scale of the line (its range of stroke widths read as the area of a symbol) to the + overlay points as well, and an `{"expr": ...}` inside an overlay object is not evaluated. 2. **Invalid-mode domains**: the scale domains are never filtered by the `invalid` mode (reported by the warning `vl-mark-invalid-domains`); `show` is not supported (`vl-mark-invalid-show`). 3. **An area without a measure channel** draws nothing. diff --git a/docs/design/canvas-net-vega-lite/scales/scale-resolver.md b/docs/design/canvas-net-vega-lite/scales/scale-resolver.md index a733e1794..2e602b7f2 100644 --- a/docs/design/canvas-net-vega-lite/scales/scale-resolver.md +++ b/docs/design/canvas-net-vega-lite/scales/scale-resolver.md @@ -177,7 +177,12 @@ transform) for a A channel that a mark does not draw has no scale: `ResolveChannel` returns none for it, and the feature catalog - reports it (see _FeatureCatalog_). + reports it (see _FeatureCatalog_). The exception is a `line`, `area`, `trail`, or `rule` with an **overlay** + (`SpecNormalizer.HasPointOverlay` and `HasLineOverlay`, held in `Context.PointOverlay` and `Context.LineOverlay`): its + overlay marks draw the channels that they draw (`SpecNormalizer.OverlayDrawsChannel`), so `ResolveChannel` builds the + scale of a `shape`, an `angle`, a `strokeDash`, or a `size` for the points (`ChannelIsDrawn(channel, "point")`), and the + `strokeDash` and `size` of an `area` for its line overlay (`ChannelIsDrawn(channel, "line")`). The size range of an + `area` is that of the stroke widths when it has a line overlay (the line layer comes first), else that of a point. - **Domain.** The fields a channel reads come from the `EncodingPlan`. A linear domain is the extent of the valid values (numbers, booleans as 1 and 0, numeric strings; null and NaN are ignored; an empty extent is 0 to 1) of the **Main** table, over the channel's field and its second field: for diff --git a/docs/design/canvas-net-vega-lite/spec-model.md b/docs/design/canvas-net-vega-lite/spec-model.md index 863c16957..aa9d389c7 100644 --- a/docs/design/canvas-net-vega-lite/spec-model.md +++ b/docs/design/canvas-net-vega-lite/spec-model.md @@ -23,8 +23,9 @@ the other subsystems, and, through `InternalsVisibleTo`, the test assembly. It c _FeatureCatalog Unit Design_ (`spec-model/feature-catalog.md`) - **ConfigResolver** - the internal static `ConfigResolver`, `ResolvedConfig`, `ConfigNode`, and `ConfigNodeKind`; see _ConfigResolver Unit Design_ (`spec-model/config-resolver.md`) -- **SpecNormalizer** - the internal static partial `SpecNormalizer` (`SpecNormalizer.cs`, `SpecNormalizer.Composition.cs`, - `SpecNormalizer.Repeat.cs`, `SpecNormalizer.Composite.cs`, `SpecNormalizer.BoxPlot.cs`, and `SpecNormalizer.ErrorBar.cs`), +- **SpecNormalizer** - the internal static partial `SpecNormalizer` (`SpecNormalizer.cs`, + `SpecNormalizer.Composition.cs`, `SpecNormalizer.Repeat.cs`, `SpecNormalizer.Composite.cs`, + `SpecNormalizer.BoxPlot.cs`, `SpecNormalizer.ErrorBar.cs`, and `SpecNormalizer.PathOverlay.cs`), the tree types `LayerTree`, `LayerNode`, `LayerResolve`, `ResolveMode`, `ViewKind`, `CompositionSettings`, `CompositionAlign`, `FacetDefinition`, and `RepeaterValues`, `ExpandedLayers`, and the `CompositeBuilder` and `CompositeAxis` helpers: it turns the views of a specification into the tree of views (layers, concatenations, facets, diff --git a/docs/design/canvas-net-vega-lite/spec-model/feature-catalog.md b/docs/design/canvas-net-vega-lite/spec-model/feature-catalog.md index 2fe4f78db..24ba85061 100644 --- a/docs/design/canvas-net-vega-lite/spec-model/feature-catalog.md +++ b/docs/design/canvas-net-vega-lite/spec-model/feature-catalog.md @@ -135,7 +135,18 @@ sentinel unsupported channel), where `arc` and `theta` were before. The identifi `angle` by `point`, `circle`, `square`, and `text`, `strokeDash` by every mark but `rect`, `area`, `trail`, `text`, and `arc`, and `size` by every mark but `rect`, `area`, `arc`, and `image` (so `size` on an `area` or an `arc` is newly reported; the `rect` size stays unreported as before). `vl-channel-x2` and `vl-channel-y2` are narrowed too: a bar, - rect, rule, and (new) area that has the channel they extend accepts them. + rect, rule, and (new) area that has the channel they extend accepts them. A `shape` of a `line`, `area`, `trail`, or + `rule` that has a point overlay (`SpecNormalizer.HasPointOverlay`: an `encoding.shape` switches the overlay on unless + `point` is `false` or null) is **not** reported, because the overlay points draw it and Vega-Lite drops it from the path + layer before it checks the channels; an `angle`, a `strokeDash` or a `size` that the path mark does not draw but its + overlay points do is still reported (the path layer warns about it in Vega-Lite) with the message that only the point + overlay draws it. The catalog reads `config..point` and `config.area.line` from the effective configuration: + `FeatureCatalog.Visit(tree, config)` takes it (the renderer passes the configuration with the caller's, see + `VegaLiteDocument.ReportsFor`), and `Visit(tree)` reads the configuration of the specification alone. The channels of + the overlays are `SpecNormalizer.OverlayDrawsChannel` (a point draws shape, angle, size and dash; the line overlay of + an area draws size and dash); the message names the overlay that draws it ("only its point overlay", "its line overlay", + "its point and line overlays"). A `shape` is reported only when there is no point overlay, whatever the configuration + (the shape itself switches the overlay on). - `vl-encoding-impute` is narrowed to a channel other than `x` and `y`: the impute of a position channel is run by the pipeline, and the impute of any other channel is ignored and reported. - `vl-encoding-bandposition` no longer reports the `bandPosition` of the **stacked** `theta` or `radius` of a text mark diff --git a/docs/design/canvas-net-vega-lite/spec-model/spec-normalizer.md b/docs/design/canvas-net-vega-lite/spec-model/spec-normalizer.md index 94c3782d9..1c31dea63 100644 --- a/docs/design/canvas-net-vega-lite/spec-model/spec-normalizer.md +++ b/docs/design/canvas-net-vega-lite/spec-model/spec-normalizer.md @@ -2,13 +2,15 @@ ![SpecModel Structure](VegaLiteSpecModelView.svg) -The `SpecNormalizer` unit is the fourth software unit in the `SpecModel` subsystem. It is six partial files of the +The `SpecNormalizer` unit is the fourth software unit in the `SpecModel` subsystem. It is seven partial files of the internal static class `SpecNormalizer` in the `DemaConsulting.CanvasNet.VegaLite.SpecModel` namespace: `SpecNormalizer.cs` (the view tree and its walk), `SpecNormalizer.Composition.cs` (concatenations, facets, the faceted unit view, and the layout settings), `SpecNormalizer.Repeat.cs` (the expansion of `repeat` and the replacement of the repeat references), `SpecNormalizer.Composite.cs` (`Expand`, `ExpandedLayers`, `CompositeAxis`, and the `CompositeBuilder` helper), `SpecNormalizer.BoxPlot.cs`, and `SpecNormalizer.ErrorBar.cs` (the expansion of the composite -marks, with the `ErrorInput` enumeration). The tree types `LayerTree`, `LayerNode`, `LayerResolve`, `ResolveMode`, and +marks, with the `ErrorInput` enumeration), and `SpecNormalizer.PathOverlay.cs` (the decision of Vega-Lite's path overlay +normalizer that the other stages share, see _Path overlay decision_). The tree types `LayerTree`, `LayerNode`, +`LayerResolve`, `ResolveMode`, and `ViewKind` are declared in `SpecNormalizer.cs`; `CompositionSettings`, `CompositionAlign`, and `FacetDefinition` in `SpecNormalizer.Composition.cs`; `RepeaterValues` and `RepeatLayers` in `SpecNormalizer.Repeat.cs`. Its supporting node factories, `SpecNode.Overlay` and `SpecNode.Synthetic`, are in `SpecNode.cs`, and `SpecExpressions.With` in @@ -169,6 +171,25 @@ object of the mark definition), `Orient` and `TryOrient`, `ContinuousAxis`, `Pos node and are applied by the data stage. - `TryOrientation(type, definition, encoding, out orient, out problem)` - decides the orientation of a composite mark without throwing, for the catalog and the expansion. +- **Path overlay decision** (`SpecNormalizer.PathOverlay.cs`; Vega-Lite's `getPointOverlay` and `getLineOverlay` in its + path overlay normalizer). `HasPointOverlay` and `PointOverlayDefinition(markType, mark, encoding, configPoint)` + decide and build the point overlay of a `line`, `area`, `trail`, or `rule`: its `point` is `true`, an object, or + `"transparent"`; or its `point` is **missing** and `config..point` is truthy **or the encoding has a `shape` + channel** (`HasShapeChannel`); `false` and null switch it off. `HasLineOverlay` and + `LineOverlayDefinition(markType, mark, configLine)` do the same for the line overlay of an `area` (`line` true or an + object, else `config.area.line`; the `clip`, `interpolate`, and `tension` of the area are inherited), and + `OverlayDrawsChannel(channel, pointOverlay, lineOverlay)` tells whether an overlay draws a channel (`ChannelIsDrawn` + for `point` and for `line`). The mark builder (which builds the overlay runs from the definitions), the scale resolver + (`Context.PointOverlay` and `Context.LineOverlay`), the legend planner (the symbols of a path mark with a point + overlay are those of the filled overlay `point`), and the feature catalog all ask it, so that the points, the lines, + the scales and legends of the channels they draw, and the reports agree. Vega-Lite normalizes such a mark into + layers: the path (`omit(encoding, ['shape'])`: the shape is dropped **before** the channels are checked against the + mark, so it raises no `incompatibleChannel` warning there and does not group the path), the line overlay of an area, + and the overlay `point` (each with the whole encoding without `x2` and `y2`, so the points draw the shape, angle, + stroke dash, and size, and the line overlay the stroke dash and the size as the width). Every other channel goes to + all the layers, so the path layer still warns about an `angle`, a `strokeDash` on an area or trail, and a `size` on + an area (`initEncoding` in `encoding.ts`); the feature catalog reports them with a message that says which overlay + draws them. `IsTruthyConfig` is the JavaScript truthiness of a configuration value. **Boxplot expansion** (Vega-Lite's `normalizeBoxPlot`, without tooltips). The orientation is the continuous (quantitative or temporal, as written or as `ChannelDefinitions.TypeOf` infers it) channel; a plot with both diff --git a/docs/design/introduction.md b/docs/design/introduction.md index e1eae6dc4..8298a2d55 100644 --- a/docs/design/introduction.md +++ b/docs/design/introduction.md @@ -1225,7 +1225,8 @@ src/DemaConsulting.CanvasNet.VegaLite/ │ ├── SpecNormalizer.Repeat.cs — SpecNormalizer: repeat expansion and repeat references │ ├── SpecNormalizer.Composite.cs — SpecNormalizer: Expand and the composite-mark expansion into layers │ ├── SpecNormalizer.BoxPlot.cs — SpecNormalizer: the boxplot expansion -│ └── SpecNormalizer.ErrorBar.cs — SpecNormalizer: the errorbar and errorband expansion +│ ├── SpecNormalizer.ErrorBar.cs — SpecNormalizer: the errorbar and errorband expansion +│ └── SpecNormalizer.PathOverlay.cs — SpecNormalizer: the point overlay decision of the path marks ├── Data/ — Data subsystem (internal) │ ├── NamespaceDoc.cs — Data: namespace-level XML documentation │ ├── DataTable.cs — DataTable: DataValue, JsNumber, FieldPath, and DataTable diff --git a/docs/reqstream/canvas-net-vega-lite.yaml b/docs/reqstream/canvas-net-vega-lite.yaml index 4aa9bd613..a353c31ea 100644 --- a/docs/reqstream/canvas-net-vega-lite.yaml +++ b/docs/reqstream/canvas-net-vega-lite.yaml @@ -1343,14 +1343,21 @@ sections: title: >- The library shall draw the point overlay of a line, area, trail, or rule (a symbol at every row) and the line overlay of an area (a line along its top edge), from the mark definition or the - configuration, with the base encoding and the documented default opacity. + configuration, with the base encoding and the documented default opacity; and shall give the overlay + points the shape channel of the mark (which switches the overlay on unless the point property is + false or null) without a report, and the legend of that shape with filled symbols; shall give the line + overlay of an area the dash and the width of its encoding; and shall report what it draws, also when + the caller's configuration decides the overlays. tags: [system] justification: | - A line with points and an area with a line are common forms of the path marks. + A line with points and an area with a line are common forms of the path marks, and Vega-Lite draws + the points of a line by group with the shape channel. children: - CanvasNetVegaLite-Marks-MarkBuilder-Overlays tests: - CanvasNetVegaLite_SystemIntegration_Overlays_LinePointsAndAreaLineAreDrawn + - CanvasNetVegaLite_SystemIntegration_Overlays_ShapeChannelShapesTheOverlayPointsInStrictMode + - CanvasNetVegaLite_SystemIntegration_Overlays_CallerConfigurationAndLineOverlayAgreeWithTheReports - id: CanvasNetVegaLite-InvalidData title: >- diff --git a/docs/reqstream/canvas-net-vega-lite/guides/legend-builder.yaml b/docs/reqstream/canvas-net-vega-lite/guides/legend-builder.yaml index f76fccdc2..8c8867d21 100644 --- a/docs/reqstream/canvas-net-vega-lite/guides/legend-builder.yaml +++ b/docs/reqstream/canvas-net-vega-lite/guides/legend-builder.yaml @@ -264,11 +264,15 @@ sections: explicitly not merged but given a legend each, the channels of different layers whose domains agree merging into one legend, the symbols of a member drawn as the mark of the layer that the member comes from, and a disabled legend of - the layer honored; and shall give a view with one layer the same plan as the plan of that view. + the layer honored; shall give a view with one layer the same plan as the plan of that view; and + shall plan the shape of a path mark that has a point overlay as the points draw it, in one legend + with the color of the same field (with filled symbols, those of the overlay points) and in a + legend of its own for another field. justification: | A color that two layers share must give one legend, not two, and a legend that a layer keeps apart must stay apart; a single view must not change. tests: + - LegendPlan_Create_ShapeOfALineWithAPointOverlayHasALegendMergedWithTheColorOfTheSameField - LegendPlan_Create_SameFieldInTwoLayersIsOneLegend - LegendPlan_Create_TitlesOfDifferentFieldsJoin - LegendPlan_Create_WrittenTitleOfAnyLayerWinsOverDerivedTitles diff --git a/docs/reqstream/canvas-net-vega-lite/marks/mark-builder.yaml b/docs/reqstream/canvas-net-vega-lite/marks/mark-builder.yaml index 220171181..07cb2dab8 100644 --- a/docs/reqstream/canvas-net-vega-lite/marks/mark-builder.yaml +++ b/docs/reqstream/canvas-net-vega-lite/marks/mark-builder.yaml @@ -400,14 +400,27 @@ sections: a line along the top edge of an area whose line property is true or an object - with the base encoding without the secondary channels, the stacked end of a stacked channel, the default opacity of 0.7 for an area that has an overlay and no opacity of its own, and the overlays that - config..point and config..line enable. + config..point and config..line enable; shall switch the point overlay on for an + encoding that has a shape channel when the mark definition has no point property and the + configuration does not enable it (point false or null keeps it off); and shall draw the + channels of a point mark that the path does not draw (the shape, the angle, and the stroke dash, + and the size of an area) on the overlay points, the shape of a path mark being left out of the + path (it does not group the paths); and shall draw the line overlay of an area with the channels + of a line (its stroke dash as the dash of the line and its size as the width, with the range of the + stroke widths). justification: | A line with points and an area with a line are the common forms of the path marks; Vega-Lite - draws them as layers of the base mark and the overlay must match. + draws them as layers of the base mark and the overlay must match, and its overlay points are + the ones that take the shape of a path mark's shape channel. tests: - MarkBuilder_Build_PointOverlayDrawsSymbolsWithTheOverlayDefinition - MarkBuilder_Build_AreaLineOverlayAndDefaultOpacity - MarkBuilder_Build_OverlayFromConfigAndTransparentPoints + - MarkBuilder_Build_ShapeChannelOfALineShapesTheOverlayPoints + - MarkBuilder_Build_ShapeChannelEnablesThePointOverlayUnlessSwitchedOff + - MarkBuilder_Build_ShapeChannelOfAnAreaShapesTheOverlayPoints + - MarkBuilder_Build_PointChannelsOfThePathMarkReachTheOverlayPoints + - MarkBuilder_Build_LineOverlayOfAnAreaDrawsTheSizeAndTheDashOfTheEncoding - id: CanvasNetVegaLite-Marks-MarkBuilder-DrawOrder title: >- diff --git a/docs/reqstream/canvas-net-vega-lite/scales/scale-resolver.yaml b/docs/reqstream/canvas-net-vega-lite/scales/scale-resolver.yaml index 0e89ac282..9a68232dd 100644 --- a/docs/reqstream/canvas-net-vega-lite/scales/scale-resolver.yaml +++ b/docs/reqstream/canvas-net-vega-lite/scales/scale-resolver.yaml @@ -80,14 +80,20 @@ sections: The ScaleResolver unit shall give a channel a scale only for the marks that draw it (theta and radius for arc and text, theta2 and radius2 for arc, size for every mark but rect, area, arc, and image, stroke dash for every mark but rect, area, trail, text, and arc, angle for point, - circle, square, and text, shape for point, and text for text), so that the feature catalog and - the builders agree on which channels a mark ignores. + circle, square, and text, shape for point, and text for text) and, for a line, area, trail, or + rule that has a point overlay, also for the channels that the overlay points draw (shape, angle, + stroke dash, and size, the size of an area with the range of a point) and, for an area that has + a line overlay, for the channels of its line (stroke dash and size, with the range of the stroke + widths), so that the feature + catalog and the builders agree on which channels a mark ignores. justification: | A channel that a mark does not draw must be ignored and reported, not resolved into a scale and a - legend that explain nothing. + legend that explain nothing; the points of a path overlay do draw it, and need its scale and + legend. tests: - ScaleResolver_ChannelIsDrawn_FollowsTheSupportTable - ScaleResolver_Resolve_ChannelsThatTheMarkDoesNotDrawHaveNoScale + - ScaleResolver_Resolve_PointOverlayBuildsTheScalesOfThePointChannels - id: CanvasNetVegaLite-Scales-ScaleResolver-Domains title: >- diff --git a/docs/reqstream/canvas-net-vega-lite/spec-model.yaml b/docs/reqstream/canvas-net-vega-lite/spec-model.yaml index 3a940c022..d8e9fb06f 100644 --- a/docs/reqstream/canvas-net-vega-lite/spec-model.yaml +++ b/docs/reqstream/canvas-net-vega-lite/spec-model.yaml @@ -206,6 +206,7 @@ sections: - CanvasNetVegaLite-SpecModel-SpecNormalizer-ErrorBar - CanvasNetVegaLite-SpecModel-SpecNormalizer-ErrorBand - CanvasNetVegaLite-SpecModel-SpecNormalizer-CompositeErrors + - CanvasNetVegaLite-SpecModel-SpecNormalizer-PathOverlay tests: - SpecNormalizer_Layers_LayersAreUnitsInDocumentOrder - SpecNormalizer_Layers_EncodingIsMergedInPlace diff --git a/docs/reqstream/canvas-net-vega-lite/spec-model/feature-catalog.yaml b/docs/reqstream/canvas-net-vega-lite/spec-model/feature-catalog.yaml index 34a172584..3d0eeffa2 100644 --- a/docs/reqstream/canvas-net-vega-lite/spec-model/feature-catalog.yaml +++ b/docs/reqstream/canvas-net-vega-lite/spec-model/feature-catalog.yaml @@ -102,7 +102,11 @@ sections: strokeWidth, strokeDash, fillOpacity, strokeOpacity, angle, xError, xError2, yError, and yError2 (and the accepted and ignored tooltip, href, description, and key) as vl-channel-name, the channels of a mark that does not - draw them (as vl-channel-name, the channel being ignored), the geographic types, and the + draw them (as vl-channel-name, the channel being ignored; a shape of a line, area, trail, or + rule that has a point overlay, which a shape switches on unless point is false or null, is not + reported, and an angle, a stroke dash, or a size that only the overlay points draw is reported + with a message that says so), the overlays being decided with the effective configuration of the + rendering (the caller's included) when there is one, the geographic types, and the encoding properties impute (on a channel other than x and y) and bandPosition when they change the chart (a bandPosition of a field without a time unit), but not the temporal type, the time unit, the properties aggregate, stack, and sort (in its supported forms), the impute of x and @@ -133,6 +137,8 @@ sections: - FeatureCatalog_Visit_Phase6FeaturesAreNotReportedAndRemainingPartsAre - FeatureCatalog_Visit_BinOnScaleChannelsAndTheBinOrdinalScaleAreSupported - FeatureCatalog_Visit_ReportsChannelsThatTheMarkDoesNotDraw + - FeatureCatalog_Visit_ShapeOfAPathMarkWithAPointOverlayIsNotReported + - FeatureCatalog_Visit_ReportsFollowTheEffectiveConfiguration - id: CanvasNetVegaLite-SpecModel-FeatureCatalog-PathMarks title: >- diff --git a/docs/reqstream/canvas-net-vega-lite/spec-model/spec-normalizer.yaml b/docs/reqstream/canvas-net-vega-lite/spec-model/spec-normalizer.yaml index 0a63a58b5..21404d1f2 100644 --- a/docs/reqstream/canvas-net-vega-lite/spec-model/spec-normalizer.yaml +++ b/docs/reqstream/canvas-net-vega-lite/spec-model/spec-normalizer.yaml @@ -385,3 +385,22 @@ sections: tests: - SpecNormalizer_Expand_UndecidableBoxPlotIsASpecificationError - SpecNormalizer_Expand_ErrorChannelWithoutFieldIsASpecificationError + + - id: CanvasNetVegaLite-SpecModel-SpecNormalizer-PathOverlay + title: >- + The SpecNormalizer unit shall decide as Vega-Lite's path overlay normalizer does whether a + line, area, trail, or rule has a point overlay - its point property is true, an object, or + transparent, or is missing while config..point is truthy or the encoding has a shape + channel, false and null switching the overlay off - and whether an area has a line overlay (its + line property is true or an object, or is missing while config.area.line is truthy), and which + channels the overlays draw, so that the mark builder, the scale resolver, the legend planner, and + the feature catalog agree on the points, the lines, the scales of the channels they draw, and the + reports. + justification: | + Vega-Lite draws the shape channel of a line with the points of its overlay and drops it from + the path; every stage that reads the shape must decide the overlay alike. + tests: + - MarkBuilder_Build_ShapeChannelEnablesThePointOverlayUnlessSwitchedOff + - ScaleResolver_Resolve_PointOverlayBuildsTheScalesOfThePointChannels + - FeatureCatalog_Visit_ShapeOfAPathMarkWithAPointOverlayIsNotReported + - MarkBuilder_Build_LineOverlayOfAnAreaDrawsTheSizeAndTheDashOfTheEncoding diff --git a/docs/sysml2/model/canvas-net-vega-lite/spec-model/spec-normalizer.sysml b/docs/sysml2/model/canvas-net-vega-lite/spec-model/spec-normalizer.sysml index 50dd34eb9..5ec296173 100644 --- a/docs/sysml2/model/canvas-net-vega-lite/spec-model/spec-normalizer.sysml +++ b/docs/sysml2/model/canvas-net-vega-lite/spec-model/spec-normalizer.sysml @@ -2,7 +2,7 @@ package CanvasNet { part def SpecNormalizer { doc /* The internal static partial SpecNormalizer with the LayerTree, LayerNode, LayerResolve, ResolveMode, ViewKind, CompositionSettings, CompositionAlign, FacetDefinition, RepeaterValues, ExpandedLayers, CompositeAxis, and CompositeBuilder types: it reduces the views of a parsed specification to the tree of views whose leaves are the unit views that are drawn, so that every later stage draws unit views and needs no special case for layers, compositions, or composite marks. Layers(tree, limits, config) builds the LayerTree with an explicit stack: a specification without composition is one unit view, the root itself, so a single view takes the path it always took; the objects of a layer array are the layers of a layered view (unit views or layered views, to any depth); a concat, hconcat, or vconcat is a Concat node whose children are its charts; a facet with a spec, and a unit view with a row, column, or facet encoding channel (the root or a child of a concatenation, not a unit view in a layer or in the spec of a facet), is a Facet node over one chart, the synthetic body of a faceted unit view having its mark, size, and encoding without the faceting channels; a repeat is expanded without reading data into a Concat node (an array, or the row-major product of rows and columns) or a Layer node (layers) of copies of its spec, each copy knowing the values it repeats, whose {"repeat": ...} field references are replaced by those values (a reference with no value dropping its channel with a warning), the number of copies being checked against MaxViews before any copy is made. Each node of a composition has the layout settings that Vega-Lite's extractCompositionLayout reads (columns, spacing, align, center, bounds, over the configuration) and the resolve defaults of its kind (the position, theta, and radius scales of the children of a concatenation independent and their axes never shared, the scales of a facet shared except theta). A layer inherits as in Vega-Lite: the encoding of the layered views above it in its chart (the outermost first, a channel of an inner view replacing the outer channel in place and a new channel added after the existing ones, as a node that is not adopted by its parent so every pointer, line, and column stays that of the specification), the width and height of its chart, and, as the view's own, the data and the transform that the document applies down the tree (the transform of a layered view first); the resolve of each view that holds views is read into a LayerResolve. MaxViews (every view, the views of an expansion and the copies of a repeat included) and MaxCompositionDepth (the nesting of layers, concatenations, facets, and repeats) fail closed with a located VegaLiteRenderException at the exact limit. Expand(tree, config, limits) replaces a unit view whose mark is boxplot, errorbar, or errorband by a layered view of the primitive layers that Vega-Lite normalizes it to, written as synthetic nodes located at the mark, with the expressions it writes compiled into a derived specification tree: a boxplot as the outlier points, the whiskers (rules and optional end ticks over the values inside the fences, or from the minimum to the maximum for min-max), and the box with its median tick, with the defaults of config.boxplot; an errorbar from raw observations (the stderr, stdev, ci, or iqr extent around the mean or median), a pre-aggregated range, or errors, as a rule with optional ticks; an errorband as a rect (one dimension) or an area (two dimensions) with optional rule or line borders; the part switches, part properties, orientation, grouping channels, and titles follow Vega-Lite, and an orientation or encoding that cannot be decided is a VegaLiteSpecException at the mark. The unit performs no file or network access and holds no state; the expansion, composition, and repeat rules are ported from Vega-Lite compositemark, normalize, and spec with attribution (the files carry the provenance header). The data-dependent part of the tree (phase 11): LayerTree.InstantiateFacet replaces the template of a facet by one copy for each cell the data gives (the same view and unit objects, the cell on every node, their own chart roots) and refreshes the units, compositions, and view count (Refresh), FacetViews counts the views of a cell and the views outside the cells so that MaxViews is checked before the cells are made, and DataSites groups the views by the data object they declare so that a table is loaded once for the copies of a repeat and the cells of a facet, with the views and facets whose fields the loader parses as dates. */ - comment sourceRef /* Source: src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.Composition.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.Repeat.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.Composite.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.BoxPlot.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.ErrorBar.cs */ + comment sourceRef /* Source: src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.Composition.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.Repeat.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.Composite.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.BoxPlot.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.ErrorBar.cs, src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.PathOverlay.cs */ comment testRef /* Test: test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/SpecNormalizerTests.cs, test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/SpecNormalizerCompositionTests.cs, test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/SpecNormalizerRepeatTests.cs, test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/SpecNormalizerFacetCellTests.cs, test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/SpecNormalizerBoxPlotTests.cs, test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/SpecNormalizerErrorBarTests.cs */ comment designRef /* Design: docs/design/canvas-net-vega-lite/spec-model/spec-normalizer.md */ comment verificationRef /* Verification: docs/verification/canvas-net-vega-lite/spec-model/spec-normalizer.md */ diff --git a/docs/user_guide/canvas-net-vega-lite.md b/docs/user_guide/canvas-net-vega-lite.md index caa854211..87f2f96c4 100644 --- a/docs/user_guide/canvas-net-vega-lite.md +++ b/docs/user_guide/canvas-net-vega-lite.md @@ -307,7 +307,7 @@ without it. A key that Vega-Lite does not define for a view, mark, encoding, or | Views | A single view, a `layer` of views (layers may be nested and carry a `resolve` of the scales, axes, and legends; see *Vega-Lite Layers and Composite Marks*), and the compositions `concat`, `hconcat`, `vconcat` (with `columns`, `spacing`, `align`, `center`, and `bounds`), `facet` (a `row` and `column` mapping, or one field with `columns`, over a `spec` that is a unit or a layered view; the `row`, `column`, and `facet` channels of a unit view), and `repeat` (a list, a `row` and `column` mapping, a `layer` list, and `{"repeat": ...}` field references), nested within `MaxCompositionDepth` levels and `MaxViews` views, with a `resolve` of the scales, axes, and legends of each composition; see *Vega-Lite Composition* | | Data | Inline `data.values` (an array of objects, one row per object with nested values flattened to path fields such as `a.b`, or of primitives, one row `{"data": value}`); a relative local `data.url` read as JSON, CSV, TSV, or DSV; `format.type`, `delimiter`, `property`, and `parse` (see *Vega-Lite Data*); named data (`data.name`, from the caller's `Datasets` or the top-level `datasets`); and `data.sequence`. Remote URLs, geographic data, and `values` given as text are not read | | Marks | `bar`, `rect`, `point`, `circle`, `square`, `rule`, `tick`, `line`, `area`, `trail`, `text`, and `arc`, given as a string or as a definition object with `type`; see *Vega-Lite Line, Area, Text, and Arc Marks*. The composite marks `boxplot`, `errorbar`, and `errorband`, which are drawn as layers of those marks; see *Vega-Lite Layers and Composite Marks* | -| Channels | `x`, `y`, `theta`, `radius`, `color`, `fill`, `stroke`, `size`, `opacity`, `fillOpacity`, `strokeOpacity`, `strokeWidth`, `strokeDash`, `shape`, `angle`, and `text`, each as a `field`, a literal `value`, or a literal `datum` where the channel permits it (`shape` is drawn by a `point` mark, `angle` by a `point`, `circle`, `square`, or `text`, `text` by a `text` mark, `theta` and `radius` by an `arc` or `text` mark, `size` by every mark but a `rect`, `area`, and `arc`, and `strokeDash` by every mark but a `rect`, `area`, `trail`, `text`, and `arc`; see *Vega-Lite Legends, Color Schemes, and Scales*). `x2` and `y2` give the end of a range on a `bar`, `rect`, `rule`, or `area` (and the ends of the range of an `errorbar` or `errorband`), `xError`, `xError2`, `yError`, and `yError2` give the errors of an `errorbar` or `errorband` (they are reported on any other mark), `theta2` and `radius2` the end of the span of an `arc`, and `order` orders the layers of a stack, the points of a path, or the drawing order of the marks. `detail` groups the points of a path. `tooltip`, `href`, `description`, and `key` are accepted and ignored without a report, because they have no meaning in a still picture. `row`, `column`, and `facet` on a unit view facet it, as the `facet` operator does (see *Vega-Lite Composition*); inside a layer or the `spec` of a facet they are reported | +| Channels | `x`, `y`, `theta`, `radius`, `color`, `fill`, `stroke`, `size`, `opacity`, `fillOpacity`, `strokeOpacity`, `strokeWidth`, `strokeDash`, `shape`, `angle`, and `text`, each as a `field`, a literal `value`, or a literal `datum` where the channel permits it (`shape` is drawn by a `point` mark and by the overlay points of a `line`, `area`, `trail`, or `rule` (see *Overlays* under *Vega-Lite Line, Area, Text, and Arc Marks*), `angle` by a `point`, `circle`, `square`, or `text`, `text` by a `text` mark, `theta` and `radius` by an `arc` or `text` mark, `size` by every mark but a `rect`, `area`, and `arc`, and `strokeDash` by every mark but a `rect`, `area`, `trail`, `text`, and `arc`; see *Vega-Lite Legends, Color Schemes, and Scales*). `x2` and `y2` give the end of a range on a `bar`, `rect`, `rule`, or `area` (and the ends of the range of an `errorbar` or `errorband`), `xError`, `xError2`, `yError`, and `yError2` give the errors of an `errorbar` or `errorband` (they are reported on any other mark), `theta2` and `radius2` the end of the span of an `arc`, and `order` orders the layers of a stack, the points of a path, or the drawing order of the marks. `detail` groups the points of a path. `tooltip`, `href`, `description`, and `key` are accepted and ignored without a report, because they have no meaning in a still picture. `row`, `column`, and `facet` on a unit view facet it, as the `facet` operator does (see *Vega-Lite Composition*); inside a layer or the `spec` of a facet they are reported | | Field types | `quantitative`, `temporal`, `nominal`, and `ordinal` (`geojson` is reported) | | Encoding properties | `field`, `type`, `value`, `datum`, `title`, `scale`, `axis`, `legend` (an object of legend properties, or `null`), `aggregate` (all 24 operations, including `count` without a field), `bin` (on `x` and `y`: `true`, the bin parameters, or `"binned"`; on `color`, `fill`, `stroke`, `size`, the opacities, `strokeWidth`, `strokeDash`, `shape`, and `angle`: `true` or the bin parameters, with 6 bins by default, 4 for `strokeDash`, and 10 for `angle`), `timeUnit` (the 40 Vega-Lite time units, their `utc` forms, and the object form; see *Vega-Lite Time and Time Zones*), `stack` (`zero`, `center`, `normalize`, `true`, `false`, or `null`; also on `theta` and `radius`), `impute` (on `x` and `y`: an object of `keyvals`, `method`, `value`, and `frame`, or `null` to switch off the implicit impute of a stacked path mark), and `sort` (ascending, descending, `null`, an array of values, a channel such as `"-y"`, or an object that sorts by an aggregate of a field), and `condition` on the `color`, `fill`, `stroke`, `opacity`, `fillOpacity`, `strokeOpacity`, `strokeWidth`, `strokeDash`, `size`, `shape`, and `angle` channels (a `test` that is an expression or a predicate; the first condition that holds gives the mark its `value` or the scale of its field; see *Vega-Lite Conditional Encodings*); see *Vega-Lite Aggregation, Binning, and Stacking* | | Scales | The types linear, log, pow, sqrt, symlog, sequential, time, utc, band, point, ordinal, quantile, quantize, threshold, and bin-ordinal, as Vega-Lite accepts them for a channel and a field type (a scale type that the channel or the field cannot use is replaced by the default one with the warning `vl-scale-type-ignored`); a diverging color scale is a sequential one with a `domainMid`. A temporal field gets a `time` scale (a `utc` scale for a `utc` time unit), see *Vega-Lite Time and Time Zones*. The polar channels `theta` and `radius` have the ranges 0 to a full turn and 0 to half of the smaller side of the view, see *Vega-Lite Line, Area, Text, and Arc Marks*. A binned quantitative color gets the bin-ordinal scale (one color per bin, and a legend of the ranges of the bins). A log scale takes `base`, a pow scale `exponent`, and a symlog scale `constant`; a log scale has no zero, is rounded out to powers of its base, and refuses a domain that includes zero or crosses it with a located error, where a symlog scale takes such data. The properties are `type`, `domain`, `domainMid`, `domainMin`, `domainMax`, `range` (a list, or the name of an entry of `config.range`), `rangeMin`, `rangeMax`, `scheme`, `interpolate`, `zero`, `nice` (also a time interval for a time scale), `padding`, `reverse`, `paddingInner`, `paddingOuter`, `align`, `round`, `clamp`, `base`, `exponent`, and `constant`; see *Vega-Lite Legends, Color Schemes, and Scales*. A quantitative `domain` and `range` of more than two entries map piecewise exactly as in d3-scale (`min(domain length, range length)` entries are used, and `zero`, `nice` and padding change only the first and last entry), while a band or point scale uses the first two entries of its `range` | @@ -1395,9 +1395,9 @@ channels that are accepted by every mark. | `theta`, `radius` | Reported | Reported | Reported | A polar offset of the anchor | The angular and radial span | | `theta2`, `radius2` | Reported | Reported | Reported | Reported | The other end of the span | | `color`, `fill`, `stroke`, `opacity`, `fillOpacity`, `strokeOpacity`, `strokeWidth` | The paint of the path (they also **group** the rows into paths) | The paint of the path (they group) | The paint of the path (they group) | The paint of each label | The paint of each wedge | -| `size` | The stroke width of the path (it groups) | Reported | The width of the trail at each point | The font size | Reported | -| `strokeDash` | The dash of the path (it groups) | Reported | Reported | Reported | Reported | -| `shape`, `angle` | Reported | Reported | Reported | `angle` rotates the label; `shape` reported | Reported | +| `size` | The stroke width of the path (it groups) | Reported (the width of its line overlay, when it has one) | The width of the trail at each point | The font size | Reported | +| `strokeDash` | The dash of the path (it groups) | Reported (the dash of its line overlay, when it has one) | Reported | Reported | Reported | +| `shape` | The shape of the overlay points when the mark has a point overlay (see *Overlays*; it does not group the paths), else reported | The shape of the overlay points when the mark has a point overlay, else reported | The shape of the overlay points when the mark has a point overlay, else reported | Reported | Reported | | `text` | Reported | Reported | Reported | The label | Reported | | `detail`, `key` | Group the rows into paths | Group | Group | Accepted | Accepted | | `order` | The order of the points of a path (or of the layers of a stack) | The order of the layers of a stack, and the paths | The order of the points | The drawing order of the labels | The drawing order of the wedges | @@ -1469,9 +1469,23 @@ with the warning `vl-mark-invalid-domains`. A mark that is not a path drops the point mark properties (`{"size": 100, "fill": "white"}`), or `"transparent"` (points with the opacity 0), and an `area` can stroke its top edge with `"line": true` or an object of line properties. `"point": false` or `null` switches off what `config..point` enables. The overlays use the scales and the stack of the mark, and a stacked area's line -is drawn at the top of its layer. A `size` channel reaches the overlay points through the size scale of the mark that -is overlaid (so the points of a line take their area from the range of its stroke widths), and an `encoding.shape` -does **not** turn the points on (the channel is reported as one that the mark does not draw). +is drawn at the top of its layer. The overlay points draw the channels of a `point` mark that the path itself does not, +as Vega-Lite's path overlay does: the `shape` channel gives them their shapes (a circle, a square, and so on, by group), +and an `encoding.shape` also **turns the points on** when the mark has no `point` property and `config..point` +does not say otherwise, so `{"mark": "line", "encoding": {"shape": {"field": "g"}}}` draws the points; `"point": false` +or `null` keeps them off and the `shape` is then reported (`vl-channel-shape`: the mark does not draw it). The `shape` is +dropped from the path, so it does not split a line into more paths and raises no report on the line; a shape and a color +of the same field share one legend (the shapes with the colors), and another field gets its own. The symbols of that +legend are filled when the points are filled (the color is their fill, not the stroke of the +line). The `angle` and `strokeDash` channels and the `size` of an area turn, dash, and size the points too, with the +scale ranges of a point mark; the line overlay of an area (`"line": true`) draws the `strokeDash` as the dash of its line +and the +`size` as its width (the range of the stroke widths, 1 to 4 by default). The path mark itself does not draw these channels, +so they are still reported (`vl-channel-angle`, `vl-channel-strokedash`, `vl-channel-size`) with a message that names the +overlay that draws them. The overlays follow the configuration that is in effect, including the `config` of the render +options (`config.line.point`, `config.area.line`), for the reports as for the drawing. A `size` channel of a line reaches +the overlay points through the size scale of the line (so the points of a line take their area from the range of its +stroke widths). **Impute.** A stacked `line`, `area`, or `trail` with several layers must have a value for each layer at every position, or the stack leaves holes: the pipeline therefore **imputes 0** for every missing combination of a position and a layer @@ -1975,7 +1989,7 @@ thread, after the work finished and before the method returns or throws. | `vl-mark-invalid-domains` | Warning | An `invalid` of `filter` or `break-paths-filter-domains`, in the mark definition or the configuration: the scale domains of this renderer always include the rows of invalid values | | `vl-mark-interpolate-bundle-area` | Unsupported | An `interpolate` of `bundle` on an `area`, in the mark definition or the configuration, which has no outline in d3-shape (the area is drawn with `linear`) | | `vl-mark-interpolate-unknown` | Unsupported | An `interpolate` of a `line` or `area` that is not one of the 15 names of Vega-Lite; only the configuration can give one (a mark definition with such a name is an error); the line is drawn with `linear` | -| `vl-channel-` | Unsupported | A channel other than x, y, theta, radius, theta2, radius2, color, fill, stroke, size, opacity, shape, strokeWidth, strokeDash, fillOpacity, strokeOpacity, angle, text, order, and detail (tooltip, href, description, and key are ignored); `shape` is drawn by a point mark, `angle` by a point, circle, square, or text, `text` by a text mark, `theta` and `radius` by an arc or text mark, `theta2` and `radius2` by an arc, `size` by every mark but a rect, area, and arc, and `strokeDash` by every mark but a rect, area, trail, text, and arc, and the channel is reported and ignored on any other mark (a `boxplot` draws `shape`, `angle`, and `strokeDash` with its outliers, and an `errorbar` draws `strokeDash` with its rule). `x2` and `y2` are supported on a bar, rect, rule, or area that has the `x` or `y` they extend, and on an errorbar or errorband, and are reported (`vl-channel-x2`, `vl-channel-y2`) on any other mark or without it. `xError`, `xError2`, `yError`, and `yError2` are supported on an errorbar or errorband and are reported (`vl-channel-xerror`, `vl-channel-xerror2`, `vl-channel-yerror`, `vl-channel-yerror2`) on any other mark; the `size` channel of an errorbar is reported (`vl-channel-size`). `order` and `detail` are accepted by every mark | +| `vl-channel-` | Unsupported | A channel other than x, y, theta, radius, theta2, radius2, color, fill, stroke, size, opacity, shape, strokeWidth, strokeDash, fillOpacity, strokeOpacity, angle, text, order, and detail (tooltip, href, description, and key are ignored); `shape` is drawn by a point mark and by the overlay points of a line, area, trail, or rule that has a point overlay (an `encoding.shape` switches the overlay on unless `point` is `false` or `null`, so a `shape` is reported only on a path mark whose overlay is off), `angle` by a point, circle, square, or text, `text` by a text mark, `theta` and `radius` by an arc or text mark, `theta2` and `radius2` by an arc, `size` by every mark but a rect, area, and arc, and `strokeDash` by every mark but a rect, area, trail, text, and arc, and the channel is reported and ignored on any other mark (an `angle`, `strokeDash`, or `size` that only the overlay points of a path mark, or the line overlay of an area, draw is reported with a message that names the overlay) (a `boxplot` draws `shape`, `angle`, and `strokeDash` with its outliers, and an `errorbar` draws `strokeDash` with its rule). `x2` and `y2` are supported on a bar, rect, rule, or area that has the `x` or `y` they extend, and on an errorbar or errorband, and are reported (`vl-channel-x2`, `vl-channel-y2`) on any other mark or without it. `xError`, `xError2`, `yError`, and `yError2` are supported on an errorbar or errorband and are reported (`vl-channel-xerror`, `vl-channel-xerror2`, `vl-channel-yerror`, `vl-channel-yerror2`) on any other mark; the `size` channel of an errorbar is reported (`vl-channel-size`). `order` and `detail` are accepted by every mark | | `vl-channel-geo` | Unsupported | `longitude`, `latitude`, `longitude2`, `latitude2` | | `vl-channel-row`, `-column`, `-facet` | Unsupported | A `row`, `column`, or `facet` channel of a view that cannot be faceted: a layer of a layered view, a layered view whose encoding has the channel, or the `spec` of a `facet` (the channel is ignored; use the `facet` operator). The channels of a unit view that is faceted are drawn and are not reported | | `vl-facet-field-transform` | Unsupported | A `bin`, `timeUnit`, or `aggregate` of a facet field (the `facet` operator, or the `row`, `column`, and `facet` channels): the raw value of the field is the cell | diff --git a/docs/verification/canvas-net-vega-lite.md b/docs/verification/canvas-net-vega-lite.md index 2b4077f25..567895a08 100644 --- a/docs/verification/canvas-net-vega-lite.md +++ b/docs/verification/canvas-net-vega-lite.md @@ -1127,7 +1127,27 @@ Renders a line with `point: true` of the polyline rows and asserts the line `M0, opacity 0, and that two series with a color field draw each line in its own color (`#4c78a8` and `#f58518`) and each series' two points in its color. -### InvalidData: Nulls Break A Path, Filter Connects, And Show Is Reported +### Overlays: The Shape Channel Shapes The Overlay Points In Strict Mode + +**Test**: `VegaLiteLineAreaIntegrationTests.CanvasNetVegaLite_SystemIntegration_Overlays_ShapeChannelShapesTheOverlayPointsInStrictMode` + +Renders, in strict mode (any report is an exception), a line with `point: true` of two series whose `color` and `shape` +channels both follow the series, and asserts that nothing is reported, that the two lines are stroked with `#4c78a8` and +`#f58518`, that the four `mark-point` symbols are a circle, a circle, a square, and a square in the colors of their +series, and that the legend symbols are a circle and a square. Renders an area with `point: true` (the points are shaped +the same) and a line with no `point` at all (the shape switches the overlay on: four points, no report), and asserts that +with `point: false` strict mode throws for `vl-channel-shape`. + +### Overlays: The Caller's Configuration And The Line Overlay Agree With The Reports + +**Test**: `VegaLiteLineAreaIntegrationTests.CanvasNetVegaLite_SystemIntegration_Overlays_CallerConfigurationAndLineOverlayAgreeWithTheReports` + +Renders a line with a `shape` in strict mode with the caller's `{"line": {"point": true}}` and asserts that nothing is +reported and the points are a circle, a circle, a square, and a square. Renders a line with an `angle` and asserts that +the +report of `vl-channel-angle` names the point overlay with the caller's configuration and says that the channel is ignored +without it. Renders an area with `line: true`, `point: false`, and a `strokeDash` of two groups and asserts that the two +`mark-line` paths have a dash and that the report of `vl-channel-strokedash` names the line overlay. **Test**: `VegaLiteLineAreaIntegrationTests.CanvasNetVegaLite_SystemIntegration_InvalidData_NullsBreakAFilterConnectsAndShowIsReported` diff --git a/docs/verification/canvas-net-vega-lite/guides/legend-builder.md b/docs/verification/canvas-net-vega-lite/guides/legend-builder.md index dce539259..db4adb347 100644 --- a/docs/verification/canvas-net-vega-lite/guides/legend-builder.md +++ b/docs/verification/canvas-net-vega-lite/guides/legend-builder.md @@ -285,9 +285,15 @@ the labels are the same under the Turkish, German, and invariant cultures and fo `LegendPlanLayerTests.LegendPlan_Create_PropertiesOfALaterLayerAreKeptWhenTheFirstIsSilent`, `LegendPlanLayerTests.LegendPlan_Create_ExplicitOrientConflictMakesTheLegendsIndependent`, `LegendPlanLayerTests.LegendPlan_Create_LayersInDifferentScopesKeepTheirOwnLegends`, -`LegendPlanLayerTests.LegendPlan_Create_SingleLayerMatchesTheViewOverloadAndDisableIsHonored` - -Asserts that layers that color by the same field share one legend with one member and the title of the field; that the titles +`LegendPlanLayerTests.LegendPlan_Create_SingleLayerMatchesTheViewOverloadAndDisableIsHonored`, +`MarkChannelGatingTests.LegendPlan_Create_ShapeOfALineWithAPointOverlayHasALegendMergedWithTheColorOfTheSameField` + +Asserts that layers that color by the same field share one legend with one member and the title of the field; that a line +with a point overlay whose `shape` and `color` are one field has one legend that holds the color and the shape (its +symbols a circle, a square, and a triangle filled with the colors of the groups, with no stroke of that color, as the +filled overlay points are), that an overlay object with `filled: false` gives hollow symbols (the color is the stroke), +that an area with a point overlay has filled symbols too, that a shape of another field has a legend of its own, +and that with `point: false` there is no shape legend; that the titles of different fields on the shared scale join in layer order (`a, b`); that a written title (a channel `title` or a `legend.title`) of any layer, first, middle, or last, wins over the derived titles of the others, as Vega-Lite's merge of explicit and implicit titles does; that different written titles join (`One, Two`), equal ones are one, and a written diff --git a/docs/verification/canvas-net-vega-lite/marks.md b/docs/verification/canvas-net-vega-lite/marks.md index ea4e3ba8b..609a2de52 100644 --- a/docs/verification/canvas-net-vega-lite/marks.md +++ b/docs/verification/canvas-net-vega-lite/marks.md @@ -203,6 +203,8 @@ the unit verification document passes without error or unexpected exception. of those pixels have 4, 8, and 12 rows of ink (half widths 2, 4, and 6), in `#4c78a8` without a stroke. - **Overlays, Invalid Modes, And The Draw Order Through The Whole Pipeline**: `VegaLiteLineAreaIntegrationTests.CanvasNetVegaLite_SystemIntegration_Overlays_LinePointsAndAreaLineAreDrawn`, + `VegaLiteLineAreaIntegrationTests.CanvasNetVegaLite_SystemIntegration_Overlays_ShapeChannelShapesTheOverlayPointsInStrictMode`, + `VegaLiteLineAreaIntegrationTests.CanvasNetVegaLite_SystemIntegration_Overlays_CallerConfigurationAndLineOverlayAgreeWithTheReports`, `VegaLiteLineAreaIntegrationTests.CanvasNetVegaLite_SystemIntegration_InvalidData_NullsBreakAFilterConnectsAndShowIsReported`, `VegaLiteLineAreaIntegrationTests.CanvasNetVegaLite_SystemIntegration_Order_OrderChannelControlsOverlapAndPathSort`, `MarkBuilderOverlayTests.MarkBuilder_Build_PointOverlayDrawsSymbolsWithTheOverlayDefinition`, diff --git a/docs/verification/canvas-net-vega-lite/marks/mark-builder.md b/docs/verification/canvas-net-vega-lite/marks/mark-builder.md index 105058ec2..1484cdf0a 100644 --- a/docs/verification/canvas-net-vega-lite/marks/mark-builder.md +++ b/docs/verification/canvas-net-vega-lite/marks/mark-builder.md @@ -633,7 +633,12 @@ that a line without the properties has the offset 0 and no cap, join, or miter l **Tests**: `MarkBuilderOverlayTests.MarkBuilder_Build_PointOverlayDrawsSymbolsWithTheOverlayDefinition`, `MarkBuilderOverlayTests.MarkBuilder_Build_AreaLineOverlayAndDefaultOpacity`, -`MarkBuilderOverlayTests.MarkBuilder_Build_OverlayFromConfigAndTransparentPoints` +`MarkBuilderOverlayTests.MarkBuilder_Build_OverlayFromConfigAndTransparentPoints`, +`MarkBuilderOverlayTests.MarkBuilder_Build_ShapeChannelOfALineShapesTheOverlayPoints`, +`MarkBuilderOverlayTests.MarkBuilder_Build_ShapeChannelEnablesThePointOverlayUnlessSwitchedOff`, +`MarkBuilderOverlayTests.MarkBuilder_Build_ShapeChannelOfAnAreaShapesTheOverlayPoints`, +`MarkBuilderOverlayTests.MarkBuilder_Build_PointChannelsOfThePathMarkReachTheOverlayPoints`, +`MarkBuilderOverlayTests.MarkBuilder_Build_LineOverlayOfAnAreaDrawsTheSizeAndTheDashOfTheEncoding` Assert the overlays derived above: the roles `mark-line`, `mark-point` x 3 with the budget 14, the filled blue circles of the size 30 at the three pixels (the green line not inherited), the replaced properties, no overlay for `false` or null, @@ -641,7 +646,16 @@ two points for a row gap, the rule and trail overlays; the area with the opacity edge (width 2, opacity 1), the replaced line properties, the step line, the opacities 0.5, 1 (with a fill opacity of 0.4), 0.7 (with a point overlay), and 1 (with both switched off), the clip of the group, and the lines at the stack end of two stacked layers; and the configured overlays, their switch-off by the mark, the transparent points (opacity 0), and -the colors of the overlay points of a color field. +the colors of the overlay points of a color field. The shape tests assert that a line with `"point": true` (or an overlay +object) and a `shape` and a `color` of the same field has one path for each group (the shape does not split them) and +overlay points that are circles for the first group and squares for the second, in the colors of the groups, and a +constant shape value for every point; that a line, a trail, and an area with a `shape` and no `point` get the overlay while +`point: false` and `point: null` leave no symbol, and a `point` mark keeps its own shapes; that an area gets the shaped +points with `point: true`, with only `line: true`, and from `config.area.point`, with the opacity 0.7, and is opaque and +alone with `point: false`; and that the size of an area (from 4 for the smallest value, with the range of a point) and the +angle of a line reach the overlay points; and that the line overlay of an area draws the dash of the groups on its lines +(the areas have none) and the width of its lines from the size (inside the range of the stroke widths, 1 to 4, growing +with the size), and that without the line overlay only the areas are drawn. ##### The Order Channel Sorts The Drawing diff --git a/docs/verification/canvas-net-vega-lite/scales/scale-resolver.md b/docs/verification/canvas-net-vega-lite/scales/scale-resolver.md index ee440ae43..e88428647 100644 --- a/docs/verification/canvas-net-vega-lite/scales/scale-resolver.md +++ b/docs/verification/canvas-net-vega-lite/scales/scale-resolver.md @@ -197,7 +197,8 @@ an `x` datum has the scales `x`, `theta`, and `color` in that order. ##### Channels Are Resolved Only For The Marks That Draw Them **Tests**: `MarkChannelGatingTests.ScaleResolver_ChannelIsDrawn_FollowsTheSupportTable`, -`MarkChannelGatingTests.ScaleResolver_Resolve_ChannelsThatTheMarkDoesNotDrawHaveNoScale` +`MarkChannelGatingTests.ScaleResolver_Resolve_ChannelsThatTheMarkDoesNotDrawHaveNoScale`, +`MarkChannelGatingTests.ScaleResolver_Resolve_PointOverlayBuildsTheScalesOfThePointChannels` Asserts, for each of the 13 marks (point, circle, square, rect, bar, tick, rule, line, area, trail, text, arc, and image), the exact set of marks that draw a channel: `theta` and `radius` by text and arc, `theta2` and `radius2` by arc, @@ -205,7 +206,13 @@ image), the exact set of marks that draw a channel: `theta` and `radius` by text text, and arc, `angle` by point, circle, square, and text, `shape` by point, and the position and paint channels by all; and, resolving a one-channel encoding of a small table, that a size on an area or an arc, a stroke dash on an area, a trail, a text, or an arc, an angle on a line, and a shape on an arc have no scale while a size on a line, a trail, or -a text, a stroke dash on a line, and an angle on a text do. +a text, a stroke dash on a line, and an angle on a text do. With a point overlay (`point` true, an object, or +`"transparent"`, an `area` with only a `line` overlay and a `shape`, or a `shape` alone on a `line` or `trail`) a shape +on a line, trail, or area, an angle on a line, a size on an area, and a stroke dash on a trail or area have a scale, +while with `point: false` or null, on an arc, or for a `text` channel they do not. With a line overlay of an area (`line` +true or an object, or `config.area.line`) a size and a stroke dash have a scale (a shape and an angle do not, with the +points off), and the size range is that of the stroke widths: the largest size of the field is mapped to 4; with +`line: false` or null, or on a trail, they do not. ##### Zero, Nice, Domain, Range, And Padding diff --git a/docs/verification/canvas-net-vega-lite/spec-model/feature-catalog.md b/docs/verification/canvas-net-vega-lite/spec-model/feature-catalog.md index dccabc006..97de1e5e7 100644 --- a/docs/verification/canvas-net-vega-lite/spec-model/feature-catalog.md +++ b/docs/verification/canvas-net-vega-lite/spec-model/feature-catalog.md @@ -111,7 +111,9 @@ and that the location of a mark report is the value of the `mark` property, with `FeatureCatalogTests.FeatureCatalog_Visit_ChannelsReportExceptSupportedAndIgnored`, `FeatureCatalogTests.FeatureCatalog_Visit_ShapeAngleAndDashChannelsAreReportedForMarksThatDoNotDrawThem`, `FeatureCatalogTests.FeatureCatalog_Visit_UnknownChannelIsNotReported`, -`MarkChannelGatingTests.FeatureCatalog_Visit_ReportsChannelsThatTheMarkDoesNotDraw` +`MarkChannelGatingTests.FeatureCatalog_Visit_ReportsChannelsThatTheMarkDoesNotDraw`, +`MarkChannelGatingTests.FeatureCatalog_Visit_ShapeOfAPathMarkWithAPointOverlayIsNotReported`, +`MarkChannelGatingTests.FeatureCatalog_Visit_ReportsFollowTheEffectiveConfiguration` Asserts, as a theory over seventeen mark types, that `bar`, `rect`, `point`, `circle`, `square`, `rule`, `tick`, `arc`, `area`, `line`, `text`, `trail`, `boxplot`, `errorbar`, and `errorband` are silent (written as a string and as a definition, @@ -131,10 +133,19 @@ a `rect`; that an unknown channel name is not reported again by the catalog (the parser warns about it once); and that the channels that a mark does not draw are reported at the channel and ignored, by the table of the marks that draw each channel: a `size` on an `area` (a field) or on an `arc` (a value) reports `vl-channel-size`, a `strokeDash` on a `trail`, on a `text`, and on an `area` reports -`vl-channel-strokedash`, a `shape` or an `angle` on a `line` reports `vl-channel-shape` and `vl-channel-angle`, while +`vl-channel-strokedash`, a `shape` on a `line` with `point: false` (the overlay off) reports `vl-channel-shape` and an +`angle` on a `line` reports `vl-channel-angle` (with a message that says that only a point overlay would draw it, when +the line has one), while a `shape` on a `line`, `trail`, `rule`, or `area` that has a point overlay (`point` true, an +object, or `"transparent"`, an `area` with a `line` overlay, the `config.line.point` of the specification, or no `point` +at all, which the shape switches on) is silent, and a `shape` on a `bar` or an `arc` is reported +(`FeatureCatalog_Visit_ShapeOfAPathMarkWithAPointOverlayIsNotReported`); the drawn channels are silent (a `size` and a `strokeDash` on a `line`, a `size` and an `angle` on a `text`, a `size` on a `trail`, a `size` and a `strokeDash` on a `bar`, and a `size` on a `rect`, which is the long-standing exception that -the catalog does not report). +the catalog does not report). The overlay of an area is counted too: a size or a dash on an area with a `line` overlay names +the line overlay, with both overlays "point and line overlays", and a trail or an area without overlay says that the +channel is ignored. With the effective configuration (`FeatureCatalog.Visit(tree, config)`, with the caller's +`config.line.point` or `config.area.line`) the messages follow what is drawn, the specification alone reports the +channels as ignored, and a shape is silent either way (`FeatureCatalog_Visit_ReportsFollowTheEffectiveConfiguration`). ##### Data diff --git a/docs/verification/canvas-net-vega-lite/spec-model/spec-normalizer.md b/docs/verification/canvas-net-vega-lite/spec-model/spec-normalizer.md index 9a106b6bb..60280df9a 100644 --- a/docs/verification/canvas-net-vega-lite/spec-model/spec-normalizer.md +++ b/docs/verification/canvas-net-vega-lite/spec-model/spec-normalizer.md @@ -399,3 +399,19 @@ Asserts, as a theory over the channel combinations, that a range or error channe observations) the continuous channel, and that a mark that cannot be decided reports the problem without throwing from `TryOrientation`; that an explicit `orient` decides observations whose channels are both continuous but not a range or errors; and that a range channel that is not a field is a specification error located at the mark. + +##### The Point Overlay Decision Of The Path Marks + +**Tests**: `MarkBuilderOverlayTests.MarkBuilder_Build_ShapeChannelEnablesThePointOverlayUnlessSwitchedOff`, +`MarkChannelGatingTests.ScaleResolver_Resolve_PointOverlayBuildsTheScalesOfThePointChannels`, +`MarkChannelGatingTests.FeatureCatalog_Visit_ShapeOfAPathMarkWithAPointOverlayIsNotReported` + +`SpecNormalizer.HasPointOverlay` and `HasLineOverlay` have no test of their own; their callers pin them (the line overlay +by `MarkChannelGatingTests.ScaleResolver_Resolve_PointOverlayBuildsTheScalesOfThePointChannels` and +`MarkBuilderOverlayTests.MarkBuilder_Build_LineOverlayOfAnAreaDrawsTheSizeAndTheDashOfTheEncoding`). Asserts that a line, +a trail, and an +area with a `shape` and no `point` have the overlay points, that `point: false` and null leave none, that +`"transparent"`, an +object, and `true` have them, that a falsy `config..point` leaves the decision to the shape while a truthy one +enables the overlay, that a mark that is not a line, area, trail, or rule (a bar, an arc) has no overlay, and that the +scales and the reports follow the decision. diff --git a/src/DemaConsulting.CanvasNet.VegaLite/Guides/LegendPlan.cs b/src/DemaConsulting.CanvasNet.VegaLite/Guides/LegendPlan.cs index 554a6633f..6e7eb33b4 100644 --- a/src/DemaConsulting.CanvasNet.VegaLite/Guides/LegendPlan.cs +++ b/src/DemaConsulting.CanvasNet.VegaLite/Guides/LegendPlan.cs @@ -208,20 +208,31 @@ public static LegendMarkFacts Create(SpecNode view, ResolvedConfig config) _ => string.Empty, }; var def = markNode is { IsObject: true } ? markNode : null; + var encoding = view["encoding"] is { IsObject: true } e ? e : null; + + // The symbols of a path mark with a point overlay are those of the overlay points: Vega-Lite normalizes the mark into the path and a filled point layer, and the legend merge + // prefers the circle of the points to the stroke of the path (mergeSymbolType), so the legend shows filled symbols (the overlay definition replaces the mark definition) + var overlay = SpecNormalizer.PointOverlayDefinition(type, def, encoding, config.VegaLite[type]?["point"]); + var definition = overlay ?? (def is null ? null : ConfigNode.FromSpec(def)); + if (overlay is not null) + { + type = "point"; + } + var styleNames = new List { type }; - if (def?["style"] is { } style) + if (definition?["style"] is { } style) { - if (style.IsString) + if (style.Kind == ConfigNodeKind.String) { styleNames.Add(style.StringValue!); } - else if (style.IsArray) + else if (style.Kind == ConfigNodeKind.Array) { - styleNames.AddRange(style.Items.Where(i => i.IsString).Select(i => i.StringValue!)); + styleNames.AddRange(style.Items.Where(i => i.Kind == ConfigNodeKind.String).Select(i => i.StringValue!)); } } - ConfigNode? Def(string name) => def?[name] is { } node ? ConfigNode.FromSpec(node) : null; + ConfigNode? Def(string name) => definition?[name]; ConfigNode? Vl(string name) { var vl = config.VegaLite; @@ -277,8 +288,6 @@ public static LegendMarkFacts Create(SpecNode view, ResolvedConfig config) opacity = Vl("opacity")?.AsNumber(); } - var encoding = view["encoding"] is { IsObject: true } e ? e : null; - // A color channel that no field drives gives the symbols its first conditional value, else its value (Vega-Lite's getFirstConditionValue) if (ChannelDefinitions.FirstValue(encoding?["fill"] ?? (filled ? encoding?["color"] : null))?.AsString() is { } channelFill) { diff --git a/src/DemaConsulting.CanvasNet.VegaLite/Marks/MarkBuilder.Overlays.cs b/src/DemaConsulting.CanvasNet.VegaLite/Marks/MarkBuilder.Overlays.cs index f2375836c..2ef04acd1 100644 --- a/src/DemaConsulting.CanvasNet.VegaLite/Marks/MarkBuilder.Overlays.cs +++ b/src/DemaConsulting.CanvasNet.VegaLite/Marks/MarkBuilder.Overlays.cs @@ -22,119 +22,29 @@ private sealed record OverlaySettings(ConfigNode Definition, string? Orient); /// private sealed partial class Run { - /// - /// Tells whether a configuration value is truthy as JavaScript sees it. - /// - /// The value. - /// for true, a number other than zero, a text that is not empty, an object and an array. - private static bool IsTruthy(ConfigNode node) => node.Kind switch - { - ConfigNodeKind.Boolean => node.BoolValue, - ConfigNodeKind.Number => node.NumberValue != 0 && !double.IsNaN(node.NumberValue), - ConfigNodeKind.String => node.StringValue!.Length > 0, - ConfigNodeKind.Array or ConfigNodeKind.Object => true, - _ => false, - }; - /// /// Works out the point overlay of the mark: the point of the mark definition (true, an object, or "transparent"), else that of config.<mark>. /// /// /// Vega-Lite's getPointOverlay. The overlay is a point mark with opacity: 1, filled: true and the clip of the mark, whatever the overlay /// object adds to or replaces; "transparent" is the overlay {"opacity": 0}. false and null switch the overlay off, also when the configuration enables it. - /// (Vega-Lite enables it also for an encoding with a shape channel; this renderer does not.) + /// An encoding with a shape channel enables it when the mark definition has no point and the configuration does not enable it. + /// The points draw every channel of the encoding that a point mark draws (a shape, an angle, a strokeDash, a size), which the path mark itself may not. /// /// The mark definition of the overlay; null when the mark has no point overlay. - private ConfigNode? PointOverlayDefinition() - { - if (_type is not ("line" or "area" or "trail" or "rule")) - { - return null; - } - - ConfigNode overlay; - if (Def("point") is { } point) - { - if (point is { Kind: ConfigNodeKind.String, StringValue: "transparent" }) - { - overlay = ConfigNode.Create(new Dictionary { ["opacity"] = ConfigNode.FromNumber(0) }); - } - else if (IsTruthy(point)) - { - overlay = point.IsObject ? point : ConfigNode.EmptyObject; - } - else - { - return null; - } - } - else if (_owner._config.VegaLite[_type]?["point"] is { } configured && IsTruthy(configured)) - { - overlay = configured.IsObject ? configured : ConfigNode.EmptyObject; - } - else - { - return null; - } - - var defaults = new Dictionary(StringComparer.Ordinal) - { - ["opacity"] = ConfigNode.FromNumber(1), - ["filled"] = ConfigNode.FromBoolean(true), - }; - if (Def("clip") is { } clip) - { - defaults["clip"] = clip; - } - - return ConfigNode.Merge(ConfigNode.Create(defaults), overlay); - } + private ConfigNode? PointOverlayDefinition() => + SpecNormalizer.PointOverlayDefinition(_type, _def, _view["encoding"], _owner._config.VegaLite[_type]?["point"]); /// /// Works out the line overlay of an area: the line of the mark definition (true or an object), else that of config.area. /// /// - /// Vega-Lite's getLineOverlay. The overlay is a line mark with the clip, interpolate and tension of the area, whatever the overlay object adds - /// to or replaces. The line is drawn at the edge of the area, so it has no x2 and y2. + /// Vega-Lite's getLineOverlay (see ). The overlay is a line mark with the clip, interpolate and tension of the area, + /// whatever the overlay object adds to or replaces. The line is drawn at the edge of the area, so it has no x2 and y2. /// /// The mark definition of the overlay; null when the mark has no line overlay. - private ConfigNode? LineOverlayDefinition() - { - if (_type != "area") - { - return null; - } - - ConfigNode overlay; - if (Def("line") is { } line) - { - if (!IsTruthy(line)) - { - return null; - } - - overlay = line.IsObject ? line : ConfigNode.EmptyObject; - } - else if (_owner._config.VegaLite[_type]?["line"] is { } configured && IsTruthy(configured)) - { - overlay = configured.IsObject ? configured : ConfigNode.EmptyObject; - } - else - { - return null; - } - - var defaults = new Dictionary(StringComparer.Ordinal); - foreach (var name in new[] { "clip", "interpolate", "tension" }) - { - if (Def(name) is { } inherited) - { - defaults[name] = inherited; - } - } - - return ConfigNode.Merge(ConfigNode.Create(defaults), overlay); - } + private ConfigNode? LineOverlayDefinition() => + SpecNormalizer.LineOverlayDefinition(_type, _def, _owner._config.VegaLite[_type]?["line"]); /// /// Builds the overlays of the mark after its own items: the line of an area, then the points. diff --git a/src/DemaConsulting.CanvasNet.VegaLite/Scales/ScaleResolver.cs b/src/DemaConsulting.CanvasNet.VegaLite/Scales/ScaleResolver.cs index 082d2a0b5..5b02ac3b9 100644 --- a/src/DemaConsulting.CanvasNet.VegaLite/Scales/ScaleResolver.cs +++ b/src/DemaConsulting.CanvasNet.VegaLite/Scales/ScaleResolver.cs @@ -669,6 +669,7 @@ public static ResolvedScales Resolve( return null; } + var markDefinition = view["mark"] is { IsObject: true } mark ? mark : null; return new Context { Plan = plan, @@ -676,6 +677,8 @@ public static ResolvedScales Resolve( Config = config, MarkType = markType, Orient = plan.Orient, + PointOverlay = SpecNormalizer.HasPointOverlay(markType, markDefinition, encoding, config.VegaLite[markType]?["point"]), + LineOverlay = SpecNormalizer.HasLineOverlay(markType, markDefinition, config.VegaLite[markType]?["line"]), Encoding = encoding, SourceName = sourceName, Limits = limits ?? VegaLiteLimits.Default, @@ -952,7 +955,7 @@ private static double MinStepOf(SpecNode? size, ResolvedConfig config, string na return null; } - if (!ChannelIsDrawn(channel, context.MarkType)) + if (!ChannelIsDrawn(channel, context.MarkType) && !SpecNormalizer.OverlayDrawsChannel(channel, context.PointOverlay, context.LineOverlay)) { return null; } @@ -1814,7 +1817,19 @@ private static (double Inner, double Outer) Paddings(CommonInputs input, ScaleKi private static (double Min, double Max)? SizeRange(Context context) { var scale = context.Config; - switch (context.MarkType) + + // The overlays of an area draw its size (the area itself has none): the width of its line overlay, which comes first among the layers, else the size of its points + var sizeMark = context.MarkType; + if (sizeMark == "area" && context.LineOverlay) + { + sizeMark = "line"; + } + else if (sizeMark == "area" && context.PointOverlay) + { + sizeMark = "point"; + } + + switch (sizeMark) { case "bar" or "tick": return (scale.GetNumber("scale.minBandSize") ?? 2, scale.GetNumber("scale.maxBandSize") ?? (context.MinStep - 1)); @@ -1994,6 +2009,12 @@ private sealed record Context /// Gets the mark type. public required string MarkType { get; init; } + /// Gets a value indicating whether the mark has a point overlay, whose points draw the channels of a point mark (a shape on a line, for example). + public bool PointOverlay { get; init; } + + /// Gets a value indicating whether the mark (an area) has a line overlay, which draws the channels of a line mark (its size as the width and its strokeDash). + public bool LineOverlay { get; init; } + /// Gets the inferred orientation of the mark. public string? Orient { get; init; } diff --git a/src/DemaConsulting.CanvasNet.VegaLite/SpecModel/FeatureCatalog.cs b/src/DemaConsulting.CanvasNet.VegaLite/SpecModel/FeatureCatalog.cs index 8cc464db1..1adf3f330 100644 --- a/src/DemaConsulting.CanvasNet.VegaLite/SpecModel/FeatureCatalog.cs +++ b/src/DemaConsulting.CanvasNet.VegaLite/SpecModel/FeatureCatalog.cs @@ -173,12 +173,17 @@ internal static class FeatureCatalog /// Lists the recognized-but-unsupported constructs of a specification. /// /// The parsed specification. Must not be null. + /// + /// The effective configuration (defaults, specification and the caller's configuration), or null to read the configuration of the specification alone. The decisions that depend on + /// the configuration of the renderer (whether a path mark has a point overlay, which says whether a shape is drawn) use it, so a rendering with a caller's configuration + /// reports what it draws. + /// /// The reports in document order; empty when the specification uses only supported constructs. /// Thrown when is null. - public static IReadOnlyList Visit(SpecTree tree) + public static IReadOnlyList Visit(SpecTree tree, ResolvedConfig? config = null) { ArgumentNullException.ThrowIfNull(tree); - var walker = new Walker(tree); + var walker = new Walker(tree, config); walker.Run(); // LINQ's ordering is stable, so reports at one position keep the order in which they were found; a finding that several layers share (a channel of the encoding that @@ -265,11 +270,35 @@ private sealed class Walker /// The stack decision of the view whose encoding is visited (decided when it is first needed), or null outside an encoding. private Lazy? _stack; + /// The effective configuration, or null when only the configuration of the specification is read. + private readonly ResolvedConfig? _config; + /// /// Initializes a walker. /// /// The specification. - public Walker(SpecTree tree) => _tree = tree; + /// The effective configuration, or null. + public Walker(SpecTree tree, ResolvedConfig? config) + { + _tree = tree; + _config = config; + } + + /// + /// Reads the point or line that the configuration gives a mark type: the effective configuration when there is one, else the specification's own. + /// + /// The mark type. + /// The property, point or line. + /// The value, or null. + private ConfigNode? ConfiguredOverlay(string markType, string overlay) + { + if (_config is not null) + { + return _config.VegaLite[markType]?[overlay]; + } + + return _tree.Root["config"]?[markType]?[overlay] is { } node ? ConfigNode.FromSpec(node) : null; + } /// Gets the reports found so far, in the order they were found. public List Reports { get; } = []; @@ -803,6 +832,9 @@ private void VisitEncoding(SpecNode view, SpecNode encoding) var stackDecision = new Lazy(() => StackRules.Decide(markType, ScaleResolver.InferOrient(markType, mark?["orient"]?.AsString(), encoding), encoding)); _stack = stackDecision; var is2D = markType == "errorband" && encoding["x"] is { IsNull: false } && encoding["y"] is { IsNull: false }; + // The overlays of a path mark: the configuration is the effective one when the caller gave one (a rendering, see Visit), else that of the specification alone + var pointOverlay = SpecNormalizer.HasPointOverlay(markType, _mark, encoding, ConfiguredOverlay(markType, "point")); + var lineOverlay = SpecNormalizer.HasLineOverlay(markType, _mark, ConfiguredOverlay(markType, "line")); var drawnAs = markType switch { "boxplot" => "point", @@ -884,11 +916,22 @@ private void VisitEncoding(SpecNode view, SpecNode encoding) Unsupported(Id("channel", name), $"The '{name}' channel is not supported yet.", channel); } } - else if ((name is "shape" or "angle" or "strokeDash" or "text" or "theta" or "radius" or "theta2" or "radius2" || (name == "size" && markType is "area" or "arc")) && !ScaleResolver.ChannelIsDrawn(name, drawnAs)) + else if ((name is "shape" or "angle" or "strokeDash" or "text" or "theta" or "radius" or "theta2" or "radius2" || (name == "size" && markType is "area" or "arc")) && !ScaleResolver.ChannelIsDrawn(name, drawnAs) + && !(name == "shape" && pointOverlay)) { // The channel is supported, but the mark does not draw it (a shape needs a point, an angle a symbol or text, a dash a mark with a stroke line, a size a mark that has one, a text a text mark, - // an angle (theta) or radius a text or arc mark and their second ends an arc mark); the outliers of a boxplot are points - Unsupported(Id("channel", name), $"The '{name}' channel is not drawn by the '{markType}' mark; it is ignored.", channel); + // an angle (theta) or radius a text or arc mark and their second ends an arc mark); the outliers of a boxplot are points. A shape of a path mark with a point overlay is not reported: + // Vega-Lite drops it from the path layer before it checks the channels, and the overlay points draw it. An angle, a dash or a size is checked against the path mark as it is (Vega-Lite + // warns about it there), and the overlay marks still draw it: the points what a point draws, the line overlay of an area what a line draws. + var drawnByOverlay = name != "shape" && SpecNormalizer.OverlayDrawsChannel(name, pointOverlay, lineOverlay); + var overlayName = "line overlay"; + if (SpecNormalizer.OverlayDrawsChannel(name, pointOverlay, false)) + { + overlayName = SpecNormalizer.OverlayDrawsChannel(name, false, lineOverlay) ? "point and line overlays" : "point overlay"; + } + Unsupported(Id("channel", name), drawnByOverlay + ? $"The '{name}' channel is not drawn by the '{markType}' mark itself; only its {overlayName} draws it." + : $"The '{name}' channel is not drawn by the '{markType}' mark; it is ignored.", channel); } else if (channel.IsObject) { diff --git a/src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.PathOverlay.cs b/src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.PathOverlay.cs new file mode 100644 index 000000000..615540a4a --- /dev/null +++ b/src/DemaConsulting.CanvasNet.VegaLite/SpecModel/SpecNormalizer.PathOverlay.cs @@ -0,0 +1,198 @@ +// Portions derived from Vega-Lite (BSD-3-Clause): the path overlay normalizer (getPointOverlay); see third-party/README.md +using DemaConsulting.CanvasNet.VegaLite.Scales; + +namespace DemaConsulting.CanvasNet.VegaLite.SpecModel; + +/// +/// The rules of Vega-Lite's path overlay normalizer that more than one stage needs: whether a mark has a point overlay or a line overlay (an area) and +/// which channels the overlays draw. +/// +/// +/// +/// Vega-Lite splits a line, area, trail or rule that has an overlay into layers: the path (the mark without its point and line, +/// with every channel but shape), the line overlay of an area and the overlay point (each with every channel but x2 and y2). The shape channel is dropped from the path layer +/// before the channels are checked against the mark, so it raises no warning there; it is also what getPointOverlay reads to switch the overlay on +/// when the mark definition does not say (point is missing) and the configuration does not (config.<mark>.point). +/// +/// +/// Every other channel goes to all the layers, so each is checked against the path mark (which warns about a channel it does not draw) and drawn by the overlay marks +/// when they draw it: the scales of such a channel are built for the overlays even though the path mark has no use for them (the size and the strokeDash of an area +/// are the width and the dash of its line overlay, the shape, angle and size those of its points). +/// +/// +internal static partial class SpecNormalizer +{ + /// The marks that have a point overlay (area also has a line overlay). + private static readonly HashSet PointOverlayMarks = ["line", "area", "trail", "rule"]; + + /// + /// Tells whether a configuration value is truthy as JavaScript sees it. + /// + /// The value. + /// for true, a number other than zero, a text that is not empty, an object and an array. + public static bool IsTruthyConfig(ConfigNode node) + { + ArgumentNullException.ThrowIfNull(node); + return node.Kind switch + { + ConfigNodeKind.Boolean => node.BoolValue, + ConfigNodeKind.Number => node.NumberValue != 0 && !double.IsNaN(node.NumberValue), + ConfigNodeKind.String => node.StringValue!.Length > 0, + ConfigNodeKind.Array or ConfigNodeKind.Object => true, + _ => false, + }; + } + + /// + /// Tells whether the encoding has a shape channel, which switches the point overlay of a path mark on (the encoding.shape of getPointOverlay). + /// + /// The encoding object, or null. + /// when the encoding has a shape definition. + public static bool HasShapeChannel(SpecNode? encoding) => encoding?["shape"] is { IsObject: true }; + + /// + /// Works out the point overlay of a mark (Vega-Lite's getPointOverlay and the overlay mark of PathOverlayNormalizer.run). + /// + /// The mark type. + /// The mark definition object, or null for a mark given by its name. + /// The encoding object, or null. + /// The point of config.<mark>, or null. + /// + /// The mark definition of the overlay: a point mark with opacity: 1, filled: true and the clip of the mark, whatever the overlay object adds to or replaces + /// ("transparent" is {"opacity": 0}). It exists for a line, area, trail or rule whose point is true, an object or "transparent", or is missing while + /// is truthy or the encoding has a shape; false and null switch the overlay off. Null when the mark has no point overlay. + /// + public static ConfigNode? PointOverlayDefinition(string markType, SpecNode? mark, SpecNode? encoding, ConfigNode? configPoint) + { + ArgumentNullException.ThrowIfNull(markType); + if (!PointOverlayMarks.Contains(markType)) + { + return null; + } + + ConfigNode overlay; + if (mark?["point"] is { } written) + { + var point = ConfigNode.FromSpec(written); + if (point is { Kind: ConfigNodeKind.String, StringValue: "transparent" }) + { + overlay = ConfigNode.Create(new Dictionary { ["opacity"] = ConfigNode.FromNumber(0) }); + } + else if (IsTruthyConfig(point)) + { + overlay = point.IsObject ? point : ConfigNode.EmptyObject; + } + else + { + return null; + } + } + else if (configPoint is not null && IsTruthyConfig(configPoint)) + { + overlay = configPoint.IsObject ? configPoint : ConfigNode.EmptyObject; + } + else if (HasShapeChannel(encoding)) + { + // An encoding with a shape channel enables the overlay when neither the mark nor the configuration says anything about it + overlay = ConfigNode.EmptyObject; + } + else + { + return null; + } + + var defaults = new Dictionary(StringComparer.Ordinal) + { + ["opacity"] = ConfigNode.FromNumber(1), + ["filled"] = ConfigNode.FromBoolean(true), + }; + if (mark?["clip"] is { } clip) + { + defaults["clip"] = ConfigNode.FromSpec(clip); + } + + return ConfigNode.Merge(ConfigNode.Create(defaults), overlay); + } + + /// + /// Works out the line overlay of an area (Vega-Lite's getLineOverlay and the overlay mark of PathOverlayNormalizer.run). + /// + /// The mark type. + /// The mark definition object, or null for a mark given by its name. + /// The line of config.area, or null. + /// + /// The mark definition of the overlay: a line mark with the clip, interpolate and tension of the area, whatever the overlay object adds to or replaces. It exists for an + /// area whose line is true or an object, or is missing while is truthy; false and null switch it off. Null when the mark has no line overlay. + /// + public static ConfigNode? LineOverlayDefinition(string markType, SpecNode? mark, ConfigNode? configLine) + { + ArgumentNullException.ThrowIfNull(markType); + if (markType != "area") + { + return null; + } + + ConfigNode overlay; + if (mark?["line"] is { } written) + { + var line = ConfigNode.FromSpec(written); + if (!IsTruthyConfig(line)) + { + return null; + } + + overlay = line.IsObject ? line : ConfigNode.EmptyObject; + } + else if (configLine is not null && IsTruthyConfig(configLine)) + { + overlay = configLine.IsObject ? configLine : ConfigNode.EmptyObject; + } + else + { + return null; + } + + var defaults = new Dictionary(StringComparer.Ordinal); + foreach (var name in new[] { "clip", "interpolate", "tension" }) + { + if (mark?[name] is { } inherited) + { + defaults[name] = ConfigNode.FromSpec(inherited); + } + } + + return ConfigNode.Merge(ConfigNode.Create(defaults), overlay); + } + + /// + /// Tells whether a mark has a point overlay (see ). + /// + /// The mark type. + /// The mark definition object, or null for a mark given by its name. + /// The encoding object, or null. + /// The point of config.<mark>, or null. + /// when the mark has a point overlay. + public static bool HasPointOverlay(string markType, SpecNode? mark, SpecNode? encoding, ConfigNode? configPoint) => + PointOverlayDefinition(markType, mark, encoding, configPoint) is not null; + + /// + /// Tells whether an area has a line overlay (see ). + /// + /// The mark type. + /// The mark definition object, or null for a mark given by its name. + /// The line of config.area, or null. + /// when the mark has a line overlay. + public static bool HasLineOverlay(string markType, SpecNode? mark, ConfigNode? configLine) => + LineOverlayDefinition(markType, mark, configLine) is not null; + + /// + /// Tells whether the overlays of a path mark draw a channel: the overlay points draw what a point mark draws, and the line overlay of an area what a line draws + /// (Vega-Lite gives both overlay layers the whole encoding, so each keeps what its mark supports). + /// + /// The channel. + /// Whether the mark has a point overlay. + /// Whether the mark has a line overlay. + /// when an overlay draws the channel. + public static bool OverlayDrawsChannel(string channel, bool pointOverlay, bool lineOverlay) => + (pointOverlay && ScaleResolver.ChannelIsDrawn(channel, "point")) || (lineOverlay && ScaleResolver.ChannelIsDrawn(channel, "line")); +} diff --git a/src/DemaConsulting.CanvasNet.VegaLite/VegaLiteDocument.Render.cs b/src/DemaConsulting.CanvasNet.VegaLite/VegaLiteDocument.Render.cs index fe828df7a..a7dd5bd93 100644 --- a/src/DemaConsulting.CanvasNet.VegaLite/VegaLiteDocument.Render.cs +++ b/src/DemaConsulting.CanvasNet.VegaLite/VegaLiteDocument.Render.cs @@ -182,7 +182,7 @@ private T Run(VegaLiteRenderOptions options, CancellationToken cancellationTo T result; try { - result = finish(BuildPlan(plan, sink, cancellationToken)); + result = finish(BuildPlan(plan, options, sink, cancellationToken)); } catch { @@ -485,7 +485,7 @@ private ChartPlan PrepareChartOrReport(VegaLiteRenderOptions options, Cancellati var sink = new VegaLiteReportSink(options.Limits.MaxDiagnostics, options.ThrowOnUnsupportedFeature); try { - RecordReports(sink, cancellationToken); + RecordReports(options, sink, cancellationToken); // The findings of the data stage come after those of the specification, as when the chart renders foreach (var warning in dataWarnings) @@ -507,12 +507,13 @@ private ChartPlan PrepareChartOrReport(VegaLiteRenderOptions options, Cancellati /// /// Records the findings of the specification model in the sink, in document order. /// + /// The effective options (the caller's configuration decides the reports that depend on it). /// The sink. /// The token that stops the work. /// Thrown in strict mode at the first unsupported feature. - private void RecordReports(VegaLiteReportSink sink, CancellationToken cancellationToken) + private void RecordReports(VegaLiteRenderOptions options, VegaLiteReportSink sink, CancellationToken cancellationToken) { - foreach (var report in Reports) + foreach (var report in ReportsFor(options)) { cancellationToken.ThrowIfCancellationRequested(); if (report.Kind == FeatureReportKind.Warning) @@ -535,13 +536,14 @@ private void RecordReports(VegaLiteReportSink sink, CancellationToken cancellati /// draw yet are, with their stable identifiers. /// /// The prepared plan. + /// The effective options (the caller's configuration decides the reports that depend on it). /// The sink that records the reports. /// The token that stops the work. /// The plan. - private ChartPlan BuildPlan(ChartPlan plan, VegaLiteReportSink sink, CancellationToken cancellationToken) + private ChartPlan BuildPlan(ChartPlan plan, VegaLiteRenderOptions options, VegaLiteReportSink sink, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); - RecordReports(sink, cancellationToken); + RecordReports(options, sink, cancellationToken); // The data stage's own findings follow those of the specification text foreach (var warning in plan.DataWarnings ?? []) diff --git a/src/DemaConsulting.CanvasNet.VegaLite/VegaLiteDocument.cs b/src/DemaConsulting.CanvasNet.VegaLite/VegaLiteDocument.cs index 931bd7cd9..cbd48c51a 100644 --- a/src/DemaConsulting.CanvasNet.VegaLite/VegaLiteDocument.cs +++ b/src/DemaConsulting.CanvasNet.VegaLite/VegaLiteDocument.cs @@ -156,6 +156,30 @@ private VegaLiteDocument(SpecTree tree, VegaLiteOpenOptions options) /// internal IReadOnlyList Reports { get; } + /// + /// Gets the findings about the text for a rendering with the given options. + /// + /// + /// Without a caller's these are . With one, the catalog is visited again with the effective configuration, so that the + /// findings that depend on the configuration (whether a path mark has a point overlay, which says whether its shape is drawn) are those of what the renderer draws. + /// + /// The effective options. + /// The reports in document order. + internal IReadOnlyList ReportsFor(VegaLiteRenderOptions options) + { + if (options.Config is null) + { + return Reports; + } + + return _tree.Warnings + .Concat(FeatureCatalog.Visit(_tree, ConfigResolver.Resolve(_tree, options.Config))) + .OrderBy(r => r.Location.Line) + .ThenBy(r => r.Location.Column) + .ToList() + .AsReadOnly(); + } + /// /// Parses Vega-Lite specification text. /// diff --git a/src/DemaConsulting.CanvasNet.VegaLite/third-party/README.md b/src/DemaConsulting.CanvasNet.VegaLite/third-party/README.md index f5cd9b972..ee9392c16 100644 --- a/src/DemaConsulting.CanvasNet.VegaLite/third-party/README.md +++ b/src/DemaConsulting.CanvasNet.VegaLite/third-party/README.md @@ -321,7 +321,7 @@ projects that apply to the file). | Vega-Lite | `src/compile/mark/encode/position-point.ts`, `position-rect.ts`, `position-range.ts`, `valueref.ts` | the point, the polar span and the range position of the marks, the middle of a slice (`bandPosition`), the interpolation of a stacked value | | Vega-Lite | `src/compile/mark/encode/text.ts`, `src/compile/format.ts` | the text of a row: the number, time, binned and plain formats | | Vega-Lite | `src/compile/mark/init.ts` | the orientation of the marks that follow the measure or the time | -| Vega-Lite | `src/normalize/pathoverlay.ts` | the point and the line overlay of a path mark: which marks have them and the overlay mark definitions | +| Vega-Lite | `src/normalize/pathoverlay.ts` | the point and the line overlay of a path mark: which marks have them, the overlay mark definitions, the `shape` channel that switches the point overlay on, and the channels that the overlay points draw (`SpecNormalizer.PathOverlay.cs`) | | Vega-Lite | `src/compile/data/parse.ts`, `src/compile/data/impute.ts`, `src/compile/data/stack.ts` | the order of the implicit transforms, the implicit impute of a stacked path mark and the impute of an encoding | | Vega-Lite | `src/compile/scale/properties.ts`, `range.ts`, `type.ts`, `src/scale.ts` | the zero rule, the ranges and the types of the polar scales | | Vega-Lite | `src/compile/legend/encode.ts` | the legend symbol of a path mark (the symbol of a trail is stroked and not filled) | @@ -333,7 +333,7 @@ property and are not accepted; the curve `bundle` is not drawn for an area (a sp area is drawn with `linear`); the arc outline is a total function (an input that is not finite or whose magnitude is above 1e9 gives an empty path); two coincident points of a trail start their circle with a move rather than with a line; the invalid-data modes `show` and `null` are reported and not applied, and the scale domains are never filtered -by the invalid-data mode; the overlay points are not enabled by a `shape` channel; the implicit impute of a stacked path +by the invalid-data mode; the implicit impute of a stacked path mark is skipped for a binned dimension; a text longer than the string limit is an error; and the number of labels, the text length, the segments and the scene items are bounded by the render limits. diff --git a/test/DemaConsulting.CanvasNet.VegaLite.Tests/Marks/MarkBuilderOverlayTests.cs b/test/DemaConsulting.CanvasNet.VegaLite.Tests/Marks/MarkBuilderOverlayTests.cs index 39be65c23..eae949d75 100644 --- a/test/DemaConsulting.CanvasNet.VegaLite.Tests/Marks/MarkBuilderOverlayTests.cs +++ b/test/DemaConsulting.CanvasNet.VegaLite.Tests/Marks/MarkBuilderOverlayTests.cs @@ -172,4 +172,160 @@ public void MarkBuilder_Build_OverlayFromConfigAndTransparentPoints() var points = ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("""{ "type": "line", "point": true }""", colored, rows), 300, 200), "mark-point"); Assert.Equal([Blue, Orange], points.Select(p => p.Fill)); } + + /// The rows of two groups, a and b, of two points each. + private const string TwoGroups = """[ { "x": 0, "y": 1, "g": "a" }, { "x": 1, "y": 2, "g": "a" }, { "x": 0, "y": 3, "g": "b" }, { "x": 1, "y": 4, "g": "b" } ]"""; + + /// The position channels with a color and a shape that both follow the group. + private const string ColorAndShape = """ + { "x": { "field": "x", "type": "quantitative" }, "y": { "field": "y", "type": "quantitative" }, + "color": { "field": "g", "type": "nominal" }, "shape": { "field": "g", "type": "nominal" } } + """; + + /// + /// Validates that the shape channel of a line with a point overlay shapes the overlay points of each group and leaves the paths alone (Vega-Lite drops the shape from + /// the path layer and keeps it in the overlay): a circle for the first group, a square for the second, colored by the group, and one path for each group. + /// + [Fact] + public void MarkBuilder_Build_ShapeChannelOfALineShapesTheOverlayPoints() + { + // Act + var group = ChartTestHelpers.Marks(Chart("""{ "type": "line", "point": true }""", ColorAndShape, TwoGroups), 300, 200); + + // Assert: two lines (one for each group; the shape does not split them further) and four points + Assert.Equal(["mark-line", "mark-line", "mark-point", "mark-point", "mark-point", "mark-point"], group.Children.Select(c => c.Role)); + Assert.Equal([Blue, Orange], ChartTestHelpers.Of(group, "mark-line").Select(l => l.Stroke)); + + // Assert: the points of the first group are circles, those of the second squares, with the colors of the groups + var points = ChartTestHelpers.Of(group, "mark-point"); + Assert.Equal(["circle", "circle", "square", "square"], points.Select(p => p.Shape)); + Assert.Equal([Blue, Blue, Orange, Orange], points.Select(p => p.Fill)); + + // Assert: a point overlay object works the same + var custom = ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("""{ "type": "line", "point": { "size": 100 } }""", ColorAndShape, TwoGroups), 300, 200), "mark-point"); + Assert.Equal(["circle", "circle", "square", "square"], custom.Select(p => p.Shape)); + Assert.All(custom, p => Assert.Equal(100.0, p.Size)); + + // Assert: a shape that is not driven by a field is the shape of every point + const string fixedShape = """{ "x": { "field": "x", "type": "quantitative" }, "y": { "field": "y", "type": "quantitative" }, "shape": { "value": "diamond" } }"""; + Assert.All(ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("""{ "type": "line", "point": true }""", fixedShape, TwoGroups), 300, 200), "mark-point"), p => Assert.Equal("diamond", p.Shape)); + } + + /// + /// Validates that a shape channel switches the point overlay on when neither the mark nor the configuration says anything about it (Vega-Lite's getPointOverlay), + /// and that point: false (or null) keeps the overlay off, which leaves the shape unused. + /// + [Fact] + public void MarkBuilder_Build_ShapeChannelEnablesThePointOverlayUnlessSwitchedOff() + { + // Assert: a line, a trail and an area with a shape and no point get the overlay + Assert.Equal(["circle", "circle", "square", "square"], ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("\"line\"", ColorAndShape, TwoGroups), 300, 200), "mark-point").Select(p => p.Shape)); + Assert.Equal(4, ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("\"trail\"", ColorAndShape, TwoGroups), 300, 200), "mark-point").Count); + Assert.Equal(4, ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("\"area\"", ColorAndShape, TwoGroups), 300, 200), "mark-point").Count); + + // Assert: a point of false or null leaves the line alone, with no symbols + Assert.Empty(ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("""{ "type": "line", "point": false }""", ColorAndShape, TwoGroups), 300, 200), "mark-point")); + Assert.Empty(ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("""{ "type": "line", "point": null }""", ColorAndShape, TwoGroups), 300, 200), "mark-point")); + + // Assert: a point mark is not an overlay mark (its shape is its own) + Assert.Equal(["circle", "circle", "square", "square"], ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("\"point\"", ColorAndShape, TwoGroups), 300, 200), "mark-point").Select(p => p.Shape)); + } + + /// + /// Validates the point overlay of an area (whether given by point, by the line overlay together with a shape, or by the configuration): the overlay points take the + /// shape, and the area itself is drawn as before, with the reduced opacity of an area that has an overlay. + /// + [Fact] + public void MarkBuilder_Build_ShapeChannelOfAnAreaShapesTheOverlayPoints() + { + // Act: an area with the point overlay + var group = ChartTestHelpers.Marks(Chart("""{ "type": "area", "point": true }""", ColorAndShape, TwoGroups), 300, 200); + + // Assert: the areas of the two groups, then the points shaped by their group + Assert.Equal(["mark-area", "mark-area", "mark-point", "mark-point", "mark-point", "mark-point"], group.Children.Select(c => c.Role)); + Assert.Equal(["circle", "circle", "square", "square"], ChartTestHelpers.Of(group, "mark-point").Select(p => p.Shape)); + Assert.All(ChartTestHelpers.Of(group, "mark-area"), a => Assert.Equal(0.7, a.Opacity)); + + // Act / Assert: the line overlay alone leaves the point overlay to the shape, which switches it on + var withLine = ChartTestHelpers.Marks(Chart("""{ "type": "area", "line": true }""", ColorAndShape, TwoGroups), 300, 200); + Assert.Equal(["mark-area", "mark-area", "mark-line", "mark-line", "mark-point", "mark-point", "mark-point", "mark-point"], withLine.Children.Select(c => c.Role)); + Assert.Equal(["circle", "circle", "square", "square"], ChartTestHelpers.Of(withLine, "mark-point").Select(p => p.Shape)); + + // Act / Assert: the overlay of the configuration works the same + var configured = ChartTestHelpers.Marks(Chart("\"area\"", ColorAndShape, TwoGroups, """{ "area": { "point": true } }"""), 300, 200); + Assert.Equal(["circle", "circle", "square", "square"], ChartTestHelpers.Of(configured, "mark-point").Select(p => p.Shape)); + + // Assert: switched off, the area is drawn alone and opaque + var off = ChartTestHelpers.Marks(Chart("""{ "type": "area", "point": false }""", ColorAndShape, TwoGroups), 300, 200); + Assert.Equal(["mark-area", "mark-area"], off.Children.Select(c => c.Role)); + Assert.All(ChartTestHelpers.Of(off, "mark-area"), a => Assert.Equal(1.0, a.Opacity)); + } + + /// + /// Validates that the other channels of a point mark that the path mark does not draw reach the overlay points too: the size of an area (with the range of a point) and + /// the strokeDash of an area; the angle of a line only when it has an overlay. + /// + [Fact] + public void MarkBuilder_Build_PointChannelsOfThePathMarkReachTheOverlayPoints() + { + // Act: an area whose points are sized by a field + const string sized = """ + { "x": { "field": "x", "type": "quantitative" }, "y": { "field": "y", "type": "quantitative", "stack": null }, "size": { "field": "y", "type": "quantitative" } } + """; + var points = ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("""{ "type": "area", "point": true }""", sized, Basic), 300, 200), "mark-point"); + + // Assert: the sizes grow with the field (the scale has the range of a point: from 4 square pixels up) + Assert.Equal(3, points.Count); + Assert.True(points[0].Size < points[2].Size && points[2].Size < points[1].Size); + Assert.Equal(4.0, points[0].Size); + + // Act / Assert: an angle turns the points of a line with an overlay, and has no effect on a line without + const string turned = """ + { "x": { "field": "x", "type": "quantitative" }, "y": { "field": "y", "type": "quantitative" }, "angle": { "field": "y", "type": "quantitative" } } + """; + var angled = ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("""{ "type": "line", "point": true }""", turned, Basic), 300, 200), "mark-point"); + Assert.Equal(3, angled.Count); + Assert.Equal(3, angled.Select(p => p.Angle).Distinct().Count()); + } + + /// + /// Validates that the line overlay of an area draws the channels of a line (Vega-Lite gives the line layer the whole encoding): the strokeDash of the groups dashes the line + /// of each group (the area has none), and a size that is constant in a group is the width of its line, with the range of the stroke widths and not that of a symbol. + /// + [Fact] + public void MarkBuilder_Build_LineOverlayOfAnAreaDrawsTheSizeAndTheDashOfTheEncoding() + { + // Arrange: two groups with a width each (the size groups the line, as it does a line mark) + const string rows = """ + [ { "x": 0, "y": 1, "g": "a", "w": 1 }, { "x": 1, "y": 2, "g": "a", "w": 1 }, { "x": 0, "y": 3, "g": "b", "w": 3 }, { "x": 1, "y": 4, "g": "b", "w": 3 } ] + """; + const string dashed = """ + { "x": { "field": "x", "type": "quantitative" }, "y": { "field": "y", "type": "quantitative" }, "strokeDash": { "field": "g", "type": "nominal" } } + """; + const string widths = """ + { "x": { "field": "x", "type": "quantitative" }, "y": { "field": "y", "type": "quantitative" }, "detail": { "field": "g" }, "size": { "field": "w", "type": "quantitative" } } + """; + + // Act: the line overlay alone (the points are switched off) + var group = ChartTestHelpers.Marks(Chart("""{ "type": "area", "line": true, "point": false }""", dashed, rows), 300, 200); + + // Assert: the areas have no dash; the lines have the dash of their group, which differ + Assert.Equal(["mark-area", "mark-area", "mark-line", "mark-line"], group.Children.Select(c => c.Role)); + Assert.All(ChartTestHelpers.Of(group, "mark-area"), a => Assert.Null(a.StrokeDash)); + var lines = ChartTestHelpers.Of(group, "mark-line"); + Assert.All(lines, l => Assert.NotNull(l.StrokeDash)); + Assert.NotEqual(lines[0].StrokeDash, lines[1].StrokeDash); + + // Act: the widths + var wide = ChartTestHelpers.Of(ChartTestHelpers.Marks(Chart("""{ "type": "area", "line": true, "point": false }""", widths, rows), 300, 200), "mark-line"); + + // Assert: two lines, the width of each from the stroke width range (1 to 4) and growing with the size + Assert.Equal(2, wide.Count); + Assert.True(wide[0].StrokeWidth < wide[1].StrokeWidth); + Assert.All(wide, l => Assert.InRange(l.StrokeWidth ?? 0, 1.0, 4.0)); + + // Act / Assert: without a line overlay the same encoding draws only the areas, which keep their own look + var plain = ChartTestHelpers.Marks(Chart("""{ "type": "area", "line": false, "point": false }""", dashed, rows), 300, 200); + Assert.Equal(["mark-area", "mark-area"], plain.Children.Select(c => c.Role)); + } } diff --git a/test/DemaConsulting.CanvasNet.VegaLite.Tests/Scales/MarkChannelGatingTests.cs b/test/DemaConsulting.CanvasNet.VegaLite.Tests/Scales/MarkChannelGatingTests.cs index aa0d3af91..3032bb724 100644 --- a/test/DemaConsulting.CanvasNet.VegaLite.Tests/Scales/MarkChannelGatingTests.cs +++ b/test/DemaConsulting.CanvasNet.VegaLite.Tests/Scales/MarkChannelGatingTests.cs @@ -1,5 +1,6 @@ using DemaConsulting.CanvasNet.VegaLite.Data; using DemaConsulting.CanvasNet.VegaLite.Scales; +using DemaConsulting.CanvasNet.VegaLite.Scenegraph; using DemaConsulting.CanvasNet.VegaLite.SpecModel; namespace DemaConsulting.CanvasNet.VegaLite.Tests.Scales; @@ -104,7 +105,7 @@ public void FeatureCatalog_Visit_ReportsChannelsThatTheMarkDoesNotDraw() Assert.Equal(["vl-channel-strokedash"], ChannelReports("trail", """ "strokeDash": {"field":"v","type":"nominal"} """)); Assert.Equal(["vl-channel-strokedash"], ChannelReports("text", """ "strokeDash": {"value": [2, 2]} """)); Assert.Equal(["vl-channel-strokedash"], ChannelReports("area", """ "strokeDash": {"field":"v","type":"nominal"} """)); - Assert.Equal(["vl-channel-shape"], ChannelReports("line", """ "shape": {"field":"v","type":"nominal"} """)); + Assert.Equal(["vl-channel-shape"], ChannelReports("line", """ "shape": {"field":"v","type":"nominal"} """, overlay: false)); Assert.Equal(["vl-channel-angle"], ChannelReports("line", """ "angle": {"field":"v","type":"quantitative"} """)); // Assert: the drawn channels are not reported @@ -146,21 +147,223 @@ public void SpecParser_Parse_EvaluatesSizeConditionsOfMarksThatUseASize() Assert.True(ChannelDefinitions.CanCondition("angle")); } + /// + /// Validates that the point overlay of a path mark makes the scales of the channels that its points draw (Vega-Lite gives the overlay layer every channel but the second ends + /// of the positions): a shape of a line or an area, an angle of a line, a size of an area (with the range of a point) and a dash of a trail, and that without an overlay none of them has a scale. + /// + [Fact] + public void ScaleResolver_Resolve_PointOverlayBuildsTheScalesOfThePointChannels() + { + // Arrange: (mark, channel, field type, has a scale) + var vectors = new (string Mark, string Channel, string Type, bool HasScale)[] + { + ("""{"type":"line","point":true}""", "shape", "nominal", true), + ("""{"type":"line","point":{"size":80}}""", "shape", "nominal", true), + ("""{"type":"line","point":"transparent"}""", "shape", "nominal", true), + ("\"line\"", "shape", "nominal", true), + ("\"trail\"", "shape", "nominal", true), + ("""{"type":"area","line":true}""", "shape", "nominal", true), + ("""{"type":"area","point":true}""", "shape", "nominal", true), + ("""{"type":"line","point":false}""", "shape", "nominal", false), + ("""{"type":"line","point":null}""", "shape", "nominal", false), + ("""{"type":"area","point":false}""", "shape", "nominal", false), + ("""{"type":"arc","point":true}""", "shape", "nominal", false), + ("""{"type":"line","point":true}""", "angle", "quantitative", true), + ("""{"type":"line","point":false}""", "angle", "quantitative", false), + ("""{"type":"area","point":true}""", "size", "quantitative", true), + ("""{"type":"area","point":false}""", "size", "quantitative", false), + ("""{"type":"trail","point":true}""", "strokeDash", "nominal", true), + ("""{"type":"area","point":true}""", "strokeDash", "nominal", true), + ("""{"type":"area","point":true}""", "text", "nominal", false), + ("""{"type":"area","line":true,"point":false}""", "size", "quantitative", true), + ("""{"type":"area","line":true,"point":false}""", "strokeDash", "nominal", true), + ("""{"type":"area","line":{"color":"red"},"point":false}""", "size", "quantitative", true), + ("""{"type":"area","line":true,"point":false}""", "shape", "nominal", false), + ("""{"type":"area","line":true,"point":false}""", "angle", "quantitative", false), + ("""{"type":"area","line":false,"point":false}""", "size", "quantitative", false), + ("""{"type":"area","line":null,"point":false}""", "strokeDash", "nominal", false), + ("""{"type":"trail","line":true,"point":false}""", "strokeDash", "nominal", false), + }; + + // Act / Assert + foreach (var (mark, channel, type, hasScale) in vectors) + { + var tree = SpecParser.Parse( + "{\"data\": {\"values\": [{\"f\": 1, \"g\": \"a\"}, {\"f\": 2, \"g\": \"b\"}]}, \"mark\": " + mark + ", \"encoding\": {\"" + + channel + "\": {\"field\": \"" + (type == "nominal" ? "g" : "f") + "\", \"type\": \"" + type + "\"}}}"); + var table = DataLoader.Load(tree.Root["data"], tree.SourceName, null, TestContext.Current.CancellationToken); + var scales = ScaleResolver.Resolve(tree.Root, table, ConfigResolver.Resolve(tree, null), tree.SourceName, null, TestContext.Current.CancellationToken); + Assert.True(hasScale == (scales[channel] is not null), $"The '{channel}' scale of {mark}: expected {hasScale}."); + } + + // Assert: the shape scale of a line with an overlay has the groups of the field as its domain; a falsy configuration of the point leaves the decision to the shape + var configured = SpecParser.Parse("{\"data\": {\"values\": [{\"g\": \"a\"}, {\"g\": \"b\"}]}, \"mark\": \"line\", \"encoding\": {\"shape\": {\"field\": \"g\", \"type\": \"nominal\"}}, \"config\": {\"line\": {\"point\": false}}}"); + var configuredTable = DataLoader.Load(configured.Root["data"], configured.SourceName, null, TestContext.Current.CancellationToken); + var shaped = ScaleResolver.Resolve(configured.Root, configuredTable, ConfigResolver.Resolve(configured, null), configured.SourceName, null, TestContext.Current.CancellationToken); + Assert.Equal(["a", "b"], shaped["shape"]!.DiscreteDomain.Select(d => d.Text)); + + // Assert: the line overlay of the configuration builds the scales of the line too; the size of an area then has the range of the stroke widths of its line (not that of a symbol) + var area = SpecParser.Parse("{\"data\": {\"values\": [{\"f\": 1}, {\"f\": 2}]}, \"mark\": {\"type\": \"area\", \"point\": false}, \"encoding\": {\"size\": {\"field\": \"f\", \"type\": \"quantitative\"}}, \"config\": {\"area\": {\"line\": true}}}"); + var areaTable = DataLoader.Load(area.Root["data"], area.SourceName, null, TestContext.Current.CancellationToken); + var lineSize = ScaleResolver.Resolve(area.Root, areaTable, ConfigResolver.Resolve(area, null), area.SourceName, null, TestContext.Current.CancellationToken)["size"]; + Assert.NotNull(lineSize); + Assert.Equal(4.0, lineSize.CreateModel(0).Map(2.0)); + } + + /// + /// Validates the reports of the feature catalog for the channels of a path mark with a point overlay: a shape is not reported (Vega-Lite drops it from the path layer), while a + /// size of an area, a dash of an area or a trail and an angle of a line are (the path layer warns about them), with a message that says that the points draw them; and that + /// a path mark without an overlay (point: false) still reports the shape. + /// + [Fact] + public void FeatureCatalog_Visit_ShapeOfAPathMarkWithAPointOverlayIsNotReported() + { + // Assert: no report for the shape, whatever way the overlay is switched on + const string shape = """ "shape": {"field":"v","type":"nominal"} """; + Assert.Empty(ChannelReports("""{"type":"line","point":true}""", shape)); + Assert.Empty(ChannelReports("""{"type":"line","point":{"color":"red"}}""", shape)); + Assert.Empty(ChannelReports("""{"type":"line","point":"transparent"}""", shape)); + Assert.Empty(ChannelReports("\"line\"", shape)); + Assert.Empty(ChannelReports("""{"type":"trail"}""", shape)); + Assert.Empty(ChannelReports("""{"type":"rule"}""", shape)); + Assert.Empty(ChannelReports("""{"type":"area","point":true}""", shape)); + Assert.Empty(ChannelReports("""{"type":"area","line":true}""", shape)); + + // Assert: the shape is still reported without an overlay, and on the marks that have none + Assert.Equal(["vl-channel-shape"], ChannelReports("""{"type":"line","point":false}""", shape)); + Assert.Equal(["vl-channel-shape"], ChannelReports("""{"type":"line","point":null}""", shape)); + Assert.Equal(["vl-channel-shape"], ChannelReports("""{"type":"area","point":false}""", shape)); + Assert.Equal(["vl-channel-shape"], ChannelReports("\"bar\"", shape)); + Assert.Equal(["vl-channel-shape"], ChannelReports("\"arc\"", shape)); + + // Assert: the overlay of the configuration of the specification counts as well + var configured = FeatureCatalog.Visit(SpecParser.Parse(""" + { "data": { "values": [ { "v": "a" } ] }, "mark": { "type": "line", "point": false }, "config": { "line": { "point": true } }, + "encoding": { "shape": { "field": "v", "type": "nominal" } } } + """)); + Assert.Contains(configured, r => r.Id == "vl-channel-shape"); + var enabled = FeatureCatalog.Visit(SpecParser.Parse(""" + { "data": { "values": [ { "v": "a" } ] }, "mark": "line", "config": { "line": { "point": true } }, + "encoding": { "shape": { "field": "v", "type": "nominal" } } } + """)); + Assert.DoesNotContain(enabled, r => r.Id == "vl-channel-shape"); + + // Assert: the channels that the path layer keeps are still reported, but they say that the points draw them + var angle = FeatureCatalog.Visit(SpecParser.Parse(Spec("""{"type":"line","point":true}""", """ "angle": {"field":"v","type":"quantitative"} """))).Single(r => r.Id == "vl-channel-angle"); + Assert.Contains("point overlay", angle.Message, StringComparison.Ordinal); + Assert.DoesNotContain("ignored", angle.Message, StringComparison.Ordinal); + Assert.Equal(["vl-channel-size"], ChannelReports("""{"type":"area","point":true}""", """ "size": {"field":"v","type":"quantitative"} """)); + Assert.Equal(["vl-channel-strokedash"], ChannelReports("""{"type":"trail","point":true}""", """ "strokeDash": {"field":"v","type":"nominal"} """)); + Assert.Contains("ignored", FeatureCatalog.Visit(SpecParser.Parse(Spec("\"line\"", """ "angle": {"field":"v","type":"quantitative"} """))).Single(r => r.Id == "vl-channel-angle").Message, StringComparison.Ordinal); + + // Assert: the line overlay of an area counts the same way: its size and its dash are drawn by the line, the message names the overlay that draws them + const string size = """ "size": {"field":"v","type":"quantitative"} """; + const string dash = """ "strokeDash": {"field":"v","type":"nominal"} """; + string Message(string mark, string channels, string id) => + FeatureCatalog.Visit(SpecParser.Parse(Spec(mark, channels))).Single(r => r.Id == id).Message; + var lineOnly = Message("""{"type":"area","line":true,"point":false}""", size, "vl-channel-size"); + Assert.Contains("line overlay", lineOnly, StringComparison.Ordinal); + Assert.DoesNotContain("point", lineOnly, StringComparison.Ordinal); + Assert.Contains("point and line overlays", Message("""{"type":"area","line":true,"point":true}""", dash, "vl-channel-strokedash"), StringComparison.Ordinal); + Assert.Contains("ignored", Message("""{"type":"area","line":false,"point":false}""", size, "vl-channel-size"), StringComparison.Ordinal); + Assert.Contains("ignored", Message("""{"type":"trail","line":true,"point":false}""", dash, "vl-channel-strokedash"), StringComparison.Ordinal); + } + + /// + /// Validates that the reports follow the configuration of the rendering when there is one: the angle of a line is drawn by the overlay points that config.line.point of the + /// caller enables (the message says so), and the size of an area by the line overlay that config.area.line enables, while the same specification visited without that + /// configuration reports them as ignored. + /// + [Fact] + public void FeatureCatalog_Visit_ReportsFollowTheEffectiveConfiguration() + { + // Arrange + var angle = SpecParser.Parse(Spec("\"line\"", """ "angle": {"field":"v","type":"quantitative"} """)); + var size = SpecParser.Parse(Spec("""{"type":"area","point":false}""", """ "size": {"field":"v","type":"quantitative"} """)); + + // Act / Assert: the specification alone has no overlay + Assert.Contains("ignored", FeatureCatalog.Visit(angle).Single(r => r.Id == "vl-channel-angle").Message, StringComparison.Ordinal); + Assert.Contains("ignored", FeatureCatalog.Visit(size).Single(r => r.Id == "vl-channel-size").Message, StringComparison.Ordinal); + + // Act / Assert: the effective configuration (with the caller's) enables them + var points = FeatureCatalog.Visit(angle, ConfigResolver.Resolve(angle, """{ "line": { "point": true } }""")).Single(r => r.Id == "vl-channel-angle"); + Assert.Contains("point overlay", points.Message, StringComparison.Ordinal); + var line = FeatureCatalog.Visit(size, ConfigResolver.Resolve(size, """{ "area": { "line": true } }""")).Single(r => r.Id == "vl-channel-size"); + Assert.Contains("line overlay", line.Message, StringComparison.Ordinal); + + // Assert: a shape is not reported either way (it switches the overlay on) + var shape = SpecParser.Parse(Spec("\"line\"", """ "shape": {"field":"v","type":"nominal"} """)); + Assert.Empty(FeatureCatalog.Visit(shape)); + Assert.Empty(FeatureCatalog.Visit(shape, ConfigResolver.Resolve(shape, """{ "line": { "point": true } }"""))); + } + + /// + /// Validates the legends of a line with a point overlay: a shape and a color of the same field are one legend whose symbols have the shapes and the colors of the groups, and a shape of + /// another field is a legend of its own. + /// + [Fact] + public void LegendPlan_Create_ShapeOfALineWithAPointOverlayHasALegendMergedWithTheColorOfTheSameField() + { + // Arrange + const string rows = """[ { "x": 0, "y": 1, "g": "a", "h": "p" }, { "x": 1, "y": 2, "g": "b", "h": "p" }, { "x": 2, "y": 3, "g": "c", "h": "q" } ]"""; + static string Json(string channels) => + "{ \"data\": { \"values\": " + rows + " }, \"mark\": { \"type\": \"line\", \"point\": true }, \"encoding\": { \"x\": { \"field\": \"x\", \"type\": \"quantitative\" }, \"y\": { \"field\": \"y\", \"type\": \"quantitative\" }, " + + channels + " } }"; + + // Act: the same field in both channels + var json = Json(""" + "color": { "field": "g", "type": "nominal" }, "shape": { "field": "g", "type": "nominal" } + """); + var merged = ChartTestHelpers.Legends(json); + + // Assert: one legend that holds the color and the shape + var legend = Assert.Single(merged); + Assert.Equal(["color", "shape"], legend.Members.Select(m => m.Channel)); + + // Assert: the symbols of the built legend have the shapes of the shape scale (a circle, a square, a triangle) and the colors of the groups + var symbols = Assert.IsType(ChartTestHelpers.Legend(json).Children[0]).Children.OfType().ToList(); + Assert.Equal(["circle", "square", "triangle-up"], symbols.Select(s => s.Shape)); + + // Assert: the symbols are filled with the colors of the groups, as the filled points of the overlay are (the stroke of the line does not make them hollow) + Assert.Equal(["#4c78a8", "#f58518", "#e45756"], symbols.Select(s => s.Fill)); + Assert.All(symbols, s => Assert.NotEqual(s.Fill, s.Stroke)); + + // Assert: an overlay object that says so keeps the points, and so the symbols, unfilled; an area with a point overlay is filled like a line + var hollowJson = json.Replace("\"point\": true", "\"point\": { \"filled\": false }", StringComparison.Ordinal); + var hollow = Assert.IsType(ChartTestHelpers.Legend(hollowJson).Children[0]).Children.OfType().ToList(); + Assert.Equal(["#4c78a8", "#f58518", "#e45756"], hollow.Select(s => s.Stroke)); + var areaJson = json.Replace("\"type\": \"line\"", "\"type\": \"area\"", StringComparison.Ordinal); + var areaSymbols = Assert.IsType(ChartTestHelpers.Legend(areaJson).Children[0]).Children.OfType().ToList(); + Assert.Equal(["#4c78a8", "#f58518", "#e45756"], areaSymbols.Select(s => s.Fill)); + Assert.Equal(["#4c78a8", "#f58518", "#e45756"], symbols.Select(s => s.Stroke ?? s.Fill)); + + // Act / Assert: another field for the shape is a legend of its own + var apart = ChartTestHelpers.Legends(Json(""" + "color": { "field": "g", "type": "nominal" }, "shape": { "field": "h", "type": "nominal" } + """)); + Assert.Equal(["color", "shape"], apart.Select(l => l.Members.Single().Channel)); + + // Act / Assert: without an overlay (point: false) the shape has no scale and so no legend + var off = ChartTestHelpers.Legends(json.Replace("\"point\": true", "\"point\": false", StringComparison.Ordinal)); + Assert.Equal(["color"], Assert.Single(off).Members.Select(m => m.Channel)); + } + /// /// Builds a specification of one mark over a tiny data set. /// - /// The mark. + /// The JSON text of the mark (a name in quotes or a mark definition). /// The properties of the encoding object, without the braces. /// The specification text. private static string Spec(string mark, string channels) => - "{\"data\": {\"values\": [{\"v\": 1}, {\"v\": 2}]}, \"mark\": \"" + mark + "\", \"encoding\": {" + channels + "}}"; + "{\"data\": {\"values\": [{\"v\": 1}, {\"v\": 2}]}, \"mark\": " + (mark.StartsWith('{') || mark.StartsWith('"') ? mark : "\"" + mark + "\"") + ", \"encoding\": {" + channels + "}}"; /// /// Lists the identifiers of the channel reports (vl-channel-*) of a one-mark specification. /// - /// The mark. + /// The JSON text of the mark (a name, or a name in quotes, or a mark definition). /// The properties of the encoding object, without the braces. + /// to switch the point overlay off ("point": false), which a shape channel would otherwise enable on a path mark; only for a mark given by its name. /// The identifiers in the order of the catalog. - private static string[] ChannelReports(string mark, string channels) => - [.. FeatureCatalog.Visit(SpecParser.Parse(Spec(mark, channels))).Where(r => r.Id.StartsWith("vl-channel-", StringComparison.Ordinal)).Select(r => r.Id)]; + private static string[] ChannelReports(string mark, string channels, bool overlay = true) => + [.. FeatureCatalog.Visit(SpecParser.Parse(Spec(overlay ? mark : "{\"type\": \"" + mark + "\", \"point\": false}", channels))).Where(r => r.Id.StartsWith("vl-channel-", StringComparison.Ordinal)).Select(r => r.Id)]; } diff --git a/test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/FeatureCatalogTests.cs b/test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/FeatureCatalogTests.cs index 6f8c3e6dd..8e1392a08 100644 --- a/test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/FeatureCatalogTests.cs +++ b/test/DemaConsulting.CanvasNet.VegaLite.Tests/SpecModel/FeatureCatalogTests.cs @@ -1644,7 +1644,7 @@ public void FeatureCatalog_Report_LineAreaTrailAreSupportedAndGeoshapeImageAreNo /// /// Validates which channels the path marks accept and which they report: x2 and y2 for an area with the channel they extend, size not for an area, - /// strokeDash not for an area and a trail, shape and angle never, and order and detail always. + /// strokeDash not for an area and a trail, shape not for a path mark whose point overlay is off, angle never, and order and detail always. /// [Fact] public void FeatureCatalog_Report_ChannelGatingFollowsTheSupportTable() @@ -1662,7 +1662,7 @@ public void FeatureCatalog_Report_ChannelGatingFollowsTheSupportTable() ("line", ", \"strokeDash\": { \"field\": \"c\", \"type\": \"nominal\" }", []), ("area", ", \"strokeDash\": { \"field\": \"c\", \"type\": \"nominal\" }", ["vl-channel-strokedash"]), ("trail", ", \"strokeDash\": { \"field\": \"c\", \"type\": \"nominal\" }", ["vl-channel-strokedash"]), - ("line", ", \"shape\": { \"field\": \"c\", \"type\": \"nominal\" }", ["vl-channel-shape"]), + ("line", ", \"shape\": { \"field\": \"c\", \"type\": \"nominal\" }", []), ("area", ", \"angle\": { \"field\": \"c\", \"type\": \"quantitative\" }", ["vl-channel-angle"]), ("line", ", \"detail\": [ { \"field\": \"c\" } ], \"order\": { \"field\": \"d\" }", []), ("area", ", \"detail\": { \"field\": \"c\" }, \"order\": [ { \"field\": \"d\" } ]", []), diff --git a/test/DemaConsulting.CanvasNet.VegaLite.Tests/VegaLiteLineAreaIntegrationTests.cs b/test/DemaConsulting.CanvasNet.VegaLite.Tests/VegaLiteLineAreaIntegrationTests.cs index f8f17fc71..cbf957738 100644 --- a/test/DemaConsulting.CanvasNet.VegaLite.Tests/VegaLiteLineAreaIntegrationTests.cs +++ b/test/DemaConsulting.CanvasNet.VegaLite.Tests/VegaLiteLineAreaIntegrationTests.cs @@ -429,6 +429,91 @@ public void CanvasNetVegaLite_SystemIntegration_Overlays_LinePointsAndAreaLineAr Assert.Equal(["#4c78a8", "#4c78a8", "#f58518", "#f58518"], Items(seriesScene, "mark-point").Select(p => p.Fill)); } + /// + /// Validates the shape channel of a line and an area with a point overlay in strict mode: nothing is reported (the shape is the overlay's), the points of each + /// series have the shape of the series and its color, the legend shows the shape with the color, and a line without an overlay still reports the shape. + /// + [Fact] + public void CanvasNetVegaLite_SystemIntegration_Overlays_ShapeChannelShapesTheOverlayPointsInStrictMode() + { + // Arrange / Act: two series, each with its color and its shape (strict mode throws on any report) + const string data = """ + [ { "x": 0, "y": 1, "g": "a" }, { "x": 1, "y": 2, "g": "a" }, { "x": 0, "y": 3, "g": "b" }, { "x": 1, "y": 4, "g": "b" } ] + """; + var encoding = Encoding(", \"color\": { \"field\": \"g\", \"type\": \"nominal\" }, \"shape\": { \"field\": \"g\", \"type\": \"nominal\" }"); + using var line = Draw(Chart("{ \"type\": \"line\", \"point\": true }", data, encoding), out var scene, out var warnings); + + // Assert: no report; two lines in the colors of the series; the points of a series have its shape and its color + Assert.Empty(warnings); + Assert.Equal(["#4c78a8", "#f58518"], Items(scene, "mark-line").Select(l => l.Stroke)); + var points = Items(scene, "mark-point"); + Assert.Equal(["circle", "circle", "square", "square"], points.Select(p => p.Shape)); + Assert.Equal(["#4c78a8", "#4c78a8", "#f58518", "#f58518"], points.Select(p => p.Fill)); + + // Assert: a legend of one title with the two entries, drawn with the shapes of the series + var legendSymbols = scene.Enumerate().Select(e => e.Item).OfType().Where(s => s.Role != "mark-point").ToList(); + Assert.Equal(["circle", "square"], legendSymbols.Select(s => s.Shape)); + + // Arrange / Act: an area with a point overlay, and the shape alone (it switches the overlay on) + using var area = Draw(Chart("{ \"type\": \"area\", \"point\": true }", data, Encoding(", \"color\": { \"field\": \"g\", \"type\": \"nominal\" }, \"shape\": { \"field\": \"g\", \"type\": \"nominal\" }")), out var areaScene, out var areaWarnings); + Assert.Empty(areaWarnings); + Assert.Equal(["circle", "circle", "square", "square"], Items(areaScene, "mark-point").Select(p => p.Shape)); + using var bare = Draw(Chart("\"line\"", data, encoding), out var bareScene, out var bareWarnings); + Assert.Empty(bareWarnings); + Assert.Equal(4, Items(bareScene, "mark-point").Count); + + // Assert: with the overlay switched off the shape is reported (an exception in strict mode) + var off = VegaLiteDocument.Parse(Chart("{ \"type\": \"line\", \"point\": false }", data, encoding)); + var ex = Assert.Throws(() => off.Render(new VegaLiteRenderOptions { ThrowOnUnsupportedFeature = true }, Ct)); + Assert.Equal("vl-channel-shape", ex.Feature); + } + + /// + /// Validates that the reports and the drawing agree when the caller gives a configuration: a shape with config.line.point of the caller is drawn without a report in strict mode, + /// an angle that the points that this configuration enables draw is reported as drawn by the point overlay (and as ignored without the configuration), and the dash of an area + /// with a line overlay is drawn by the line, with the report naming the line overlay. + /// + [Fact] + public void CanvasNetVegaLite_SystemIntegration_Overlays_CallerConfigurationAndLineOverlayAgreeWithTheReports() + { + // Arrange + const string data = """ + [ { "x": 0, "y": 1, "g": "a" }, { "x": 1, "y": 2, "g": "a" }, { "x": 0, "y": 3, "g": "b" }, { "x": 1, "y": 4, "g": "b" } ] + """; + const string caller = """{ "line": { "point": true } }"""; + var shaped = VegaLiteDocument.Parse(Chart("\"line\"", data, Encoding(", \"color\": { \"field\": \"g\", \"type\": \"nominal\" }, \"shape\": { \"field\": \"g\", \"type\": \"nominal\" }"))); + + // Act: strict mode with the caller's configuration + var strict = new VegaLiteRenderOptions { Config = caller, ThrowOnUnsupportedFeature = true }; + var scene = shaped.BuildScene(strict, Ct); + using var surface = shaped.Render(strict, Ct); + + // Assert: no report, and the points are shaped + Assert.Equal(["circle", "circle", "square", "square"], Items(scene, "mark-point").Select(p => p.Shape)); + + // Arrange / Act: an angle on a line is reported by the catalog of the rendering that has the caller's configuration as drawn by the points, and as ignored otherwise + var angled = VegaLiteDocument.Parse(Chart("\"line\"", data, Encoding(", \"angle\": { \"field\": \"y\", \"type\": \"quantitative\" }"))); + string Report(string? config) + { + var reported = new List(); + using var drawn = angled.Render(new VegaLiteRenderOptions { Config = config, UnsupportedFeatureHandler = reported.Add }, Ct); + return Assert.Single(reported, f => f.Feature == "vl-channel-angle").Message; + } + + Assert.Contains("point overlay", Report(caller), StringComparison.Ordinal); + Assert.Contains("ignored", Report(null), StringComparison.Ordinal); + + // Arrange / Act: the dash of an area with a line overlay is the dash of its lines (the report names the line overlay) + var dashed = VegaLiteDocument.Parse(Chart("{ \"type\": \"area\", \"line\": true, \"point\": false }", data, Encoding(", \"strokeDash\": { \"field\": \"g\", \"type\": \"nominal\" }"))); + var reports = new List(); + var areaScene = dashed.BuildScene(new VegaLiteRenderOptions { UnsupportedFeatureHandler = reports.Add }, Ct); + using var areaSurface = dashed.Render(new VegaLiteRenderOptions { UnsupportedFeatureHandler = reports.Add }, Ct); + + // Assert + Assert.Equal(2, Items(areaScene, "mark-line").Count(l => l.StrokeDash is { Count: > 0 })); + Assert.Contains("line overlay", Assert.Single(reports, f => f.Feature == "vl-channel-strokedash").Message, StringComparison.Ordinal); + } + /// /// Validates the invalid data modes: a null y in the middle of five points breaks the default line into two subpaths (two moves), the filter mode connects the points on both /// sides, the filter mode warns that the scale domains include the filtered rows, and the modes show and null are reported as unsupported (and thrown in strict mode).