Public
Edited
Aug 13, 2023
Paused
1 fork
Importers
9 stars
Insert cell
Insert cell
Insert cell
colorTable(colorData, {
// Required: Specify the column that contains the color value.
colorColumn: "rowColor",
// Optionally specify a color opacity.
colorOpacity: .3,
// Any additional table options ...
})
Insert cell
data = penguins
Insert cell
// Add a color property to our data.
colorData = {
const valueOf = d => d.flipper_length_mm;
const color = d3.scaleSequential(d3.extent(data, valueOf), d3.interpolateTurbo);
return data.map(row => ({
...row,
rowColor: color(valueOf(row)),
}));
}
Insert cell
Insert cell
function colorTable(data, { colorColumn, colorOpacity = 1, columns = undefined, format = {}, ...options}) {
const [row] = data;
if(!row) return Inputs.table(data, options);
let index = Object.keys(row).indexOf(colorColumn);
if(index < 0) throw Error("colorColumn not found in data");
if(format[colorColumn]) throw Error("colorColumn is reserved");
if(columns && columns.indexOf(colorColumn) < 0) columns.push(colorColumn);
if(columns) index = columns.indexOf(colorColumn);
const nth = `nth-child(${index + 2})`;

const form = Inputs.table(data, {
format: {
...format,
[colorColumn]: d => htl.html`<div style="--row-color:${d}">`
},
columns,
...options
});
const scope = DOM.uid().id;
form.classList.add(scope);
form.append(htl.html`<style>

/* Ensure that the sticky header always stays on top */
.${scope} thead { position: relative; z-index: 2 }

/* Hide the last column */
.${scope} th:${nth},
.${scope} td:${nth} { width: 0; padding: 0 }
.${scope} th:${nth} { visibility: hidden }

/* Inject the background color */
.${scope} tr { position: relative }
.${scope} td:${nth} div:after {
opacity: ${colorOpacity};
content: "";
display: block;
height: 100%;
width: 100%;
position: absolute;
left: 0;
top: 0;
z-index: -1;
background-color: var(--row-color);
}
`);

return form;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more