diff --git a/classes/Visualizer/ChartBuilder/src/AIBuilder/DataSource.js b/classes/Visualizer/ChartBuilder/src/AIBuilder/DataSource.js index 3b4a4a9d4..e671b80ac 100644 --- a/classes/Visualizer/ChartBuilder/src/AIBuilder/DataSource.js +++ b/classes/Visualizer/ChartBuilder/src/AIBuilder/DataSource.js @@ -122,6 +122,8 @@ export default function DataSource( { chartId, uploadNonce, onDataReady, dataLoa const fileInputRef = useRef( null ); // Skip the initial auto-upload only when editing existing data. const skipUploadRef = useRef( !! initialCsvText ); + const uploadSeqRef = useRef( 0 ); + const uploadQueueRef = useRef( Promise.resolve() ); // URL const [ fileUrl, setFileUrl ] = useState( '' ); @@ -208,16 +210,18 @@ 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; + // Text that equals the current text starts no upload, so it has nothing to skip. + if ( initialCsvText !== csvText ) skipUploadRef.current = true; lastCsvRef.current = initialCsvText.trim(); setCsvText( initialCsvText ); }, [ initialCsvText ] ); // eslint-disable-line react-hooks/exhaustive-deps // 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; + // The skip belongs to the CSV that arrives now, also while the builder is locked. Kept, it drops the next edit. if ( skipUploadRef.current ) { skipUploadRef.current = false; return; } + if ( disabled ) return; const trimmed = csvText.trim(); if ( lastCsvRef.current === trimmed ) return; const parsed = parseCsv( trimmed ); @@ -225,49 +229,50 @@ export default function DataSource( { chartId, uploadNonce, onDataReady, dataLoa 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 ); - onDataReady( r.series, r.data ); - lastCsvRef.current = trimmed; - } catch ( e ) { setError( e.message ); } - finally { setLoading( false ); } - }, 700 ); + const t = setTimeout( () => runUpload( () => uploadCsvString( chartId, uploadNonce, trimmed ), ( r ) => { + onDataReady( r.series, r.data ); + lastCsvRef.current = trimmed; + } ), 700 ); return () => clearTimeout( t ); }, [ 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 ) { + const seq = ++uploadSeqRef.current; + setLoading( true ); setError( null ); + uploadQueueRef.current = uploadQueueRef.current.then( async () => { + try { + apply( await request() ); + } catch ( e ) { + setError( e.message ); + } finally { + if ( seq === uploadSeqRef.current ) setLoading( false ); + } + } ); + return uploadQueueRef.current; + } + + // 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 ) { + skipUploadRef.current = true; + setCsvText( csv ); + } + setSource( 'manual' ); + } + // 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 runUpload( () => uploadFile( chartId, uploadNonce, file ), applyImport ); } 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 runUpload( () => uploadFileUrl( chartId, uploadNonce, fileUrl.trim() ), applyImport ); } // Keep spreadsheet grid in sync with CSV when switching sources or external updates. diff --git a/classes/Visualizer/ChartBuilder/src/AIBuilder/index.js b/classes/Visualizer/ChartBuilder/src/AIBuilder/index.js index 33bc9de4c..01da9c24b 100644 --- a/classes/Visualizer/ChartBuilder/src/AIBuilder/index.js +++ b/classes/Visualizer/ChartBuilder/src/AIBuilder/index.js @@ -8,36 +8,87 @@ import { useState, useEffect, useRef } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { Box, Flex, Spinner, Text } from '@chakra-ui/react'; -import * as d3 from 'd3'; -import * as topojson from 'topojson-client'; import CodeMirror from '@uiw/react-codemirror'; import { javascript } from '@codemirror/lang-javascript'; import { createChart, getChartNonce, fetchChart, saveChart, generateChart, pollStatus, uploadCsvString } from './api'; import DataSource from './DataSource'; -/** Convert Visualizer series + data arrays to plain objects for D3. */ -function toD3Values( series, data ) { - return data.map( ( row ) => { - const obj = {}; - series.forEach( ( col, i ) => { obj[ col.label ] = row[ i ]; } ); - return obj; - } ); -} +/** How long the sandbox gets to answer before the render counts as failed. */ +const RENDER_TIMEOUT_MS = 10000; -/** Execute D3 code in a container element. Returns an error message if it fails. */ +/** + * Run D3 code for a container, inside the sandboxed iframe of the D3 renderer. + * + * Chart code is saved by any user who can create charts, so it never runs in the wp-admin document. + * + * @param {string} code Chart code. + * @param {HTMLElement} container Element that receives the iframe. It must be in the document. + * @param {Array} series Chart series. + * @param {Array} data Chart rows. + * @return {Promise} The error message when the code fails, otherwise null. + */ function renderD3( code, container, series, data ) { - if ( ! code || ! container ) return; - const values = toD3Values( series, data ); + if ( ! code || ! container ) return Promise.resolve( null ); container.innerHTML = ''; - try { - // eslint-disable-next-line no-new-func - new Function( 'd3', 'topojson', 'container', 'data', code )( d3, topojson, container, values ); - return null; - } catch ( err ) { - const msg = `Chart error: ${ err.message }`; - container.innerHTML = `

${ msg }

`; - return msg; + + const iframeJsUrl = window.vizAIBuilder && window.vizAIBuilder.iframeJsUrl; + if ( ! iframeJsUrl ) { + return Promise.resolve( 'Chart error: the chart renderer is not loaded.' ); } + + return new Promise( ( resolve ) => { + const view = container.ownerDocument.defaultView; + const iframe = container.ownerDocument.createElement( 'iframe' ); + iframe.setAttribute( 'sandbox', 'allow-scripts' ); + iframe.setAttribute( + 'srcdoc', + '' + + '' + + '
' + + '