diff --git a/classes/Visualizer/ChartBuilder/src/AIBuilder/index.js b/classes/Visualizer/ChartBuilder/src/AIBuilder/index.js index 33bc9de4c..6edf45292 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.vizD3Renderer && window.vizD3Renderer.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', + '' + + '' + + '' + + '