Added support for hierarchical bar graphs

This commit is contained in:
Jeremy Rangel
2025-01-15 22:31:22 -08:00
parent 83f5cad36f
commit 9ce6586662
9 changed files with 236 additions and 64 deletions

View File

@ -17,6 +17,14 @@
"style": "file:./style-index.css",
"viewScript": "file:./view.js",
"attributes": {
"enableHierarchicalView": {
"type": "boolean",
"default": false
},
"selectedParentId": {
"type": "string",
"default": null
},
"chartColorSource": {
"type": "string",
"default": "default"

View File

@ -1 +1 @@
<?php return array('dependencies' => array('react-jsx-runtime', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n'), 'version' => 'd3e2bb3c261756c0085a');
<?php return array('dependencies' => array('react-jsx-runtime', 'wp-block-editor', 'wp-blocks', 'wp-components', 'wp-element', 'wp-i18n'), 'version' => '1180f00c82e4e13ed149');

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
<?php return array('dependencies' => array(), 'version' => '70f08b60c296a36b16fe');
<?php return array('dependencies' => array(), 'version' => 'cd3eca3e743bd29f75fd');

File diff suppressed because one or more lines are too long

View File

@ -17,6 +17,14 @@
"style": "file:./style-index.css",
"viewScript": "file:./view.js",
"attributes": {
"enableHierarchicalView": {
"type": "boolean",
"default": false
},
"selectedParentId": {
"type": "string",
"default": null
},
"chartColorSource": {
"type": "string",
"default": "default"

View File

@ -19,7 +19,10 @@ const BarGraph = ({
colorSource,
defaultBarColor,
customColors,
barOpacity
barOpacity,
enableHierarchicalView,
selectedParentId,
setAttributes
}) => {
const svgRef = useRef();
const containerRef = useRef();
@ -30,22 +33,38 @@ const BarGraph = ({
// Clear previous content
d3.select(svgRef.current).selectAll("*").remove();
// Convert data to simple array
const chartData = [];
for (const [dataset, items] of Object.entries(data)) {
for (const item of items) {
chartData.push({
dataset,
label: item.label,
value: parseInt(item.value, 10),
color: item.color || '#FF6384'
});
}
// Filter data based on hierarchical view
let displayData = data;
if (enableHierarchicalView) {
displayData = {};
Object.entries(data).forEach(([dataset, items]) => {
const filteredItems = items.filter(item => item.parent === selectedParentId);
if (filteredItems.length > 0) {
displayData[dataset] = filteredItems;
}
});
}
// Convert data to array format
const chartDataArray = [];
Object.entries(displayData).forEach(([dataset, items]) => {
items.forEach(item => {
chartDataArray.push({
id: item.id,
dataset,
label: item.label || '',
value: parseFloat(item.value) || 0,
color: item.color || defaultBarColor,
hasChildren: Object.values(data).some(dataItems =>
dataItems.some(dataItem => dataItem.parent === item.id)
)
});
});
});
// Get container dimensions
const containerWidth = containerRef.current.clientWidth;
const containerHeight = containerRef.current.clientHeight;
const containerHeight = typeof height === 'number' ? height : 400;
// Basic dimensions with extra margin for axis labels
const margin = {
@ -54,13 +73,14 @@ const BarGraph = ({
bottom: xAxisLabel ? 50 : 30,
left: yAxisLabel ? 60 : 40
};
const innerWidth = containerWidth - margin.left - margin.right;
const innerHeight = containerHeight - margin.top - margin.bottom;
const innerWidth = Math.max(containerWidth - margin.left - margin.right, 0);
const innerHeight = Math.max(containerHeight - margin.top - margin.bottom, 0);
// Create SVG
const svg = d3.select(svgRef.current)
.attr('width', containerWidth)
.attr('height', containerHeight);
.attr('height', containerHeight)
.style('background-color', backgroundColor);
// Add title if present
if (title) {
@ -78,12 +98,12 @@ const BarGraph = ({
// Create scales
const xScale = d3.scaleBand()
.domain(chartData.map(d => d.label))
.domain(chartDataArray.map(d => d.label))
.range([0, innerWidth])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0, d3.max(chartData, d => d.value)])
.domain([0, d3.max(chartDataArray, d => d.value) || 100])
.range([innerHeight, 0]);
// Get color for a datapoint based on color source
@ -92,7 +112,7 @@ const BarGraph = ({
case 'singleColor':
return defaultBarColor;
case 'customColors':
const customColor = customColors.find(
const customColor = customColors?.find(
c => c.dataset === datapoint.dataset && c.label === datapoint.label
);
return customColor ? customColor.color : datapoint.color;
@ -127,7 +147,7 @@ const BarGraph = ({
// Add bars
const bars = g.selectAll('rect')
.data(chartData)
.data(chartDataArray)
.enter()
.append('rect')
.attr('x', d => xScale(d.label))
@ -135,12 +155,44 @@ const BarGraph = ({
.attr('width', xScale.bandwidth())
.attr('height', d => innerHeight - yScale(d.value))
.attr('fill', d => getColor(d))
.style('opacity', barOpacity);
.style('opacity', barOpacity)
.style('cursor', d => d.hasChildren ? 'pointer' : 'default');
if (enableHierarchicalView) {
bars.on('click', function(event, d) {
if (d.hasChildren && setAttributes) {
setAttributes({ selectedParentId: d.id });
}
});
// Add back button if not at root level
if (selectedParentId !== null) {
svg.append('text')
.attr('x', margin.left)
.attr('y', margin.top / 2)
.attr('class', 'back-button')
.style('cursor', 'pointer')
.style('font-weight', 'bold')
.text('← Back')
.on('click', function() {
if (setAttributes) {
let parentParentId = null;
Object.values(data).forEach(items => {
const currentItem = items.find(item => item.id === selectedParentId);
if (currentItem) {
parentParentId = currentItem.parent;
}
});
setAttributes({ selectedParentId: parentParentId });
}
});
}
}
// Add bar values
if (showBarValues) {
g.selectAll('.bar-value')
.data(chartData)
.data(chartDataArray)
.enter()
.append('text')
.attr('class', 'bar-value')
@ -153,7 +205,12 @@ const BarGraph = ({
// Add X axis
g.append('g')
.attr('transform', `translate(0,${innerHeight})`)
.call(d3.axisBottom(xScale));
.call(d3.axisBottom(xScale))
.selectAll('text')
.style('text-anchor', 'end')
.attr('dx', '-.8em')
.attr('dy', '.15em')
.attr('transform', 'rotate(-45)');
// Add Y axis
g.append('g')
@ -182,7 +239,7 @@ const BarGraph = ({
.text(yAxisLabel);
}
}, [data, width, height, title, showGridX, showGridY, xGridColor, yGridColor, xGridWidth, yGridWidth, showBarValues, xAxisLabel, yAxisLabel, colorSource, defaultBarColor, customColors, barOpacity]);
}, [data, width, height, title, showGridX, showGridY, xGridColor, yGridColor, xGridWidth, yGridWidth, showBarValues, xAxisLabel, yAxisLabel, colorSource, defaultBarColor, customColors, barOpacity, enableHierarchicalView, selectedParentId]);
return (
<div

View File

@ -12,7 +12,8 @@ import {
TabPanel,
TextControl,
Button,
Popover
Popover,
TextareaControl
} from '@wordpress/components';
import {useState} from '@wordpress/element';
@ -50,7 +51,9 @@ export default function Edit({ attributes, setAttributes }) {
xAxisLabel,
yAxisLabel,
chartColorSource,
chartCustomColors } = attributes;
chartCustomColors,
enableHierarchicalView,
selectedParentId } = attributes;
const blockProps = useBlockProps();
@ -163,6 +166,43 @@ export default function Edit({ attributes, setAttributes }) {
// Debug log to check chartData
console.log('Chart data:', chartData);
// Ensure chartData is an object
if (!attributes.chartData || typeof attributes.chartData !== 'object') {
setAttributes({ chartData: {} });
}
const updateChartData = (value) => {
try {
// Attempt to parse the JSON input
const parsedData = JSON.parse(value);
// Validate the structure
if (typeof parsedData === 'object' && parsedData !== null) {
// Check if the data follows our expected format
let isValid = true;
Object.entries(parsedData).forEach(([dataset, items]) => {
if (!Array.isArray(items)) {
isValid = false;
} else {
items.forEach(item => {
if (!item.id || typeof item.id !== 'string') {
isValid = false;
}
});
}
});
if (isValid) {
setAttributes({ chartData: parsedData });
} else {
console.error('Invalid data structure');
}
}
} catch (e) {
console.error('Invalid JSON:', e);
}
};
return (
<div {...blockProps}>
<InspectorControls>
@ -192,6 +232,7 @@ export default function Edit({ attributes, setAttributes }) {
return (
<Panel>
<PanelBody title="Data Settings">
<LCPDataSelector
value={chartData}
onChange={handleDataChange}
@ -200,6 +241,17 @@ export default function Edit({ attributes, setAttributes }) {
/>
</PanelBody>
<PanelBody title="Chart Settings">
<ToggleControl
label={__('Enable Hierarchical View', 'lcp')}
help={__('Display data hierarchically. Click bars to show their children.', 'lcp')}
checked={attributes.enableHierarchicalView}
onChange={(value) => {
setAttributes({
enableHierarchicalView: value,
selectedParentId: null // Reset when toggling
});
}}
/>
<ToggleControl
label={__('Display Chart Title', 'lcp')}
checked={displayChartTitle}
@ -439,17 +491,18 @@ export default function Edit({ attributes, setAttributes }) {
showGridX={showGridX}
showGridY={showGridY}
yGridColor={yGridColor}
xGridColor={xGridColor}
xGridColor={xGridColor}
xGridWidth={xGridWidth}
yGridWidth={yGridWidth}
title={displayChartTitle ? chartTitle : ''}
showSorting={showSorting}
showFiltering={showFiltering}
showBarValues={showBarValues}
xAxisLabel={xAxisLabel}
yAxisLabel={yAxisLabel}
colorSource={chartColorSource}
customColors={chartCustomColors}
enableHierarchicalView={enableHierarchicalView}
selectedParentId={selectedParentId}
setAttributes={setAttributes}
/>
) : (
<div

View File

@ -23,12 +23,8 @@
import * as d3 from 'd3';
window.addEventListener('load', function() {
// Check if we have any bar graphs to render
if (!window.lcpBarGraphData) {
return;
}
if (!window.lcpBarGraphData) return;
// Render each bar graph
Object.entries(window.lcpBarGraphData).forEach(([blockId, data]) => {
const { attributes } = data;
const container = document.getElementById(blockId);
@ -38,36 +34,52 @@ window.addEventListener('load', function() {
});
});
function filterDataByParent(chartData, parentId) {
const filteredData = {};
Object.entries(chartData).forEach(([dataset, items]) => {
const filteredItems = items.filter(item => item.parent === parentId);
if (filteredItems.length > 0) {
filteredData[dataset] = filteredItems;
}
});
return filteredData;
}
function hasChildren(chartData, itemId) {
return Object.values(chartData).some(items =>
items.some(item => item.parent === itemId)
);
}
function renderBarGraph(container, attrs) {
// Clear any existing content
const graphContainer = container.querySelector('.bar-graph-container');
if (!graphContainer) return;
graphContainer.innerHTML = '';
// Get the actual width of the container
const containerWidth = graphContainer.clientWidth;
// Set up dimensions
const margin = { top: 40, right: 20, bottom: 60, left: 60 };
const width = containerWidth - margin.left - margin.right;
const height = attrs.chartHeight - margin.top - margin.bottom;
// Get data for current level
const currentData = filterDataByParent(attrs.chartData, attrs.selectedParentId);
// Convert data to array format
const chartDataArray = [];
if (attrs.chartData && typeof attrs.chartData === 'object') {
Object.entries(attrs.chartData).forEach(([dataset, items]) => {
if (Array.isArray(items)) {
items.forEach(item => {
chartDataArray.push({
dataset,
label: item.label || '',
value: parseFloat(item.value) || 0,
color: item.color || attrs.barColor
});
});
}
Object.entries(currentData).forEach(([dataset, items]) => {
items.forEach(item => {
chartDataArray.push({
id: item.id,
dataset,
label: item.label || '',
value: parseFloat(item.value) || 0,
color: item.color || attrs.barColor,
hasChildren: hasChildren(attrs.chartData, item.id)
});
});
}
});
// Create SVG
const svg = d3.select(graphContainer)
@ -105,7 +117,7 @@ function renderBarGraph(container, attrs) {
}
};
// Add X grid
// Add grids
if (attrs.showGridX) {
g.append('g')
.attr('class', 'grid x-grid')
@ -117,7 +129,6 @@ function renderBarGraph(container, attrs) {
.tickFormat(''));
}
// Add Y grid
if (attrs.showGridY) {
g.append('g')
.attr('class', 'grid y-grid')
@ -129,7 +140,7 @@ function renderBarGraph(container, attrs) {
}
// Add bars
g.selectAll('rect')
const bars = g.selectAll('rect')
.data(chartDataArray)
.enter()
.append('rect')
@ -138,7 +149,45 @@ function renderBarGraph(container, attrs) {
.attr('width', xScale.bandwidth())
.attr('height', d => height - yScale(d.value))
.attr('fill', d => getColor(d))
.style('opacity', attrs.barOpacity);
.style('opacity', attrs.barOpacity)
.style('cursor', d => d.hasChildren ? 'pointer' : 'default');
// Add click handlers for bars
bars.on('click', function(event, d) {
if (d.hasChildren) {
const blockData = window.lcpBarGraphData[container.id];
if (blockData) {
blockData.attributes.selectedParentId = d.id;
renderBarGraph(container, blockData.attributes);
}
}
});
// Add back button if not at root level
if (attrs.selectedParentId !== null) {
svg.append('text')
.attr('x', margin.left)
.attr('y', margin.top / 2)
.attr('class', 'back-button')
.style('cursor', 'pointer')
.style('font-weight', 'bold')
.text('← Back')
.on('click', function() {
const blockData = window.lcpBarGraphData[container.id];
if (blockData) {
// Find current item's parent
let parentParentId = null;
Object.values(attrs.chartData).forEach(items => {
const currentItem = items.find(item => item.id === attrs.selectedParentId);
if (currentItem) {
parentParentId = currentItem.parent;
}
});
blockData.attributes.selectedParentId = parentParentId;
renderBarGraph(container, blockData.attributes);
}
});
}
// Add bar values
if (attrs.showBarValues) {
@ -153,7 +202,7 @@ function renderBarGraph(container, attrs) {
.text(d => d.value);
}
// Add X axis
// Add axes
g.append('g')
.attr('class', 'x-axis')
.attr('transform', `translate(0,${height})`)
@ -164,7 +213,6 @@ function renderBarGraph(container, attrs) {
.attr('dy', '.15em')
.attr('transform', 'rotate(-45)');
// Add Y axis
g.append('g')
.attr('class', 'y-axis')
.call(d3.axisLeft(yScale));
@ -179,7 +227,7 @@ function renderBarGraph(container, attrs) {
.text(attrs.chartTitle);
}
// Add X axis label
// Add axis labels
if (attrs.xAxisLabel) {
svg.append('text')
.attr('x', containerWidth / 2)
@ -188,7 +236,6 @@ function renderBarGraph(container, attrs) {
.text(attrs.xAxisLabel);
}
// Add Y axis label
if (attrs.yAxisLabel) {
svg.append('text')
.attr('transform', 'rotate(-90)')
@ -202,7 +249,6 @@ function renderBarGraph(container, attrs) {
const resizeObserver = new ResizeObserver(() => {
const newWidth = graphContainer.clientWidth;
if (newWidth !== containerWidth) {
// Clear and redraw
graphContainer.innerHTML = '';
renderBarGraph(container, attrs);
}