attributeconverters.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * @license Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md.
  4. */
  5. import AttributeElement from '../view/attributeelement';
  6. import buildModelConverter from './buildmodelconverter';
  7. import buildViewConverter from './buildviewconverter';
  8. export function viewToModelAttribute( attributeName, attributeValue, view, dispatchers ) {
  9. const viewDefinitions = view.from ? view.from : [ view ];
  10. for ( const viewDefinition of viewDefinitions ) {
  11. const element = viewDefinition.name;
  12. const classes = viewDefinition.class;
  13. const styles = viewDefinition.style;
  14. const pattern = { name: element };
  15. if ( classes ) {
  16. pattern.class = classes;
  17. }
  18. if ( styles ) {
  19. pattern.style = styles;
  20. }
  21. buildViewConverter()
  22. .for( ...dispatchers )
  23. .from( pattern )
  24. .toAttribute( () => ( {
  25. key: attributeName,
  26. value: attributeValue
  27. } ) );
  28. }
  29. }
  30. export function modelAttributeToView( attributeName, attributeValue, view, dispatchers ) {
  31. buildModelConverter()
  32. .for( ...dispatchers )
  33. .fromAttribute( attributeName )
  34. .toElement( value => {
  35. // TODO: string vs numeric values
  36. if ( value != attributeValue ) {
  37. return;
  38. }
  39. const viewDefinition = view.to ? view.to : view;
  40. // TODO: AttributeElement.fromDefinition() ?
  41. const classes = viewDefinition.class;
  42. const styles = viewDefinition.style;
  43. const attributes = {};
  44. // TODO: AttributeElement does no accept Array
  45. if ( classes ) {
  46. attributes.class = Array.isArray( classes ) ? classes.join( ' ' ) : classes;
  47. }
  48. // TODO: Attribute element does not accept Object
  49. if ( styles ) {
  50. attributes.style = typeof styles === 'string' ? styles : toStylesString( styles );
  51. }
  52. return new AttributeElement( viewDefinition.name, attributes );
  53. } );
  54. }
  55. function toStylesString( stylesObject ) {
  56. const styles = [];
  57. for ( const key in stylesObject ) {
  58. styles.push( key + ':' + stylesObject[ key ] );
  59. }
  60. return styles.join( ';' );
  61. }