Dynamically injecting CSS

In most cases you will style your components using SASS or CSS and create a theme for the application which you include with the @Theme annotation. This is always the preferred way of theming your application. But in some cases this is not enough. Sometimes you will want your user to be able to change some property on-the-fly without providing pre-made class names. To do this you can use CSS style injection. In this example I am going to show you how you can use CSS injection to create an editor which you can use to modify text visually with, a WYSIWYG of sorts. Here is an image of the final component I am going to create:

Theme editor

First lets start by defining the UI of the editor component, it looks like this:

Java

  1. private Component createEditor(String text) {
  2. Panel editor = new Panel("Text Editor");
  3. editor.setWidth("580px");
  4. VerticalLayout panelContent = new VerticalLayout();
  5. panelContent.setSpacing(true);
  6. panelContent.setMargin(new MarginInfo(true, false, false, false));
  7. editor.setContent(panelContent);
  8. // Create the toolbar
  9. HorizontalLayout toolbar = new HorizontalLayout();
  10. toolbar.setSpacing(true);
  11. toolbar.setMargin(new MarginInfo(false, false, false, true));
  12. // Create the font family selector
  13. toolbar.addComponent(createFontSelect());
  14. // Create the font size selector
  15. toolbar.addComponent(createFontSizeSelect());
  16. // Create the text color selector
  17. toolbar.addComponent(createTextColorSelect());
  18. // Create the background color selector
  19. toolbar.addComponent(createBackgroundColorSelect());
  20. panelContent.addComponent(toolbar);
  21. panelContent.setComponentAlignment(toolbar, Alignment.MIDDLE_LEFT);
  22. // Spacer between toolbar and text
  23. panelContent.addComponent(new Label("<hr />", ContentMode.HTML));
  24. // The text to edit
  25. TextArea textLabel = new TextArea(null, text);
  26. textLabel.setWidth("100%");
  27. textLabel.setHeight("200px");
  28. // IMPORTANT: We are here setting the style name of the label, we are going to use this in our injected styles to target the label
  29. textLabel.setStyleName("text-label");
  30. panelContent.addComponent(textLabel);
  31. return editor;
  32. }

Basically the editor component is a Panel with a text area and some buttons which you can use to modify the text area text with. The important thing here is that we give the text area a style name “text-label”. With this style name we will be able to inject CSS styles targeted at that text area and modify colors and fonts of it. Lets next take a look at how the controls in the toolbar is implemented. They are all pretty similar but lets first take a look at how the Font selector was made:

Java

  1. private Component createFontSelect() {
  2. final ComboBox select = new ComboBox(null,
  3. Arrays.asList("Arial", "Helvetica", "Verdana", "Courier", "Times", "sans-serif"));
  4. select.setValue("Arial");
  5. select.setWidth("200px");
  6. select.setInputPrompt("Font");
  7. select.setDescription("Font");
  8. select.setImmediate(true);
  9. select.setNullSelectionAllowed(false);
  10. select.setNewItemsAllowed(false);
  11. select.addValueChangeListener(new ValueChangeListener() {
  12. @Override
  13. public void valueChange( ValueChangeEvent event ) {
  14. // Get the new font family
  15. String fontFamily = select.getValue().toString();
  16. // Get the stylesheet of the page
  17. Styles styles = Page.getCurrent().getStyles();
  18. // inject the new font size as a style. We need .v-app to override Vaadin's default styles here
  19. styles.add(".v-app .v-textarea.text-label { font-family:" + fontFamily + "; }");
  20. }
  21. });
  22. return select;
  23. }

The important part here is what is inside the ValueChangeListener. Once we get the value from the ComboBox we are ready to inject it to the page so the user can visually see what have changed. To do this we fetch the StyleSheet for the current Page by calling Page.getCurrent(). Once we have the current Page we can get its StyleSheet by calling Page.getstyleSheet(). Once we got the StyleSheet we are free to inject any CSS string into the page by using StyleSheet.inject(String css). As you see here we use the style name we gave to the TextArea as the selector and apply the font-family attribute to change the font family to the one the user has selected. For the sake of clarity, lets look at how another one, the text color selector, was implemented:

Java

  1. private Component createTextColorSelect( ) {
  2. // Colorpicker for changing text color
  3. ColorPicker textColor = new ColorPicker("Color", Color.BLACK);
  4. textColor.setWidth("110px");
  5. textColor.setCaption("Color");
  6. textColor.addColorChangeListener(new ColorChangeListener() {
  7. @Override
  8. public void colorChanged( ColorChangeEvent event ) {
  9. // Get the new text color
  10. Color color = event.getColor();
  11. // Get the stylesheet of the page
  12. Styles styles = Page.getCurrent().getStyles();
  13. // inject the new color as a style
  14. styles.add(".v-app .v-textarea.text-label { color:" + color.getCSS() + "; }");
  15. }
  16. });
  17. return textColor;
  18. }

Again, the important part in this method is in the ColorChangeListener. Basically here we do the exactly same thing as we did with the font family except here we are dealing with a color. To change the color of the text we just simply apply the ‘color’ attribute for text area. The ColorPicker.Color even provides us with a convenient method of directly converting the received Color object into a CSS color. And finally, for completeness, here is the full example code which will produce the demo application in the picture above for you to try out:

Java

  1. /**
  2. * Imports and package definition omitted
  3. */
  4. public class CSSInjectWithColorpicker extends UI {
  5. @Override
  6. protected void init( VaadinRequest request ) { // Create a text editor
  7. Component editor =
  8. createEditor("Lorem ipsum dolor sit amet, lacus pharetra sed, sit a "
  9. + "tortor. Id aliquam lorem pede, orci ut enim metus, diam nulla mi "
  10. + "suspendisse tempor tortor. Eleifend lorem proin, morbi vel diam ut. "
  11. + "Tempor est tellus vitae, pretium condimentum facilisis sit. Sagittis "
  12. + "quam, ac urna eros est cras id cras, eleifend eu mattis nec."
  13. + "Lorem ipsum dolor sit amet, lacus pharetra sed, sit a "
  14. + "tortor. Id aliquam lorem pede, orci ut enim metus, diam nulla mi "
  15. + "suspendisse tempor tortor. Eleifend lorem proin, morbi vel diam ut. "
  16. + "Tempor est tellus vitae, pretium condimentum facilisis sit. Sagittis "
  17. + "quam, ac urna eros est cras id cras, eleifend eu mattis nec."
  18. + "Lorem ipsum dolor sit amet, lacus pharetra sed, sit a "
  19. + "tortor. Id aliquam lorem pede, orci ut enim metus, diam nulla mi "
  20. + "suspendisse tempor tortor. Eleifend lorem proin, morbi vel diam ut. "
  21. + "Tempor est tellus vitae, pretium condimentum facilisis sit. Sagittis "
  22. + "quam, ac urna eros est cras id cras, eleifend eu mattis nec."
  23. + "Lorem ipsum dolor sit amet, lacus pharetra sed, sit a "
  24. + "tortor. Id aliquam lorem pede, orci ut enim metus, diam nulla mi "
  25. + "suspendisse tempor tortor. Eleifend lorem proin, morbi vel diam ut. "
  26. + "Tempor est tellus vitae, pretium condimentum facilisis sit. Sagittis "
  27. + "quam, ac urna eros est cras id cras, eleifend eu mattis nec.");
  28. VerticalLayout content = new VerticalLayout(editor);
  29. content.setMargin(true);
  30. setContent(content);
  31. }
  32. /**
  33. * Creates a text editor for visually editing text
  34. *
  35. * @param text The text editor
  36. * @return
  37. */
  38. private Component createEditor( String text ) {
  39. Panel editor = new Panel("Text Editor");
  40. editor.setWidth("580px");
  41. VerticalLayout panelContent = new VerticalLayout();
  42. panelContent.setSpacing(true);
  43. panelContent.setMargin(new MarginInfo(true, false, false, false));
  44. editor.setContent(panelContent);
  45. // Create the toolbar
  46. HorizontalLayout toolbar = new HorizontalLayout();
  47. toolbar.setSpacing(true);
  48. toolbar.setMargin(new MarginInfo(false, false, false, true));
  49. // Create the font family selector
  50. toolbar.addComponent(createFontSelect());
  51. // Create the font size selector
  52. toolbar.addComponent(createFontSizeSelect());
  53. // Create the text color selector
  54. toolbar.addComponent(createTextColorSelect());
  55. // Create the background color selector
  56. toolbar.addComponent(createBackgroundColorSelect());
  57. panelContent.addComponent(toolbar);
  58. panelContent.setComponentAlignment(toolbar, Alignment.MIDDLE_LEFT);
  59. // Spacer between toolbar and text
  60. panelContent.addComponent(new Label("<hr />", ContentMode.HTML));
  61. // The text to edit
  62. TextArea textLabel = new TextArea(null, text);
  63. textLabel.setWidth("100%");
  64. textLabel.setHeight("200px");
  65. // IMPORTANT: We are here setting the style name of the label, we are going to use this in our injected styles to
  66. // target the label
  67. textLabel.setStyleName("text-label");
  68. panelContent.addComponent(textLabel);
  69. return editor;
  70. }
  71. /**
  72. * Creates a background color select dialog
  73. */
  74. private Component createBackgroundColorSelect( ) {
  75. ColorPicker bgColor = new ColorPicker("Background", Color.WHITE);
  76. bgColor.setWidth("110px");
  77. bgColor.setCaption("Background");
  78. bgColor.addColorChangeListener(new ColorChangeListener() {
  79. @Override
  80. public void colorChanged( ColorChangeEvent event ) {
  81. // Get the new background color
  82. Color color = event.getColor();
  83. // Get the stylesheet of the page
  84. Styles styles = Page.getCurrent().getStyles();
  85. // inject the new background color
  86. styles.add(".v-app .v-textarea.text-label { background-color:" + color.getCSS() + "; }");
  87. }
  88. });
  89. return bgColor;
  90. }
  91. /**
  92. * Create a text color selection dialog
  93. */
  94. private Component createTextColorSelect( ) {
  95. // Colorpicker for changing text color
  96. ColorPicker textColor = new ColorPicker("Color", Color.BLACK);
  97. textColor.setWidth("110px");
  98. textColor.setCaption("Color");
  99. textColor.addColorChangeListener(new ColorChangeListener() {
  100. @Override
  101. public void colorChanged( ColorChangeEvent event ) {
  102. // Get the new text color
  103. Color color = event.getColor();
  104. // Get the stylesheet of the page
  105. Styles styles = Page.getCurrent().getStyles();
  106. // inject the new color as a style
  107. styles.add(".v-app .v-textarea.text-label { color:" + color.getCSS() + "; }");
  108. }
  109. });
  110. return textColor;
  111. }
  112. /**
  113. * Creates a font family selection dialog
  114. */
  115. private Component createFontSelect( ) {
  116. final ComboBox select =
  117. new ComboBox(null, Arrays.asList("Arial", "Helvetica", "Verdana", "Courier", "Times", "sans-serif"));
  118. select.setValue("Arial");
  119. select.setWidth("200px");
  120. select.setInputPrompt("Font");
  121. select.setDescription("Font");
  122. select.setImmediate(true);
  123. select.setNullSelectionAllowed(false);
  124. select.setNewItemsAllowed(false);
  125. select.addValueChangeListener(new ValueChangeListener() {
  126. @Override
  127. public void valueChange( ValueChangeEvent event ) {
  128. // Get the new font family
  129. String fontFamily = select.getValue().toString();
  130. // Get the stylesheet of the page
  131. Styles styles = Page.getCurrent().getStyles();
  132. // inject the new font size as a style. We need .v-app to override Vaadin's default styles here
  133. styles.add(".v-app .v-textarea.text-label { font-family:" + fontFamily + "; }");
  134. }
  135. });
  136. return select;
  137. }
  138. /**
  139. * Creates a font size selection control
  140. */
  141. private Component createFontSizeSelect( ) {
  142. final ComboBox select = new ComboBox(null, Arrays.asList(8, 9, 10, 12, 14, 16, 20, 25, 30, 40, 50));
  143. select.setWidth("100px");
  144. select.setValue(12);
  145. select.setInputPrompt("Font size");
  146. select.setDescription("Font size");
  147. select.setImmediate(true);
  148. select.setNullSelectionAllowed(false);
  149. select.setNewItemsAllowed(false);
  150. select.addValueChangeListener(new ValueChangeListener() {
  151. @Override
  152. public void valueChange( ValueChangeEvent event ) {
  153. // Get the new font size
  154. Integer fontSize = (Integer) select.getValue();
  155. // Get the stylesheet of the page
  156. Styles styles = Page.getCurrent().getStyles();
  157. // inject the new font size as a style. We need .v-app to override Vaadin's default styles here
  158. styles.add(".v-app .v-textarea.text-label { font-size:" + String.valueOf(fontSize) + "px; }");
  159. }
  160. });
  161. return select;
  162. }
  163. }