preview.es6.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * @file
  3. * Attaches preview-related behavior for the Color module.
  4. */
  5. (function($, Drupal) {
  6. /**
  7. * Namespace for color-related functionality for Drupal.
  8. *
  9. * @namespace
  10. */
  11. Drupal.color = {
  12. /**
  13. * The callback for when the color preview has been attached.
  14. *
  15. * @param {Element} context
  16. * The context to initiate the color behaviour.
  17. * @param {object} settings
  18. * Settings for the color functionality.
  19. * @param {HTMLFormElement} form
  20. * The form to initiate the color behaviour on.
  21. * @param {object} farb
  22. * The farbtastic object.
  23. * @param {number} height
  24. * Height of gradient.
  25. * @param {number} width
  26. * Width of gradient.
  27. */
  28. callback(context, settings, form, farb, height, width) {
  29. let accum;
  30. let delta;
  31. // Solid background.
  32. form
  33. .find('.color-preview')
  34. .css(
  35. 'backgroundColor',
  36. form.find('.color-palette input[name="palette[base]"]').val(),
  37. );
  38. // Text preview.
  39. form
  40. .find('#text')
  41. .css(
  42. 'color',
  43. form.find('.color-palette input[name="palette[text]"]').val(),
  44. );
  45. form
  46. .find('#text a, #text h2')
  47. .css(
  48. 'color',
  49. form.find('.color-palette input[name="palette[link]"]').val(),
  50. );
  51. function gradientLineColor(i, element) {
  52. Object.keys(accum || {}).forEach(k => {
  53. accum[k] += delta[k];
  54. });
  55. element.style.backgroundColor = farb.pack(accum);
  56. }
  57. // Set up gradients if there are some.
  58. let colorStart;
  59. let colorEnd;
  60. Object.keys(settings.gradients || {}).forEach(i => {
  61. colorStart = farb.unpack(
  62. form
  63. .find(
  64. `.color-palette input[name="palette[${
  65. settings.gradients[i].colors[0]
  66. }]"]`,
  67. )
  68. .val(),
  69. );
  70. colorEnd = farb.unpack(
  71. form
  72. .find(
  73. `.color-palette input[name="palette[${
  74. settings.gradients[i].colors[1]
  75. }]"]`,
  76. )
  77. .val(),
  78. );
  79. if (colorStart && colorEnd) {
  80. delta = [];
  81. Object.keys(colorStart || {}).forEach(colorStartKey => {
  82. delta[colorStartKey] =
  83. (colorEnd[colorStartKey] - colorStart[colorStartKey]) /
  84. (settings.gradients[i].vertical ? height[i] : width[i]);
  85. });
  86. accum = colorStart;
  87. // Render gradient lines.
  88. form.find(`#gradient-${i} > div`).each(gradientLineColor);
  89. }
  90. });
  91. },
  92. };
  93. })(jQuery, Drupal);