Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added toArray() helper to cast any value to an array #8449

Merged
merged 5 commits into from
Nov 20, 2020
Merged
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
9 changes: 4 additions & 5 deletions packages/ckeditor5-engine/src/conversion/conversion.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
import UpcastHelpers from './upcasthelpers';
import DowncastHelpers from './downcasthelpers';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

/**
* A utility class that helps add converters to upcast and downcast dispatchers.
Expand Down Expand Up @@ -74,10 +75,10 @@ export default class Conversion {
this._helpers = new Map();

// Define default 'downcast' & 'upcast' dispatchers groups. Those groups are always available as two-way converters needs them.
this._downcast = Array.isArray( downcastDispatchers ) ? downcastDispatchers : [ downcastDispatchers ];
this._downcast = toArray( downcastDispatchers );
this._createConversionHelpers( { name: 'downcast', dispatchers: this._downcast, isDowncast: true } );

this._upcast = Array.isArray( upcastDispatchers ) ? upcastDispatchers : [ upcastDispatchers ];
this._upcast = toArray( upcastDispatchers );
this._createConversionHelpers( { name: 'upcast', dispatchers: this._upcast, isDowncast: false } );
}

Expand Down Expand Up @@ -636,9 +637,7 @@ function* _getUpcastDefinition( model, view, upcastAlso ) {
yield { model, view };

if ( upcastAlso ) {
upcastAlso = Array.isArray( upcastAlso ) ? upcastAlso : [ upcastAlso ];

for ( const upcastAlsoItem of upcastAlso ) {
for ( const upcastAlsoItem of toArray( upcastAlso ) ) {
yield { model, view: upcastAlsoItem };
}
}
Expand Down
5 changes: 3 additions & 2 deletions packages/ckeditor5-engine/src/conversion/downcasthelpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import ConversionHelpers from './conversionhelpers';

import { cloneDeep } from 'lodash-es';
import CKEditorError from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

/**
* Downcast conversion helper functions.
Expand Down Expand Up @@ -1136,7 +1137,7 @@ function changeAttribute( attributeCreator ) {
// First remove the old attribute if there was one.
if ( data.attributeOldValue !== null && oldAttribute ) {
if ( oldAttribute.key == 'class' ) {
const classes = Array.isArray( oldAttribute.value ) ? oldAttribute.value : [ oldAttribute.value ];
const classes = toArray( oldAttribute.value );

for ( const className of classes ) {
viewWriter.removeClass( className, viewElement );
Expand All @@ -1155,7 +1156,7 @@ function changeAttribute( attributeCreator ) {
// Then set the new attribute.
if ( data.attributeNewValue !== null && newAttribute ) {
if ( newAttribute.key == 'class' ) {
const classes = Array.isArray( newAttribute.value ) ? newAttribute.value : [ newAttribute.value ];
const classes = toArray( newAttribute.value );

for ( const className of classes ) {
viewWriter.addClass( className, viewElement );
Expand Down
16 changes: 10 additions & 6 deletions packages/ckeditor5-engine/src/view/element.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import Node from './node';
import Text from './text';
import TextProxy from './textproxy';
import toMap from '@ckeditor/ckeditor5-utils/src/tomap';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';
import isIterable from '@ckeditor/ckeditor5-utils/src/isiterable';
import Matcher from './matcher';
import StylesMap from './stylesmap';
Expand Down Expand Up @@ -724,8 +725,9 @@ export default class Element extends Node {
_addClass( className ) {
this._fireChange( 'attributes', this );

className = Array.isArray( className ) ? className : [ className ];
className.forEach( name => this._classes.add( name ) );
for ( const name of toArray( className ) ) {
this._classes.add( name );
}
}

/**
Expand All @@ -742,8 +744,9 @@ export default class Element extends Node {
_removeClass( className ) {
this._fireChange( 'attributes', this );

className = Array.isArray( className ) ? className : [ className ];
className.forEach( name => this._classes.delete( name ) );
for ( const name of toArray( className ) ) {
this._classes.delete( name );
}
}

/**
Expand Down Expand Up @@ -789,8 +792,9 @@ export default class Element extends Node {
_removeStyle( property ) {
this._fireChange( 'attributes', this );

property = Array.isArray( property ) ? property : [ property ];
property.forEach( name => this._styles.remove( name ) );
for ( const name of toArray( property ) ) {
this._styles.remove( name );
}
}

/**
Expand Down
4 changes: 3 additions & 1 deletion packages/ckeditor5-engine/tests/conversion/upcasthelpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import ViewRange from '../../src/view/range';
import { StylesProcessor } from '../../src/view/stylesmap';
import Writer from '../../src/model/writer';

import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

/* globals console */

describe( 'UpcastHelpers', () => {
Expand Down Expand Up @@ -899,7 +901,7 @@ describe( 'UpcastHelpers', () => {
const conversionResult = model.change( writer => upcastDispatcher.convert( viewToConvert, writer ) );

if ( markers ) {
markers = Array.isArray( markers ) ? markers : [ markers ];
markers = toArray( markers );

for ( const marker of markers ) {
expect( conversionResult.markers.has( marker.name ) ).to.be.true;
Expand Down
5 changes: 2 additions & 3 deletions packages/ckeditor5-image/src/image/imageinsertcommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import Command from '@ckeditor/ckeditor5-core/src/command';
import { insertImage, isImageAllowed } from './utils';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

/**
* @module image/image/imageinsertcommand
Expand Down Expand Up @@ -50,9 +51,7 @@ export default class ImageInsertCommand extends Command {
execute( options ) {
const model = this.editor.model;

const sources = Array.isArray( options.source ) ? options.source : [ options.source ];

for ( const src of sources ) {
for ( const src of toArray( options.source ) ) {
insertImage( model, { src } );
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import FileRepository from '@ckeditor/ckeditor5-upload/src/filerepository';
import Command from '@ckeditor/ckeditor5-core/src/command';
import { insertImage, isImageAllowed } from '../image/utils';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

/**
* @module image/imageupload/imageuploadcommand
Expand Down Expand Up @@ -63,9 +64,7 @@ export default class ImageUploadCommand extends Command {

const fileRepository = editor.plugins.get( FileRepository );

const filesToUpload = Array.isArray( options.file ) ? options.file : [ options.file ];

for ( const file of filesToUpload ) {
for ( const file of toArray( options.file ) ) {
uploadImage( model, fileRepository, file );
}
}
Expand Down
7 changes: 2 additions & 5 deletions packages/ckeditor5-media-embed/src/mediaregistry.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import TooltipView from '@ckeditor/ckeditor5-ui/src/tooltip/tooltipview';
import IconView from '@ckeditor/ckeditor5-ui/src/icon/iconview';
import Template from '@ckeditor/ckeditor5-ui/src/template';
import { logWarning } from '@ckeditor/ckeditor5-utils/src/ckeditorerror';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

const mediaPlaceholderIconViewBox = '0 0 64 42';

Expand Down Expand Up @@ -113,11 +114,7 @@ export default class MediaRegistry {

for ( const definition of this.providerDefinitions ) {
const previewRenderer = definition.html;
let pattern = definition.url;

if ( !Array.isArray( pattern ) ) {
pattern = [ pattern ];
}
const pattern = toArray( definition.url );

for ( const subPattern of pattern ) {
const match = this._getUrlMatches( url, subPattern );
Expand Down
2 changes: 1 addition & 1 deletion packages/ckeditor5-table/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"dependencies": {
"@ckeditor/ckeditor5-core": "^23.1.0",
"@ckeditor/ckeditor5-ui": "^23.1.0",
"@ckeditor/ckeditor5-utils": "^23.1.0",
"@ckeditor/ckeditor5-widget": "^23.1.0",
"lodash-es": "^4.17.15"
},
Expand All @@ -29,7 +30,6 @@
"@ckeditor/ckeditor5-paragraph": "^23.1.0",
"@ckeditor/ckeditor5-typing": "^23.1.0",
"@ckeditor/ckeditor5-undo": "^23.1.0",
"@ckeditor/ckeditor5-utils": "^23.1.0",
"json-diff": "^0.5.4"
},
"engines": {
Expand Down
13 changes: 5 additions & 8 deletions packages/ckeditor5-table/src/converters/downcast.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import TableWalker from './../tablewalker';
import { setHighlightHandling, toWidget, toWidgetEditable } from '@ckeditor/ckeditor5-widget/src/utils';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

/**
* Model table element to view table element conversion helper.
Expand Down Expand Up @@ -314,8 +315,8 @@ function renameViewTableCell( tableCell, desiredCellElementName, conversionApi )
setHighlightHandling(
renamedCell,
viewWriter,
( element, descriptor, writer ) => writer.addClass( normalizeToArray( descriptor.classes ), element ),
( element, descriptor, writer ) => writer.removeClass( normalizeToArray( descriptor.classes ), element )
( element, descriptor, writer ) => writer.addClass( toArray( descriptor.classes ), element ),
( element, descriptor, writer ) => writer.removeClass( toArray( descriptor.classes ), element )
);

viewWriter.insert( viewWriter.createPositionAfter( viewCell ), renamedCell );
Expand Down Expand Up @@ -363,8 +364,8 @@ function createViewTableCellElement( tableSlot, tableAttributes, insertPosition,
setHighlightHandling(
cellElement,
conversionApi.writer,
( element, descriptor, writer ) => writer.addClass( normalizeToArray( descriptor.classes ), element ),
( element, descriptor, writer ) => writer.removeClass( normalizeToArray( descriptor.classes ), element )
( element, descriptor, writer ) => writer.addClass( toArray( descriptor.classes ), element ),
( element, descriptor, writer ) => writer.removeClass( toArray( descriptor.classes ), element )
);
}

Expand Down Expand Up @@ -521,7 +522,3 @@ function getViewTable( viewFigure ) {
function hasAnyAttribute( element ) {
return !![ ...element.getAttributeKeys() ].length;
}

function normalizeToArray( classes ) {
return Array.isArray( classes ) ? classes : [ classes ];
}
6 changes: 3 additions & 3 deletions packages/ckeditor5-typing/tests/twostepcaretmovement.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import Position from '@ckeditor/ckeditor5-engine/src/model/position';
import testUtils from '@ckeditor/ckeditor5-core/tests/_utils/utils';
import { keyCodes } from '@ckeditor/ckeditor5-utils/src/keyboard';
import { setData } from '@ckeditor/ckeditor5-engine/src/dev-utils/model';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

import '@ckeditor/ckeditor5-core/tests/_utils/assertions/attribute';

Expand Down Expand Up @@ -963,11 +964,10 @@ describe( 'TwoStepCaretMovement()', () => {
else {
const stepIndex = scenario.indexOf( step );
const stepString = `in step #${ stepIndex }`;
let caretPosition = step.caretPosition;

if ( caretPosition !== undefined ) {
if ( step.caretPosition !== undefined ) {
// Normalize position
caretPosition = Array.isArray( step.caretPosition ) ? caretPosition : [ caretPosition ];
const caretPosition = toArray( step.caretPosition );
expect( selection.getFirstPosition(), `in step #${ stepIndex }, selection's first position` )
.to.have.deep.property( 'path', caretPosition );
}
Expand Down
11 changes: 4 additions & 7 deletions packages/ckeditor5-ui/src/template.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import View from './view';
import ViewCollection from './viewcollection';
import isNode from '@ckeditor/ckeditor5-utils/src/dom/isnode';
import { isObject, cloneDeepWith } from 'lodash-es';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

const xhtmlNs = 'http://www.w3.org/1999/xhtml';

Expand Down Expand Up @@ -1225,7 +1226,7 @@ function normalize( def ) {
function normalizeAttributes( attributes ) {
for ( const a in attributes ) {
if ( attributes[ a ].value ) {
attributes[ a ].value = [].concat( attributes[ a ].value );
attributes[ a ].value = toArray( attributes[ a ].value );
}

arrayify( attributes, a );
Expand Down Expand Up @@ -1290,9 +1291,7 @@ function normalizePlainTextDefinition( def ) {
//
// @param {module:ui/template~TemplateDefinition} def
function normalizeTextDefinition( def ) {
if ( !Array.isArray( def.text ) ) {
def.text = [ def.text ];
}
def.text = toArray( def.text );
}

// Wraps an entry in Object in an Array, if not already one.
Expand All @@ -1312,9 +1311,7 @@ function normalizeTextDefinition( def ) {
// @param {Object} obj
// @param {String} key
function arrayify( obj, key ) {
if ( !Array.isArray( obj[ key ] ) ) {
obj[ key ] = [ obj[ key ] ];
}
obj[ key ] = toArray( obj[ key ] );
}

// A helper which concatenates the value avoiding unwanted
Expand Down
3 changes: 2 additions & 1 deletion packages/ckeditor5-undo/tests/redocommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import Batch from '@ckeditor/ckeditor5-engine/src/model/batch';
import UndoCommand from '../src/undocommand';
import RedoCommand from '../src/redocommand';
import { itemAt, getText } from '@ckeditor/ckeditor5-engine/tests/model/_utils/utils';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

describe( 'RedoCommand', () => {
let editor, model, root, redo, undo;
Expand All @@ -28,7 +29,7 @@ describe( 'RedoCommand', () => {

describe( 'RedoCommand', () => {
describe( 'execute()', () => {
const p = pos => model.createPositionFromPath( root, [].concat( pos ) );
const p = pos => model.createPositionFromPath( root, toArray( pos ) );
const r = ( a, b ) => model.createRange( p( a ), p( b ) );

let batch0, batch1, batch2;
Expand Down
3 changes: 2 additions & 1 deletion packages/ckeditor5-undo/tests/undocommand.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import ModelTestEditor from '@ckeditor/ckeditor5-core/tests/_utils/modeltestedit
import Batch from '@ckeditor/ckeditor5-engine/src/model/batch';
import UndoCommand from '../src/undocommand';
import { itemAt, getText } from '@ckeditor/ckeditor5-engine/tests/model/_utils/utils';
import toArray from '@ckeditor/ckeditor5-utils/src/toarray';

describe( 'UndoCommand', () => {
let editor, model, doc, root, undo;
Expand All @@ -27,7 +28,7 @@ describe( 'UndoCommand', () => {
} );

describe( 'UndoCommand', () => {
const p = pos => model.createPositionFromPath( root, [].concat( pos ) );
const p = pos => model.createPositionFromPath( root, toArray( pos ) );
const r = ( a, b ) => model.createRange( p( a ), p( b ) );

describe( 'execute()', () => {
Expand Down
5 changes: 2 additions & 3 deletions packages/ckeditor5-utils/src/locale.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

/* globals console */

import toArray from './toarray';
import { _translate } from './translation-service';

const RTL_LANGUAGE_CODES = [ 'ar', 'fa', 'he', 'ku', 'ug' ];
Expand Down Expand Up @@ -153,9 +154,7 @@ export default class Locale {
* @returns {String}
*/
_t( message, values = [] ) {
if ( !Array.isArray( values ) ) {
values = [ values ];
}
values = toArray( values );

if ( typeof message === 'string' ) {
message = { string: message };
Expand Down
18 changes: 18 additions & 0 deletions packages/ckeditor5-utils/src/toarray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/

/**
* @module utils/toarray
*/

/**
* Transforms any value to an array. If the provided value is already an array, it is returned unchanged.
*
* @param {*} data Value to transform to an array.
* @returns {Array} Array created from data.
*/
export default function toArray( data ) {
return Array.isArray( data ) ? data : [ data ];
}
29 changes: 29 additions & 0 deletions packages/ckeditor5-utils/tests/toarray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/

import toArray from '../src/toarray';

describe( 'utils', () => {
describe( 'toArray', () => {
it( 'should wrap non-array values in an array', () => {
expect( toArray( 0 ) ).to.deep.equal( [ 0 ] );
expect( toArray( 1 ) ).to.deep.equal( [ 1 ] );
expect( toArray( '' ) ).to.deep.equal( [ '' ] );
expect( toArray( 'foo' ) ).to.deep.equal( [ 'foo' ] );
expect( toArray( false ) ).to.deep.equal( [ false ] );
expect( toArray( true ) ).to.deep.equal( [ true ] );
expect( toArray( null ) ).to.deep.equal( [ null ] );
expect( toArray( {} ) ).to.deep.equal( [ {} ] );
expect( toArray() ).to.deep.equal( [ undefined ] );
} );

it( 'should return array values by reference and unchanged', () => {
const array = toArray( [ 'foo' ] );

expect( toArray( array ) ).to.equal( array );
expect( toArray( array ) ).to.deep.equal( [ 'foo' ] );
} );
} );
} );
Loading