style-packs-customizer.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * File style-packs-customizer.js.
  3. *
  4. * Contains the customizer bindings for style packs.
  5. */
  6. ( function( $ ) {
  7. // Style packs data.
  8. var config = stylePacksData;
  9. var body = document.body;
  10. loadPreviewStylesheets();
  11. // Active style pack.
  12. wp.customize( 'active_style_pack', function( value ) {
  13. var currentStyle = value();
  14. value.bind( function( to ) {
  15. removeCustomStyles();
  16. if ( 'default' === to ) {
  17. removeStyle( currentStyle );
  18. } else {
  19. applyStyle( to, currentStyle );
  20. }
  21. fireEvent( 'change', {
  22. from: currentStyle,
  23. to: to
  24. } );
  25. body.classList.remove( getBodyClass( currentStyle ) );
  26. body.classList.add( getBodyClass( to ) );
  27. currentStyle = to;
  28. } );
  29. } );
  30. function fireEvent( evt, payload ) {
  31. $( document ).trigger( ['style_packs', evt].join( '.' ), payload );
  32. }
  33. function createLink( id, uri ) {
  34. var link = document.createElement( 'link' );
  35. link.setAttribute( 'rel', 'stylesheet' );
  36. link.setAttribute( 'id', id );
  37. link.setAttribute( 'href', uri );
  38. return link;
  39. }
  40. function getBodyClass( style ) {
  41. return stylePacksData.body_class_format.replace( '%s', style );
  42. }
  43. function applyStyle( style, prevStyle ) {
  44. if ( prevStyle ) {
  45. removeStyle( prevStyle );
  46. }
  47. var styleData = config.styles[ style ];
  48. if ( styleData ) {
  49. link = createLink( styleData.id, styleData.uri );
  50. document.head.appendChild( link );
  51. }
  52. _.each( config.fonts[ style ], function( uri, id ) {
  53. var link = createLink( id, uri );
  54. document.head.appendChild( link );
  55. } );
  56. }
  57. function removeStyle( style ) {
  58. if ( 'default' !== style ) {
  59. if ( config.styles[ style ] ) {
  60. $( 'head #' + config.styles[ style ].id ).remove();
  61. }
  62. _.each( config.fonts[ style ], function( uri, id ) {
  63. $( 'head #' + id ).remove();
  64. } );
  65. }
  66. }
  67. function loadPreviewStylesheets() {
  68. var style = config.preview_style, data = config.styles[ style ];
  69. _.each( config.fonts[ style ], function( uri, id ) {
  70. document.head.appendChild( createLink( id, uri ) );
  71. } );
  72. if ( data ) {
  73. document.head.appendChild( createLink( data.id, data.uri ) );
  74. }
  75. }
  76. function removeCustomStyles() {
  77. $( '#custom-colors-css, #custom-background-css, #jetpack-custom-fonts-css', document.head ).remove();
  78. }
  79. } )( jQuery );