Files
lcp-visualizer/blocks/components/LCPDatasetBuilder.js
2025-01-27 02:56:29 -08:00

102 lines
4.4 KiB
JavaScript

import { useState } from '@wordpress/element';
import { Button, Modal } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import LCPDataGrid from './LCPDataGrid';
const LCPDatasetBuilder = ({ attributes, setAttributes }) => {
const [isOpen, setIsOpen] = useState(false);
const [activeTab, setActiveTab] = useState(0); // Track the active tab
const handleUpdateDataset = (index, newData) => {
// Log the newData in a readable format
console.log("newData (formatted for copy-pasting):", JSON.stringify(newData, null, 2));
// Make a shallow copy of the datasets to avoid mutation
const datasets = [...attributes.datasets];
// Ensure the data structure is correct before replacing
if (newData && newData.data) {
// Replace the data array at the specified index with the new data
datasets[0].data = newData.data;
// Log the datasets before the update
console.log("Before Update:", JSON.stringify(datasets, null, 2));
// Update the attributes with the modified datasets
setAttributes({
datasets: datasets
});
// Log the updated attributes (you can check this after re-rendering)
console.log("After Update:", JSON.stringify(datasets, null, 2));
} else {
console.error("Invalid data format:", newData);
}
};
return (
<>
<Button
variant="secondary"
onClick={() => setIsOpen(true)}
style={{ marginBottom: '10px', width: '100%' }}
>
{__('Edit Dataset', 'lcp-visualize')}
</Button>
{isOpen && (
<Modal
onRequestClose={() => setIsOpen(false)}
title={__('Dataset Builder', 'lcp-visualize')}
style={{ width: '90vw', height: '90vh' }}
>
<div style={{ height: 'calc(90vh - 40px)', padding: '20px' }}>
{/* Tabs */}
<div style={{ display: 'flex', marginBottom: '20px' }}>
{attributes.datasets.map((dataset, index) => (
<button
key={index}
onClick={() => setActiveTab(index)} // Set the active tab
style={{
padding: '10px 20px',
margin: '0 5px',
backgroundColor: activeTab === index ? '#007cba' : '#f1f1f1',
color: activeTab === index ? 'white' : 'black',
border: '1px solid #ccc',
borderRadius: '5px',
cursor: 'pointer',
transition: 'background-color 0.3s ease',
}}
>
{dataset.name}
</button>
))}
</div>
{/* Render all the LCPDataGrid components */}
<div style={{ display: 'flex', flexDirection: 'column' }}>
{attributes.datasets.map((dataset, index) => (
<div
key={index}
style={{
display: activeTab === index ? 'block' : 'none', // Show only the active tab
transition: 'display 0.3s ease',
}}
>
<LCPDataGrid
dataset={dataset.data} // Pass the specific dataset data (only the data, not the entire dataset)
index={index}
updateDataset={handleUpdateDataset} // Function defined outside of class context
/>
</div>
))}
</div>
</div>
</Modal>
)}
</>
);
};
export default LCPDatasetBuilder;