Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
340e3e5
fix: render the AI builder preview in the sandboxed frame
vytisbulkevicius Nov 27, 2026
d034a1a
test: let the sandbox check chart finish its drawing
vytisbulkevicius Nov 27, 2026
a941148
fix: give the AI builder its own renderer address and drop stale code…
vytisbulkevicius Nov 28, 2026
e0f20ae
Merge remote-tracking branch 'origin/development' into bugfix/pro/658
vytisbulkevicius Dec 1, 2026
9a155cd
fix: give the block editor builder its renderer address and drop supe…
vytisbulkevicius Dec 1, 2026
e0abf6d
fix: drop data checks of replaced chart code and version the frame sc…
vytisbulkevicius Dec 1, 2026
b933958
fix: show the data of a generated chart at once and check pending dat…
vytisbulkevicius Dec 1, 2026
1cf27b8
fix: show data that arrived during a repair in the preview with the r…
vytisbulkevicius Dec 1, 2026
068cfa1
test: cover a repair whose code fails with data that arrived during it
vytisbulkevicius Dec 1, 2026
046272b
fix: keep data that the preview does not show yet for the next chart …
vytisbulkevicius Dec 1, 2026
0c27706
test: fix the order of the failed-check repair case and cover data th…
vytisbulkevicius Dec 2, 2026
91884d5
test: hold the repair job before the repair can start
vytisbulkevicius Dec 2, 2026
cd1c360
fix: read the current code and the newest data in work that outlives …
vytisbulkevicius Dec 2, 2026
4564e37
fix: replace the chart code after the data of the generation is read
vytisbulkevicius Dec 2, 2026
d52b6c9
Merge remote-tracking branch 'origin/development' into bugfix/pro/658
vytisbulkevicius Dec 2, 2026
ca37631
Merge remote-tracking branch 'origin/development' into bugfix/pro/658
vytisbulkevicius Dec 2, 2026
1462120
fix: lock the AI builder while the chart loads and while it is published
vytisbulkevicius Dec 2, 2026
49dbe50
fix: upload the first data edit after the AI builder unlocks
vytisbulkevicius Dec 2, 2026
4da8b32
fix: take the upload skip of loaded data while the AI builder is locked
vytisbulkevicius Dec 2, 2026
ad22e4c
fix: tie uploads, repairs and generations of the AI builder to the ne…
vytisbulkevicius Dec 2, 2026
6915cac
fix: run the uploads of the AI builder one after another
vytisbulkevicius Dec 2, 2026
932fb0d
fix: start no queued upload after the AI builder closes
vytisbulkevicius Dec 2, 2026
e31d268
fix: keep the queued uploads of the AI builder while its code editor …
vytisbulkevicius Dec 2, 2026
555092d
Keep one upload queue while the code editor opens and closes
vytisbulkevicius Dec 2, 2026
74916fe
Upload the data of a generation after the uploads before it
vytisbulkevicius Dec 2, 2026
11e18ce
Order the writes of a chart and lock the data source during an import
vytisbulkevicius Dec 2, 2026
5397051
Upload text again after its upload failed
vytisbulkevicius Dec 2, 2026
6049f16
Load a reopened chart after the queued writes
vytisbulkevicius Dec 2, 2026
8054e9b
Return the rows of every source to the builder and keep the data edit…
vytisbulkevicius Dec 2, 2026
d8fd387
Keep a data edit that a generation did not get
vytisbulkevicius Dec 4, 2026
6b00350
Compare the rows the job gets and keep the data of a generation on a …
vytisbulkevicius Dec 4, 2026
11af29b
Count a data edit from the moment the user makes it
vytisbulkevicius Dec 4, 2026
15bb2c2
Compare the editor text with the rows the builder has
vytisbulkevicius Dec 4, 2026
15b88e9
Clear the edit marker when the editor is empty
vytisbulkevicius Dec 4, 2026
fc42748
Keep any data change that the user started before a generation
vytisbulkevicius Dec 4, 2026
5e72120
Read the owed data changes of the data source at the click
vytisbulkevicius Dec 4, 2026
6fc2e8f
Correct two comments
vytisbulkevicius Dec 4, 2026
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
114 changes: 75 additions & 39 deletions classes/Visualizer/ChartBuilder/src/AIBuilder/DataSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useState, useRef, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Box, Flex, Stack, Text } from '@chakra-ui/react';
import { HotTable } from '@handsontable/react';
import { uploadCsvString, uploadFile, uploadFileUrl } from './api';
import { queueWrite, uploadCsvString, uploadFile, uploadFileUrl } from './api';

// ── Warm neutral palette ──────────────────────────────────────────────────────
const C = {
Expand Down Expand Up @@ -103,11 +103,14 @@ const SOURCES = [
const SAMPLE_CSV = `Task,Hours per Day\nstring,number\nWork,11\nEat,2\nCommute,2\nWatch TV,2\nSleep,7`;
const PLACEHOLDER_CSV = `Month,Revenue,Costs\nstring,number,number\nJan,45000,32000\nFeb,52000,38000`;

export default function DataSource( { chartId, uploadNonce, onDataReady, dataLoaded, initialCsvText = '', disabled = false, dataWarning = null, onClearWarning = null } ) {
export default function DataSource( { chartId, uploadNonce, onDataReady, dataLoaded, initialCsvText = '', openRef, hasOwedDataRef, disabled: builderLocked = false, dataWarning = null, onClearWarning = null } ) {
const isPro = !! window?.vizAIBuilder?.isPro;
const [ source, setSource ] = useState( 'manual' );
const [ loading, setLoading ] = useState( false );
const [ error, setError ] = useState( null );
// An import replaces the rows of the editors, so the editors wait for it.
const [ importing, setImporting ] = useState( false );
const disabled = builderLocked || importing;

// Manual — pre-load sample data for new charts (no initialCsvText means no existing data).
const [ csvText, setCsvText ] = useState( initialCsvText || SAMPLE_CSV );
Expand All @@ -120,12 +123,18 @@ export default function DataSource( { chartId, uploadNonce, onDataReady, dataLoa
// File
const [ file, setFile ] = useState( null );
const fileInputRef = useRef( null );
// Skip the initial auto-upload only when editing existing data.
const skipUploadRef = useRef( !! initialCsvText );
const uploadSeqRef = useRef( 0 );

// URL
const [ fileUrl, setFileUrl ] = useState( '' );
// The CSV that the server holds after the uploads in the queue.
const lastCsvRef = useRef( null );
// The CSV of the rows that the builder has, or null before the data source brought any.
const appliedCsvRef = useRef( null );
// The uploads of user data that wait or run.
const pendingUploadsRef = useRef( 0 );
// The sample of a data source that brought no rows yet is not data of the user.
const isSample = ( text ) => appliedCsvRef.current === null && text === SAMPLE_CSV;

function parseCsv( text ) {
const lines = text.split( /\r?\n/ ).map( ( l ) => l.trim() ).filter( Boolean );
Expand Down Expand Up @@ -194,7 +203,6 @@ export default function DataSource( { chartId, uploadNonce, onDataReady, dataLoa
function switchSource( id ) {
if ( id === 'manual' && source === 'sheet' ) {
const cleaned = cleanGrid( sheetRows );
skipUploadRef.current = true;
setSheetRows( cleaned );
setCsvText( gridToCsv( cleaned ) );
}
Expand All @@ -208,66 +216,94 @@ export default function DataSource( { chartId, uploadNonce, onDataReady, dataLoa
// Populate manual textarea from initialCsvText (edit mode), without triggering upload.
useEffect( () => {
if ( ! initialCsvText ) return;
skipUploadRef.current = true;
lastCsvRef.current = initialCsvText.trim();
appliedCsvRef.current = initialCsvText.trim();
setCsvText( initialCsvText );
}, [ initialCsvText ] ); // eslint-disable-line react-hooks/exhaustive-deps

// Tells the builder whether the user started a data change that its rows do not have yet: an upload of an
// edit or of an import that waits or runs, or editor text that differs from the rows, also after its upload
// failed. Empty text and the untouched first sample are not data changes.
useEffect( () => {
hasOwedDataRef.current = () => {
const trimmed = csvText.trim();
return pendingUploadsRef.current > 0 || ( !! trimmed && ! isSample( trimmed ) && appliedCsvRef.current !== trimmed );
};
} );

// Manual CSV: debounce 700 ms — uploads whenever the full CSV text changes.
useEffect( () => {
if ( disabled ) return;
if ( ( source !== 'manual' && source !== 'sheet' ) || ! csvText.trim() || ! chartId || ! uploadNonce ) return;
if ( skipUploadRef.current ) { skipUploadRef.current = false; return; }
if ( disabled ) return;
const trimmed = csvText.trim();
if ( lastCsvRef.current === trimmed ) return;
const parsed = parseCsv( trimmed );
if ( ! parsed ) {
setError( __( 'CSV must include header and types rows.', 'visualizer' ) );
return;
}
const t = setTimeout( async () => {
setLoading( true ); setError( null );
try {
const r = await uploadCsvString( chartId, uploadNonce, trimmed );
const t = setTimeout( () => {
const userData = ! isSample( trimmed );
lastCsvRef.current = trimmed;
runUpload( () => uploadCsvString( chartId, uploadNonce, trimmed ).catch( ( e ) => {
// The server does not hold this text, so the editor can upload it again.
if ( lastCsvRef.current === trimmed ) lastCsvRef.current = null;
throw e;
} ), ( r ) => {
appliedCsvRef.current = trimmed;
onDataReady( r.series, r.data );
lastCsvRef.current = trimmed;
} catch ( e ) { setError( e.message ); }
finally { setLoading( false ); }
}, userData );
}, 700 );
return () => clearTimeout( t );
Comment on lines +245 to 257

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

correctness A data edit is lost when the user publishes and closes the builder within 700 ms of typing. The edit uploads only when the debounce fires (DataSource.js:245-256). Publish saves only the title and code (index.js:588) and does not wait for the edit. When Publish answers first, Done closes the builder and return () => clearTimeout( t ) cancels the upload. The published chart keeps the older rows, and the reopened builder shows them. This path was already in the code the earlier review saw. Fix: report Publish as done only when the server holds the editor's data: wait for a pending edit and its queued upload, and report an edit whose upload failed. Add an ai-builder.spec.js case that edits, publishes, clicks Done at once, reopens and expects the edit.

}, [ source, csvText, uploadNonce ] ); // eslint-disable-line react-hooks/exhaustive-deps

// Runs the uploads one after another. Requests that overlap can reach the server and answer in any order,
// and both the server and the preview keep the rows of the last one.
function runUpload( request, apply, userData = true ) {
const seq = ++uploadSeqRef.current;
setLoading( true ); setError( null );
if ( userData ) pendingUploadsRef.current++;
return queueWrite( async () => {
try {
// A closed builder starts no upload: it would replace newer rows of the chart.
if ( ! openRef.current ) return;
apply( await request() );
} catch ( e ) {
setError( e.message );
} finally {
if ( userData ) pendingUploadsRef.current--;
if ( seq === uploadSeqRef.current ) setLoading( false );
}
} );
}

// Shows imported rows in the manual editor, without an upload of the same rows.
function applyImport( r ) {
onDataReady( r.series, r.data );
const csv = buildCsv( r.series, r.data );
if ( csv ) {
lastCsvRef.current = csv.trim();
appliedCsvRef.current = csv.trim();
setCsvText( csv );
}
setSource( 'manual' );
}

async function runImport( request ) {
setImporting( true );
await runUpload( request, applyImport );
setImporting( false );
}

// File and URL import are manual (button-triggered).
async function handleImportFile() {
if ( disabled || ! file || ! chartId ) return;
setLoading( true ); setError( null );
try {
const r = await uploadFile( chartId, uploadNonce, file );
onDataReady( r.series, r.data );
const csv = buildCsv( r.series, r.data );
if ( csv ) {
skipUploadRef.current = true;
setCsvText( csv );
}
setSource( 'manual' );
} catch ( e ) { setError( e.message ); }
finally { setLoading( false ); }
await runImport( () => uploadFile( chartId, uploadNonce, file ) );
}

async function handleImportUrl() {
if ( disabled || ! fileUrl.trim() || ! chartId ) return;
setLoading( true ); setError( null );
try {
const r = await uploadFileUrl( chartId, uploadNonce, fileUrl.trim() );
onDataReady( r.series, r.data );
const csv = buildCsv( r.series, r.data );
if ( csv ) {
skipUploadRef.current = true;
setCsvText( csv );
}
setSource( 'manual' );
} catch ( e ) { setError( e.message ); }
finally { setLoading( false ); }
await runImport( () => uploadFileUrl( chartId, uploadNonce, fileUrl.trim() ) );
}

// Keep spreadsheet grid in sync with CSV when switching sources or external updates.
Expand Down
17 changes: 17 additions & 0 deletions classes/Visualizer/ChartBuilder/src/AIBuilder/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,23 @@ async function post( action, body, options = {} ) {
return json.data;
}

// One queue for the data and code writes of every builder on the page. A write that started before a builder
// closed answers before a write of the builder that opens next, so the server keeps the newer rows and code.
let writeQueue = Promise.resolve();

/**
* Run a write after the writes queued before it.
*
* @template T
* @param {() => T|Promise<T>} write Starts the write.
* @return {Promise<T>} The result of the write.
*/
export function queueWrite( write ) {
const result = writeQueue.then( write );
writeQueue = result.catch( () => {} );
return result;
}

Comment thread
pirate-bot marked this conversation as resolved.
Resolved
/** Create an auto-draft chart post. Returns { chart_id, upload_nonce }. */
export async function createChart() {
return post( 'visualizer-ai-create', {} );
Expand Down
Loading
Loading