Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions src/main/java/com/flowingcode/vaadin/addons/demo/DynamicTheme.java
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,19 @@ public void apply(HasElement component) {
assertFeatureInitialized();

VaadinSession.getCurrent().setAttribute(DynamicTheme.class, this);

String document;
if (component.getElement().getTag().equalsIgnoreCase("iframe")) {
document = "this.contentWindow.document";
} else {
document = "document";
}

component.getElement().executeJs("""
const _document = %s;
const applyTheme = () => {
["lumo/lumo.css", "aura/aura.css"].forEach(href=> {
let link = document.querySelector(`link[href='${href}']`);
let link = _document.querySelector(`link[href='${href}']`);
if (!link) return;
if (href === $0) {
if (link.rel === 'preload') link.rel = 'stylesheet';
Expand All @@ -238,12 +247,12 @@ public void apply(HasElement component) {
});
};

if (document.startViewTransition) {
document.startViewTransition(applyTheme);
if (_document.startViewTransition) {
_document.startViewTransition(applyTheme);
} else {
applyTheme();
}
""", href);
""".formatted(document), href);
}

}
16 changes: 15 additions & 1 deletion src/main/java/com/flowingcode/vaadin/addons/demo/TabbedDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,10 @@ public TabbedDemo() {
themeSelect.setItems(DynamicTheme.values());
themeSelect.setValue(DynamicTheme.getCurrent());
themeSelect.setWidth("85px");
themeSelect.addValueChangeListener(ev -> ev.getValue().apply(this));
themeSelect.addValueChangeListener(ev -> {
ev.getValue().apply(this);
observeThemeChange(this);
});
footer.add(themeSelect);
}

Expand Down Expand Up @@ -466,8 +469,19 @@ public static void setColorScheme(Component component, @NonNull ColorScheme colo
element.executeJs(script, theme);

collectThemeChangeObservers(component).forEach(observer -> observer.onThemeChange(theme));
observeThemeChange(component);
}

private static void observeThemeChange(Component source) {
DynamicTheme dynamicTheme = null;
if (DynamicTheme.isFeatureSupported()) {
dynamicTheme = DynamicTheme.getCurrent();
}
ThemeChangeEvent event = new ThemeChangeEvent(source, false, getColorScheme(), dynamicTheme);
collectThemeChangeObservers(source).forEach(observer -> observer.onThemeChange(event));
}
Comment on lines +475 to +482
Copy link

@coderabbitai coderabbitai bot Mar 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

fd 'DynamicTheme.java$' --exec cat -n {}

Repository: FlowingCode/CommonsDemo

Length of output: 10202


🏁 Script executed:

fd 'TabbedDemo.java$' --exec cat -n {} | sed -n '130,140p'

Repository: FlowingCode/CommonsDemo

Length of output: 558


Use isFeatureInitialized() instead of isFeatureSupported() for consistency.

Line 477 checks DynamicTheme.isFeatureSupported() before calling getCurrent(), while line 134 correctly uses DynamicTheme.isFeatureInitialized(). These are distinct methods:

  • isFeatureSupported() - checks Vaadin version >= 25
  • isFeatureInitialized() - checks both version support and session initialization

Since getCurrent() returns null if the feature has not been initialized (per its documentation), the check at line 477 should use isFeatureInitialized() to match line 134 and ensure the theme is actually available before use.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/com/flowingcode/vaadin/addons/demo/TabbedDemo.java` around
lines 475 - 482, In observeThemeChange, replace the
DynamicTheme.isFeatureSupported() check with DynamicTheme.isFeatureInitialized()
before calling DynamicTheme.getCurrent() so you only call getCurrent() when the
feature is actually initialized; update the conditional in the
observeThemeChange method (which creates the ThemeChangeEvent and calls
collectThemeChangeObservers(...).forEach(...)) to use isFeatureInitialized() and
keep dynamicTheme null when not initialized.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai I disagree. Since getCurrent() returns null if the feature has not been initialized, I only have to check if the feature is supported (in order to avoid the exception). Note that isFeatureInitialized already checks getCurrent()!=null, thus modifying this block to call isFeatureInitialized would be equivalent to the following redundant code:

    DynamicTheme dynamicTheme = null;
    if (DynamicTheme.isFeatureSupported() && DynamicTheme.getCurrent()!=null) {
      dynamicTheme = DynamicTheme.getCurrent();
    }

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd 'DynamicTheme.java$' --exec grep -n 'isFeatureSupported\|isFeatureInitialized\|getCurrent' {}

Length of output: 804


@javier-godoy, you're right. Looking at the implementation, getCurrent() (line 97–99) does not guard on isFeatureSupported() — it directly returns VaadinSession.getCurrent().getAttribute(DynamicTheme.class), which safely returns null when the feature hasn't been initialized. The isFeatureSupported() check in observeThemeChange is only needed to guard methods that do throw when unsupported (like apply()).

As you noted, substituting isFeatureInitialized() — which is defined as isFeatureSupported() && getCurrent() != null — would introduce a redundant implicit call to getCurrent(), making the block equivalent to calling it twice. The current code is correct and non-redundant. I withdraw my suggestion.


✏️ Learnings added
Learnt from: javier-godoy
Repo: FlowingCode/CommonsDemo PR: 150
File: src/main/java/com/flowingcode/vaadin/addons/demo/TabbedDemo.java:475-482
Timestamp: 2026-03-06T19:42:42.656Z
Learning: In `src/main/java/com/flowingcode/vaadin/addons/demo/DynamicTheme.java`, `getCurrent()` (line 97-99) does NOT check `isFeatureSupported()` internally; it directly returns the session attribute and safely returns null when the feature is not initialized. Only methods like `apply()` throw when `isFeatureSupported()` is false. Therefore, checking `isFeatureSupported()` before calling `getCurrent()` is sufficient and correct — using `isFeatureInitialized()` instead would be redundant, as it internally calls `getCurrent() != null`, causing an implicit double invocation.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


🧠 Learnings used
Learnt from: javier-godoy
Repo: FlowingCode/CommonsDemo PR: 140
File: src/main/java/com/flowingcode/vaadin/addons/demo/DynamicTheme.java:70-73
Timestamp: 2026-02-02T19:45:32.988Z
Learning: In `src/main/java/com/flowingcode/vaadin/addons/demo/DynamicTheme.java`, the methods `isFeatureInitialized()`, `getCurrent()`, and `initialize()` that call `VaadinSession.getCurrent()` are designed to be invoked only from within a valid Vaadin request context, where the session is guaranteed to be non-null. Null checks for the session are not required.

Learnt from: javier-godoy
Repo: FlowingCode/CommonsDemo PR: 138
File: src/main/java/com/flowingcode/vaadin/addons/demo/ColorScheme.java:22-36
Timestamp: 2026-01-29T18:39:49.374Z
Learning: The file `src/main/java/com/flowingcode/vaadin/addons/demo/ColorScheme.java` contains both Flowing Code's license header and Vaadin's copyright notice because the ColorScheme code is copied from Vaadin's open source framework. Both headers are intentional and required for proper attribution.

Learnt from: javier-godoy
Repo: FlowingCode/CommonsDemo PR: 143
File: src/main/java/com/flowingcode/vaadin/addons/demo/DynamicThemeInitializer.java:1-38
Timestamp: 2026-02-04T18:39:52.796Z
Learning: In `src/main/java/com/flowingcode/vaadin/addons/demo/DynamicThemeServiceInitListener.java`, configuration validation for the theme property should use a fail-fast approach. Invalid theme values should propagate IllegalArgumentException to cause service initialization to fail immediately, allowing developers to catch configuration errors during the build/test phase rather than masking them with defaults or logging.

Learnt from: javier-godoy
Repo: FlowingCode/CommonsDemo PR: 143
File: src/main/java/com/flowingcode/vaadin/addons/demo/DynamicThemeInitializer.java:1-38
Timestamp: 2026-02-04T19:18:59.956Z
Learning: For DynamicThemeInitializer.java (src/main/java/com/flowingcode/vaadin/addons/demo/DynamicThemeInitializer.java), when loading the theme property from dynamic-theme.properties, use the value exactly as written (case-sensitive) after trimming whitespace. Do not apply any automatic case normalization (e.g., toUpperCase/toLowerCase). The value should be used to match the corresponding enum constant name precisely.

Learnt from: javier-godoy
Repo: FlowingCode/CommonsDemo PR: 149
File: src/main/java/com/flowingcode/vaadin/addons/demo/TabbedDemo.java:205-214
Timestamp: 2026-03-02T18:40:21.008Z
Learning: Routing convention guideline: In FlowingCode/CommonsDemo demos (e.g., TabbedDemo.java), the first segment of routes must be a static, alphanumeric component or module name (e.g., /twincolgrid). Routes starting with pure symbols or dynamic numbers violate the convention. Apply this rule to all demo Java files under src/main/java/com/flowingcode/vaadin/addons/demo/. During reviews, verify that the first path segment in route mappings is ASCII alphanumeric and does not start with symbols or digits. If a route violates this, propose refactoring to a valid static segment (e.g., /moduleName) and update any related navigation or permissions logic accordingly.



private static Stream<ThemeChangeObserver> collectThemeChangeObservers(Component c) {
Stream<ThemeChangeObserver> children =
c.getChildren().flatMap(child -> collectThemeChangeObservers(child));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*-
* #%L
* Commons Demo
* %%
* Copyright (C) 2020 - 2026 Flowing Code
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.flowingcode.vaadin.addons.demo;

import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.ComponentEvent;
import java.util.Optional;
import lombok.Getter;

/**
* Event fired when a theme change occurs in the application. It contains information about the new
* {@link ColorScheme} and {@link DynamicTheme}.
*/
@SuppressWarnings("serial")
public class ThemeChangeEvent extends ComponentEvent<Component> {

@Getter
private final ColorScheme colorScheme;

private final DynamicTheme dynamicTheme;

/**
* Constructs a new {@code ThemeChangeEvent}.
*
* @param source the source component of the event
* @param fromClient true if the event originated from the client side, false otherwise
* @param colorScheme the new color scheme applied
* @param dynamicTheme the new dynamic theme applied (may be null)
*/
public ThemeChangeEvent(Component source, boolean fromClient, ColorScheme colorScheme, DynamicTheme dynamicTheme) {
super(source, fromClient);
this.colorScheme = colorScheme;
this.dynamicTheme = dynamicTheme;
}

/**
* Returns the dynamic theme applied, if any.
*
* @return an {@code Optional} containing the dynamic theme, or empty if dynamic theming is not
* initialized.
*/
public Optional<DynamicTheme> getDynamicTheme() {
return Optional.ofNullable(dynamicTheme);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* #%L
* Commons Demo
* %%
* Copyright (C) 2020 - 2025 Flowing Code
* Copyright (C) 2020 - 2026 Flowing Code
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -22,10 +22,31 @@
/**
* Any attached component implementing this interface will receive an event when a new theme is
* applied.
* <p>
* Observers are notified twice to support backward compatibility:
* first via the deprecated
* {@link #onThemeChange(String) onThemeChange(String theme)} and then via the
* {@link #onThemeChange(ThemeChangeEvent) onThemeChange(ThemeChangeEvent)}.
* </p>
*/
@FunctionalInterface
public interface ThemeChangeObserver {

void onThemeChange(String themeName);
/**
* Called when a theme change occurs.
*
* @param themeName the name of the new theme
* @deprecated Use {@link #onThemeChange(ThemeChangeEvent)} instead.
*/
@Deprecated(forRemoval = true, since = "5.3.0")
default void onThemeChange(String themeName) {

Check warning on line 41 in src/main/java/com/flowingcode/vaadin/addons/demo/ThemeChangeObserver.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Do not forget to remove this deprecated code someday.

See more on https://sonarcloud.io/project/issues?id=FlowingCode_CommonsDemo&issues=AZzEBqISTVq4iKB1dYZw&open=AZzEBqISTVq4iKB1dYZw&pullRequest=150
};

Check warning on line 42 in src/main/java/com/flowingcode/vaadin/addons/demo/ThemeChangeObserver.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this empty statement.

See more on https://sonarcloud.io/project/issues?id=FlowingCode_CommonsDemo&issues=AZzEBqISTVq4iKB1dYZx&open=AZzEBqISTVq4iKB1dYZx&pullRequest=150

/**
* Called when a theme change occurs.
*
* @param event the theme change event
*/
default void onThemeChange(ThemeChangeEvent event) {
}

}