Przeglądaj źródła

Added: treeController.selectionToView selection to view default converters.

Szymon Cofalik 9 lat temu
rodzic
commit
8f72266827

+ 160 - 0
packages/ckeditor5-engine/src/treecontroller/selection-to-view-converters.js

@@ -0,0 +1,160 @@
+/**
+ * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+'use strict';
+
+import ViewElement from '../treeview/element.js';
+import ViewRange from '../treeview/range.js';
+
+/**
+ * Contains {@link engine.treeModel.Selection model selection} to {@link engine.treeView.Selection view selection} converters for
+ * {@link engine.treeController.ModelConversionDispatcher}.
+ *
+ * @namespace engine.treeController.selectionToView
+ */
+
+/**
+ * Function factory, creates a converter that converts non-collapsed {@link engine.treeModel.Selection model selection} to
+ * {@link engine.treeView.Selection view selection}. The converter consumes appropriate value from `consumable` object
+ * and maps model positions from selection to view positions.
+ *
+ *		modelDispatcher.on( 'selection', convertRangeSelection() );
+ *
+ * @external engine.treeController.selectionToView
+ * @function engine.treeController.selectionToView.convertRangeSelection
+ * @returns {Function} Selection converter.
+ */
+export function convertRangeSelection() {
+	return ( evt, selection, consumable, conversionApi ) => {
+		if ( selection.isCollapsed ) {
+			return;
+		}
+
+		if ( !consumable.consume( selection, 'selection' ) ) {
+			return;
+		}
+
+		for ( let range of selection.getRanges() ) {
+			const startPosition = conversionApi.mapper.toViewPosition( range.start );
+			const endPosition = conversionApi.mapper.toViewPosition( range.end );
+
+			const viewRange = new ViewRange( startPosition, endPosition );
+			conversionApi.viewSelection.addRange( viewRange, selection.isBackward );
+		}
+	};
+}
+
+/**
+ * Function factory, creates a converter that converts collapsed {@link engine.treeModel.Selection model selection} to
+ * {@link engine.treeView.Selection view selection}. The converter consumes appropriate value from `consumable` object,
+ * maps model selection position to view position and breaks {@link engine.treeView.AttributeElement attribute elements}
+ * at the selection position.
+ *
+ *		modelDispatcher.on( 'selection', convertCollapsedSelection() );
+ *
+ * Example of view state before and after converting collapsed selection:
+ *
+ *		<p><strong>f^oo<strong>bar</p> -> <p><strong>f</strong>^<strong>oo</strong>bar</p>
+ *
+ * By breaking attribute elements like `<strong>` selection is in correct elements. See also complementary
+ * {@link engine.treeController.selectionToView.convertSelectionAttribute attribute converter} for selection attributes,
+ * which wraps collapsed selection into view elements. Those converters together ensure, that selection ends up in
+ * appropriate elements.
+ *
+ * @external engine.treeController.selectionToView
+ * @function engine.treeController.selectionToView.convertCollapsedSelection
+ * @returns {Function} Selection converter.
+ */
+export function convertCollapsedSelection() {
+	return ( evt, selection, consumable, conversionApi ) => {
+		if ( !selection.isCollapsed ) {
+			return;
+		}
+
+		if ( !consumable.consume( selection, 'selection' ) ) {
+			return;
+		}
+
+		// If selection is collapsed, there still might be multiple, collapsed ranges.
+		for ( let range of selection.getRanges() ) {
+			const viewPosition = conversionApi.mapper.toViewPosition( range.start );
+			const brokenPosition = conversionApi.writer.breakAttributes( viewPosition );
+
+			conversionApi.viewSelection.addRange( new ViewRange( brokenPosition, brokenPosition ), selection.isBackward );
+		}
+	};
+}
+
+/**
+ * Function factory, creates a converter that converts {@link engine.treeModel.Selection model selection} attributes to
+ * {@link engine.treeView.AttributeElement view attribute elements}. The converter works only for collapsed selection.
+ * The converter consumes appropriate value from `consumable` object, maps model selection position to view position and
+ * wraps that position into a view attribute element.
+ *
+ * The wrapping node depends on passed parameter. If {@link engine.treeView.Element} was passed, it will be cloned and
+ * the copy will become the wrapping element. If `Function` is provided, it is passed all the parameters of the
+ * {@link engine.treeController.ModelConversionDispatcher#event:selectionAttribute selectionAttribute event}. It's expected that
+ * the function returns a {@link engine.treeView.AttributeElement}. The result of the function will be the wrapping element.
+ *
+ *		modelDispatcher.on( 'selectionAttribute:italic', convertSelectionAttribute( new ViewAttributeElement( 'em' ) ) );
+ *
+ *		function styleElementCreator( styleValue ) {
+ *			if ( styleValue == 'important' ) {
+ *				return new ViewAttributeElement( 'strong', { style: 'text-transform:uppercase;' } );
+ *			} else if ( styleValue == 'gold' ) {
+ *				return new ViewAttributeElement( 'span', { style: 'color:yellow;' } );
+ *			}
+ *		}
+ *		modelDispatcher.on( 'selectionAttribute:style', convertSelectionAttribute( styleCreator ) );
+ *
+ * **Note:** You can use the same `elementCreator` function for this converter factory and {@link engine.treeController.modelToView.wrap}
+ * model to view converter, as long as the `elementCreator` function uses only the first parameter (attribute value).
+ *
+ * Example of view state after converting collapsed selection. The scenario is: selection is inside bold text (`<strong>` element)
+ * but it does not have bold attribute itself, but has italic attribute instead (let's assume that user turned off bold and turned
+ * on italic with selection collapsed):
+ *
+ *		modelDispatcher.on( 'selectionAttribute:italic', convertSelectionAttribute( new ViewAttributeElement( 'em' ) ) );
+ *		modelDispatcher.on( 'selection', convertCollapsedSelection() );
+ *
+ * Example of view states before and after converting collapsed selection:
+ *
+ *		<p><em>f^oo</em>bar</p> 		->	<p><em>f^oo</em>bar</p>
+ *		<p><strong>f^oo<strong>bar</p>  ->	<p><strong>f</strong><em>^</em><strong>oo</strong>bar</p>
+ *
+ * In first example, nothing has changed, because first `<em>` element got broken by `convertCollapsedSelection()` converter,
+ * but then it got wrapped-back by `convertSelectionAttribute()` converter. In second example, notice how `<strong>` element
+ * is broken to prevent putting selection in it, since selection has no `bold` attribute.
+ *
+ * @external engine.treeController.selectionToView
+ * @function engine.treeController.selectionToView.convertCollapsedSelection
+ * @param {engine.treeView.AttributeElement|Function} elementCreator View element, or function returning a view element, which will
+ * be used for wrapping.
+ * @returns {Function} Selection converter.
+ */
+export function convertSelectionAttribute( elementCreator ) {
+	return ( evt, data, consumable, conversionApi ) => {
+		if ( !data.selection.isCollapsed ) {
+			return;
+		}
+
+		if ( !consumable.consume( data.selection, 'selectionAttribute:' + data.key ) ) {
+			return;
+		}
+
+		const ranges = Array.from( conversionApi.viewSelection.getRanges() );
+		conversionApi.viewSelection.removeAllRanges();
+
+		for ( let range of ranges ) {
+			const viewElement = elementCreator instanceof ViewElement ?
+				elementCreator.clone( true ) :
+				elementCreator( data.value, data.selection, consumable, conversionApi );
+
+			const viewPosition = conversionApi.writer.wrapPosition( range.start, viewElement );
+
+			conversionApi.viewSelection.addRange( new ViewRange( viewPosition, viewPosition ), data.selection.isBackward );
+		}
+	};
+}

+ 390 - 0
packages/ckeditor5-engine/tests/treecontroller/selection-to-view-converters.js

@@ -0,0 +1,390 @@
+/**
+ * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
+ * For licensing, see LICENSE.md.
+ */
+
+/* bender-tags: treecontroller */
+
+'use strict';
+
+import ModelDocument from '/ckeditor5/engine/treemodel/document.js';
+import ModelElement from '/ckeditor5/engine/treemodel/element.js';
+import ModelRange from '/ckeditor5/engine/treemodel/range.js';
+import ModelPosition from '/ckeditor5/engine/treemodel/position.js';
+
+import ViewContainerElement from '/ckeditor5/engine/treeview/containerelement.js';
+import ViewAttributeElement from '/ckeditor5/engine/treeview/attributeelement.js';
+import ViewWriter from  '/ckeditor5/engine/treeview/writer.js';
+import ViewSelection from  '/ckeditor5/engine/treeview/selection.js';
+
+import Mapper from '/ckeditor5/engine/treecontroller/mapper.js';
+import ModelConversionDispatcher from '/ckeditor5/engine/treecontroller/modelconversiondispatcher.js';
+import {
+	convertRangeSelection,
+	convertCollapsedSelection,
+	convertSelectionAttribute
+} from '/ckeditor5/engine/treecontroller/selection-to-view-converters.js';
+
+import {
+	insertElement,
+	insertText,
+	wrap
+} from '/ckeditor5/engine/treecontroller/model-to-view-converters.js';
+
+import { setData } from '/tests/engine/_utils/model.js';
+import { stringify } from '/tests/engine/_utils/view.js';
+
+let dispatcher, modelDoc, modelRoot, mapper, viewRoot, writer, viewSelection;
+
+beforeEach( () => {
+	modelDoc = new ModelDocument();
+	modelRoot = modelDoc.createRoot( 'modelRoot' );
+	viewRoot = new ViewContainerElement( 'viewRoot' );
+
+	mapper = new Mapper();
+	mapper.bindElements( modelRoot, viewRoot );
+
+	writer = new ViewWriter();
+	viewSelection = new ViewSelection();
+
+	dispatcher = new ModelConversionDispatcher( { mapper, writer, viewSelection } );
+
+	dispatcher.on( 'insert:$text', insertText() );
+	dispatcher.on( 'addAttribute:bold', wrap( new ViewAttributeElement( 'strong' ) ) );
+
+	// Default selection converters.
+	dispatcher.on( 'selection', convertRangeSelection() );
+	dispatcher.on( 'selection', convertCollapsedSelection() );
+} );
+
+describe( 'default converters', () => {
+	beforeEach( () => {
+		// Selection converters for selection attributes.
+		dispatcher.on( 'selectionAttribute:bold', convertSelectionAttribute( new ViewAttributeElement( 'strong' ) ) );
+		dispatcher.on( 'selectionAttribute:italic', convertSelectionAttribute( new ViewAttributeElement( 'em' ) ) );
+	} );
+
+	describe( 'range selection', () => {
+		it( 'in same container', () => {
+			test(
+				[ 1, 4 ],
+				'foobar',
+				'f{oob}ar'
+			);
+		} );
+
+		it( 'in same container, over attribute', () => {
+			test(
+				[ 1, 5 ],
+				'fo<$text bold=true>ob</$text>ar',
+				'f{o<strong>ob</strong>a}r'
+			);
+		} );
+
+		it( 'in same container, next to attribute', () => {
+			test(
+				[ 1, 2 ],
+				'fo<$text bold=true>ob</$text>ar',
+				'f{o}<strong>ob</strong>ar'
+			);
+		} );
+
+		it( 'in same attribute', () => {
+			test(
+				[ 2, 4 ],
+				'f<$text bold=true>ooba</$text>r',
+				'f<strong>o{ob}a</strong>r'
+			);
+		} );
+
+		it( 'in same attribute, selection same as attribute', () => {
+			test(
+				[ 2, 4 ],
+				'fo<$text bold=true>ob</$text>ar',
+				'fo{<strong>ob</strong>}ar'
+			);
+		} );
+
+		it( 'starts in text node, ends in attribute #1', () => {
+			test(
+				[ 1, 3 ],
+				'fo<$text bold=true>ob</$text>ar',
+				'f{o<strong>o}b</strong>ar'
+			);
+		} );
+
+		it( 'starts in text node, ends in attribute #2', () => {
+			test(
+				[ 1, 4 ],
+				'fo<$text bold=true>ob</$text>ar',
+				'f{o<strong>ob</strong>}ar'
+			);
+		} );
+
+		it( 'starts in attribute, ends in text node', () => {
+			test(
+				[ 3, 5 ],
+				'fo<$text bold=true>ob</$text>ar',
+				'fo<strong>o{b</strong>a}r'
+			);
+		} );
+
+		it( 'consumes consumable values properly', () => {
+			// Add callback that will fire before default ones.
+			// This should prevent default callback doing anything.
+			dispatcher.on( 'selection', ( evt, selection, consumable ) => {
+				expect( consumable.consume( selection, 'selection' ) ).to.be.true;
+			}, null, 0 );
+
+			// Similar test case as the first in this suite.
+			test(
+				[ 1, 4 ],
+				'foobar',
+				'foobar' // No selection in view.
+			);
+		} );
+	} );
+
+	describe( 'collapsed selection', () => {
+		it( 'in container', () => {
+			test(
+				[ 1, 1 ],
+				'foobar',
+				'f{}oobar'
+			);
+		} );
+
+		it( 'in attribute', () => {
+			test(
+				[ 3, 3 ],
+				'f<$text bold=true>ooba</$text>r',
+				'f<strong>oo{}ba</strong>r'
+			);
+		} );
+
+		it( 'in container with extra attributes', () => {
+			test(
+				[ 1, 1 ],
+				'foobar',
+				'f<em>[]</em>oobar',
+				{ italic: true }
+			);
+		} );
+
+		it( 'in attribute with extra attributes', () => {
+			test(
+				[ 3, 3 ],
+				'f<$text bold=true>ooba</$text>r',
+				'f<strong>oo</strong><em><strong>[]</strong></em><strong>ba</strong>r',
+				{ italic: true }
+			);
+		} );
+
+		it( 'consumes consumable values properly', () => {
+			// Add callbacks that will fire before default ones.
+			// This should prevent default callbacks doing anything.
+			dispatcher.on( 'selection', ( evt, selection, consumable ) => {
+				expect( consumable.consume( selection, 'selection' ) ).to.be.true;
+			}, null, 0 );
+
+			dispatcher.on( 'selectionAttribute:bold', ( evt, data, consumable ) => {
+				expect( consumable.consume( data.selection, 'selectionAttribute:bold' ) ).to.be.true;
+			}, null, 0 );
+
+			// Similar test case as above
+			test(
+				[ 3, 3 ],
+				'f<$text bold=true>ooba</$text>r',
+				'f<strong>ooba</strong>r' // No selection in view.
+			);
+		} );
+	} );
+} );
+
+describe( 'using element creator for attributes conversion', () => {
+	beforeEach( () => {
+		function styleElementCreator( styleValue ) {
+			if ( styleValue == 'important' ) {
+				return new ViewAttributeElement( 'strong', { style: 'text-transform:uppercase;' } );
+			} else if ( styleValue == 'gold' ) {
+				return new ViewAttributeElement( 'span', { style: 'color:yellow;' } );
+			}
+		}
+
+		dispatcher.on( 'selectionAttribute:style', convertSelectionAttribute( styleElementCreator ) );
+		dispatcher.on( 'addAttribute:style', wrap( styleElementCreator ) );
+
+		dispatcher.on( 'selectionAttribute:italic', convertSelectionAttribute( new ViewAttributeElement( 'em' ) ) );
+	} );
+
+	describe( 'range selection', () => {
+		it( 'in same container, over attribute', () => {
+			test(
+				[ 1, 5 ],
+				'fo<$text style="gold">ob</$text>ar',
+				'f{o<span style="color:yellow;">ob</span>a}r'
+			);
+		} );
+
+		it( 'in same attribute', () => {
+			test(
+				[ 2, 4 ],
+				'f<$text style="gold">ooba</$text>r',
+				'f<span style="color:yellow;">o{ob}a</span>r'
+			);
+		} );
+
+		it( 'in same attribute, selection same as attribute', () => {
+			test(
+				[ 2, 4 ],
+				'fo<$text style="important">ob</$text>ar',
+				'fo{<strong style="text-transform:uppercase;">ob</strong>}ar'
+			);
+		} );
+
+		it( 'starts in attribute, ends in text node', () => {
+			test(
+				[ 3, 5 ],
+				'fo<$text style="important">ob</$text>ar',
+				'fo<strong style="text-transform:uppercase;">o{b</strong>a}r'
+			);
+		} );
+	} );
+
+	describe( 'collapsed selection', () => {
+		it( 'in attribute', () => {
+			test(
+				[ 3, 3 ],
+				'f<$text style="gold">ooba</$text>r',
+				'f<span style="color:yellow;">oo{}ba</span>r'
+			);
+		} );
+
+		it( 'in container with style attribute', () => {
+			test(
+				[ 1, 1 ],
+				'foobar',
+				'f<strong style="text-transform:uppercase;">[]</strong>oobar',
+				{ style: 'important' }
+			);
+		} );
+
+		it( 'in style attribute with extra attributes #1', () => {
+			test(
+				[ 3, 3 ],
+				'f<$text style="gold">ooba</$text>r',
+				'f<span style="color:yellow;">oo</span>' +
+				'<em><span style="color:yellow;">[]</span></em>' +
+				'<span style="color:yellow;">ba</span>r',
+				{ italic: true }
+			);
+		} );
+
+		it( 'in style attribute with extra attributes #2', () => {
+			// In contrary to test above, we don't have strong + span on the selection.
+			// This is because strong and span are both created by the same attribute.
+			// Since style="important" overwrites style="gold" on selection, we have only strong element.
+			// In example above, selection has both style and italic attribute.
+			test(
+				[ 3, 3 ],
+				'f<$text style="gold">ooba</$text>r',
+				'f<span style="color:yellow;">oo</span>' +
+				'<strong style="text-transform:uppercase;">[]</strong>' +
+				'<span style="color:yellow;">ba</span>r',
+				{ style: 'important' }
+			);
+		} );
+	} );
+} );
+
+describe( 'table cell selection converter', () => {
+	beforeEach( () => {
+		// "Universal" converter to convert table structure.
+		const tableConverter = insertElement( ( data ) => new ViewContainerElement( data.item.name ) );
+		dispatcher.on( 'insert:table', tableConverter );
+		dispatcher.on( 'insert:tr', tableConverter );
+		dispatcher.on( 'insert:td', tableConverter );
+
+		// Special converter for table cells.
+		dispatcher.on( 'selection', ( evt, selection, consumable, conversionApi ) => {
+			if ( !consumable.test( selection, 'selection' ) || selection.isCollapsed ) {
+				return;
+			}
+
+			for ( let range of selection.getRanges() ) {
+				const node = range.start.nodeAfter;
+
+				if ( node == range.end.nodeBefore && node instanceof ModelElement && node.name == 'td' ) {
+					consumable.consume( selection, 'selection' );
+
+					let viewNode = conversionApi.mapper.toViewElement( node );
+					viewNode.addClass( 'selected' );
+				}
+			}
+		}, null, 0 );
+	} );
+
+	it( 'should not be used to convert selection that is not on table cell', () => {
+		test(
+			[ 1, 5 ],
+			'f<selection>o<$text bold=true>ob</$text>a</selection>r',
+			'f{o<strong>ob</strong>a}r'
+		);
+	} );
+
+	it( 'should add a class to the selected table cell', () => {
+		test(
+			// table tr#0, table tr#1
+			[ [ 0, 0, 0 ], [ 0, 0, 1 ] ],
+			'<table><tr><td>foo</td></tr><tr><td>bar</td></tr></table>',
+			'<table><tr><td class="selected">foo</td></tr><tr><td>bar</td></tr></table>'
+		);
+	} );
+
+	it( 'should not be used if selection contains more than just a table cell', () => {
+		test(
+			// table tr td#1, table tr#2
+			[ [ 0, 0, 0, 1 ], [ 0, 0, 2 ] ],
+			'<table><tr><td>foo</td><td>bar</td></tr></table>',
+			'<table><tr><td>f{oo</td><td>bar</td>]</tr></table>'
+		);
+	} );
+} );
+
+// Tests if the selection got correctly converted.
+// Because `setData` might use selection converters itself to set the selection, we can't use it
+// to set the selection (because then we would test converters using converters).
+// Instead, the `test` function expects to be passed `selectionPaths` which is an array containing two numbers or two arrays,
+// that are offsets or paths of selection positions in root element.
+function test( selectionPaths, modelInput, expectedView, selectionAttributes = {} ) {
+	// Parse passed `modelInput` string and set it as current model.
+	setData( modelDoc, 'modelRoot', modelInput );
+
+	// Manually set selection ranges using passed `selectionPaths`.
+	let startPath = typeof selectionPaths[ 0 ] == 'number' ? [ selectionPaths[ 0 ] ] : selectionPaths[ 0 ];
+	let endPath = typeof selectionPaths[ 1 ] == 'number' ? [ selectionPaths[ 1 ] ] : selectionPaths[ 1 ];
+	let startPos = new ModelPosition( modelRoot, startPath );
+	let endPos = new ModelPosition( modelRoot, endPath );
+	modelDoc.selection.setRanges( [ new ModelRange( startPos, endPos ) ] );
+
+	// Updated selection attributes according to model.
+	modelDoc.selection._updateAttributes();
+
+	// And add or remove passed attributes.
+	for ( let key in selectionAttributes ) {
+		let value = selectionAttributes[ key ];
+
+		if ( value ) {
+			modelDoc.selection.setAttribute( key, value );
+		} else {
+			modelDoc.selection.removeAttribute( key );
+		}
+	}
+
+	// Convert model to view.
+	dispatcher.convertInsert( ModelRange.createFromElement( modelRoot ) );
+	dispatcher.convertSelection( modelDoc.selection );
+
+	// Stringify view and check if it is same as expected.
+	expect( stringify( viewRoot, viewSelection, { showType: false } ) ).to.equal( '<viewRoot>' + expectedView + '</viewRoot>' );
+}