Skip to content

Commit a9d8de0

Browse files
authored
fix: Import all document styles using style tags (#16247)
Maintains the expected override order in all cases. Can also be extended to support hot reload more easily Fixes #16231
1 parent 9217ed0 commit a9d8de0

12 files changed

Lines changed: 173 additions & 107 deletions

File tree

‎flow-client/src/main/java/com/vaadin/client/ResourceLoader.java‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import com.google.gwt.core.client.Scheduler;
2424
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
2525
import com.google.gwt.user.client.Timer;
26-
2726
import com.vaadin.client.flow.collection.JsArray;
2827
import com.vaadin.client.flow.collection.JsCollections;
2928
import com.vaadin.client.flow.collection.JsMap;
@@ -604,7 +603,7 @@ public void run() {
604603
}
605604
}
606605

607-
getHead().appendChild(linkElement);
606+
addInHeadBeforeComment(linkElement, "Stylesheet end");
608607
}
609608
}
610609

@@ -639,10 +638,33 @@ public void inlineStyleSheet(String styleSheetContents,
639638

640639
addCssLoadHandler(styleSheetContents, event, styleSheetElement);
641640

642-
getHead().appendChild(styleSheetElement);
641+
addInHeadBeforeComment(styleSheetElement, "Stylesheet end");
643642
}
644643
}
645644

645+
private void addInHeadBeforeComment(Element element, String comment) {
646+
elemental.dom.Node commentNode = findCommentInHead(comment);
647+
if (commentNode == null) {
648+
Console.error("Expected to find a '" + comment
649+
+ "' comment inside <head> but none was found. Appending instead.");
650+
}
651+
getHead().insertBefore(element, commentNode);
652+
}
653+
654+
private elemental.dom.Node findCommentInHead(String comment) {
655+
NodeList childNodes = getHead().getChildNodes();
656+
int count = childNodes.getLength();
657+
for (int i = 0; i < count; i++) {
658+
elemental.dom.Node childNode = childNodes.item(i);
659+
if (childNode.getNodeType() == elemental.dom.Node.COMMENT_NODE
660+
&& comment.equals(childNode.getNodeValue())) {
661+
return childNode;
662+
}
663+
}
664+
665+
return null;
666+
}
667+
646668
/**
647669
* Loads a dynamic import via the provided JS {@code expression} and reports
648670
* the result via the {@code resourceLoadListener}.

‎flow-server/src/main/java/com/vaadin/flow/server/communication/IndexHtmlRequestHandler.java‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.util.Optional;
2626

2727
import org.jsoup.Jsoup;
28+
import org.jsoup.nodes.Comment;
2829
import org.jsoup.nodes.DataNode;
2930
import org.jsoup.nodes.Document;
3031
import org.jsoup.nodes.Element;
@@ -108,6 +109,8 @@ public boolean synchronizedHandleRequest(VaadinSession session,
108109

109110
configureHiddenElementStyles(indexDocument);
110111

112+
addStyleTagReferences(indexDocument);
113+
111114
response.setContentType(CONTENT_TYPE_TEXT_HTML_UTF_8);
112115

113116
VaadinContext context = session.getService().getContext();
@@ -168,6 +171,14 @@ private void applyThemeVariant(Document indexDocument,
168171
theme.variant()));
169172
}
170173

174+
private void addStyleTagReferences(Document indexDocument) {
175+
Comment cssImportComment = new Comment("CSSImport end");
176+
indexDocument.head().appendChild(cssImportComment);
177+
178+
Comment stylesheetComment = new Comment("Stylesheet end");
179+
indexDocument.head().appendChild(stylesheetComment);
180+
}
181+
171182
private void redirectToOldBrowserPageWhenNeeded(Document indexDocument) {
172183
addScript(indexDocument, """
173184
if (!('CSSLayerBlockRule' in window)) {

‎flow-server/src/main/java/com/vaadin/flow/server/frontend/AbstractUpdateImports.java‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,21 +63,26 @@
6363
*/
6464
abstract class AbstractUpdateImports implements Runnable {
6565

66+
private static final String IMPORT_INJECT = "import { injectGlobalCss } from 'Frontend/generated/jar-resources/theme-util.js';\n";
6667
private static final String EXPORT_MODULES = "export const addCssBlock = function(block, before = false) {\n"
6768
+ " const tpl = document.createElement('template');\n"
6869
+ " tpl.innerHTML = block;\n"
6970
+ " document.head[before ? 'insertBefore' : 'appendChild'](tpl.content, document.head.firstChild);\n"
7071
+ "};";
7172

72-
private static final String CSS_IMPORT = "import $cssFromFile_%d from '%s';%n" //
73+
private static final String CSS_IMPORT = "import $cssFromFile_%d from '%s';%n";
74+
private static final String CSS_IMPORT_AND_MAKE_LIT_CSS = CSS_IMPORT
7375
+ "const $css_%1$d = typeof $cssFromFile_%1$d === 'string' ? unsafeCSS($cssFromFile_%1$d) : $cssFromFile_%1$d;";
74-
private static final String CSS_PRE = CSS_IMPORT + "%n" + "addCssBlock(`";
76+
private static final String CSS_PRE = CSS_IMPORT_AND_MAKE_LIT_CSS + "%n"
77+
+ "addCssBlock(`";
7578
private static final String CSS_POST = "`);";
7679
private static final String CSS_BASIC_TPL = CSS_PRE
7780
+ "<style%s>${$css_%1$d}</style>" + CSS_POST;
81+
private static final String INJECT_CSS = CSS_IMPORT
82+
+ "%ninjectGlobalCss($cssFromFile_%1$d.toString(), 'CSSImport end', document);%n";
7883
private static final String THEMABLE_MIXIN_IMPORT = "import { css, unsafeCSS, registerStyles } from '@vaadin/vaadin-themable-mixin';";
79-
private static final String REGISTER_STYLES_FOR_TEMPLATE = CSS_IMPORT + "%n"
80-
+ "registerStyles('%s', $css_%1$d%s);";
84+
private static final String REGISTER_STYLES_FOR_TEMPLATE = CSS_IMPORT_AND_MAKE_LIT_CSS
85+
+ "%n" + "registerStyles('%s', $css_%1$d%s);";
8186

8287
private static final String IMPORT_TEMPLATE = "import '%s';";
8388

@@ -159,6 +164,7 @@ public void run() {
159164
protected Collection<String> getExportLines() {
160165
Collection<String> lines = new ArrayList<>();
161166
addLines(lines, EXPORT_MODULES);
167+
addLines(lines, IMPORT_INJECT);
162168
return lines;
163169
}
164170

@@ -553,12 +559,14 @@ protected boolean addCssLines(Collection<String> lines, CssData cssData,
553559
: "";
554560
addLines(lines, String.format(REGISTER_STYLES_FOR_TEMPLATE, i,
555561
cssImport, themeFor, optionals));
556-
} else {
562+
} else if (cssData.getInclude() != null) {
557563
String include = cssData.getInclude() != null
558564
? " include=\"" + cssData.getInclude() + "\""
559565
: "";
560566
addLines(lines,
561567
String.format(CSS_BASIC_TPL, i, cssImport, include));
568+
} else {
569+
addLines(lines, String.format(INJECT_CSS, i, cssImport));
562570
}
563571
return found;
564572
}

‎flow-server/src/main/java/com/vaadin/flow/server/frontend/TaskRunDevBundleBuild.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -594,7 +594,7 @@ private static void compareFrontendHashes(JsonObject frontendHashes,
594594
}
595595
}
596596

597-
private static String calculateHash(String fileContent) {
597+
static String calculateHash(String fileContent) {
598598
String content = fileContent.replaceAll("\\r\\n", "\n");
599599
return StringUtil.getHash(content, StandardCharsets.UTF_8);
600600
}

‎flow-server/src/main/resources/META-INF/frontend/theme-util.js‎

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,21 +42,48 @@ const createLinkReferences = (css, target) => {
4242
return styleCss;
4343
};
4444

45+
const addAdoptedStyle = (cssText, target, first) => {
46+
const sheet = new CSSStyleSheet();
47+
sheet.replaceSync(cssText);
48+
if (first) {
49+
target.adoptedStyleSheets = [sheet, ...target.adoptedStyleSheets];
50+
} else {
51+
target.adoptedStyleSheets = [...target.adoptedStyleSheets, sheet];
52+
}
53+
};
54+
55+
const addStyleTag = (cssText, referenceComment) => {
56+
const styleTag = document.createElement('style');
57+
styleTag.type = 'text/css';
58+
styleTag.textContent = cssText;
59+
60+
let beforeThis = undefined;
61+
if (referenceComment) {
62+
const comments = Array.from(document.head.childNodes).filter(elem => elem.nodeType === Node.COMMENT_NODE);
63+
const container = comments.find(comment => comment.data.trim() === referenceComment);
64+
if (container) {
65+
beforeThis = container;
66+
}
67+
}
68+
document.head.insertBefore(styleTag, beforeThis);
69+
};
70+
4571
// target: Document | ShadowRoot
46-
export const injectGlobalCss = (css, target, first) => {
72+
export const injectGlobalCss = (css, referenceComment, target, first) => {
4773
if (target === document) {
4874
const hash = getHash(css);
4975
if (window.Vaadin.theme.injectedGlobalCss.indexOf(hash) !== -1) {
5076
return;
5177
}
5278
window.Vaadin.theme.injectedGlobalCss.push(hash);
5379
}
54-
const sheet = new CSSStyleSheet();
55-
sheet.replaceSync(createLinkReferences(css, target));
56-
if (first) {
57-
target.adoptedStyleSheets = [sheet, ...target.adoptedStyleSheets];
80+
const cssText = createLinkReferences(css, target);
81+
82+
// We avoid mixing style tags and adoptedStyleSheets to make override order clear
83+
if (target === document) {
84+
addStyleTag(cssText, referenceComment);
5885
} else {
59-
target.adoptedStyleSheets = [...target.adoptedStyleSheets, sheet];
86+
addAdoptedStyle(cssText, target, first);
6087
}
6188
};
6289

‎flow-server/src/main/resources/plugins/application-theme-plugin/theme-generator.js‎

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,11 @@ const { sync } = glob;
2929
const themeComponentsFolder = 'components';
3030
// The contents of a global CSS file with this name in a theme is always added to
3131
// the document. E.g. @font-face must be in this
32-
const documentCssFile = 'document.css';
32+
const documentCssFilename = 'document.css';
3333
// styles.css is the only entrypoint css file with document.css. Everything else should be imported using css @import
34-
const stylesCssFile = 'styles.css';
34+
const stylesCssFilename = 'styles.css';
3535

36+
const CSSIMPORT_COMMENT = 'CSSImport end';
3637
const headerImport = `import 'construct-style-sheets-polyfill';
3738
`;
3839

@@ -48,8 +49,8 @@ const headerImport = `import 'construct-style-sheets-polyfill';
4849
function generateThemeFile(themeFolder, themeName, themeProperties, options) {
4950
const productionMode = !options.devMode;
5051
const useDevServer = !options.useDevBundle;
51-
const styles = resolve(themeFolder, stylesCssFile);
52-
const document = resolve(themeFolder, documentCssFile);
52+
const styles = resolve(themeFolder, stylesCssFilename);
53+
const documentCssFile = resolve(themeFolder, documentCssFilename);
5354
const autoInjectComponents = themeProperties.autoInjectComponents ?? true;
5455
let themeFile = headerImport;
5556
var componentsFiles;
@@ -73,7 +74,6 @@ function generateThemeFile(themeFolder, themeName, themeProperties, options) {
7374

7475
const imports = [];
7576
const globalCssCode = [];
76-
const lumoCssCode = [];
7777
const lumoCssShadowOnlyCode = [];
7878
const componentCssCode = [];
7979
const parentTheme = themeProperties.parent ? 'applyBaseTheme(target);\n' : '';
@@ -97,12 +97,10 @@ function generateThemeFile(themeFolder, themeName, themeProperties, options) {
9797
// styles.css will always be available as we write one if it doesn't exist.
9898
let filename = basename(styles);
9999
let variable = camelCase(filename);
100-
if (useDevServer) {
101-
imports.push(`import ${variable} from 'themes/${themeName}/${filename}?inline';\n`);
102-
}
103-
/* Lumo must be first so that custom styles override Lumo styles */
100+
101+
/* LUMO */
104102
const lumoImports = themeProperties.lumoImports || ['color', 'typography'];
105-
if (lumoImports && lumoImports.length > 0) {
103+
if (lumoImports) {
106104
lumoImports.forEach((lumoImport) => {
107105
imports.push(`import { ${lumoImport} } from '@vaadin/vaadin-lumo-styles/${lumoImport}.js';\n`);
108106
if (lumoImport === 'utility' || lumoImport === 'badge') {
@@ -113,20 +111,22 @@ function generateThemeFile(themeFolder, themeName, themeProperties, options) {
113111

114112
lumoImports.forEach((lumoImport) => {
115113
// Lumo is injected to the document by Lumo itself
116-
lumoCssShadowOnlyCode.push(`injectGlobalCss(${lumoImport}.cssText, target, true);\n`);
114+
lumoCssShadowOnlyCode.push(`injectGlobalCss(${lumoImport}.cssText, '', target, true);\n`);
117115
});
118116
}
119117

118+
/* Theme */
120119
if (useDevServer) {
121-
globalCssCode.push(`injectGlobalCss(${variable}.toString(), target);\n `);
120+
imports.push(`import ${variable} from 'themes/${themeName}/${filename}?inline';\n`);
121+
globalCssCode.push(`injectGlobalCss(${variable}.toString(), '', target);\n `);
122122
}
123-
if (existsSync(document)) {
124-
filename = basename(document);
123+
if (existsSync(documentCssFile)) {
124+
filename = basename(documentCssFile);
125125
variable = camelCase(filename);
126126

127127
if (useDevServer) {
128128
imports.push(`import ${variable} from 'themes/${themeName}/${filename}?inline';\n`);
129-
globalCssCode.push(`injectGlobalCss(${variable}.toString(), document);\n `);
129+
globalCssCode.push(`injectGlobalCss(${variable}.toString(),'', document);\n `);
130130
}
131131
}
132132

@@ -147,9 +147,9 @@ function generateThemeFile(themeFolder, themeName, themeProperties, options) {
147147
// Due to chrome bug https://bugs.chromium.org/p/chromium/issues/detail?id=336876 font-face will not work
148148
// inside shadowRoot so we need to inject it there also.
149149
globalCssCode.push(`if(target !== document) {
150-
injectGlobalCss(${variable}.toString(), target);
150+
injectGlobalCss(${variable}.toString(), '', target);
151151
}\n `);
152-
globalCssCode.push(`injectGlobalCss(${variable}.toString(), document);\n `);
152+
globalCssCode.push(`injectGlobalCss(${variable}.toString(), '${CSSIMPORT_COMMENT}', document);\n `);
153153
});
154154
}
155155
if (themeProperties.importCss) {
@@ -165,7 +165,7 @@ function generateThemeFile(themeFolder, themeName, themeProperties, options) {
165165
themeProperties.importCss.forEach((cssPath) => {
166166
const variable = 'module' + i++;
167167
imports.push(`import ${variable} from '${cssPath}';\n`);
168-
globalCssCode.push(`injectGlobalCss(${variable}.toString(), target);\n`);
168+
globalCssCode.push(`injectGlobalCss(${variable}.toString(), '${CSSIMPORT_COMMENT}', target);\n`);
169169
});
170170
}
171171

@@ -191,10 +191,8 @@ function generateThemeFile(themeFolder, themeName, themeProperties, options) {
191191
// If targets check that we only register the style parts once, checks exist for global css and component css
192192
const themeFileApply = `export const applyTheme = (target) => {
193193
if (target !== document) {
194-
// Lumo is injected to the document by Lumo itself, except for the utility module
195194
${lumoCssShadowOnlyCode.join('')}
196195
}
197-
${lumoCssCode.join('')}
198196
${parentTheme}
199197
${globalCssCode.join('')}
200198

‎flow-server/src/test/java/com/vaadin/flow/server/frontend/AbstractNodeUpdateImportsTest.java‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,10 @@ public void generateImportsFile_fileContainsThemeLinesAndExpectedImportsAndCssIm
143143
.add("import $cssFromFile_6 from 'Frontend/foo.css?inline';");
144144
expectedLines.add(
145145
"import { css, unsafeCSS, registerStyles } from '@vaadin/vaadin-themable-mixin';");
146-
expectedLines.add("addCssBlock(`<style>${$css_0}</style>`);");
147-
expectedLines.add("addCssBlock(`<style>${$css_1}</style>`);");
146+
expectedLines.add(
147+
"injectGlobalCss($cssFromFile_0.toString(), 'CSSImport end', document);");
148+
expectedLines.add(
149+
"injectGlobalCss($cssFromFile_1.toString(), 'CSSImport end', document);");
148150
expectedLines.add(
149151
"addCssBlock(`<style include=\"bar\">${$css_2}</style>`);");
150152
expectedLines.add("registerStyles('', $css_3, {moduleId: 'baz'});");

‎flow-server/src/test/java/com/vaadin/flow/server/frontend/AbstractUpdateImportsTest.java‎

Lines changed: 5 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -344,8 +344,10 @@ public void generateLines_resultingLinesContainsThemeLinesAndExpectedImportsAndC
344344
.add("import $cssFromFile_5 from 'Frontend/foo.css?inline';");
345345
expectedLines
346346
.add("import $cssFromFile_6 from 'Frontend/foo.css?inline';");
347-
expectedLines.add("addCssBlock(`<style>${$css_0}</style>`);");
348-
expectedLines.add("addCssBlock(`<style>${$css_1}</style>`);");
347+
expectedLines.add(
348+
"injectGlobalCss($cssFromFile_0.toString(), 'CSSImport end', document);");
349+
expectedLines.add(
350+
"injectGlobalCss($cssFromFile_1.toString(), 'CSSImport end', document);");
349351
expectedLines.add(
350352
"addCssBlock(`<style include=\"bar\">${$css_2}</style>`);");
351353
expectedLines.add("registerStyles('', $css_3, {moduleId: 'baz'});");
@@ -463,24 +465,6 @@ private static class MainView extends Component {
463465
NodeTestComponents.JavaScriptOrder javaScriptOrder;
464466
}
465467

466-
@Test
467-
public void plainCssImportWorks() throws MalformedURLException {
468-
Class<?>[] testClasses = { SimpleCssImport.class };
469-
ClassFinder classFinder = getClassFinder(testClasses);
470-
471-
options.withTokenFile(new File(tmpRoot, TOKEN_FILE));
472-
updater = new UpdateImports(classFinder, getScanner(classFinder),
473-
options);
474-
updater.run();
475-
476-
Assert.assertTrue("Should import unsafeCSS",
477-
updater.getCssLines().stream()
478-
.anyMatch(line -> line.matches("import.*unsafeCSS.*")));
479-
Assert.assertTrue("Should use unsafeCSS",
480-
updater.getCssLines().stream().anyMatch(line -> line
481-
.matches(".*unsafeCSS\\(\\$cssFromFile_.*")));
482-
}
483-
484468
@Test
485469
public void assertFullSortOrder() throws MalformedURLException {
486470
Class[] testClasses = { MainView.class,
@@ -514,6 +498,7 @@ public void assertFullSortOrder() throws MalformedURLException {
514498
List<String> internals = expectedImports.stream()
515499
.filter(importValue -> importValue
516500
.contains(FrontendUtils.FRONTEND_FOLDER_ALIAS))
501+
.filter(importValue -> !importValue.contains("theme-util.js"))
517502
.sorted().collect(Collectors.toList());
518503
updater.getGeneratedModules().stream().map(this::updateToImport)
519504
.forEach(expectedImports::add);

‎flow-server/src/test/java/com/vaadin/flow/server/frontend/NodeUpdateImportsTest.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -157,8 +157,8 @@ Logger log() {
157157
// Contains CSS import lines
158158
MatcherAssert.assertThat(mainContent, CoreMatchers.containsString(
159159
"import $cssFromFile_0 from '@vaadin/vaadin-mixed-component/bar.css?inline';"));
160-
MatcherAssert.assertThat(mainContent, CoreMatchers
161-
.containsString("addCssBlock(`<style>${$css_0}</style>`);"));
160+
MatcherAssert.assertThat(mainContent, CoreMatchers.containsString(
161+
"injectGlobalCss($cssFromFile_0.toString(), 'CSSImport end', document);"));
162162

163163
MatcherAssert.assertThat(mainContent, CoreMatchers.containsString(
164164
"import $cssFromFile_5 from 'Frontend/foo.css?inline';"));

0 commit comments

Comments
 (0)