-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDynamicTheme.java
More file actions
249 lines (221 loc) · 7.9 KB
/
DynamicTheme.java
File metadata and controls
249 lines (221 loc) · 7.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package com.flowingcode.vaadin.addons.demo;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.HasElement;
import com.vaadin.flow.component.page.AppShellConfigurator;
import com.vaadin.flow.component.page.Inline.Position;
import com.vaadin.flow.server.AppShellRegistry;
import com.vaadin.flow.server.AppShellSettings;
import com.vaadin.flow.server.VaadinContext;
import com.vaadin.flow.server.VaadinService;
import com.vaadin.flow.server.VaadinSession;
import com.vaadin.flow.server.Version;
import com.vaadin.flow.server.communication.IndexHtmlResponse;
import com.vaadin.flow.theme.Theme;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.jsoup.nodes.Element;
/**
* Enumeration representing supported themes for dynamic switching.
* <p>
* This enum facilitates switching between themes (e.g., Lumo, Aura) at runtime.
* </p>
*/
@RequiredArgsConstructor
public enum DynamicTheme {
/**
* The standard Lumo theme.
*/
LUMO("lumo/lumo.css", "hsl(214, 35%, 21%)"),
/**
* The standard Aura theme.
*/
AURA("aura/aura.css", "oklch(0.2 0.01 260)"),
/**
* A base theme without specific styling.
*/
BASE(null, "#000");
@Getter
private final String href;
@Getter
private final String bgColor;
private static void assertFeatureSupported() {
if (!isFeatureSupported()) {
throw new UnsupportedOperationException("Dynamic theme switching requires Vaadin 25+");
}
}
/**
* Checks if the dynamic theme feature is supported. The feature is supported in Vaadin 25.
*
* @return {@code true} if the feature is supported and initialized; {@code false} otherwise.
*/
public static boolean isFeatureSupported() {
return Version.getMajorVersion() >= 25;
}
private static void assertFeatureInitialized() {
assertFeatureSupported();
if (!isFeatureInitialized()) {
throw new IllegalStateException("Dynamic theme switching has not been initialized");
}
}
/**
* Checks if the dynamic theme feature has been initialized for the current session.
*
* @return {@code true} if the feature is supported and initialized; {@code false} otherwise.
*/
public static boolean isFeatureInitialized() {
return isFeatureSupported()
&& VaadinSession.getCurrent().getAttribute(DynamicTheme.class) != null;
}
private static void assertNotLegacyTheme() {
VaadinContext context = VaadinService.getCurrent().getContext();
Class<? extends AppShellConfigurator> appShellClass =
AppShellRegistry.getInstance(context).getShell();
if (appShellClass != null && appShellClass.getAnnotation(Theme.class) != null) {
throw new IllegalStateException("App shell is configured with legacy @Theme annotation");
}
}
/**
* Return the current dynamic theme.
*
* @throws UnsupportedOperationException if the runtime Vaadin version is older than 25.
* @return the current dynamic theme, or {@code null} if the feature has not been initialized.
*/
public static DynamicTheme getCurrent() {
assertFeatureSupported();
return VaadinSession.getCurrent().getAttribute(DynamicTheme.class);
}
/**
* Initializes the theme settings into the provided {@code AppShellSettings}.
* <p>
* This method performs a lazy initialization of the {@code DynamicTheme} within the
* current {@link VaadinSession}. If no theme is present, it registers this instance
* as the session default. Subsequently, it injects the corresponding CSS stylesheet
* link into the document head.
* </p>
*
* @param settings the application shell settings to be modified
* @throws UnsupportedOperationException if the runtime Vaadin version is older than 25
* @throws IllegalStateException if the {@link AppShellConfigurator} is configured with the legacy
* {@link Theme} annotation
*/
public void initialize(AppShellSettings settings) {
assertFeatureSupported();
assertNotLegacyTheme();
DynamicTheme theme = getCurrent();
if (theme == null) {
theme = this;
VaadinSession.getCurrent().setAttribute(DynamicTheme.class, theme);
}
switch (theme) {
case AURA:
settings.addLink(Position.APPEND, "stylesheet", "aura/aura.css");
break;
case LUMO:
settings.addLink(Position.APPEND, "stylesheet", "lumo/lumo.css");
break;
default:
break;
}
}
/**
* Initializes the theme settings into the provided {@code IndexHtmlResponse}.
* <p>
* This method performs a lazy initialization of the {@code DynamicTheme} within the
* current {@link VaadinSession}. If no theme is present, it registers this instance
* as the session default. Subsequently, it injects the corresponding CSS stylesheet
* link into the document head.
* </p>
*
* @param response the index HTML response to be modified
* @throws UnsupportedOperationException if the runtime Vaadin version is older than 25
*/
public void initialize(IndexHtmlResponse response) {
assertFeatureSupported();
assertNotLegacyTheme();
DynamicTheme theme = getCurrent();
if (theme == null) {
theme = this;
VaadinSession.getCurrent().setAttribute(DynamicTheme.class, theme);
}
String href = null;
switch (theme) {
case AURA:
href = "aura/aura.css";
break;
case LUMO:
href = "lumo/lumo.css";
break;
default:
break;
}
if (href != null) {
Element link = response.getDocument().createElement("link");
link.attr("rel", "stylesheet");
link.attr("href", href);
response.getDocument().head().appendChild(link);
}
}
/**
* Prepares the component for dynamic theme switching by preloading stylesheets.
* <p>
* Adds a client-side listener to the component that detects mouseover events.
* When triggered, it preloads the theme stylesheets (Lumo and Aura) to ensure
* they can be applied immediately when needed.
* </p>
*
* @param component the component to attach the listener to
* @throws IllegalStateException if the dynamic theme feature has not been initialized
*/
public static void prepare(Component component) {
assertFeatureInitialized();
component.addAttachListener(ev -> doPrepare(component));
if (component.isAttached()) {
doPrepare(component);
}
}
private static void doPrepare(Component component) {
component.getElement().executeJs("""
this.addEventListener('mouseover', function() {
["lumo/lumo.css", "aura/aura.css"].forEach(href=> {
let link = document.querySelector(`link[href="${href}"]`);
if (!link) {
link = document.createElement("link");
link.href = href;
link.as = 'style';
link.rel = 'preload';
document.head.prepend(link);
}
});
}, {once:true} );
""");
}
/**
* Applies this theme to the view.
*
* @param component a component in the view
* @throws IllegalStateException if the dynamic theme feature has not been initialized
*/
public void apply(HasElement component) {
assertFeatureInitialized();
VaadinSession.getCurrent().setAttribute(DynamicTheme.class, this);
component.getElement().executeJs("""
const applyTheme = () => {
["lumo/lumo.css", "aura/aura.css"].forEach(href=> {
let link = document.querySelector(`link[href='${href}']`);
if (!link) return;
if (href === $0) {
if (link.rel === 'preload') link.rel = 'stylesheet';
if (link.disabled) link.disabled = false;
} else if (link.rel === 'stylesheet' && !link.disabled) {
link.disabled = true;
}
});
};
if (document.startViewTransition) {
document.startViewTransition(applyTheme);
} else {
applyTheme();
}
""", href);
}
}