preview.es6.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 behavior.
  17. * @param {object} settings
  18. * Settings for the color functionality.
  19. * @param {HTMLFormElement} form
  20. * The form to initiate the color behavior 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[${settings.gradients[i].colors[0]}]"]`,
  65. )
  66. .val(),
  67. );
  68. colorEnd = farb.unpack(
  69. form
  70. .find(
  71. `.color-palette input[name="palette[${settings.gradients[i].colors[1]}]"]`,
  72. )
  73. .val(),
  74. );
  75. if (colorStart && colorEnd) {
  76. delta = [];
  77. Object.keys(colorStart || {}).forEach(colorStartKey => {
  78. delta[colorStartKey] =
  79. (colorEnd[colorStartKey] - colorStart[colorStartKey]) /
  80. (settings.gradients[i].vertical ? height[i] : width[i]);
  81. });
  82. accum = colorStart;
  83. // Render gradient lines.
  84. form.find(`#gradient-${i} > div`).each(gradientLineColor);
  85. }
  86. });
  87. },
  88. };
  89. })(jQuery, Drupal);