Skip to content

Commit 3f54789

Browse files
authored
feat: Allow StyleSheet on AppShellConfigurator class (#22352)
Allows StyleSheet annotation on top of AppShellConfigurator extending class. This allows to load stylesheets globally and also import Vaadin themes in V25 as they are shipped as single CSS files. Fixes #22344
1 parent 740a1ed commit 3f54789

13 files changed

Lines changed: 270 additions & 11 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/component/dependency/StyleSheet.java‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,26 @@
2727
import com.vaadin.flow.shared.ui.LoadMode;
2828

2929
/**
30-
* Defines style sheet dependencies on a {@link Component} class. For adding
31-
* multiple style sheets for a single component, you can use this annotation
32-
* multiple times.
30+
* Loads style sheets into the browser according to a given loading mode. Style
31+
* sheet URLs can be either a file served by the application itself, or an
32+
* external URL.
3333
* <p>
34+
* Can defines style sheet dependencies for a {@link Component} class or
35+
* globally.
36+
* <p>
37+
* When this annotation is placed on the
38+
* {@link com.vaadin.flow.component.page.AppShellConfigurator}, the referenced
39+
* style sheets are injected globally into the generated {@code index.html}
40+
* during bootstrap. In this case the style sheet is always inlined in the body
41+
* of the html page, thus {@link LoadMode} values are ignored.
42+
* <p>
43+
* For adding multiple style sheets, you can use this annotation multiple times.
3444
* It is guaranteed that dependencies will be loaded only once.
3545
* <p>
46+
* Absolute URLs are used as-is; values prefixed with {@code context://} are
47+
* resolved using context path (e.g. {@code context://styles.css} becomes
48+
* {@code /my-app/styles.css}) for context path {@code /my-app}.
49+
* <p>
3650
* NOTE: while this annotation is not inherited using the
3751
* {@link Inherited @Inherited} annotation, the annotations of the possible
3852
* parent components or implemented interfaces are read when sending the

‎flow-server/src/main/java/com/vaadin/flow/server/AppShellRegistry.java‎

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,20 @@
1717

1818
import java.io.Serializable;
1919
import java.lang.annotation.Annotation;
20+
import java.util.ArrayList;
2021
import java.util.Arrays;
22+
import java.util.Collection;
2123
import java.util.Collections;
24+
import java.util.LinkedHashSet;
2225
import java.util.List;
26+
import java.util.Set;
2327
import java.util.function.Consumer;
2428

2529
import com.vaadin.flow.component.Component;
2630
import org.jsoup.nodes.Document;
2731
import org.jsoup.nodes.Element;
32+
import org.slf4j.Logger;
33+
import org.slf4j.LoggerFactory;
2834

2935
import com.vaadin.flow.component.PushConfiguration;
3036
import com.vaadin.flow.component.WebComponentExporter;
@@ -37,7 +43,10 @@
3743
import com.vaadin.flow.component.page.TargetElement;
3844
import com.vaadin.flow.component.page.Viewport;
3945
import com.vaadin.flow.router.PageTitle;
46+
import com.vaadin.flow.shared.ApplicationConstants;
47+
import com.vaadin.flow.shared.ui.LoadMode;
4048
import com.vaadin.flow.theme.Theme;
49+
import com.vaadin.flow.component.dependency.StyleSheet;
4150

4251
import static com.vaadin.flow.server.startup.AbstractAnnotationValidator.getClassAnnotations;
4352
import static com.vaadin.flow.server.startup.VaadinAppShellInitializer.getValidAnnotations;
@@ -68,6 +77,8 @@ public class AppShellRegistry implements Serializable {
6877
// There must be no more than one of the following elements per document
6978
private static final String[] UNIQUE_ELEMENTS = { "meta[name=viewport]",
7079
"meta[name=description]", "title", "base" };
80+
private static final Logger log = LoggerFactory
81+
.getLogger(AppShellRegistry.class);
7182

7283
private Class<? extends AppShellConfigurator> appShellClass;
7384

@@ -164,6 +175,9 @@ public String validateClass(Class<?> clz) {
164175
List<Class<?>> validOnlyForAppShell = (List) getValidAnnotations();
165176
// PageTitle can be in AppShell and Views
166177
validOnlyForAppShell.remove(PageTitle.class);
178+
// StyleSheet is allowed on Components; do not treat it as an
179+
// AppShell-only annotation
180+
validOnlyForAppShell.remove(StyleSheet.class);
167181
if (WebComponentExporter.class.isAssignableFrom(clz)) {
168182
// Webcomponent exporter should have the theme annotation
169183
// and Push annotation as it is not appShell configured.
@@ -179,7 +193,7 @@ public String validateClass(Class<?> clz) {
179193
return error;
180194
}
181195

182-
private AppShellSettings createSettings() {
196+
private AppShellSettings createSettings(String contextPath) {
183197
AppShellSettings settings = new AppShellSettings();
184198

185199
getAnnotations(Meta.class).forEach(
@@ -211,9 +225,56 @@ private AppShellSettings createSettings() {
211225
settings.setPageTitle(pageTitles.get(0).value());
212226
}
213227
getAnnotations(Inline.class).forEach(settings::addInline);
228+
229+
Set<String> stylesheets = new LinkedHashSet<>();
230+
for (StyleSheet sheet : getAnnotations(StyleSheet.class)) {
231+
String href = resolveStyleSheetHref(sheet.value(), contextPath);
232+
if (href != null && !href.isBlank()) {
233+
stylesheets.add(href);
234+
}
235+
}
236+
stylesheets.forEach(href -> settings.addLink("stylesheet", href));
237+
214238
return settings;
215239
}
216240

241+
private String resolveStyleSheetHref(String href, String contextPath) {
242+
if (href == null || href.isBlank()) {
243+
return null;
244+
}
245+
href = href.trim();
246+
// Accept absolute http(s) URLs unchanged
247+
String lower = href.toLowerCase();
248+
if (lower.startsWith("http://") || lower.startsWith("https://")) {
249+
return href;
250+
}
251+
// Accept context-relative URLs: context://path -> /path
252+
String contextProtocol = ApplicationConstants.CONTEXT_PROTOCOL_PREFIX;
253+
if (lower.startsWith(contextProtocol)) {
254+
String path = href.substring(contextProtocol.length());
255+
if (!path.startsWith("/")) {
256+
path = "/" + path;
257+
}
258+
if (contextPath != null && !contextPath.isEmpty()) {
259+
return contextPath + path;
260+
}
261+
return path;
262+
}
263+
// Treat ./ as relative path to static resources location
264+
if (href.startsWith("./")) {
265+
href = href.substring(2);
266+
}
267+
// Accept bare paths beginning with '/' as-is
268+
href = href.startsWith("/") ? href : "/" + href;
269+
if (HandlerHelper.isPathUnsafe(href)) {
270+
log.warn(
271+
"@StyleSheet href containing traversals ('../') are not allowed, ignored: "
272+
+ href);
273+
return null;
274+
}
275+
return href;
276+
}
277+
217278
/**
218279
* Modifies the `index.html` document based on the
219280
* {@link AppShellConfigurator} annotations or
@@ -225,7 +286,7 @@ private AppShellSettings createSettings() {
225286
* The request to handle
226287
*/
227288
public void modifyIndexHtml(Document document, VaadinRequest request) {
228-
AppShellSettings settings = createSettings();
289+
AppShellSettings settings = createSettings(request.getContextPath());
229290
if (appShellClass != null) {
230291
VaadinService.getCurrent().getInstantiator()
231292
.getOrCreate(appShellClass).configurePage(settings);

‎flow-server/src/main/java/com/vaadin/flow/server/InvalidApplicationConfigurationException.java‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,18 @@
1616
package com.vaadin.flow.server;
1717

1818
/**
19-
* Exception indicating that the application's routes have been configured
20-
* incorrectly.
19+
* Exception indicating that the application configuration is incorrect.
20+
* <p>
21+
* Usually thrown if {@link com.vaadin.flow.component.page.AppShellConfigurator}
22+
* extending class has incorrent annotations.
2123
*
2224
* @since 1.0
2325
*/
2426
public class InvalidApplicationConfigurationException extends RuntimeException {
2527

2628
/**
27-
* Constructs a new invalid route configuration runtime exception with the
28-
* specified detail message.
29+
* Constructs a new invalid application configuration runtime exception with
30+
* the specified detail message.
2931
*
3032
* @param message
3133
* the detail message. The detail message is saved for later

‎flow-server/src/main/java/com/vaadin/flow/server/startup/VaadinAppShellInitializer.java‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import org.slf4j.Logger;
3131
import org.slf4j.LoggerFactory;
3232

33+
import com.vaadin.flow.component.dependency.StyleSheet;
3334
import com.vaadin.flow.component.page.AppShellConfigurator;
3435
import com.vaadin.flow.component.page.BodySize;
3536
import com.vaadin.flow.component.page.Inline;
@@ -60,8 +61,8 @@
6061
*/
6162
@HandlesTypes({ AppShellConfigurator.class, Meta.class, Meta.Container.class,
6263
PWA.class, Inline.class, Inline.Container.class, Viewport.class,
63-
BodySize.class, PageTitle.class, Push.class, Theme.class,
64-
NoTheme.class })
64+
BodySize.class, PageTitle.class, Push.class, Theme.class, NoTheme.class,
65+
StyleSheet.class, StyleSheet.Container.class })
6566
// @WebListener is needed so that servlet containers know that they have to run
6667
// it
6768
@WebListener

‎flow-server/src/test/java/com/vaadin/flow/server/startup/VaadinAppShellInitializerTest.java‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@
5858
import com.vaadin.flow.shared.ui.Transport;
5959
import com.vaadin.flow.theme.AbstractTheme;
6060
import com.vaadin.flow.theme.Theme;
61+
import com.vaadin.flow.component.dependency.StyleSheet;
6162

6263
import jakarta.servlet.ServletContext;
6364
import jakarta.servlet.ServletRegistration;
@@ -188,6 +189,41 @@ public static class AppShellExtendingComponent extends Component
188189
implements AppShellConfigurator {
189190
}
190191

192+
@StyleSheet("./foo.css")
193+
public static class ComponentWithStylesheet extends Component {
194+
}
195+
196+
@StyleSheet("context://my-styles.css")
197+
@StyleSheet("https://cdn.example.com/ui.css")
198+
public static class MyAppShellWithStyleSheets
199+
implements AppShellConfigurator {
200+
}
201+
202+
@StyleSheet("context://theme-base.css")
203+
@StyleSheet("context://theme-base.css")
204+
public static class MyAppShellWithDuplicateStyles
205+
implements AppShellConfigurator {
206+
}
207+
208+
@StyleSheet(" /trimmed.css ")
209+
@StyleSheet(" ")
210+
@StyleSheet("foo/bar.css")
211+
@StyleSheet("HTTP://cdn.Example.com/u.css")
212+
@StyleSheet("context://assets/site.css")
213+
@StyleSheet("context:///already-absolute.css")
214+
public static class MyAppShellWithVariousStyleSheets
215+
implements AppShellConfigurator {
216+
}
217+
218+
@StyleSheet("./local.css")
219+
public static class MyAppShellWithDotSlash implements AppShellConfigurator {
220+
}
221+
222+
@StyleSheet("../secrets.css")
223+
public static class MyAppShellWithTraversal
224+
implements AppShellConfigurator {
225+
}
226+
191227
@Rule
192228
public ExpectedException exception = ExpectedException.none();
193229

@@ -437,6 +473,34 @@ public void should_not_throw_when_appShellAnnotationsAreAllowed_and_offendingCla
437473
assertEquals(0, elements.size());
438474
}
439475

476+
@Test
477+
public void styleSheetOnAppShell_injectedAsLinksInOrder() throws Exception {
478+
classes.add(MyAppShellWithStyleSheets.class);
479+
initializer.process(classes, servletContext);
480+
481+
AppShellRegistry.getInstance(context).modifyIndexHtml(document,
482+
createVaadinRequest("/"));
483+
484+
List<Element> links = document.head().select("link[rel=stylesheet]");
485+
assertEquals(2, links.size());
486+
assertEquals("/my-styles.css", links.get(0).attr("href"));
487+
assertEquals("https://cdn.example.com/ui.css",
488+
links.get(1).attr("href"));
489+
}
490+
491+
@Test
492+
public void duplicateStyleSheets_deduplicated() throws Exception {
493+
classes.add(MyAppShellWithDuplicateStyles.class);
494+
initializer.process(classes, servletContext);
495+
496+
AppShellRegistry.getInstance(context).modifyIndexHtml(document,
497+
createVaadinRequest("/"));
498+
499+
List<Element> links = document.head().select("link[rel=stylesheet]");
500+
assertEquals(1, links.size());
501+
assertEquals("/theme-base.css", links.get(0).attr("href"));
502+
}
503+
440504
@Test
441505
public void should_link_to_PWA_article() throws Exception {
442506
Mockito.when(appConfig.getBooleanProperty(
@@ -469,6 +533,55 @@ public void should_throwException_when_appShellExtendsComponent()
469533
initializer.process(classes, servletContext);
470534
}
471535

536+
@Test
537+
public void styleSheetOnComponent_notOffending() throws Exception {
538+
classes.add(ComponentWithStylesheet.class);
539+
// Should not throw as @StyleSheet is allowed on Components
540+
initializer.process(classes, servletContext);
541+
}
542+
543+
@Test
544+
public void styleSheetResolution_variousScenarios() throws Exception {
545+
classes.add(MyAppShellWithVariousStyleSheets.class);
546+
initializer.process(classes, servletContext);
547+
548+
AppShellRegistry.getInstance(context).modifyIndexHtml(document,
549+
createVaadinRequest("/", "/ctx"));
550+
551+
List<Element> links = document.head().select("link[rel=stylesheet]");
552+
assertEquals(5, links.size());
553+
assertEquals("/trimmed.css", links.get(0).attr("href"));
554+
assertEquals("/foo/bar.css", links.get(1).attr("href"));
555+
assertEquals("HTTP://cdn.Example.com/u.css", links.get(2).attr("href"));
556+
assertEquals("/ctx/assets/site.css", links.get(3).attr("href"));
557+
assertEquals("/ctx/already-absolute.css", links.get(4).attr("href"));
558+
}
559+
560+
@Test
561+
public void styleSheetResolution_handlesDotSlash() throws Exception {
562+
classes.add(MyAppShellWithDotSlash.class);
563+
initializer.process(classes, servletContext);
564+
565+
AppShellRegistry.getInstance(context).modifyIndexHtml(document,
566+
createVaadinRequest("/", "/ctx"));
567+
568+
List<Element> links = document.head().select("link[rel=stylesheet]");
569+
assertEquals(1, links.size());
570+
assertEquals("/local.css", links.get(0).attr("href"));
571+
}
572+
573+
@Test
574+
public void styleSheetResolution_rejectsTraversal() throws Exception {
575+
classes.add(MyAppShellWithTraversal.class);
576+
initializer.process(classes, servletContext);
577+
578+
AppShellRegistry.getInstance(context).modifyIndexHtml(document,
579+
createVaadinRequest("/", "/ctx"));
580+
581+
List<Element> links = document.head().select("link[rel=stylesheet]");
582+
assertEquals(0, links.size());
583+
}
584+
472585
private VaadinServletRequest createVaadinRequest(String pathInfo) {
473586
HttpServletRequest request = createRequest(pathInfo);
474587
return new VaadinServletRequest(request, service);
@@ -515,4 +628,21 @@ private ApplicationConfiguration mockApplicationConfiguration() {
515628
.thenAnswer(invocation -> invocation.getArgument(1));
516629
return config;
517630
}
631+
632+
private VaadinServletRequest createVaadinRequest(String pathInfo,
633+
String contextPath) {
634+
HttpServletRequest request = createRequest(pathInfo, contextPath);
635+
return new VaadinServletRequest(request, service);
636+
}
637+
638+
private HttpServletRequest createRequest(String pathInfo,
639+
String contextPath) {
640+
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
641+
Mockito.when(request.getServletPath()).thenReturn("");
642+
Mockito.when(request.getPathInfo()).thenReturn(pathInfo);
643+
Mockito.when(request.getRequestURL())
644+
.thenReturn(new StringBuffer(pathInfo));
645+
Mockito.when(request.getContextPath()).thenReturn(contextPath);
646+
return request;
647+
}
518648
}

‎flow-tests/pom.xml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@
254254
<module>test-common</module>
255255
<module>test-lumo</module>
256256
<module>test-express-build</module>
257+
<module>test-aura</module>
257258
</modules>
258259

259260
<profiles>

‎flow-tests/test-aura/pom.xml‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
<parent>
7+
<groupId>com.vaadin</groupId>
8+
<artifactId>flow-tests</artifactId>
9+
<version>25.0-SNAPSHOT</version>
10+
</parent>
11+
<artifactId>test-aura</artifactId>
12+
<name>Flow Test Theme: Aura</name>
13+
<packaging>jar</packaging>
14+
<properties>
15+
<maven.deploy.skip>true</maven.deploy.skip>
16+
</properties>
17+
</project>
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/* Fake Aura theme css for tests. When this file is served, it proves classpath META-INF resource lookup for @vaadin/aura works. */
2+
:root { --fake-aura-theme-loaded: 1; }

0 commit comments

Comments
 (0)