Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
20 changes: 12 additions & 8 deletions classes/Visualizer/D3Renderer/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,17 @@ function downloadDataUrl( dataUrl, name ) {
/**
* Render a single D3 chart into its container element via a sandboxed iframe.
*
* @param {string} id - DOM element ID of the container
* @param {object} chart - chart entry from visualizer.charts
* @param {string} id - DOM element ID of the container
* @param {object} chart - chart entry from visualizer.charts
* @param {?HTMLElement} [element] - container element, needed when it lives in another document such as the editor iframe
*/
function renderD3Chart( id, chart ) {
const container = document.getElementById( id );
function renderD3Chart( id, chart, element ) {
const container = element || document.getElementById( id );
if ( ! container ) return;

// The sandbox posts to its parent window, which is the container's window.
const containerWindow = container.ownerDocument.defaultView;

const code = typeof chart.code === 'string' ? chart.code : null;

if ( ! code ) {
Expand Down Expand Up @@ -83,7 +87,7 @@ function renderD3Chart( id, chart ) {
'<body><div id="chart"></div>' +
'<script src="' + iframeJsUrl + '"><\/script></body></html>';

const iframe = document.createElement( 'iframe' );
const iframe = container.ownerDocument.createElement( 'iframe' );
iframe.setAttribute( 'sandbox', 'allow-scripts' );
iframe.setAttribute( 'srcdoc', srcdoc );
iframe.setAttribute( 'data-viz-id', id );
Expand All @@ -95,14 +99,14 @@ function renderD3Chart( id, chart ) {
if ( event.source !== iframe.contentWindow ) return;
const msg = event.data;
if ( ! msg || msg.type !== 'iframe-ready' ) return;
window.removeEventListener( 'message', onReady );
containerWindow.removeEventListener( 'message', onReady );
iframe.contentWindow.postMessage(
{ type: 'render', code, series: chart.series, data: chart.data },
'*'
);
}

window.addEventListener( 'message', onReady );
containerWindow.addEventListener( 'message', onReady );

container.innerHTML = '';
container.appendChild( iframe );
Expand Down Expand Up @@ -155,7 +159,7 @@ function handleImageAction( id, name, action ) {
if ( viz.id ) {
const chart = viz.charts[ viz.id ];
if ( chart && chart.library === 'd3' ) {
renderD3Chart( viz.id, chart );
renderD3Chart( viz.id, chart, viz.container );
}
return;
}
Expand Down
77 changes: 77 additions & 0 deletions classes/Visualizer/D3Renderer/tests/container-document.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* D3 renderer must draw into a container that lives in another document,
* such as the iframed block editor canvas, and hear that sandbox's messages.
*
* @jest-environment jsdom
*/

/* eslint-disable no-undef */

const path = require( 'path' );

describe( 'D3 renderer container in another document', () => {
let renderHandlers;
let rafSpy;

beforeEach( () => {
jest.resetModules();
document.body.innerHTML = '';
renderHandlers = [];

global.jQuery = () => ( {
on( event, fn ) {
if ( 'visualizer:render:chart:start' === event ) {
renderHandlers.push( fn );
}
return this;
},
} );
window.vizD3Renderer = { iframeJsUrl: 'https://example.test/iframe.js' };
rafSpy = jest.spyOn( window, 'requestAnimationFrame' ).mockImplementation( ( cb ) => cb() );

require( path.resolve( __dirname, '../src/index.js' ) );
} );

afterEach( () => {
rafSpy.mockRestore();
delete window.vizD3Renderer;
delete global.jQuery;
} );

function trigger( viz ) {
renderHandlers.forEach( ( fn ) => fn( {}, viz ) );
}

it( 'renders into the passed container and answers the sandbox from its window', () => {
const canvas = document.createElement( 'iframe' );
document.body.appendChild( canvas );
const canvasDocument = canvas.contentDocument;
const container = canvasDocument.createElement( 'div' );
container.id = 'visualizer-d3-7';
canvasDocument.body.appendChild( container );

trigger( {
id: 'visualizer-d3-7',
container,
charts: {
'visualizer-d3-7': { library: 'd3', code: 'return 1;', series: [], data: [] },
},
} );

const sandbox = container.querySelector( 'iframe[data-viz-id="visualizer-d3-7"]' );
expect( sandbox ).not.toBeNull();
expect( sandbox.getAttribute( 'sandbox' ) ).toBe( 'allow-scripts' );
expect( document.querySelector( 'iframe[data-viz-id]' ) ).toBeNull();

const postMessage = jest.spyOn( sandbox.contentWindow, 'postMessage' ).mockImplementation( () => {} );

const ready = new canvas.contentWindow.MessageEvent( 'message', { data: { type: 'iframe-ready' } } );
Object.defineProperty( ready, 'source', { value: sandbox.contentWindow } );
canvas.contentWindow.dispatchEvent( ready );

expect( postMessage ).toHaveBeenCalledWith(
expect.objectContaining( { type: 'render', code: 'return 1;' } ),
'*'
);
} );
} );
11 changes: 8 additions & 3 deletions classes/Visualizer/Gutenberg/src/Components/ChartRender.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
import { Chart } from 'react-google-charts';
import GoogleChart from './GoogleChart.js';

import DataTable from './DataTable.js';

Expand All @@ -18,7 +18,8 @@ const { __ } = wp.i18n;

const {
Component,
Fragment
Fragment,
createRef
} = wp.element;

const {
Expand All @@ -33,6 +34,8 @@ const { BlockControls } = wp.blockEditor || wp.editor;
class ChartRender extends Component {
constructor() {
super( ...arguments );

this.d3Container = createRef();
}

getD3ContainerId() {
Expand All @@ -58,6 +61,7 @@ class ChartRender extends Component {
const code = chart['visualizer-d3-code'] || chart.code || '';
const payload = {
id: containerId,
container: this.d3Container.current,
charts: {
[ containerId ]: {
library: 'd3',
Expand Down Expand Up @@ -138,6 +142,7 @@ class ChartRender extends Component {
{ isD3 ? (
<div
id={ this.getD3ContainerId() }
ref={ this.d3Container }
className="visualizer-d3-preview"
style={ { height: '500px' } }
/>
Expand All @@ -149,7 +154,7 @@ class ChartRender extends Component {
options={ data['visualizer-settings'] }
/>
) : (
<Chart
<GoogleChart
chartVersion={ chartVersion }
chartType={ chart }
rows={ data['visualizer-data'] }
Expand Down
15 changes: 12 additions & 3 deletions classes/Visualizer/Gutenberg/src/Components/ChartSelect.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
import { Chart } from 'react-google-charts';
import GoogleChart from './GoogleChart.js';

import DataTable from './DataTable.js';

Expand All @@ -22,7 +22,8 @@ const { Button } = wp.components;

const {
Component,
Fragment
Fragment,
createRef
} = wp.element;

const { InspectorControls } = wp.blockEditor || wp.editor;
Expand Down Expand Up @@ -81,6 +82,12 @@ visualizerMediaView.Chart = wp.media.view.MediaFrame.extend(
);

class ChartSelect extends Component {
constructor() {
super( ...arguments );

this.d3Container = createRef();
}

getD3ContainerId() {
return `visualizer-d3-select-${ this.props.id }`;
}
Expand All @@ -104,6 +111,7 @@ class ChartSelect extends Component {
const code = chart['visualizer-d3-code'] || chart.code || '';
const payload = {
id: containerId,
container: this.d3Container.current,
charts: {
[ containerId ]: {
library: 'd3',
Expand Down Expand Up @@ -209,6 +217,7 @@ class ChartSelect extends Component {
isD3 ? (
<div
id={ this.getD3ContainerId() }
ref={ this.d3Container }
className="visualizer-d3-preview"
style={ { height: '500px' } }
/>
Expand All @@ -220,7 +229,7 @@ class ChartSelect extends Component {
options={ data['visualizer-settings'] }
/>
) : (
<Chart
<GoogleChart
chartVersion={ chartVersion }
chartType={ chart }
rows={ data['visualizer-data'] }
Expand Down
11 changes: 7 additions & 4 deletions classes/Visualizer/Gutenberg/src/Components/Charts.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* External dependencies
*/
import { Chart } from 'react-google-charts';
import GoogleChart from './GoogleChart.js';

import DataTable from './DataTable.js';

Expand All @@ -18,7 +18,8 @@ const { apiFetch } = wp;

const {
Component,
Fragment
Fragment,
createRef
} = wp.element;

const {
Expand All @@ -36,6 +37,7 @@ class Charts extends Component {

this.loadMoreCharts = this.loadMoreCharts.bind( this );
this.renderD3Charts = this.renderD3Charts.bind( this );
this.grid = createRef();

this.state = {
charts: null,
Expand Down Expand Up @@ -102,6 +104,7 @@ class Charts extends Component {
const code = data['visualizer-d3-code'] || data.code || '';
const payload = {
id: containerId,
container: this.grid.current.querySelector( `#${ containerId }` ),
charts: {
[ containerId ]: {
library: 'd3',
Expand All @@ -123,7 +126,7 @@ class Charts extends Component {
const { charts, isBusy, chartsLoaded, perPage } = this.state;

return (
<div className="visualizer-settings__charts">
<div className="visualizer-settings__charts" ref={ this.grid }>
<Notice
status="warning"
isDismissible={ false }
Expand Down Expand Up @@ -203,7 +206,7 @@ class Charts extends Component {
options={ data['visualizer-settings'] }
/>
) : (
<Chart
<GoogleChart
chartVersion={ chartVersion }
chartType={ chart }
rows={ data['visualizer-data'] }
Expand Down
21 changes: 15 additions & 6 deletions classes/Visualizer/Gutenberg/src/Components/DataTable.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import { v4 as uuidv4 } from 'uuid';
*/
const {
Component,
Fragment
Fragment,
createRef
} = wp.element;

class DataTables extends Component {
Expand All @@ -19,6 +20,7 @@ class DataTables extends Component {
this.dataRenderer = this.dataRenderer.bind( this );

this.table;
this.tableRef = createRef();
this.uniqueId = uuidv4();
}

Expand All @@ -34,12 +36,12 @@ class DataTables extends Component {
if ( this.props !== prevProps ) {
if ( this.props.options.responsive_bool !== prevProps.options.responsive_bool ) {
if ( 'true' === prevProps.options.responsive_bool ) {
document.getElementById( `dataTable-instances-${ this.props.id }-${ this.uniqueId }` ).classList.remove( 'collapsed' );
this.tableRef.current.classList.remove( 'collapsed' );
}
}

this.table.destroy();
document.getElementById( `dataTable-instances-${ this.props.id }-${ this.uniqueId }` ).innerHTML = '';
this.tableRef.current.innerHTML = '';
this.initDataTable( this.props.columns, this.props.rows );
}
}
Expand Down Expand Up @@ -84,7 +86,9 @@ class DataTables extends Component {
return row;
});

this.table = jQuery( `#dataTable-instances-${ this.props.id }-${ this.uniqueId }` ).DataTable({
const responsive = !! this.props.chartsScreen || 'true' === settings.responsive_bool;

this.table = jQuery( this.tableRef.current ).DataTable({
Comment thread
pirate-bot marked this conversation as resolved.
Resolved
destroy: true,
data: data,
columns: columns,
Expand All @@ -95,13 +99,18 @@ class DataTables extends Component {
fixedHeader: 'true' === settings.fixedHeader_bool ? true : false,
scrollCollapse: !! this.props.chartsScreen || 'true' === settings.scrollCollapse_bool ? true : false,
scrollY: this.props.chartsScreen && 180 || ( 'true' === settings.scrollCollapse_bool && Number( settings.scrollY_int ) || false ),
responsive: !! this.props.chartsScreen || 'true' === settings.responsive_bool ? true : false,
responsive,
searching: false,
select: false,
lengthChange: false,
bFilter: false,
bInfo: false
});

// Responsive starts from a handler on the global document, which a table in the editor iframe never reaches.
if ( responsive && ! this.table.settings()[0]._responsive ) {
new jQuery.fn.dataTable.Responsive( this.table, {} );
}
}

dataRenderer( type, index ) {
Expand Down Expand Up @@ -192,7 +201,7 @@ class DataTables extends Component {
</style>
) }

<table id={ `dataTable-instances-${ this.props.id }-${ this.uniqueId }` }></table>
<table id={ `dataTable-instances-${ this.props.id }-${ this.uniqueId }` } ref={ this.tableRef }></table>
</Fragment>
);
}
Expand Down
Loading
Loading