Skip to content

paint #1731

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft

paint #1731

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export default defineConfig({
{text: "Formats", link: "/features/formats"},
{text: "Intervals", link: "/features/intervals"},
{text: "Markers", link: "/features/markers"},
{text: "Paints", link: "/features/paints"},
{text: "Shorthand", link: "/features/shorthand"},
{text: "Accessibility", link: "/features/accessibility"}
]
Expand Down
1 change: 1 addition & 0 deletions docs/data/api.data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ function getHref(name: string, path: string): string {
case "features/interval":
case "features/mark":
case "features/marker":
case "features/paint":
case "features/plot":
case "features/projection":
return `${path}s`;
Expand Down
7 changes: 7 additions & 0 deletions docs/features/paints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Paints <VersionBadge pr="1731" />

A **paint** defines a fill or stroke implementation such as a pattern or gradient; it is an alternative to a constant color.

## linearGradient() {#linearGradient}

Returns a linear gradient.
1 change: 1 addition & 0 deletions src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export * from "./marks/tip.js";
export * from "./marks/tree.js";
export * from "./marks/vector.js";
export * from "./options.js";
export * from "./paint.js";
export * from "./plot.js";
export * from "./projection.js";
export * from "./reducer.js";
Expand Down
1 change: 1 addition & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,6 @@ export {pointer, pointerX, pointerY} from "./interactions/pointer.js";
export {formatIsoDate, formatNumber, formatWeekday, formatMonth} from "./format.js";
export {scale} from "./scales.js";
export {legend} from "./legends.js";
export {linearGradient} from "./paint.js";
export {numberInterval} from "./options.js";
export {timeInterval, utcInterval} from "./time.js";
5 changes: 3 additions & 2 deletions src/mark.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {Channel, ChannelDomainSort, ChannelValue, ChannelValues, ChannelVal
import type {Context} from "./context.js";
import type {Dimensions} from "./dimensions.js";
import type {TipOptions} from "./marks/tip.js";
import type {Paint} from "./paint.js";
import type {plot} from "./plot.js";
import type {ScaleFunctions} from "./scales.js";
import type {InitializerFunction, SortOrder, TransformFunction} from "./transforms/basic.js";
Expand Down Expand Up @@ -320,7 +321,7 @@ export interface MarkOptions {
*
* [1]: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill
*/
fill?: ChannelValueSpec;
fill?: ChannelValueSpec | Paint;

/**
* The [fill-opacity][1]; a constant number between 0 and 1, or a channel
Expand All @@ -340,7 +341,7 @@ export interface MarkOptions {
*
* [1]: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke
*/
stroke?: ChannelValueSpec;
stroke?: ChannelValueSpec | Paint;

/**
* The [stroke-dasharray][1]; a constant number indicating the length in
Expand Down
11 changes: 11 additions & 0 deletions src/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,16 @@ export function isEvery(values, is) {
return every;
}

// TODO Make isPaint the generic one (either a color or a custom paint
// implementation), rather than making isColor the generic one?
export function isPaint(value) {
return typeof value?.paint === "function";
}

// Mostly relies on d3-color, with a few extra color keywords. Currently this
// strictly requires that the value be a string; we might want to apply string
// coercion here, though note that d3-color instances would need to support
// valueOf to work correctly with InternMap.
const namedColors = new Set("none,currentcolor,transparent,aliceblue,antiquewhite,aqua,aquamarine,azure,beige,bisque,black,blanchedalmond,blue,blueviolet,brown,burlywood,cadetblue,chartreuse,chocolate,coral,cornflowerblue,cornsilk,crimson,cyan,darkblue,darkcyan,darkgoldenrod,darkgray,darkgreen,darkgrey,darkkhaki,darkmagenta,darkolivegreen,darkorange,darkorchid,darkred,darksalmon,darkseagreen,darkslateblue,darkslategray,darkslategrey,darkturquoise,darkviolet,deeppink,deepskyblue,dimgray,dimgrey,dodgerblue,firebrick,floralwhite,forestgreen,fuchsia,gainsboro,ghostwhite,gold,goldenrod,gray,green,greenyellow,grey,honeydew,hotpink,indianred,indigo,ivory,khaki,lavender,lavenderblush,lawngreen,lemonchiffon,lightblue,lightcoral,lightcyan,lightgoldenrodyellow,lightgray,lightgreen,lightgrey,lightpink,lightsalmon,lightseagreen,lightskyblue,lightslategray,lightslategrey,lightsteelblue,lightyellow,lime,limegreen,linen,magenta,maroon,mediumaquamarine,mediumblue,mediumorchid,mediumpurple,mediumseagreen,mediumslateblue,mediumspringgreen,mediumturquoise,mediumvioletred,midnightblue,mintcream,mistyrose,moccasin,navajowhite,navy,oldlace,olive,olivedrab,orange,orangered,orchid,palegoldenrod,palegreen,paleturquoise,palevioletred,papayawhip,peachpuff,peru,pink,plum,powderblue,purple,rebeccapurple,red,rosybrown,royalblue,saddlebrown,salmon,sandybrown,seagreen,seashell,sienna,silver,skyblue,slateblue,slategray,slategrey,snow,springgreen,steelblue,tan,teal,thistle,tomato,turquoise,violet,wheat,white,whitesmoke,yellow".split(",")); // prettier-ignore

// Returns true if value is a valid CSS color string. This is intentionally lax
Expand All @@ -486,6 +496,7 @@ const namedColors = new Set("none,currentcolor,transparent,aliceblue,antiquewhit
// https://www.w3.org/TR/SVG11/painting.html#SpecifyingPaint
// https://www.w3.org/TR/css-color-5/
export function isColor(value) {
if (isPaint(value)) return true;
if (typeof value !== "string") return false;
value = value.toLowerCase().trim();
return (
Expand Down
10 changes: 10 additions & 0 deletions src/paint.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type {Context} from "./context.js";

/** TODO */
export interface Paint {
/** TODO */
paint(context: Context): string | null;
}

/** TODO */
export function linearGradient(): Paint;
16 changes: 16 additions & 0 deletions src/paint.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {select} from "d3";

export function linearGradient() {
return {
paint(context) {
select(context.ownerSVGElement)
.append("linearGradient")
.attr("gradientTransform", "rotate(90)")
.attr("id", "test-paint")
.call((gradient) => gradient.append("stop").attr("offset", "5%").attr("stop-color", "purple"))
.call((gradient) => gradient.append("stop").attr("offset", "75%").attr("stop-color", "red"))
.call((gradient) => gradient.append("stop").attr("offset", "100%").attr("stop-color", "gold"));
return "url(#test-paint)";
}
};
}
6 changes: 3 additions & 3 deletions src/style.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {geoPath, group, namespaces} from "d3";
import {create} from "./context.js";
import {defined, nonempty} from "./defined.js";
import {formatDefault} from "./format.js";
import {isNone, isNoneish, isRound, maybeColorChannel, maybeNumberChannel} from "./options.js";
import {isNone, isNoneish, isPaint, isRound, maybeColorChannel, maybeNumberChannel} from "./options.js";
import {keyof, number, string} from "./options.js";
import {warn} from "./warnings.js";

Expand Down Expand Up @@ -106,7 +106,7 @@ export function styles(

// Some marks don’t support fill (e.g., tick and rule).
if (defaultFill !== null) {
mark.fill = impliedString(cfill, "currentColor");
mark.fill = isPaint(cfill) ? cfill : impliedString(cfill, "currentColor");
mark.fillOpacity = impliedNumber(cfillOpacity, 1);
}

Expand Down Expand Up @@ -349,7 +349,7 @@ function applyClip(selection, mark, dimensions, context) {
export function applyIndirectStyles(selection, mark, dimensions, context) {
applyClip(selection, mark, dimensions, context);
applyAttr(selection, "class", mark.className);
applyAttr(selection, "fill", mark.fill);
applyAttr(selection, "fill", isPaint(mark.fill) ? mark.fill.paint(context) : mark.fill);
applyAttr(selection, "fill-opacity", mark.fillOpacity);
applyAttr(selection, "stroke", mark.stroke);
applyAttr(selection, "stroke-width", mark.strokeWidth);
Expand Down
65 changes: 65 additions & 0 deletions test/output/penguinSpeciesPaint.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions test/plots/penguin-species.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ export async function penguinSpeciesCheysson() {
});
}

export async function penguinSpeciesPaint() {
const penguins = await d3.csv<any>("data/penguins.csv", d3.autoType);
return Plot.plot({
marks: [
Plot.barY(penguins, Plot.groupX({y: "count"}, {x: "species", fill: Plot.linearGradient()})),
Plot.ruleY([0])
]
});
}

export async function penguinSpeciesGradient() {
const penguins = await d3.csv<any>("data/penguins.csv", d3.autoType);
return Plot.plot({
Expand Down