%PDF- %PDF-
| Direktori : /dom645759/wp-content/plugins/fusion-builder/js/ |
| Current File : /dom645759/wp-content/plugins/fusion-builder/js/awb-table-editor.js |
/* global AWBTable, fusionBuilderText */
/* eslint-disable no-mixed-operators */
/**
* Table editor for the Table element's settings, used by both the Live
* Editor and the back-end builder.
*
* A spreadsheet like grid on top of AWBTable: click to select, type or
* double-click to edit, shift or drag to select ranges, paste from Excel or
* Google Sheets, and row/column handles to insert, move, duplicate, delete
* and configure. Every change is written back to the hidden element_content
* textarea as plain table markup, and gets its own undo step.
*
* The commands are exposed as AWBTableEditor.commands, so the on-canvas
* editing in the Live Editor runs exactly the same operations.
*
* Optional features are on unless the option container switches them off,
* ex: data-features='{"marks":false}'. This file is shared as it is by
* Avada One and Avada Classic, which offers fewer of them; see FEATURES.
*
* @since 1.0
*/
window.AWBTableEditor = ( function( $ ) {
'use strict';
var SIMPLE_TAGS = [ 'B', 'STRONG', 'I', 'EM', 'U', 'A', 'BR', 'SPAN', 'SUB', 'SUP', 'CODE', 'MARK', 'SMALL', 'S', 'DEL', 'INS' ],
DANGEROUS = 'script,style,iframe,object,embed,link,meta,base,form,input,textarea,select,button',
HISTORY_MAX = 100,
FEATURES = {
marks: true, // Check, cross and partial marks.
highlight: true, // Highlighted rows and columns.
filter: true, // Columns filtered on the page.
align: true, // Column alignment.
width: true, // Column width.
visibility: true, // Column visibility per screen size.
rowHeight: true, // Row height.
import: true, // Import Data.
ai: true // Generate with AI.
},
ICONS = {
caret: '<span class="fusiona-caret-down" aria-hidden="true"></span>',
alignLeft: '<span class="fusiona-align-left" aria-hidden="true"></span>',
alignCenter: '<span class="fusiona-align-center" aria-hidden="true"></span>',
alignRight: '<span class="fusiona-align-right" aria-hidden="true"></span>',
merge: '<span class="fusiona-table-merge" aria-hidden="true"></span>',
split: '<span class="fusiona-table-split" aria-hidden="true"></span>',
bold: '<span class="fusiona-bold" aria-hidden="true"></span>',
italic: '<span class="fusiona-italic" aria-hidden="true"></span>',
link: '<span class="fusiona-link" aria-hidden="true"></span>',
more: '<span class="fusiona-ellipsis" aria-hidden="true"></span>',
plus: '<span class="fusiona-plus" aria-hidden="true"></span>',
grip: '<span class="fusiona-icon-move" aria-hidden="true"></span>',
mark: '<span class="fusiona-check" aria-hidden="true"></span>',
expand: '<span class="fusiona-expand-alt" aria-hidden="true"></span>',
collapse: '<span class="fusiona-expand-alt" aria-hidden="true"></span>',
// Menu icons are class names.
rowAbove: 'fusiona-table-row-above',
rowBelow: 'fusiona-table-row-below',
rowDelete: 'fusiona-table-row-delete',
columnLeft: 'fusiona-table-column-left',
columnRight: 'fusiona-table-column-right',
columnDelete: 'fusiona-table-column-delete',
duplicate: 'fusiona-copy',
up: 'fusiona-arrow-up',
down: 'fusiona-arrow-down',
left: 'fusiona-arrow-left',
right: 'fusiona-arrow-right',
header: 'fusiona-table',
highlight: 'fusiona-star',
filter: 'fusiona-filter-by-attributes',
clear: 'fusiona-eraser-solid',
importData: 'fusiona-af-upload',
code: 'fusiona-code',
mergeItem: 'fusiona-table-merge',
splitItem: 'fusiona-table-split',
markYes: 'fusiona-check',
markNo: 'fusiona-close-fb',
markPartial: 'fusiona-minus',
ai: 'fusiona-avada-ai',
small: 'fusiona-mobile',
medium: 'fusiona-tablet',
large: 'fusiona-desktop'
},
instances = [];
/**
* Gets a translated string.
*
* @param {string} key - The string key.
* @param {string} fallback - Text when the string is missing.
* @return {string}
*/
function t( key, fallback ) {
var strings = 'undefined' !== typeof fusionBuilderText && fusionBuilderText.table_editor ? fusionBuilderText.table_editor : {},
text = 'string' === typeof strings[ key ] ? strings[ key ] : ( fallback || key ),
el;
// The strings are escaped for HTML, text nodes want them plain.
if ( -1 !== text.indexOf( '&' ) ) {
el = document.createElement( 'textarea' );
el.innerHTML = text;
text = el.value;
}
return text;
}
/**
* Replaces %s / %1$s placeholders.
*
* @param {string} text - The text.
* @return {string}
*/
function sprintf( text ) {
var args = Array.prototype.slice.call( arguments, 1 ),
index = 0;
return text.replace( /%(\d+\$)?s/g, function( match, position ) {
return String( position ? args[ parseInt( position, 10 ) - 1 ] : args[ index++ ] );
} );
}
/**
* Column letter for an index: A, B … Z, AA …
*
* @param {number} index - Zero based column index.
* @return {string}
*/
function columnName( index ) {
var name = '';
index++;
while ( 0 < index ) {
name = String.fromCharCode( 65 + ( index - 1 ) % 26 ) + name;
index = Math.floor( ( index - 1 ) / 26 );
}
return name;
}
/**
* Markup safe for showing in the editor. Only for display: the saved content is never touched.
*
* @param {string} html - Cell content.
* @return {string}
*/
function displayHtml( html ) {
var template = document.createElement( 'template' );
template.innerHTML = html;
template.content.querySelectorAll( DANGEROUS ).forEach( function( el ) {
el.remove();
} );
template.content.querySelectorAll( '*' ).forEach( function( el ) {
Array.prototype.slice.call( el.attributes ).forEach( function( attr ) {
if ( /^on/i.test( attr.name ) || ( /^(href|src|xlink:href|action|formaction)$/i.test( attr.name ) && /^\s*(javascript|data):/i.test( attr.value ) ) ) {
el.removeAttribute( attr.name );
}
} );
} );
// Typing must not land in the hidden label of a mark.
template.content.querySelectorAll( '.awb-table__mark' ).forEach( function( mark ) {
mark.setAttribute( 'contenteditable', 'false' );
} );
return template.innerHTML;
}
/**
* Whether cell content only has simple inline formatting, so it can be edited visually.
*
* @param {string} html - Cell content.
* @return {boolean}
*/
function isSimpleHtml( html ) {
var template = document.createElement( 'template' );
template.innerHTML = html;
return Array.prototype.every.call( template.content.querySelectorAll( '*' ), function( el ) {
return -1 !== SIMPLE_TAGS.indexOf( el.tagName );
} );
}
/**
* Cleans what a contenteditable cell produced.
*
* @param {Element} el - The edited element.
* @return {string}
*/
function cleanEditedHtml( el ) {
var html = el.innerHTML;
// Browsers wrap new lines in divs or paragraphs.
html = html.replace( /<(div|p)[^>]*>/gi, '<br>' ).replace( /<\/(div|p)>/gi, '' );
html = html.replace( /^(\s|<br\s*\/?>)+|(\s|<br\s*\/?>)+$/gi, '' );
html = html.replace( / /g, ' ' ).replace( / {2,}/g, ' ' );
html = html.replace( / contenteditable="false"/g, '' );
// Undo the & the browser adds inside shortcode attributes.
html = html.replace( /\[[^\[\]]*\]/g, function( shortcode ) {
return shortcode.replace( /&/g, '&' );
} );
return html.trim();
}
/**
* The Avada AI connection, when this site and user may use it: the site
* token is only handed to users with AI access, on a Pro plan with AI on.
*
* @return {Object|null} { token, userId }
*/
function aiConnection() {
var app = window.AwbPlusApp || null,
myAvada = app && app.my_avada ? app.my_avada : null,
token = myAvada && myAvada.connection ? myAvada.connection.site_token : '';
if ( ! token || 'pro' !== myAvada.plan || false === myAvada.is_ai_enabled ) {
return null;
}
return { token: token, userId: app.user_id || null };
}
/**
* Plain text of cell content, for describing a table to the AI: marks are words.
*
* @param {string} html - Cell content.
* @return {string}
*/
function cellText( html ) {
var template = document.createElement( 'template' );
template.innerHTML = html;
template.content.querySelectorAll( '.awb-table__mark' ).forEach( function( mark ) {
mark.replaceWith( ' [' + ( mark.getAttribute( 'data-mark' ) || '' ) + '] ' );
} );
return template.content.textContent.replace( /\s+/g, ' ' ).trim();
}
/**
* A check, cross or partial mark. Its name is saved inside it and hidden by
* CSS: editors such as TinyMCE drop empty spans, and text-only copies of
* the page (feeds, Markdown, no CSS) still read it.
*
* @param {string} type - yes, no or partial.
* @return {string}
*/
function markHtml( type ) {
var fallback = { yes: 'Yes', no: 'No', partial: 'Partly' };
return '<span class="awb-table__mark" data-mark="' + type + '">' + AWBTable.escHtml( t( 'mark_' + type, fallback[ type ] ) ) + '</span>';
}
/**
* Table markup from the worker's structured table. Every text is escaped:
* nothing the AI writes reaches the page as markup.
*
* @param {Object} data - { caption, first_column_header, columns, rows: [ [ { text, mark } ] ] }.
* @return {string}
*/
function aiTableHtml( data ) {
var html = '<table>';
function cell( tag, item, scope ) {
var mark = item && -1 !== [ 'yes', 'no', 'partial' ].indexOf( item.mark ) ? markHtml( item.mark ) : '',
text = item && item.text ? AWBTable.textToHtml( item.text ) : '';
return '<' + tag + ( scope ? ' scope="' + scope + '"' : '' ) + '>' + mark + ( mark && text ? ' ' : '' ) + text + '</' + tag + '>';
}
if ( data.caption ) {
html += '<caption>' + AWBTable.escHtml( data.caption ) + '</caption>';
}
if ( data.columns && data.columns.length ) {
html += '<thead><tr>' + data.columns.map( function( label ) {
return cell( 'th', { text: label }, 'col' );
} ).join( '' ) + '</tr></thead>';
}
html += '<tbody>' + data.rows.map( function( row ) {
return '<tr>' + row.map( function( item, index ) {
return 0 === index && data.first_column_header ? cell( 'th', item, 'row' ) : cell( 'td', item );
} ).join( '' ) + '</tr>';
} ).join( '' ) + '</tbody></table>';
return html;
}
/**
* Selection helpers. A selection is { r1, c1, r2, c2, ar, ac }: a range plus the active cell.
*/
function makeSelection( r1, c1, r2, c2, ar, ac ) {
return {
r1: Math.min( r1, r2 ),
c1: Math.min( c1, c2 ),
r2: Math.max( r1, r2 ),
c2: Math.max( c1, c2 ),
ar: 'undefined' === typeof ar ? r1 : ar,
ac: 'undefined' === typeof ac ? c1 : ac
};
}
/**
* Clamps a selection to the table, growing it over merged cells.
*
* @param {Object} table - AWBTable.Table.
* @param {Object} sel - The selection.
* @return {Object}
*/
function fitSelection( table, sel ) {
var rows = table.rowCount(),
cols = table.columnCount(),
range,
span;
if ( ! rows || ! cols ) {
return makeSelection( 0, 0, 0, 0 );
}
range = table.expandRange( {
r1: Math.max( 0, Math.min( sel.r1, rows - 1 ) ),
c1: Math.max( 0, Math.min( sel.c1, cols - 1 ) ),
r2: Math.max( 0, Math.min( sel.r2, rows - 1 ) ),
c2: Math.max( 0, Math.min( sel.c2, cols - 1 ) )
} );
span = table.getSpan( Math.max( 0, Math.min( sel.ar, rows - 1 ) ), Math.max( 0, Math.min( sel.ac, cols - 1 ) ) );
return makeSelection( range.r1, range.c1, range.r2, range.c2, span.row, span.col );
}
/**
* Whether a selection covers whole rows / whole columns.
*/
function isFullRows( table, sel ) {
return 0 === sel.c1 && sel.c2 === table.columnCount() - 1;
}
function isFullColumns( table, sel ) {
return 0 === sel.r1 && sel.r2 === table.rowCount() - 1;
}
/**
* The editing commands. Each takes the table and the selection, changes
* the table and returns the new selection, or false when it can not run.
* They are shared with the on-canvas editing in the Live Editor.
*/
var commands = {
insertRowAbove: function( table, sel ) {
var r = sel.r1;
if ( table.rowLineCrossed( r ) ) {
r = table.getSpan( r, sel.c1 ).row;
}
table.insertRow( r, table.getSection( r ) );
return makeSelection( r, sel.c1, r, sel.c2, r, sel.ac );
},
insertRowBelow: function( table, sel ) {
var r = sel.r2 + 1;
table.insertRow( r, table.getSection( sel.r2 ) );
return makeSelection( r, sel.c1, r, sel.c2, r, sel.ac );
},
insertColumnLeft: function( table, sel ) {
table.insertColumn( sel.c1 );
return makeSelection( sel.r1, sel.c1, sel.r2, sel.c1, sel.ar, sel.c1 );
},
insertColumnRight: function( table, sel ) {
var c = sel.c2 + 1;
table.insertColumn( c );
return makeSelection( sel.r1, c, sel.r2, c, sel.ar, c );
},
deleteRows: function( table, sel ) {
var r;
if ( sel.r2 - sel.r1 + 1 >= table.rowCount() ) {
return false;
}
for ( r = sel.r2; r >= sel.r1; r-- ) {
table.deleteRow( r );
}
r = Math.min( sel.r1, table.rowCount() - 1 );
return makeSelection( r, sel.c1, r, sel.c1 );
},
deleteColumns: function( table, sel ) {
var c;
if ( sel.c2 - sel.c1 + 1 >= table.columnCount() ) {
return false;
}
for ( c = sel.c2; c >= sel.c1; c-- ) {
table.deleteColumn( c );
}
c = Math.min( sel.c1, table.columnCount() - 1 );
return makeSelection( sel.r1, c, sel.r1, c );
},
duplicateRows: function( table, sel ) {
var count = sel.r2 - sel.r1 + 1;
if ( ! table.duplicateRows( sel.r1, sel.r2 ) ) {
return false;
}
return makeSelection( sel.r2 + 1, sel.c1, sel.r2 + count, sel.c2 );
},
duplicateColumns: function( table, sel ) {
var count = sel.c2 - sel.c1 + 1;
if ( ! table.duplicateColumns( sel.c1, sel.c2 ) ) {
return false;
}
return makeSelection( sel.r1, sel.c2 + 1, sel.r2, sel.c2 + count );
},
moveRowsUp: function( table, sel ) {
var r;
if ( 0 === sel.r1 || ! table.canMoveRow( sel.r1 - 1, sel.r2 ) ) {
return false;
}
// Moving the row above below the selection moves the whole selection up.
table.moveRow( sel.r1 - 1, sel.r2 );
r = sel.r1 - 1;
return makeSelection( r, sel.c1, sel.r2 - 1, sel.c2, sel.ar - 1, sel.ac );
},
moveRowsDown: function( table, sel ) {
if ( sel.r2 >= table.rowCount() - 1 || ! table.canMoveRow( sel.r2 + 1, sel.r1 ) ) {
return false;
}
table.moveRow( sel.r2 + 1, sel.r1 );
return makeSelection( sel.r1 + 1, sel.c1, sel.r2 + 1, sel.c2, sel.ar + 1, sel.ac );
},
moveColumnsLeft: function( table, sel ) {
if ( 0 === sel.c1 || ! table.canMoveColumn( sel.c1 - 1, sel.c2 ) ) {
return false;
}
table.moveColumn( sel.c1 - 1, sel.c2 );
return makeSelection( sel.r1, sel.c1 - 1, sel.r2, sel.c2 - 1, sel.ar, sel.ac - 1 );
},
moveColumnsRight: function( table, sel ) {
if ( sel.c2 >= table.columnCount() - 1 || ! table.canMoveColumn( sel.c2 + 1, sel.c1 ) ) {
return false;
}
table.moveColumn( sel.c2 + 1, sel.c1 );
return makeSelection( sel.r1, sel.c1 + 1, sel.r2, sel.c2 + 1, sel.ar, sel.ac + 1 );
},
merge: function( table, sel ) {
var range = table.merge( sel );
return range ? makeSelection( range.r1, range.c1, range.r2, range.c2 ) : false;
},
split: function( table, sel ) {
return table.split( sel ) ? sel : false;
},
clear: function( table, sel ) {
table.clearRange( sel );
return sel;
},
// Check, cross and partial marks replace the content of the selected cells, as comparison tables need.
mark: function( table, sel, type ) {
var r, c;
for ( r = sel.r1; r <= sel.r2; r++ ) {
for ( c = sel.c1; c <= sel.c2; c++ ) {
if ( table.isAnchor( r, c ) ) {
table.setCellHtml( r, c, markHtml( type ) );
}
}
}
return sel;
},
markYes: function( table, sel ) {
return commands.mark( table, sel, 'yes' );
},
markNo: function( table, sel ) {
return commands.mark( table, sel, 'no' );
},
markPartial: function( table, sel ) {
return commands.mark( table, sel, 'partial' );
},
toggleHeaderRow: function( table, sel ) {
table.setHeadRows( table.headRows ? 0 : 1 );
return sel;
},
toggleHeaderColumn: function( table, sel ) {
table.setHeaderColumn( ! table.hasHeaderColumn() );
return sel;
},
toggleFooterRow: function( table, sel ) {
if ( ! table.footRows && table.rowCount() - table.headRows < 2 ) {
table.insertRow( table.rowCount(), 'body' );
}
table.setFootRows( table.footRows ? 0 : 1 );
return sel;
},
makeHeaderThrough: function( table, sel ) {
if ( 'foot' === table.getSection( sel.r2 ) || sel.r2 + 1 >= table.rowCount() - table.footRows ) {
return false;
}
table.setHeadRows( sel.r2 + 1 );
return sel;
},
alignLeft: function( table, sel ) {
return commands.align( table, sel, 'left' );
},
alignCenter: function( table, sel ) {
return commands.align( table, sel, 'center' );
},
alignRight: function( table, sel ) {
return commands.align( table, sel, 'right' );
},
align: function( table, sel, value ) {
var c,
all = true;
for ( c = sel.c1; c <= sel.c2; c++ ) {
all = all && table.columns[ c ] && value === table.columns[ c ].align;
}
// Clicking the active alignment again goes back to the default.
for ( c = sel.c1; c <= sel.c2; c++ ) {
table.setColumnProp( c, 'align', all ? '' : value );
}
return sel;
},
highlightColumns: function( table, sel ) {
var c,
state = ! table.columns[ sel.c1 ].highlight;
for ( c = sel.c1; c <= sel.c2; c++ ) {
table.setColumnProp( c, 'highlight', state );
}
return sel;
},
filterColumns: function( table, sel ) {
var c,
state = ! table.columns[ sel.c1 ].filter;
for ( c = sel.c1; c <= sel.c2; c++ ) {
table.setColumnProp( c, 'filter', state );
}
return sel;
},
highlightRows: function( table, sel ) {
var r,
state = ! table.isRowHighlighted( sel.r1 );
for ( r = sel.r1; r <= sel.r2; r++ ) {
table.setRowHighlight( r, state );
}
return sel;
}
};
/**
* Whether this runs in the Live Editor, which keeps its own history of every change.
*
* @return {boolean}
*/
function inLiveEditor() {
return 'undefined' !== typeof window.FusionApp && 'undefined' !== typeof window.FusionEvents;
}
/**
* The editor.
*
* @param {Element} root - The option wrapper.
* @param {Element} textarea - The element_content textarea.
*/
function Editor( root, textarea ) {
this.root = root;
this.textarea = textarea;
this.table = AWBTable.parse( textarea.value );
this.sel = makeSelection( 0, 0, 0, 0 );
this.past = [];
this.future = [];
this.editing = null;
this.features = Object.assign( {}, FEATURES, this.readFeatures( root ) );
this.build();
if ( ! this.table.valid ) {
this.table = AWBTable.create( 2, 2, true );
this.openHtml( textarea.value, t( 'invalid', 'The table markup could not be read. Fix it below, or apply to start from a new table.' ) );
}
this.render();
}
Editor.prototype = {
/**
* The features the option container switches off or on, from its data-features JSON.
*
* @param {Element} root - The option container.
* @return {Object}
*/
readFeatures: function( root ) {
try {
return JSON.parse( root.getAttribute( 'data-features' ) || '{}' ) || {};
} catch ( error ) {
return {};
}
},
/**
* Menu items without those of switched off features, and without the
* separators that leaves at the start, the end or next to each other.
*
* @param {Array} items - The items; { feature } names the feature of an item.
* @return {Array}
*/
withFeatures: function( items ) {
var self = this,
out = [];
items.forEach( function( item ) {
if ( item && item.feature && ! self.features[ item.feature ] ) {
return;
}
if ( 'separator' === item && ( ! out.length || 'separator' === out[ out.length - 1 ] ) ) {
return;
}
out.push( item );
} );
while ( out.length && 'separator' === out[ out.length - 1 ] ) {
out.pop();
}
return out;
},
/**
* Builds the editor chrome.
*
* @return {void}
*/
build: function() {
var self = this;
this.root.classList.add( 'awb-te', 'initialized' );
this.root.innerHTML =
'<div class="awb-te-toolbar" role="toolbar" aria-label="' + AWBTable.escAttr( t( 'toolbar', 'Table tools' ) ) + '">' +
this.menuButton( 'row', t( 'row', 'Row' ) ) +
this.menuButton( 'column', t( 'column', 'Column' ) ) +
'<span class="awb-te-sep"></span>' +
this.button( 'merge', ICONS.merge, t( 'merge', 'Merge cells' ) ) +
this.button( 'split', ICONS.split, t( 'split', 'Split cell' ) ) +
( this.features.marks ? this.menuButton( 'mark', '', ICONS.mark, t( 'marks', 'Check marks' ) ) : '' ) +
'<span class="awb-te-format">' +
'<span class="awb-te-sep"></span>' +
this.button( 'bold', ICONS.bold, t( 'bold', 'Bold' ) + ' (Ctrl+B)' ) +
this.button( 'italic', ICONS.italic, t( 'italic', 'Italic' ) + ' (Ctrl+I)' ) +
this.button( 'link', ICONS.link, t( 'link', 'Link' ) + ' (Ctrl+K)' ) +
'</span>' +
'<span class="awb-te-spacer"></span>' +
this.button( 'expand', ICONS.expand, t( 'expand', 'Expand editor' ) ) +
this.menuButton( 'more', '', ICONS.more, t( 'more', 'More' ) ) +
'</div>' +
'<div class="awb-te-structure">' +
this.toggle( 'toggleHeaderRow', t( 'header_row', 'Header row' ) ) +
this.toggle( 'toggleHeaderColumn', t( 'header_column', 'First column header' ) ) +
this.toggle( 'toggleFooterRow', t( 'footer_row', 'Footer row' ) ) +
'</div>' +
'<div class="awb-te-scroll"><table class="awb-te-grid" tabindex="0" role="grid" aria-multiselectable="true"></table></div>' +
'<div class="awb-te-footer"><span class="awb-te-status" aria-live="polite"></span></div>' +
'<div class="awb-te-panel awb-te-html-panel" hidden></div>' +
'<div class="awb-te-panel awb-te-import-panel" hidden></div>' +
'<div class="awb-te-panel awb-te-ai-panel" hidden></div>';
this.grid = this.root.querySelector( '.awb-te-grid' );
this.status = this.root.querySelector( '.awb-te-status' );
this.menu = new window.AWBEditorUI.Menu( this.root, this.onMenuAction.bind( this ) );
this.root.addEventListener( 'click', this.onClick.bind( this ) );
this.root.addEventListener( 'mousedown', function( event ) {
// Toolbar buttons must not steal focus from a cell being edited.
if ( event.target.closest( '.awb-te-toolbar button' ) ) {
event.preventDefault();
}
} );
// Change, not click: a click on the label clicks the checkbox a second time.
this.root.addEventListener( 'change', function( event ) {
if ( event.target.hasAttribute( 'data-toggle' ) ) {
self.run( event.target.getAttribute( 'data-toggle' ) );
} else if ( event.target.matches( '.awb-te-width-input, .awb-te-height-input' ) ) {
clearTimeout( self.sizeTimer );
self.applySize( event.target, true );
}
} );
// The Width and Height fields of the menus apply while typing, once a valid value is in.
this.root.addEventListener( 'input', function( event ) {
if ( event.target.matches( '.awb-te-width-input, .awb-te-height-input' ) ) {
clearTimeout( self.sizeTimer );
self.sizeTimer = setTimeout( function() {
self.applySize( event.target, false );
}, 400 );
}
} );
// Enter in them is done: apply and close the menu.
this.menu.el.addEventListener( 'keydown', function( event ) {
if ( 'Enter' === event.key && event.target.matches( '.awb-te-width-input, .awb-te-height-input' ) ) {
event.preventDefault();
clearTimeout( self.sizeTimer );
if ( self.applySize( event.target, true ) ) {
self.menu.close();
self.focusGrid();
}
} else if ( 'Escape' === event.key && event.target.matches( '.awb-te-width-input, .awb-te-height-input' ) ) {
// The menu button it would return to was rendered anew by the live change.
self.focusGrid();
}
} );
// The settings panel treats input events inside an option as a change of
// that option, which here is the table content. The editor's own fields
// (import, HTML, width, cell source) must never reach it.
[ 'change', 'input', 'keyup', 'keydown', 'paste' ].forEach( function( type ) {
self.root.addEventListener( type, function( event ) {
if ( 'keydown' !== type || event.target.matches( 'input, textarea, select' ) ) {
event.stopPropagation();
}
} );
} );
this.grid.addEventListener( 'mousedown', this.onMouseDown.bind( this ) );
this.grid.addEventListener( 'dblclick', this.onDoubleClick.bind( this ) );
this.grid.addEventListener( 'contextmenu', this.onContextMenu.bind( this ) );
this.grid.addEventListener( 'keydown', this.onKeyDown.bind( this ) );
this.grid.addEventListener( 'copy', this.onCopy.bind( this ) );
this.grid.addEventListener( 'cut', this.onCut.bind( this ) );
this.grid.addEventListener( 'paste', this.onPaste.bind( this ) );
this.root.addEventListener( 'keydown', function( event ) {
if ( 'Escape' === event.key && self.root.classList.contains( 'is-expanded' ) && ! self.editing && ! self.menu.isOpen() ) {
event.stopPropagation();
self.toggleExpand( false );
}
} );
$( this.textarea ).on( 'change.awbTableEditor', function() {
if ( ! self.writing ) {
self.reload();
}
} );
},
/**
* Button markup.
*/
button: function( command, icon, label ) {
return '<button type="button" class="awb-te-button" data-command="' + command + '" title="' + AWBTable.escAttr( label ) + '" aria-label="' + AWBTable.escAttr( label ) + '">' + icon + '</button>';
},
menuButton: function( menu, text, icon, label ) {
label = label || text;
return '<button type="button" class="awb-te-button awb-te-menu-button" data-menu="' + menu + '" aria-haspopup="menu" aria-expanded="false" aria-label="' + AWBTable.escAttr( label ) + '" title="' + AWBTable.escAttr( label ) + '">' + ( icon || '' ) + ( text ? '<span>' + AWBTable.escHtml( text ) + '</span>' + ICONS.caret : '' ) + '</button>';
},
toggle: function( command, label ) {
return '<label class="awb-te-toggle"><input type="checkbox" data-toggle="' + command + '"><span>' + AWBTable.escHtml( label ) + '</span></label>';
},
/**
* Reloads the model from the textarea, after an outside change such as the builder's undo.
*
* @return {void}
*/
reload: function() {
var table = AWBTable.parse( this.textarea.value );
if ( table.valid && table.toHTML() !== this.table.toHTML() ) {
this.table = table;
this.sel = fitSelection( this.table, this.sel );
this.render();
}
},
/**
* Renders the grid and the toolbar state.
*
* The grid has a strip of "+" cells after the last column and after the
* last row; both add to the table the same way.
*
* @return {void}
*/
render: function() {
var self = this,
table = this.table,
rows = table.rowCount(),
cols = table.columnCount(),
addCol = AWBTable.escAttr( t( 'add_column', 'Add column' ) ),
addRow = AWBTable.escAttr( t( 'add_row', 'Add row' ) ),
html = '<thead><tr><th class="awb-te-corner" title="' + AWBTable.escAttr( t( 'select_all', 'Select all' ) ) + '"></th>',
r, c;
this.sel = fitSelection( table, this.sel );
for ( c = 0; c < cols; c++ ) {
html += '<th class="awb-te-colhead' + ( c >= this.sel.c1 && c <= this.sel.c2 ? ' is-selected' : '' ) + '" data-col="' + c + '" scope="col">' +
'<span class="awb-te-handle">' + ICONS.grip + '</span>' +
'<span class="awb-te-name">' + columnName( c ) + '</span>' +
this.columnBadges( c ) +
'<button type="button" class="awb-te-head-menu" data-menu="column" data-col="' + c + '" tabindex="-1" aria-label="' + AWBTable.escAttr( sprintf( t( 'column_menu', 'Column %s options' ), columnName( c ) ) ) + '">' + ICONS.caret + '</button>' +
'</th>';
}
html += '<th class="awb-te-add awb-te-add-handle" data-command="addColumnEnd"><button type="button" data-command="addColumnEnd" aria-label="' + addCol + '" title="' + addCol + '">' + ICONS.plus + '</button></th></tr></thead><tbody>';
for ( r = 0; r < rows; r++ ) {
html += '<tr class="awb-te-' + table.getSection( r ) + ( table.isRowHighlighted( r ) ? ' is-highlighted' : '' ) + '">' +
'<th class="awb-te-rowhead' + ( r >= this.sel.r1 && r <= this.sel.r2 ? ' is-selected' : '' ) + '" data-row="' + r + '" scope="row">' +
'<span class="awb-te-handle">' + ICONS.grip + '</span>' +
'<span class="awb-te-name">' + ( r + 1 ) + '</span>' +
'<button type="button" class="awb-te-head-menu" data-menu="row" data-row="' + r + '" tabindex="-1" aria-label="' + AWBTable.escAttr( sprintf( t( 'row_menu', 'Row %s options' ), r + 1 ) ) + '">' + ICONS.caret + '</button>' +
'</th>';
for ( c = 0; c < cols; c++ ) {
if ( table.isAnchor( r, c ) ) {
html += this.cellHtml( r, c );
}
}
html += '<td class="awb-te-add awb-te-add-column-strip" data-command="addColumnEnd" title="' + addCol + '"></td></tr>';
}
html += '<tr class="awb-te-add-row-strip">' +
'<th class="awb-te-add awb-te-add-handle" data-command="addRowEnd"><button type="button" data-command="addRowEnd" aria-label="' + addRow + '" title="' + addRow + '">' + ICONS.plus + '</button></th>' +
'<td class="awb-te-add awb-te-add-row-cell" colspan="' + ( cols + 1 ) + '" data-command="addRowEnd" title="' + addRow + '"></td>' +
'</tr></tbody>';
this.grid.innerHTML = html;
this.editing = null;
this.root.querySelectorAll( '[data-toggle]' ).forEach( function( input ) {
var key = input.getAttribute( 'data-toggle' );
input.checked = 'toggleHeaderRow' === key ? 0 < table.headRows : ( 'toggleHeaderColumn' === key ? table.hasHeaderColumn() : 0 < table.footRows );
} );
this.updateToolbar();
this.updateStatus();
this.announceSelection();
// Keep the active cell in view.
window.requestAnimationFrame( function() {
var active = self.grid.querySelector( '.is-active' );
if ( active && active.scrollIntoView && self.root.contains( document.activeElement ) ) {
active.scrollIntoView( { block: 'nearest', inline: 'nearest' } );
}
} );
},
/**
* Small markers on a column head for its settings.
*
* @param {number} c - Column index.
* @return {string}
*/
columnBadges: function( c ) {
var column = this.table.columns[ c ],
out = '';
if ( ! column ) {
return out;
}
if ( column.width ) {
out += '<span class="awb-te-badge" title="' + AWBTable.escAttr( t( 'width', 'Width' ) ) + '">' + AWBTable.escHtml( column.width ) + '</span>';
}
if ( column.hide.length ) {
out += '<span class="awb-te-badge is-hidden" title="' + AWBTable.escAttr( t( 'hidden_on', 'Hidden on' ) + ': ' + column.hide.join( ', ' ) ) + '"><span class="fusiona-eye-slash" aria-hidden="true"></span></span>';
}
if ( column.highlight ) {
out += '<span class="awb-te-badge is-highlight" title="' + AWBTable.escAttr( t( 'highlighted', 'Highlighted' ) ) + '"><span class="fusiona-star" aria-hidden="true"></span></span>';
}
if ( column.filter ) {
out += '<span class="awb-te-badge is-filter" title="' + AWBTable.escAttr( t( 'filtered', 'Filter on the page' ) ) + '"><span class="fusiona-filter-by-attributes" aria-hidden="true"></span></span>';
}
return out;
},
/**
* Markup for a grid cell.
*
* @param {number} r - Row index.
* @param {number} c - Column index.
* @return {string}
*/
cellHtml: function( r, c ) {
var table = this.table,
cell = table.getCell( r, c ),
span = table.getSpan( r, c ),
sel = this.sel,
column = table.columns[ c ] || {},
classes = [ 'awb-te-cell', 'awb-te-cell-' + cell.tag ],
attrs = '';
if ( span.row <= sel.r2 && span.row + span.rowspan - 1 >= sel.r1 && span.col <= sel.c2 && span.col + span.colspan - 1 >= sel.c1 ) {
classes.push( 'is-selected' );
}
if ( r === sel.ar && c === sel.ac ) {
classes.push( 'is-active' );
}
if ( column.align ) {
classes.push( 'is-align-' + column.align );
}
if ( column.highlight && 'head' !== table.getSection( r ) ) {
classes.push( 'is-highlighted' );
}
if ( 1 < span.colspan ) {
attrs += ' colspan="' + span.colspan + '"';
}
if ( 1 < span.rowspan ) {
attrs += ' rowspan="' + span.rowspan + '"';
}
if ( ! isSimpleHtml( cell.html ) ) {
classes.push( 'is-complex' );
}
return '<td class="' + classes.join( ' ' ) + '" data-row="' + r + '" data-col="' + c + '"' + attrs + ' role="gridcell" aria-selected="' + ( -1 !== classes.indexOf( 'is-selected' ) ) + '"><div class="awb-te-content">' + displayHtml( cell.html ) + '</div></td>';
},
/**
* Enables the buttons that apply to the current selection.
*
* @return {void}
*/
updateToolbar: function() {
var table = this.table,
sel = this.sel,
states = {
merge: table.canMerge( sel ),
split: table.hasMergedCells( sel )
};
this.root.querySelectorAll( '.awb-te-toolbar [data-command]' ).forEach( function( button ) {
var command = button.getAttribute( 'data-command' );
if ( 'undefined' !== typeof states[ command ] ) {
button.disabled = ! states[ command ];
}
} );
this.root.classList.toggle( 'is-editing', !! this.editing );
},
/**
* Describes the table and selection for the status line.
*
* @return {void}
*/
updateStatus: function() {
var sel = this.sel,
text = sprintf( t( 'size', '%1$s rows × %2$s columns' ), this.table.rowCount(), this.table.columnCount() );
if ( sel.r1 !== sel.r2 || sel.c1 !== sel.c2 ) {
text += ' · ' + sprintf( t( 'selected', '%1$s × %2$s selected' ), sel.r2 - sel.r1 + 1, sel.c2 - sel.c1 + 1 );
} else {
text += ' · ' + columnName( sel.ac ) + ( sel.ar + 1 );
}
this.status.textContent = text;
},
/**
* Writes the table to the textarea.
*
* @param {boolean} rerender - Whether to render the grid again.
* @return {void}
*/
save: function( rerender ) {
this.writing = true;
this.textarea.value = this.table.toHTML();
$( this.textarea ).trigger( 'change' );
this.writing = false;
if ( false !== rerender ) {
this.render();
}
},
/**
* Remembers a state for the editor's own undo. Only used outside the
* Live Editor; there the builder's history records every change.
*
* @param {string} html - The state before the change.
* @param {Object} sel - The selection before the change.
* @return {void}
*/
remember: function( html, sel ) {
this.past.push( { html: html, sel: sel } );
if ( this.past.length > HISTORY_MAX ) {
this.past.shift();
}
this.future = [];
},
/**
* Runs a change.
*
* @param {Function} change - Returns the new selection, or false when nothing changed.
* @return {boolean}
*/
change: function( change ) {
var before = this.table.toHTML(),
beforeSel = this.sel,
result;
this.commitEdit();
result = change();
if ( false === result ) {
this.notify( t( 'not_possible', 'That is not possible with merged cells in the way, or for the last row or column.' ) );
this.table = AWBTable.parse( before );
this.render();
return false;
}
if ( result ) {
this.sel = fitSelection( this.table, result );
}
if ( this.table.toHTML() !== before ) {
this.remember( before, beforeSel );
this.save();
} else {
this.render();
}
return true;
},
/**
* Runs a shared command.
*
* @param {string} name - Command name.
* @return {void}
*/
run: function( name ) {
var self = this;
if ( 'function' !== typeof commands[ name ] ) {
return;
}
this.change( function() {
return commands[ name ]( self.table, self.sel );
} );
this.focusGrid();
},
/**
* Undo: the builder's history in the Live Editor, the editor's own steps elsewhere.
*
* @return {void}
*/
undo: function() {
var state;
this.commitEdit();
if ( inLiveEditor() ) {
window.FusionEvents.trigger( 'fusion-history-undo' );
return;
}
state = this.past.pop();
if ( state ) {
this.future.push( { html: this.table.toHTML(), sel: this.sel } );
this.table = AWBTable.parse( state.html );
this.sel = state.sel;
this.save();
}
},
redo: function() {
var state;
if ( inLiveEditor() ) {
window.FusionEvents.trigger( 'fusion-history-redo' );
return;
}
state = this.future.pop();
if ( state ) {
this.past.push( { html: this.table.toHTML(), sel: this.sel } );
this.table = AWBTable.parse( state.html );
this.sel = state.sel;
this.save();
}
},
/**
* Shows a short message in the status line.
*
* @param {string} message - The message.
* @return {void}
*/
notify: function( message ) {
var self = this;
this.status.textContent = message;
this.status.classList.add( 'is-notice' );
clearTimeout( this.noticeTimer );
this.noticeTimer = setTimeout( function() {
self.status.classList.remove( 'is-notice' );
self.updateStatus();
}, 4000 );
},
focusGrid: function() {
if ( ! this.editing ) {
this.grid.focus( { preventScroll: true } );
}
},
/**
* Selects a cell or extends the selection to it.
*
* @param {number} r - Row index.
* @param {number} c - Column index.
* @param {boolean} extend - Whether to extend the current selection.
* @return {void}
*/
select: function( r, c, extend ) {
var span = this.table.getSpan( r, c );
if ( extend ) {
this.sel = fitSelection( this.table, makeSelection( this.sel.ar, this.sel.ac, r, c, this.sel.ar, this.sel.ac ) );
} else {
this.sel = fitSelection( this.table, makeSelection( span.row, span.col, span.row + span.rowspan - 1, span.col + span.colspan - 1, span.row, span.col ) );
}
this.paintSelection();
},
/**
* Selects whole rows or columns, from the canvas handles too.
*
* @param {string} type - row or column.
* @param {number} index - Row or column index.
* @param {boolean} extend - Whether to extend from the current selection.
* @return {void}
*/
selectLine: function( type, index, extend ) {
var table = this.table,
last = 'row' === type ? table.columnCount() - 1 : table.rowCount() - 1;
if ( 'row' === type ) {
this.sel = extend ? makeSelection( this.sel.ar, 0, index, last, this.sel.ar, 0 ) : makeSelection( index, 0, index, last, index, 0 );
} else {
this.sel = extend ? makeSelection( 0, this.sel.ac, last, index, 0, this.sel.ac ) : makeSelection( 0, index, last, index, 0, index );
}
this.sel = fitSelection( table, this.sel );
this.paintSelection();
},
/**
* Updates selection classes without rebuilding the grid.
*
* @return {void}
*/
paintSelection: function() {
var sel = this.sel;
this.grid.querySelectorAll( 'td.awb-te-cell' ).forEach( function( td ) {
var r = parseInt( td.getAttribute( 'data-row' ), 10 ),
c = parseInt( td.getAttribute( 'data-col' ), 10 ),
rows = td.rowSpan || 1,
cols = td.colSpan || 1,
inRange = r <= sel.r2 && r + rows - 1 >= sel.r1 && c <= sel.c2 && c + cols - 1 >= sel.c1;
td.classList.toggle( 'is-selected', inRange );
td.classList.toggle( 'is-active', r === sel.ar && c === sel.ac );
td.setAttribute( 'aria-selected', inRange ? 'true' : 'false' );
} );
this.grid.querySelectorAll( '.awb-te-colhead' ).forEach( function( th ) {
var c = parseInt( th.getAttribute( 'data-col' ), 10 );
th.classList.toggle( 'is-selected', c >= sel.c1 && c <= sel.c2 );
} );
this.grid.querySelectorAll( '.awb-te-rowhead' ).forEach( function( th ) {
var r = parseInt( th.getAttribute( 'data-row' ), 10 );
th.classList.toggle( 'is-selected', r >= sel.r1 && r <= sel.r2 );
} );
this.updateToolbar();
this.updateStatus();
this.announceSelection();
},
/**
* Lets the Live Editor show the selection on the table in the preview.
*
* @return {void}
*/
announceSelection: function() {
$( document ).trigger( 'awb-table-editor-select', [ this, this.sel ] );
},
/**
* Sets the content of a cell from outside the grid (editing in the preview).
*
* @param {number} r - Row index.
* @param {number} c - Column index.
* @param {string} html - The content.
* @return {void}
*/
setCell: function( r, c, html ) {
var self = this;
this.change( function() {
self.table.setCellHtml( r, c, html );
return self.sel;
} );
},
/**
* The grid cell element of a slot.
*
* @param {number} r - Row index.
* @param {number} c - Column index.
* @return {Element|null}
*/
cellElement: function( r, c ) {
var span = this.table.getSpan( r, c );
return this.grid.querySelector( 'td[data-row="' + span.row + '"][data-col="' + span.col + '"]' );
},
/**
* Starts editing the active cell.
*
* @param {string} text - Optional text that replaces the content (typing into a selected cell).
* @return {void}
*/
startEdit: function( text ) {
var self = this,
r = this.sel.ar,
c = this.sel.ac,
cell = this.table.getCell( r, c ),
td = this.cellElement( r, c ),
rich = isSimpleHtml( cell.html ),
field, range;
if ( ! td || this.editing ) {
return;
}
this.select( r, c );
this.editing = { r: r, c: c, original: cell.html, rich: rich };
if ( rich ) {
field = td.querySelector( '.awb-te-content' );
field.contentEditable = 'true';
field.setAttribute( 'role', 'textbox' );
field.setAttribute( 'aria-multiline', 'true' );
if ( 'string' === typeof text ) {
field.textContent = text;
}
field.focus();
// Caret to the end.
range = document.createRange();
range.selectNodeContents( field );
range.collapse( false );
window.getSelection().removeAllRanges();
window.getSelection().addRange( range );
} else {
// Cells with elements or layout markup are edited as source, so nothing is lost.
field = document.createElement( 'textarea' );
field.className = 'awb-te-source';
field.value = 'string' === typeof text ? text : cell.html;
field.setAttribute( 'aria-label', t( 'cell_source', 'Cell content (HTML)' ) );
td.querySelector( '.awb-te-content' ).replaceWith( field );
field.focus();
field.setSelectionRange( field.value.length, field.value.length );
}
td.classList.add( 'is-editing' );
this.editing.field = field;
field.addEventListener( 'keydown', this.onEditKeyDown.bind( this ) );
field.addEventListener( 'blur', function() {
// Toolbar clicks keep focus (mousedown is prevented), so a blur means the user left the cell.
setTimeout( function() {
if ( self.editing && self.editing.field === field && document.activeElement !== field ) {
self.commitEdit();
}
}, 0 );
} );
field.addEventListener( 'paste', function( event ) {
var data = event.clipboardData,
text = data ? data.getData( 'text/plain' ) : '',
html = data ? data.getData( 'text/html' ) : '';
// A pasted range belongs into the grid, not into one cell.
if ( ( html && /<table/i.test( html ) ) || /\t/.test( text ) ) {
event.preventDefault();
self.commitEdit();
self.pasteData( html, text );
return;
}
if ( rich ) {
event.preventDefault();
document.execCommand( 'insertHTML', false, AWBTable.textToHtml( text ) );
}
} );
this.updateToolbar();
},
/**
* Finishes editing, keeping or discarding the edit.
*
* @param {boolean} cancel - Whether to discard.
* @return {void}
*/
commitEdit: function( cancel ) {
var editing = this.editing,
html;
if ( ! editing ) {
return;
}
this.editing = null;
html = editing.rich ? cleanEditedHtml( editing.field ) : editing.field.value.trim();
if ( ! cancel && html !== editing.original ) {
this.remember( this.table.toHTML(), this.sel );
this.table.setCellHtml( editing.r, editing.c, html );
this.save();
} else {
this.render();
}
},
/**
* Moves the active cell.
*
* @param {number} dr - Rows to move.
* @param {number} dc - Columns to move.
* @param {boolean} extend - Whether to extend the selection.
* @return {void}
*/
move: function( dr, dc, extend ) {
var table = this.table,
span = table.getSpan( this.sel.ar, this.sel.ac ),
r = this.sel.ar,
c = this.sel.ac,
end;
if ( extend ) {
// Grow or shrink the range from the side opposite the anchor.
end = {
r: this.sel.r1 === this.sel.ar && this.sel.r2 !== this.sel.ar ? this.sel.r2 : ( this.sel.r2 === this.sel.ar ? this.sel.r1 : this.sel.r2 ),
c: this.sel.c1 === this.sel.ac && this.sel.c2 !== this.sel.ac ? this.sel.c2 : ( this.sel.c2 === this.sel.ac ? this.sel.c1 : this.sel.c2 )
};
end.r = Math.max( 0, Math.min( table.rowCount() - 1, end.r + dr ) );
end.c = Math.max( 0, Math.min( table.columnCount() - 1, end.c + dc ) );
this.sel = fitSelection( table, makeSelection( this.sel.ar, this.sel.ac, end.r, end.c, this.sel.ar, this.sel.ac ) );
this.paintSelection();
return;
}
if ( 0 < dr ) {
r = span.row + span.rowspan;
} else if ( 0 > dr ) {
r = span.row - 1;
}
if ( 0 < dc ) {
c = span.col + span.colspan;
} else if ( 0 > dc ) {
c = span.col - 1;
}
r = Math.max( 0, Math.min( table.rowCount() - 1, r ) );
c = Math.max( 0, Math.min( table.columnCount() - 1, c ) );
this.select( r, c );
this.scrollActiveIntoView();
},
scrollActiveIntoView: function() {
var active = this.grid.querySelector( '.is-active' );
if ( active && active.scrollIntoView ) {
active.scrollIntoView( { block: 'nearest', inline: 'nearest' } );
}
},
/**
* Tab order: next cell, wrapping to the next row; past the last cell a new row is added.
*
* @param {boolean} back - Whether to go backwards.
* @return {void}
*/
tab: function( back ) {
var table = this.table,
span = table.getSpan( this.sel.ar, this.sel.ac ),
r = span.row,
c = back ? span.col - 1 : span.col + span.colspan;
if ( c >= table.columnCount() ) {
c = 0;
r = span.row + 1;
if ( r >= table.rowCount() ) {
this.change( function() {
table.insertRow( table.rowCount(), table.getSection( table.rowCount() - 1 ) );
return makeSelection( r, 0, r, 0 );
} );
this.focusGrid();
return;
}
} else if ( 0 > c ) {
r = span.row - 1;
c = table.columnCount() - 1;
if ( 0 > r ) {
return;
}
}
// Skip slots covered by a merged cell.
while ( ! table.isAnchor( r, c ) && c < table.columnCount() && 0 <= c ) {
c += back ? -1 : 1;
}
this.select( r, Math.max( 0, Math.min( c, table.columnCount() - 1 ) ) );
this.scrollActiveIntoView();
},
/**
* Keyboard handling on the grid.
*
* @param {Event} event - The keydown event.
* @return {void}
*/
onKeyDown: function( event ) {
var key = event.key,
mod = event.ctrlKey || event.metaKey,
done = true;
if ( this.editing || event.target !== this.grid ) {
return;
}
if ( mod && 'z' === key.toLowerCase() && ! event.shiftKey ) {
this.undo();
} else if ( mod && ( 'y' === key.toLowerCase() || ( 'z' === key.toLowerCase() && event.shiftKey ) ) ) {
this.redo();
} else if ( mod && 'a' === key.toLowerCase() ) {
this.sel = fitSelection( this.table, makeSelection( 0, 0, this.table.rowCount() - 1, this.table.columnCount() - 1, 0, 0 ) );
this.paintSelection();
} else if ( mod && ( 'c' === key.toLowerCase() || 'x' === key.toLowerCase() || 'v' === key.toLowerCase() ) ) {
// Let the browser fire copy, cut and paste.
done = false;
} else if ( 'ArrowUp' === key ) {
this.move( -1, 0, event.shiftKey );
} else if ( 'ArrowDown' === key ) {
this.move( 1, 0, event.shiftKey );
} else if ( 'ArrowLeft' === key ) {
this.move( 0, this.isRtl() ? 1 : -1, event.shiftKey );
} else if ( 'ArrowRight' === key ) {
this.move( 0, this.isRtl() ? -1 : 1, event.shiftKey );
} else if ( 'Tab' === key ) {
this.tab( event.shiftKey );
} else if ( 'Enter' === key || 'F2' === key ) {
this.startEdit();
} else if ( 'Delete' === key || 'Backspace' === key ) {
this.run( 'clear' );
} else if ( 'Escape' === key && ! this.root.classList.contains( 'is-expanded' ) ) {
this.select( this.sel.ar, this.sel.ac );
} else if ( 'ContextMenu' === key || ( 'F10' === key && event.shiftKey ) ) {
this.openMenu( 'cell', this.cellElement( this.sel.ar, this.sel.ac ) );
} else if ( 1 === key.length && ! mod && ! event.altKey ) {
// Typing into a selected cell replaces its content, as in a spreadsheet.
event.preventDefault();
this.startEdit( key );
return;
} else {
done = false;
}
if ( done ) {
event.preventDefault();
event.stopPropagation();
}
},
/**
* Keyboard handling while a cell is edited.
*
* @param {Event} event - The keydown event.
* @return {void}
*/
onEditKeyDown: function( event ) {
var key = event.key,
mod = event.ctrlKey || event.metaKey;
// The builder has its own shortcuts; typing in a cell must not trigger them.
event.stopPropagation();
if ( 'Escape' === key ) {
event.preventDefault();
this.commitEdit( true );
this.focusGrid();
} else if ( 'Enter' === key && ! event.shiftKey && ! event.altKey ) {
event.preventDefault();
this.commitEdit();
this.focusGrid();
this.move( 1, 0 );
} else if ( 'Enter' === key && event.shiftKey && this.editing && this.editing.rich ) {
event.preventDefault();
document.execCommand( 'insertLineBreak' );
} else if ( 'Tab' === key ) {
event.preventDefault();
this.commitEdit();
this.focusGrid();
this.tab( event.shiftKey );
} else if ( mod && 'k' === key.toLowerCase() && this.editing && this.editing.rich ) {
event.preventDefault();
this.format( 'link' );
} else if ( mod && 'b' === key.toLowerCase() && this.editing && this.editing.rich ) {
event.preventDefault();
this.format( 'bold' );
} else if ( mod && 'i' === key.toLowerCase() && this.editing && this.editing.rich ) {
event.preventDefault();
this.format( 'italic' );
}
},
/**
* Inline formatting of the cell being edited.
*
* @param {string} type - bold, italic or link.
* @return {void}
*/
format: function( type ) {
var url;
if ( ! this.editing || ! this.editing.rich ) {
return;
}
this.editing.field.focus();
if ( 'link' === type ) {
url = window.prompt( t( 'link_prompt', 'Link URL' ), 'https://' );
if ( url && /^(https?:|mailto:|tel:|\/|#)/i.test( url.trim() ) ) {
document.execCommand( 'createLink', false, url.trim() );
}
return;
}
document.execCommand( type );
},
isRtl: function() {
return 'rtl' === window.getComputedStyle( this.grid ).direction;
},
/**
* Mouse down: select a cell, a row, a column or everything; start drag selection or reordering.
*
* @param {Event} event - The mousedown event.
* @return {void}
*/
onMouseDown: function( event ) {
var self = this,
target = event.target,
td = target.closest( 'td.awb-te-cell' ),
head = target.closest( '.awb-te-colhead, .awb-te-rowhead' ),
r, c;
if ( 0 !== event.button && ! ( 2 === event.button && ( td || head ) ) ) {
return;
}
if ( target.closest( 'button, .awb-te-add' ) || ( this.editing && td && td.classList.contains( 'is-editing' ) ) ) {
return;
}
if ( this.editing ) {
this.commitEdit();
td = td ? this.cellElement( parseInt( td.getAttribute( 'data-row' ), 10 ), parseInt( td.getAttribute( 'data-col' ), 10 ) ) : null;
head = head ? this.grid.querySelector( head.classList.contains( 'awb-te-colhead' ) ? '.awb-te-colhead[data-col="' + head.getAttribute( 'data-col' ) + '"]' : '.awb-te-rowhead[data-row="' + head.getAttribute( 'data-row' ) + '"]' ) : null;
}
// Right clicks inside the selection keep it, for the context menu.
if ( 2 === event.button && td ) {
r = parseInt( td.getAttribute( 'data-row' ), 10 );
c = parseInt( td.getAttribute( 'data-col' ), 10 );
if ( r >= this.sel.r1 && r <= this.sel.r2 && c >= this.sel.c1 && c <= this.sel.c2 ) {
return;
}
}
event.preventDefault();
this.grid.focus( { preventScroll: true } );
if ( target.closest( '.awb-te-corner' ) ) {
this.sel = fitSelection( this.table, makeSelection( 0, 0, this.table.rowCount() - 1, this.table.columnCount() - 1, 0, 0 ) );
this.paintSelection();
return;
}
if ( head ) {
this.headDown( event, head );
return;
}
if ( ! td ) {
return;
}
r = parseInt( td.getAttribute( 'data-row' ), 10 );
c = parseInt( td.getAttribute( 'data-col' ), 10 );
this.select( r, c, event.shiftKey );
if ( 2 === event.button ) {
return;
}
// Drag to select a range.
function onMove( moveEvent ) {
var over = document.elementFromPoint( moveEvent.clientX, moveEvent.clientY ),
cell = over ? over.closest( 'td.awb-te-cell' ) : null;
if ( cell && self.grid.contains( cell ) ) {
self.select( parseInt( cell.getAttribute( 'data-row' ), 10 ), parseInt( cell.getAttribute( 'data-col' ), 10 ), true );
}
}
function onUp() {
document.removeEventListener( 'mousemove', onMove );
document.removeEventListener( 'mouseup', onUp );
}
document.addEventListener( 'mousemove', onMove );
document.addEventListener( 'mouseup', onUp );
},
/**
* Mouse down on a row or column head: select it, extend with shift, or drag to reorder.
*
* @param {Event} event - The mousedown event.
* @param {Element} head - The head cell.
* @return {void}
*/
headDown: function( event, head ) {
var self = this,
isColumn = head.classList.contains( 'awb-te-colhead' ),
index = parseInt( head.getAttribute( isColumn ? 'data-col' : 'data-row' ), 10 ),
table = this.table,
scroll = this.root.querySelector( '.awb-te-scroll' ),
startX = event.clientX,
startY = event.clientY,
inside = isColumn ? index >= this.sel.c1 && index <= this.sel.c2 && isFullColumns( table, this.sel ) : index >= this.sel.r1 && index <= this.sel.r2 && isFullRows( table, this.sel ),
dragging = false,
target = null,
marker;
if ( event.shiftKey ) {
this.selectLine( isColumn ? 'column' : 'row', index, true );
return;
}
if ( ! inside ) {
this.selectLine( isColumn ? 'column' : 'row', index );
}
if ( 2 === event.button ) {
return;
}
function onMove( moveEvent ) {
var heads, i, rect, pos, gridRect;
if ( ! dragging && Math.abs( moveEvent.clientX - startX ) + Math.abs( moveEvent.clientY - startY ) < 6 ) {
return;
}
if ( ! dragging ) {
dragging = true;
self.root.classList.add( 'is-reordering' );
marker = document.createElement( 'div' );
marker.className = 'awb-te-drop-marker' + ( isColumn ? ' is-column' : '' );
scroll.appendChild( marker );
}
heads = self.grid.querySelectorAll( isColumn ? '.awb-te-colhead' : '.awb-te-rowhead' );
gridRect = scroll.getBoundingClientRect();
target = heads.length;
for ( i = 0; i < heads.length; i++ ) {
rect = heads[ i ].getBoundingClientRect();
pos = isColumn ? moveEvent.clientX < rect.left + rect.width / 2 : moveEvent.clientY < rect.top + rect.height / 2;
if ( pos ) {
target = i;
break;
}
}
rect = heads[ Math.min( target, heads.length - 1 ) ].getBoundingClientRect();
if ( isColumn ) {
marker.style.left = ( ( target < heads.length ? rect.left : rect.right ) - gridRect.left + scroll.scrollLeft ) + 'px';
marker.style.top = '0';
marker.style.height = self.grid.offsetHeight + 'px';
} else {
marker.style.top = ( ( target < heads.length ? rect.top : rect.bottom ) - gridRect.top + scroll.scrollTop ) + 'px';
marker.style.left = '0';
marker.style.width = self.grid.offsetWidth + 'px';
}
}
function onUp() {
document.removeEventListener( 'mousemove', onMove );
document.removeEventListener( 'mouseup', onUp );
self.root.classList.remove( 'is-reordering' );
if ( marker ) {
marker.remove();
}
if ( ! dragging || null === target ) {
return;
}
self.moveSelectionTo( isColumn ? 'column' : 'row', target );
}
document.addEventListener( 'mousemove', onMove );
document.addEventListener( 'mouseup', onUp );
},
/**
* Moves the selected whole rows or columns, as dragged by their handles.
*
* @param {string} type - row or column.
* @param {number} target - The row or column index to drop before; the count drops after the last.
* @return {boolean} Whether anything moved.
*/
moveSelectionTo: function( type, target ) {
var self = this,
sel = this.sel,
isColumn = 'column' === type,
from = isColumn ? sel.c1 : sel.r1,
count = isColumn ? sel.c2 - sel.c1 + 1 : sel.r2 - sel.r1 + 1,
to;
// Dropping inside or right next to the selection changes nothing.
if ( target >= from && target <= from + count ) {
return false;
}
to = target > from ? target - count : target;
return this.change( function() {
var i, ok = true;
for ( i = 0; i < count; i++ ) {
if ( isColumn ) {
ok = ok && self.table.moveColumn( target > from ? from : from + i, target > from ? to + count - 1 : to + i );
} else {
ok = ok && self.table.moveRow( target > from ? from : from + i, target > from ? to + count - 1 : to + i );
}
}
if ( ! ok ) {
return false;
}
return isColumn ? makeSelection( 0, to, self.table.rowCount() - 1, to + count - 1, 0, to ) : makeSelection( to, 0, to + count - 1, self.table.columnCount() - 1, to, 0 );
} );
},
/**
* Applies a Width or Height field of the menus to the selected columns or rows.
* A plain number is pixels; "auto" or nothing leaves the size to the content.
*
* @param {Element} input - The field.
* @param {boolean} notify - Whether to explain an invalid value.
* @return {boolean} Whether the value is valid.
*/
applySize: function( input, notify ) {
var self = this,
isHeight = input.classList.contains( 'awb-te-height-input' ),
value = input.value.trim().replace( /^auto$/i, '' ),
widths = {},
same = true,
i;
value = /^\d+(\.\d+)?$/.test( value ) ? value + 'px' : value;
if ( '' !== value && ! ( isHeight ? /^\d+(\.\d+)?(px|em|rem|vh)$/ : /^\d+(\.\d+)?(px|%|em|rem|vw|ch)$/ ).test( value ) ) {
if ( notify ) {
this.notify( isHeight ? t( 'height_invalid', 'Use a height like 60px or 4em, or leave it empty for auto.' ) : t( 'width_invalid', 'Use a width like 25% or 200px, or leave it empty for auto.' ) );
}
return false;
}
if ( isHeight ) {
for ( i = this.sel.r1; i <= this.sel.r2; i++ ) {
same = same && this.table.getRowHeight( i ) === value;
}
if ( ! same ) {
this.change( function() {
var r;
for ( r = self.sel.r1; r <= self.sel.r2; r++ ) {
self.table.setRowHeight( r, value );
}
return self.sel;
} );
}
return true;
}
for ( i = this.sel.c1; i <= this.sel.c2; i++ ) {
same = same && this.table.columns[ i ] && this.table.columns[ i ].width === value;
widths[ i ] = value;
}
if ( ! same ) {
this.setColumnWidths( widths );
}
return true;
},
/**
* Sets column widths, as one change.
*
* @param {Object} widths - { column index: width }, an empty width is auto.
* @return {boolean}
*/
setColumnWidths: function( widths ) {
var self = this;
return this.change( function() {
Object.keys( widths ).forEach( function( c ) {
self.table.setColumnProp( parseInt( c, 10 ), 'width', widths[ c ] );
} );
return self.sel;
} );
},
onDoubleClick: function( event ) {
var td = event.target.closest( 'td.awb-te-cell' );
if ( td && ! td.classList.contains( 'is-editing' ) ) {
this.select( parseInt( td.getAttribute( 'data-row' ), 10 ), parseInt( td.getAttribute( 'data-col' ), 10 ) );
this.startEdit();
}
},
onContextMenu: function( event ) {
var td = event.target.closest( 'td.awb-te-cell' ),
head = event.target.closest( '.awb-te-colhead, .awb-te-rowhead' );
if ( this.editing && td && td.classList.contains( 'is-editing' ) ) {
return;
}
if ( td || head ) {
event.preventDefault();
this.openMenu( head ? ( head.classList.contains( 'awb-te-colhead' ) ? 'column' : 'row' ) : 'cell', null, event.clientX, event.clientY );
}
},
/**
* Clicks on buttons and menu buttons.
*
* @param {Event} event - The click event.
* @return {void}
*/
onClick: function( event ) {
var button = event.target.closest( '[data-command], [data-menu]' ),
command,
index;
if ( ! button || ! this.root.contains( button ) || this.menu.el.contains( button ) ) {
return;
}
if ( button.hasAttribute( 'data-menu' ) ) {
event.preventDefault();
// A head menu button first selects its row or column.
if ( button.hasAttribute( 'data-col' ) ) {
index = parseInt( button.getAttribute( 'data-col' ), 10 );
if ( ! ( index >= this.sel.c1 && index <= this.sel.c2 && isFullColumns( this.table, this.sel ) ) ) {
this.selectLine( 'column', index );
}
} else if ( button.hasAttribute( 'data-row' ) ) {
index = parseInt( button.getAttribute( 'data-row' ), 10 );
if ( ! ( index >= this.sel.r1 && index <= this.sel.r2 && isFullRows( this.table, this.sel ) ) ) {
this.selectLine( 'row', index );
}
}
if ( this.menu.isOpen() && this.menu.owner === button ) {
this.menu.close();
} else {
this.openMenu( button.getAttribute( 'data-menu' ), button );
}
return;
}
command = button.getAttribute( 'data-command' );
if ( button.disabled ) {
return;
}
if ( 'bold' === command || 'italic' === command || 'link' === command ) {
this.format( command );
} else if ( 'expand' === command ) {
this.toggleExpand();
} else if ( 'addRowEnd' === command ) {
this.addRowEnd();
} else if ( 'addColumnEnd' === command ) {
this.addColumnEnd();
} else {
this.run( command );
}
},
addRowEnd: function() {
var table = this.table;
this.change( function() {
var at = table.rowCount() - table.footRows;
table.insertRow( at, 'body' );
return makeSelection( at, 0, at, 0 );
} );
this.focusGrid();
},
addColumnEnd: function() {
var table = this.table;
this.change( function() {
var c = table.columnCount();
table.insertColumn( c );
return makeSelection( 0, c, 0, c );
} );
this.focusGrid();
},
/**
* Shows the editor bigger, over the builder, for large tables. The textarea
* stays where it is, so the builder keeps receiving every change.
*
* @param {boolean} state - Optional; toggles when omitted.
* @return {void}
*/
toggleExpand: function( state ) {
var self = this,
expand = 'boolean' === typeof state ? state : ! this.root.classList.contains( 'is-expanded' ),
button = this.root.querySelector( '[data-command="expand"]' );
this.commitEdit();
this.menu.close();
if ( expand && ! this.placeholder ) {
this.placeholder = document.createElement( 'div' );
this.root.parentNode.insertBefore( this.placeholder, this.root );
this.backdrop = document.createElement( 'div' );
this.backdrop.className = 'awb-te-backdrop';
this.backdrop.addEventListener( 'mousedown', function() {
self.toggleExpand( false );
} );
document.body.appendChild( this.backdrop );
document.body.appendChild( this.root );
this.root.classList.add( 'is-expanded' );
} else if ( ! expand && this.placeholder ) {
this.placeholder.replaceWith( this.root );
this.placeholder = null;
this.backdrop.remove();
this.backdrop = null;
this.root.classList.remove( 'is-expanded' );
}
button.innerHTML = expand ? ICONS.collapse : ICONS.expand;
button.setAttribute( 'aria-label', expand ? t( 'collapse', 'Collapse editor' ) : t( 'expand', 'Expand editor' ) );
button.setAttribute( 'title', button.getAttribute( 'aria-label' ) );
button.classList.toggle( 'is-active', expand );
this.focusGrid();
},
/**
* Opens a menu for the current selection.
*
* @param {string} type - row, column, cell or more.
* @param {Element} owner - Element to open under.
* @param {number} x - Optional client x.
* @param {number} y - Optional client y.
* @return {void}
*/
openMenu: function( type, owner, x, y ) {
this.commitEdit();
this.menuType = type;
this.menu.open( this.menuItems( type ), owner, x, y );
},
/**
* Menu items for the current selection.
*
* @param {string} type - row, column, cell or more.
* @return {Array}
*/
menuItems: function( type ) {
var table = this.table,
sel = this.sel,
rows = sel.r2 - sel.r1 + 1,
cols = sel.c2 - sel.c1 + 1,
column = table.columns[ sel.c1 ] || { hide: [], width: '', align: '' },
self = this,
rowItems, columnItems, markItems, hide;
rowItems = [
{ action: 'insertRowAbove', icon: ICONS.rowAbove, label: t( 'insert_row_above', 'Insert row above' ) },
{ action: 'insertRowBelow', icon: ICONS.rowBelow, label: t( 'insert_row_below', 'Insert row below' ) },
{ action: 'duplicateRows', icon: ICONS.duplicate, label: 1 < rows ? t( 'duplicate_rows', 'Duplicate rows' ) : t( 'duplicate_row', 'Duplicate row' ) },
{ action: 'moveRowsUp', icon: ICONS.up, label: t( 'move_up', 'Move up' ), disabled: 0 === sel.r1 || ! table.canMoveRow( sel.r1 - 1, sel.r2 ) },
{ action: 'moveRowsDown', icon: ICONS.down, label: t( 'move_down', 'Move down' ), disabled: sel.r2 >= table.rowCount() - 1 || ! table.canMoveRow( sel.r2 + 1, sel.r1 ) },
{ action: 'makeHeaderThrough', icon: ICONS.header, label: t( 'make_header', 'Make header rows up to here' ), disabled: 'foot' === table.getSection( sel.r2 ) || sel.r2 + 1 >= table.rowCount() - table.footRows },
{ action: 'highlightRows', icon: ICONS.highlight, label: t( 'highlight_row', 'Highlight' ), checked: table.isRowHighlighted( sel.r1 ), feature: 'highlight' },
'separator',
{ html: '<label class="awb-te-menu-row"><span class="awb-te-menu-label">' + AWBTable.escHtml( t( 'height', 'Height' ) ) + '</span><input type="text" class="awb-te-height-input" value="' + AWBTable.escAttr( table.getRowHeight( sel.r1 ) ) + '" placeholder="' + AWBTable.escAttr( t( 'height_placeholder', 'auto, ex: 60px' ) ) + '"></label>', feature: 'rowHeight' },
'separator',
{ action: 'deleteRows', icon: ICONS.rowDelete, label: 1 < rows ? sprintf( t( 'delete_rows', 'Delete %s rows' ), rows ) : t( 'delete_row', 'Delete row' ), disabled: rows >= table.rowCount(), danger: true }
];
// One row of buttons, like the column alignment.
markItems = [
{ html: '<span class="awb-te-menu-label">' + AWBTable.escHtml( t( 'mark', 'Mark' ) ) + '</span><span class="awb-te-menu-buttons">' +
[ [ 'markYes', ICONS.markYes, t( 'mark_yes_set', 'Set to check mark' ) ], [ 'markNo', ICONS.markNo, t( 'mark_no_set', 'Set to cross mark' ) ], [ 'markPartial', ICONS.markPartial, t( 'mark_partial_set', 'Set to partial mark' ) ] ].map( function( button ) {
return '<button type="button" class="awb-te-chip" data-action="' + button[ 0 ] + '" title="' + AWBTable.escAttr( button[ 2 ] ) + '" aria-label="' + AWBTable.escAttr( button[ 2 ] ) + '"><span class="' + button[ 1 ] + '" aria-hidden="true"></span></button>';
} ).join( '' ) + '</span>', feature: 'marks' }
];
hide = AWBTable.hideValues.map( function( size ) {
var visible = -1 === column.hide.indexOf( size );
// Like the builder's visibility options: on means shown, switch off to hide.
return '<button type="button" class="awb-te-chip' + ( visible ? ' is-active' : '' ) + '" data-action="hide" data-size="' + size + '" aria-pressed="' + visible + '" title="' + AWBTable.escAttr( t( 'size_' + size, size ) ) + '"><span class="' + ICONS[ size ] + '" aria-hidden="true"></span></button>';
} ).join( '' );
columnItems = [
{ action: 'insertColumnLeft', icon: ICONS.columnLeft, label: t( 'insert_column_left', 'Insert column left' ) },
{ action: 'insertColumnRight', icon: ICONS.columnRight, label: t( 'insert_column_right', 'Insert column right' ) },
{ action: 'duplicateColumns', icon: ICONS.duplicate, label: 1 < cols ? t( 'duplicate_columns', 'Duplicate columns' ) : t( 'duplicate_column', 'Duplicate column' ) },
{ action: 'moveColumnsLeft', icon: ICONS.left, label: t( 'move_left', 'Move left' ), disabled: 0 === sel.c1 || ! table.canMoveColumn( sel.c1 - 1, sel.c2 ) },
{ action: 'moveColumnsRight', icon: ICONS.right, label: t( 'move_right', 'Move right' ), disabled: sel.c2 >= table.columnCount() - 1 || ! table.canMoveColumn( sel.c2 + 1, sel.c1 ) },
{ action: 'highlightColumns', icon: ICONS.highlight, label: t( 'highlight_column', 'Highlight' ), checked: !! column.highlight, feature: 'highlight' },
{ action: 'filterColumns', icon: ICONS.filter, label: t( 'filter_column', 'Filter on the page' ), checked: !! column.filter, feature: 'filter' },
'separator',
{ html: '<span class="awb-te-menu-label">' + AWBTable.escHtml( t( 'align', 'Align' ) ) + '</span><span class="awb-te-menu-buttons">' +
[ [ 'alignLeft', ICONS.alignLeft, 'left', t( 'align_left', 'Align column left' ) ], [ 'alignCenter', ICONS.alignCenter, 'center', t( 'align_center', 'Align column center' ) ], [ 'alignRight', ICONS.alignRight, 'right', t( 'align_right', 'Align column right' ) ] ].map( function( button ) {
return '<button type="button" class="awb-te-chip' + ( column.align === button[ 2 ] ? ' is-active' : '' ) + '" data-action="' + button[ 0 ] + '" title="' + AWBTable.escAttr( button[ 3 ] ) + '" aria-label="' + AWBTable.escAttr( button[ 3 ] ) + '">' + button[ 1 ] + '</button>';
} ).join( '' ) + '</span>', feature: 'align' },
{ html: '<label class="awb-te-menu-row"><span class="awb-te-menu-label">' + AWBTable.escHtml( t( 'width', 'Width' ) ) + '</span><input type="text" class="awb-te-width-input" value="' + AWBTable.escAttr( column.width ) + '" placeholder="' + AWBTable.escAttr( t( 'width_placeholder', 'auto, ex: 25%' ) ) + '"></label>', feature: 'width' },
{ html: '<span class="awb-te-menu-label">' + AWBTable.escHtml( t( 'visibility', 'Visibility' ) ) + '</span><span class="awb-te-menu-buttons">' + hide + '</span>', feature: 'visibility' },
'separator',
{ action: 'deleteColumns', icon: ICONS.columnDelete, label: 1 < cols ? sprintf( t( 'delete_columns', 'Delete %s columns' ), cols ) : t( 'delete_column', 'Delete column' ), disabled: cols >= table.columnCount(), danger: true }
];
if ( 'row' === type ) {
return this.withFeatures( rowItems );
}
if ( 'column' === type ) {
return this.withFeatures( columnItems );
}
if ( 'mark' === type ) {
return this.withFeatures( markItems );
}
if ( 'cell' === type ) {
return this.withFeatures( [
{ action: 'merge', icon: ICONS.mergeItem, label: t( 'merge', 'Merge cells' ), disabled: ! table.canMerge( sel ) },
{ action: 'split', icon: ICONS.splitItem, label: t( 'split', 'Split cell' ), disabled: ! table.hasMergedCells( sel ) },
'separator',
{ action: 'insertRowAbove', icon: ICONS.rowAbove, label: t( 'insert_row_above', 'Insert row above' ) },
{ action: 'insertRowBelow', icon: ICONS.rowBelow, label: t( 'insert_row_below', 'Insert row below' ) },
{ action: 'insertColumnLeft', icon: ICONS.columnLeft, label: t( 'insert_column_left', 'Insert column left' ) },
{ action: 'insertColumnRight', icon: ICONS.columnRight, label: t( 'insert_column_right', 'Insert column right' ) },
'separator'
].concat( markItems, [
'separator',
{ action: 'clear', icon: ICONS.clear, label: t( 'clear', 'Clear content' ), danger: true },
{ action: 'deleteRows', icon: ICONS.rowDelete, label: 1 < rows ? sprintf( t( 'delete_rows', 'Delete %s rows' ), rows ) : t( 'delete_row', 'Delete row' ), disabled: rows >= table.rowCount(), danger: true },
{ action: 'deleteColumns', icon: ICONS.columnDelete, label: 1 < cols ? sprintf( t( 'delete_columns', 'Delete %s columns' ), cols ) : t( 'delete_column', 'Delete column' ), disabled: cols >= table.columnCount(), danger: true }
] ) );
}
return this.withFeatures( ( aiConnection() ? [ { action: 'ai', icon: ICONS.ai, label: t( 'ai', 'Generate with AI' ), feature: 'ai' } ] : [] ).concat( [
{ action: 'import', icon: ICONS.importData, label: t( 'import', 'Import Data' ), feature: 'import' },
{ action: 'html', icon: ICONS.code, label: t( 'edit_html', 'Edit as HTML' ) },
'separator',
{ action: 'clearAll', icon: ICONS.clear, label: t( 'clear_all', 'Clear all content' ), danger: true }
] ) );
},
/**
* Runs a menu item.
*
* @param {string} action - The action.
* @param {Element} button - The menu button.
* @return {void}
*/
onMenuAction: function( action, button ) {
var self = this,
owner = this.menu.owner,
type = this.menuType,
size;
if ( 'hide' === action ) {
size = button.getAttribute( 'data-size' );
this.change( function() {
var c, hide;
for ( c = self.sel.c1; c <= self.sel.c2; c++ ) {
hide = self.table.columns[ c ].hide.slice();
// An active chip means visible, so switching it off hides the column there.
if ( ! button.classList.contains( 'is-active' ) ) {
hide = hide.filter( function( item ) {
return item !== size;
} );
} else if ( -1 === hide.indexOf( size ) ) {
hide.push( size );
}
self.table.setColumnProp( c, 'hide', AWBTable.hideValues.filter( function( item ) {
return -1 !== hide.indexOf( item );
} ) );
}
return self.sel;
} );
// Keep the menu open, so several settings can be changed in a row.
this.reopenMenu( type, owner );
return;
}
if ( 0 === action.indexOf( 'align' ) ) {
this.run( action );
this.reopenMenu( type, owner );
return;
}
this.menu.close();
if ( 'ai' === action ) {
this.openAi();
} else if ( 'import' === action ) {
this.openImport();
} else if ( 'html' === action ) {
this.openHtml();
} else if ( 'clearAll' === action ) {
this.change( function() {
self.table.clearRange( { r1: 0, c1: 0, r2: self.table.rowCount() - 1, c2: self.table.columnCount() - 1 } );
return self.sel;
} );
this.focusGrid();
} else {
this.run( action );
}
},
/**
* Opens a menu again after the grid was rendered, under the new copy of its owner.
*
* @param {string} type - The menu type.
* @param {Element} owner - The old owner.
* @return {void}
*/
reopenMenu: function( type, owner ) {
var fresh = null;
if ( owner && owner.hasAttribute( 'data-col' ) ) {
fresh = this.grid.querySelector( '.awb-te-head-menu[data-col="' + owner.getAttribute( 'data-col' ) + '"]' );
} else if ( owner && owner.hasAttribute( 'data-row' ) ) {
fresh = this.grid.querySelector( '.awb-te-head-menu[data-row="' + owner.getAttribute( 'data-row' ) + '"]' );
} else if ( owner && this.root.contains( owner ) ) {
fresh = owner;
}
this.openMenu( type, fresh || this.grid.querySelector( '.awb-te-colhead[data-col="' + this.sel.c1 + '"]' ) );
},
/**
* Copies the selection as tab separated text and as a table.
*
* @param {Event} event - The copy event.
* @return {void}
*/
onCopy: function( event ) {
var data = this.table.readData( this.sel ),
text = data.map( function( line ) {
return line.map( function( html ) {
var value = $( '<div>' ).html( html.replace( /<br\s*\/?>/gi, '\n' ) ).text();
return /[\t\n"]/.test( value ) ? '"' + value.replace( /"/g, '""' ) + '"' : value;
} ).join( '\t' );
} ).join( '\n' ),
html = '<table>' + data.map( function( line ) {
return '<tr>' + line.map( function( cell ) {
return '<td>' + cell + '</td>';
} ).join( '' ) + '</tr>';
} ).join( '' ) + '</table>';
if ( this.editing || ! event.clipboardData ) {
return;
}
event.preventDefault();
event.clipboardData.setData( 'text/plain', text );
event.clipboardData.setData( 'text/html', html );
},
onCut: function( event ) {
if ( this.editing ) {
return;
}
this.onCopy( event );
this.run( 'clear' );
},
onPaste: function( event ) {
var data = event.clipboardData;
if ( this.editing || ! data ) {
return;
}
event.preventDefault();
this.pasteData( data.getData( 'text/html' ), data.getData( 'text/plain' ) );
},
/**
* Writes pasted data into the grid from the active cell, growing the table as needed.
* A single value pasted over a range fills the range.
*
* @param {string} html - Clipboard markup.
* @param {string} text - Clipboard text.
* @return {void}
*/
pasteData: function( html, text ) {
var self = this,
data = html && /<table/i.test( html ) ? AWBTable.dataFromHtml( html ) : null;
if ( ! data ) {
data = AWBTable.parseDelimited( text, -1 !== ( text || '' ).indexOf( '\t' ) ? '\t' : '\u0000' ).map( function( line ) {
return line.map( AWBTable.textToHtml );
} );
}
if ( ! data || ! data.length ) {
return;
}
this.change( function() {
var range, r, c;
if ( 1 === data.length && 1 === data[ 0 ].length && ( self.sel.r1 !== self.sel.r2 || self.sel.c1 !== self.sel.c2 ) ) {
for ( r = self.sel.r1; r <= self.sel.r2; r++ ) {
for ( c = self.sel.c1; c <= self.sel.c2; c++ ) {
if ( self.table.isAnchor( r, c ) ) {
self.table.setCellHtml( r, c, data[ 0 ][ 0 ] );
}
}
}
return self.sel;
}
range = self.table.writeData( self.sel.r1, self.sel.c1, data );
return range ? makeSelection( range.r1, range.c1, range.r2, range.c2, range.r1, range.c1 ) : false;
} );
if ( 1 < data.length || 1 < data[ 0 ].length ) {
this.notify( sprintf( t( 'pasted', 'Pasted %1$s × %2$s cells' ), data.length, data[ 0 ].length ) );
}
this.focusGrid();
},
/**
* Markup for a panel heading, in the look of an option title and description.
*
* @param {string} title - The title.
* @param {string} description - The description.
* @return {string}
*/
panelHead: function( title, description ) {
return '<div class="awb-te-panel-head"><h3 class="awb-te-panel-title">' + AWBTable.escHtml( title ) + '</h3>' +
( description ? '<p class="awb-te-panel-desc">' + AWBTable.escHtml( description ) + '</p>' : '' ) + '</div>';
},
/**
* Markup for the panel buttons, in the look of the media option's Remove and Edit buttons.
*
* @param {string} apply - The label of the main button.
* @return {string}
*/
panelActions: function( apply ) {
return '<div class="awb-te-panel-actions"><span class="awb-te-panel-error" role="alert"></span>' +
'<button type="button" class="awb-te-action is-secondary awb-te-panel-cancel">' + AWBTable.escHtml( t( 'cancel', 'Cancel' ) ) + '</button>' +
'<button type="button" class="awb-te-action is-primary awb-te-panel-apply">' + AWBTable.escHtml( apply ) + '</button>' +
'</div>';
},
/**
* Shows the import panel.
*
* @return {void}
*/
openImport: function() {
var self = this,
panel = this.root.querySelector( '.awb-te-import-panel' ),
text, name, error;
if ( ! this.features.import ) {
return;
}
this.closePanels( true );
panel.innerHTML =
this.panelHead( t( 'import_title', 'Import Data' ), t( 'import_help', 'Choose a CSV file from the Media Library, or paste CSV, tab separated text or a table copied from a spreadsheet or web page below.' ) ) +
'<div class="awb-te-file">' +
'<input type="text" class="awb-te-file-name" readonly placeholder="' + AWBTable.escAttr( t( 'import_file', 'CSV file' ) ) + '">' +
'<button type="button" class="awb-te-file-clear" aria-label="' + AWBTable.escAttr( t( 'import_clear', 'Remove file' ) ) + '"><span class="fusiona-close-fb" aria-hidden="true"></span></button>' +
'<button type="button" class="awb-te-file-select" aria-label="' + AWBTable.escAttr( t( 'import_select', 'Select CSV file' ) ) + '" title="' + AWBTable.escAttr( t( 'import_select', 'Select CSV file' ) ) + '"><span class="fusiona-plus" aria-hidden="true"></span></button>' +
'</div>' +
'<textarea class="awb-te-import-text" rows="6" spellcheck="false" placeholder="' + AWBTable.escAttr( t( 'import_paste', 'Or paste the data here' ) ) + '"></textarea>' +
'<div class="awb-te-panel-options">' +
'<label><input type="radio" name="awb-te-import-mode" value="replace" checked> ' + AWBTable.escHtml( t( 'import_replace', 'Replace the table' ) ) + '</label>' +
'<label><input type="radio" name="awb-te-import-mode" value="append"> ' + AWBTable.escHtml( t( 'import_append', 'Add as new rows' ) ) + '</label>' +
'<label><input type="checkbox" class="awb-te-import-header" checked> ' + AWBTable.escHtml( t( 'import_header', 'First row is the header' ) ) + '</label>' +
'</div>' +
this.panelActions( t( 'import_apply', 'Import' ) );
text = panel.querySelector( '.awb-te-import-text' );
name = panel.querySelector( '.awb-te-file-name' );
error = panel.querySelector( '.awb-te-panel-error' );
panel.hidden = false;
this.root.classList.add( 'has-panel' );
text.addEventListener( 'paste', function( event ) {
var html = event.clipboardData ? event.clipboardData.getData( 'text/html' ) : '';
// Keep the table structure of rich pastes.
if ( html && /<table/i.test( html ) ) {
event.preventDefault();
text.value = html;
}
} );
panel.querySelector( '.awb-te-file-select' ).addEventListener( 'click', function() {
self.selectFile( function( fileName, contents ) {
name.value = fileName;
text.value = contents.replace( /^/, '' );
error.textContent = '';
}, function( message ) {
error.textContent = message;
} );
} );
panel.querySelector( '.awb-te-file-clear' ).addEventListener( 'click', function() {
name.value = '';
text.value = '';
} );
panel.querySelector( '.awb-te-panel-cancel' ).addEventListener( 'click', function() {
self.closePanels();
} );
panel.querySelector( '.awb-te-panel-apply' ).addEventListener( 'click', function() {
var value = text.value,
header = panel.querySelector( '.awb-te-import-header' ).checked,
mode = panel.querySelector( 'input[name="awb-te-import-mode"]:checked' ).value,
data = /<table/i.test( value ) ? AWBTable.dataFromHtml( value ) : AWBTable.parseDelimited( value ).map( function( line ) {
return line.map( AWBTable.textToHtml );
} );
if ( ! data || ! data.length ) {
error.textContent = t( 'import_empty', 'Nothing to import.' );
return;
}
self.change( function() {
if ( 'append' === mode ) {
if ( header && 1 < data.length ) {
data = data.slice( 1 );
}
self.table.appendData( data );
} else {
self.table.replaceData( data, header );
}
return makeSelection( 0, 0, 0, 0 );
} );
self.closePanels();
self.notify( sprintf( t( 'imported', 'Imported %s rows' ), data.length ) );
} );
panel.scrollIntoView( { block: 'nearest' } );
text.focus( { preventScroll: true } );
},
/**
* Shows the panel that generates the table with Avada AI, from a
* description, from pasted data, or as a change of the current table.
*
* @return {void}
*/
openAi: function() {
var self = this,
panel = this.root.querySelector( '.awb-te-ai-panel' ),
filled = this.tableText().replace( /[\t\n]/g, '' ).length,
prompt, source, current, error, apply;
if ( ! this.features.ai ) {
return;
}
this.closePanels( true );
panel.innerHTML =
this.panelHead( t( 'ai_title', 'Generate with AI' ), t( 'ai_help', 'Describe the table you need, paste notes or data to turn into a table, or both. Uses your Avada AI credits.' ) ) +
'<textarea class="awb-te-ai-prompt" rows="3" placeholder="' + AWBTable.escAttr( t( 'ai_prompt', 'Ex: Compare a Basic, Pro and Team plan by price, storage, users and support' ) ) + '"></textarea>' +
'<textarea class="awb-te-ai-source" rows="4" spellcheck="false" placeholder="' + AWBTable.escAttr( t( 'ai_source', 'Optional: notes, a list or data to put into the table' ) ) + '"></textarea>' +
'<div class="awb-te-panel-options">' +
'<label><input type="checkbox" class="awb-te-ai-current"' + ( filled ? ' checked' : '' ) + '> ' + AWBTable.escHtml( t( 'ai_current', 'Change the current table' ) ) + '</label>' +
'</div>' +
this.panelActions( t( 'ai_apply', 'Generate' ) );
prompt = panel.querySelector( '.awb-te-ai-prompt' );
source = panel.querySelector( '.awb-te-ai-source' );
current = panel.querySelector( '.awb-te-ai-current' );
error = panel.querySelector( '.awb-te-panel-error' );
apply = panel.querySelector( '.awb-te-panel-apply' );
panel.hidden = false;
this.root.classList.add( 'has-panel' );
[ prompt, source ].forEach( function( field ) {
field.addEventListener( 'input', function() {
error.textContent = '';
} );
} );
panel.querySelector( '.awb-te-panel-cancel' ).addEventListener( 'click', function() {
if ( self.aiRequest ) {
self.aiRequest.abort();
}
self.closePanels();
} );
apply.addEventListener( 'click', function() {
var connection = aiConnection(),
data = new FormData();
error.textContent = '';
if ( ! prompt.value.trim() && ! source.value.trim() ) {
error.textContent = t( 'ai_empty', 'Describe the table, or paste data for it.' );
prompt.focus();
return;
}
if ( ! connection ) {
error.textContent = t( 'ai_unavailable', 'Avada AI is not available for this site or user.' );
return;
}
data.append( 'prompt', prompt.value.trim() );
data.append( 'source', source.value.trim() );
data.append( 'table', current.checked ? self.tableText() : '' );
data.append( 'maxRows', '50' );
data.append( 'wpOptions', JSON.stringify( { userId: connection.userId, domain: window.location.hostname, mode: 'fast' } ) );
apply.disabled = true;
apply.textContent = t( 'ai_working', 'Generating…' );
self.aiRequest = new AbortController();
window.fetch( 'https://api.avada.com/v1/ai/write-table', {
method: 'POST',
headers: { 'X-Site-Token': connection.token },
body: data,
signal: self.aiRequest.signal
} ).then( function( response ) {
return response.json().catch( function() {
return {};
} ).then( function( body ) {
if ( ! response.ok || ! body.table ) {
throw { status: response.status, code: body.code || '' };
}
return body.table;
} );
} ).then( function( result ) {
var parsed = AWBTable.parse( aiTableHtml( result ) ),
keep = current.checked && parsed.columnCount() === self.table.columnCount() ? self.table.columns : null;
if ( ! parsed.valid ) {
throw { code: 'no_table' };
}
// A changed table keeps its column settings when it keeps its columns.
parsed.wrapperAttrs = self.table.wrapperAttrs;
if ( keep ) {
parsed.columns = keep;
}
self.change( function() {
self.table = parsed;
return makeSelection( 0, 0, 0, 0 );
} );
self.closePanels();
self.notify( sprintf( t( 'ai_done', 'Generated a table with %s rows' ), result.rows.length ) );
} ).catch( function( problem ) {
var messages = {
not_connected: t( 'ai_not_connected', 'This site is not connected to My Avada.' ),
insufficient_plan: t( 'ai_plan', 'Avada AI needs an Avada Pro plan.' ),
ai_disabled: t( 'ai_disabled', 'Avada AI is turned off for this site.' ),
credit_exceeded: t( 'ai_credits', 'Your Avada AI credits are used up for this period.' ),
site_credit_exceeded: t( 'ai_site_credits', 'This site reached its Avada AI credit limit.' ),
content_policy: t( 'ai_policy', 'The request was blocked by the content policy.' ),
no_table: t( 'ai_no_table', 'No table could be made from that. Try describing it differently.' )
};
if ( problem && 'AbortError' === problem.name ) {
return;
}
error.textContent = messages[ problem && problem.code ] || ( problem && 429 === problem.status ? messages.credit_exceeded : t( 'ai_failed', 'Avada AI could not be reached. Please try again.' ) );
} ).finally( function() {
self.aiRequest = null;
if ( panel.contains( apply ) ) {
apply.disabled = false;
apply.textContent = t( 'ai_apply', 'Generate' );
}
} );
} );
panel.scrollIntoView( { block: 'nearest' } );
prompt.focus( { preventScroll: true } );
},
/**
* The table as tab separated text, the header first, for the AI.
*
* @return {string}
*/
tableText: function() {
var table = this.table,
lines = [],
r, c, cells;
for ( r = 0; r < table.rowCount(); r++ ) {
cells = [];
for ( c = 0; c < table.columnCount(); c++ ) {
cells.push( table.isAnchor( r, c ) ? cellText( table.getCell( r, c ).html ) : '' );
}
lines.push( cells.join( '\t' ) );
}
return lines.join( '\n' );
},
/**
* Lets the user pick a CSV file: from the Media Library like other file
* options, or from the computer where the media modal is not available.
*
* @param {Function} done - Receives the file name and its text.
* @param {Function} fail - Receives an error message.
* @return {void}
*/
selectFile: function( done, fail ) {
var input;
if ( window.wp && window.wp.media ) {
if ( ! this.mediaFrame ) {
this.mediaFrame = window.wp.media( {
title: t( 'import_select', 'Select CSV file' ),
library: { type: [ 'text/csv', 'text/plain', 'text/tab-separated-values' ] },
button: { text: t( 'import_use', 'Use this file' ) },
multiple: false
} );
}
this.mediaFrame.off( 'select' ).on( 'select', function() {
var file = this.state().get( 'selection' ).first().toJSON();
window.fetch( file.url, { credentials: 'same-origin' } ).then( function( response ) {
if ( ! response.ok ) {
throw new Error( response.status );
}
return response.text();
} ).then( function( contents ) {
done( file.filename || file.title, contents );
} ).catch( function() {
fail( t( 'import_failed', 'The file could not be read.' ) );
} );
}.bind( this.mediaFrame ) );
this.mediaFrame.open();
return;
}
input = document.createElement( 'input' );
input.type = 'file';
input.accept = '.csv,.tsv,.txt,text/csv,text/plain';
input.addEventListener( 'change', function() {
var file = input.files && input.files[ 0 ],
reader = new FileReader();
if ( ! file ) {
return;
}
reader.onload = function() {
done( file.name, String( reader.result ) );
};
reader.onerror = function() {
fail( t( 'import_failed', 'The file could not be read.' ) );
};
reader.readAsText( file );
} );
input.click();
},
/**
* Shows the markup of the table for editing.
*
* @param {string} html - Optional markup to start from.
* @param {string} error - Optional message.
* @return {void}
*/
openHtml: function( html, error ) {
var self = this,
panel = this.root.querySelector( '.awb-te-html-panel' ),
field;
this.closePanels( true );
panel.innerHTML =
this.panelHead( t( 'edit_html_title', 'Edit as HTML' ), t( 'edit_html_help', 'The table markup, for changes the table editor does not offer. Shortcodes in cells are kept.' ) ) +
'<textarea class="awb-te-html-text" rows="12" spellcheck="false"></textarea>' +
this.panelActions( t( 'apply', 'Apply' ) );
field = panel.querySelector( '.awb-te-html-text' );
field.value = 'string' === typeof html ? html : this.prettyHtml( this.table.toHTML( { wrapper: false } ) );
if ( error ) {
panel.querySelector( '.awb-te-panel-error' ).textContent = error;
}
panel.hidden = false;
this.root.classList.add( 'has-panel' );
panel.querySelector( '.awb-te-panel-cancel' ).addEventListener( 'click', function() {
self.closePanels();
} );
panel.querySelector( '.awb-te-panel-apply' ).addEventListener( 'click', function() {
var parsed = AWBTable.parse( field.value );
if ( ! parsed.valid ) {
panel.querySelector( '.awb-te-panel-error' ).textContent = t( 'html_invalid', 'No table found in the markup.' );
return;
}
parsed.wrapperAttrs = self.table.wrapperAttrs;
self.change( function() {
self.table = parsed;
return self.sel;
} );
self.closePanels();
} );
panel.scrollIntoView( { block: 'nearest' } );
field.focus( { preventScroll: true } );
},
/**
* Puts rows on their own lines, for reading.
*
* @param {string} html - Table markup.
* @return {string}
*/
prettyHtml: function( html ) {
return html
.replace( /(<\/?(thead|tbody|tfoot|colgroup)>)/g, '\n$1' )
.replace( /(<tr[\s>])/g, '\n\t$1' )
.replace( /(<caption[\s>])/g, '\n$1' )
.replace( /<\/table>$/, '\n</table>' );
},
closePanels: function( keepFocus ) {
this.root.querySelectorAll( '.awb-te-panel' ).forEach( function( panel ) {
panel.hidden = true;
panel.innerHTML = '';
} );
this.root.classList.remove( 'has-panel' );
if ( ! keepFocus ) {
this.focusGrid();
}
},
/**
* Selects a cell from outside, for the on-canvas editing in the Live Editor.
*
* @param {number} r - Row index.
* @param {number} c - Column index.
* @return {void}
*/
selectCell: function( r, c ) {
if ( r < this.table.rowCount() && c < this.table.columnCount() ) {
this.select( r, c );
this.scrollActiveIntoView();
}
},
destroy: function() {
if ( this.placeholder ) {
this.toggleExpand( false );
}
this.menu.destroy();
$( this.textarea ).off( '.awbTableEditor' );
this.root.classList.remove( 'initialized' );
}
};
/**
* Boots every table editor inside a settings panel, and cleans up editors whose panel was closed.
*
* @param {Object} $scope - jQuery collection to search in.
* @return {void}
*/
function init( $scope ) {
instances = instances.filter( function( editor ) {
if ( ! document.contains( editor.textarea ) ) {
editor.destroy();
return false;
}
return true;
} );
$( $scope ).find( '.awb-table-editor:not(.initialized)' ).each( function() {
var textarea = $( this ).closest( '.fusion-builder-option' ).find( 'textarea.awb-table-editor-value' )[ 0 ],
editor;
if ( ! textarea ) {
return;
}
editor = new Editor( this, textarea );
instances.push( editor );
$( this ).data( 'awbTableEditor', editor );
// Now that it can be found, let the preview show the selection.
editor.announceSelection();
} );
}
return {
init: init,
Editor: Editor,
/**
* The editor bound to an element_content textarea.
*
* @param {Element} textarea - The textarea.
* @return {Object|null}
*/
forTextarea: function( textarea ) {
var found = null;
instances.forEach( function( editor ) {
if ( editor.textarea === textarea ) {
found = editor;
}
} );
return found;
},
commands: commands,
makeSelection: makeSelection,
fitSelection: fitSelection,
isSimpleHtml: isSimpleHtml,
displayHtml: displayHtml,
cleanEditedHtml: cleanEditedHtml,
t: t,
icons: ICONS
};
}( jQuery ) );