Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(theming): add custom theme support for external CSS #5887

Merged
merged 2 commits into from
Oct 28, 2022
Merged
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
26 changes: 23 additions & 3 deletions packages/base/src/InitialConfiguration.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import merge from "./thirdparty/merge.js";
import { getFeature } from "./FeaturesRegistry.js";
import { DEFAULT_THEME } from "./generated/AssetParameters.js";
import validateThemeRoot from "./validateThemeRoot.js";

let initialized = false;

let initialConfig = {
animationMode: "full",
theme: DEFAULT_THEME,
themeRoot: null,
rtl: null,
language: null,
calendarType: null,
Expand All @@ -26,6 +28,11 @@ const getTheme = () => {
return initialConfig.theme;
};

const getThemeRoot = () => {
initConfiguration();
return initialConfig.themeRoot;
};

const getRTL = () => {
initConfiguration();
return initialConfig.rtl;
Expand Down Expand Up @@ -106,7 +113,13 @@ const parseURLParameters = () => {
});
};

const normalizeParamValue = (param, value) => {
const normalizeThemeRootParamValue = value => {
const themeRoot = value.split("@")[1];

return validateThemeRoot(themeRoot);
};

const normalizeThemeParamValue = (param, value) => {
if (param === "theme" && value.includes("@")) { // the theme parameter might have @<URL-TO-THEME> in the value - strip this
return value.split("@")[0];
}
Expand All @@ -122,9 +135,15 @@ const applyURLParam = (key, value, paramType) => {
value = booleanMapping.get(lowerCaseValue);
}

value = normalizeParamValue(param, value);
if (param === "theme") {
initialConfig.theme = normalizeThemeParamValue(param, value);

initialConfig[param] = value;
if (value && value.includes("@")) {
initialConfig.themeRoot = normalizeThemeRootParamValue(value);
}
} else {
initialConfig[param] = value;
}
};

const applyOpenUI5Configuration = () => {
Expand Down Expand Up @@ -157,6 +176,7 @@ const initConfiguration = () => {
export {
getAnimationMode,
getTheme,
getThemeRoot,
getRTL,
getLanguage,
getFetchDefaultLanguage,
Expand Down
39 changes: 39 additions & 0 deletions packages/base/src/config/ThemeRoots.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import createLinkInHead from "../util/createLinkInHead.js";
import validateThemeRoot from "../validateThemeRoot.js";
import { getThemeRoot as getConfiguredThemeRoot } from "../InitialConfiguration.js";

let themeRoot;

const getThemeRoot = () => {
if (themeRoot === undefined) {
themeRoot = getConfiguredThemeRoot();
}

return themeRoot;
};

const setThemeRoot = (theme, newThemeRoot) => {
nnaydenow marked this conversation as resolved.
Show resolved Hide resolved
themeRoot = validateThemeRoot(newThemeRoot);

attachCustomThemeStylesToHead(theme);
nnaydenow marked this conversation as resolved.
Show resolved Hide resolved
};

const formatThemeLink = theme => {
return `${getThemeRoot()}Base/baseLib/${theme}/css_variables.css`;
};

const attachCustomThemeStylesToHead = async theme => {
const link = document.querySelector(`[sap-ui-webcomponents-theme="${theme}"]`);

if (link) {
document.head.removeChild(link);
}

await createLinkInHead(formatThemeLink(theme), { "sap-ui-webcomponents-theme": theme });
nnaydenow marked this conversation as resolved.
Show resolved Hide resolved
};

export {
getThemeRoot,
setThemeRoot,
attachCustomThemeStylesToHead,
};
1 change: 1 addition & 0 deletions packages/base/src/features/OpenUI5Support.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const getConfigurationSettingsObject = () => {
animationMode: config.getAnimationMode(),
language: config.getLanguage(),
theme: config.getTheme(),
themeRoot: config.getThemeRoot(),
rtl: config.getRTL(),
calendarType: config.getCalendarType(),
formatSettings: {
Expand Down
9 changes: 7 additions & 2 deletions packages/base/src/theming/applyTheme.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { removeStyle, createOrUpdateStyle } from "../ManagedStyles.js";
import getThemeDesignerTheme from "./getThemeDesignerTheme.js";
import { fireThemeLoaded } from "./ThemeLoaded.js";
import { getFeature } from "../FeaturesRegistry.js";
import { attachCustomThemeStylesToHead, getThemeRoot } from "../config/ThemeRoots.js";

const BASE_THEME_PACKAGE = "@ui5/webcomponents-theming";

Expand Down Expand Up @@ -40,7 +41,7 @@ const loadComponentPackages = async theme => {
});
};

const detectExternalTheme = () => {
const detectExternalTheme = async theme => {
// If theme designer theme is detected, use this
const extTheme = getThemeDesignerTheme();
if (extTheme) {
Expand All @@ -56,11 +57,15 @@ const detectExternalTheme = () => {
themeName: OpenUI5Support.getConfigurationSettingsObject().theme, // just themeName, baseThemeName is only relevant for custom themes
};
}
} else if (getThemeRoot()) {
await attachCustomThemeStylesToHead(theme);

return getThemeDesignerTheme();
}
};

const applyTheme = async theme => {
const extTheme = detectExternalTheme();
const extTheme = await detectExternalTheme(theme);

// Only load theme_base properties if there is no externally loaded theme, or there is, but it is not being loaded
if (!extTheme || theme !== extTheme.themeName) {
Expand Down
7 changes: 6 additions & 1 deletion packages/base/src/util/createLinkInHead.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,13 @@ const createLinkInHead = (href, attributes = {}) => {
Object.entries(attributes).forEach(pair => link.setAttribute(...pair));

link.href = href;

document.head.appendChild(link);
return link;
nnaydenow marked this conversation as resolved.
Show resolved Hide resolved

return new Promise(resolve => {
link.addEventListener("load", resolve);
link.addEventListener("error", resolve);
});
};

export default createLinkInHead;
58 changes: 58 additions & 0 deletions packages/base/src/validateThemeRoot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const getMetaTagValue = metaTagName => {
const metaTag = document.querySelector(`META[name="${metaTagName}"]`),
metaTagContent = metaTag && metaTag.getAttribute("content");

return metaTagContent;
};

const validateThemeOrigin = origin => {
const allowedOrigins = getMetaTagValue("sap-allowedThemeOrigins");

return allowedOrigins && allowedOrigins.split(",").some(allowedOrigin => {
return allowedOrigin === "*" || origin === allowedOrigin.trim();
});
};

const buildCorrectUrl = (oldUrl, newOrigin) => {
const oldUrlPath = new URL(oldUrl).pathname;

return new URL(oldUrlPath, newOrigin).toString();
};

const validateThemeRoot = themeRoot => {
let themeRootURL,
resultUrl;

try {
themeRootURL = new URL(themeRoot);

const origin = themeRootURL.origin;

themeRootURL = themeRootURL.toString();

if (themeRootURL.startsWith(".") || themeRootURL.startsWith("/")) {
// Handle relative url
// new URL("/newExmPath", "http://example.com/exmPath") => http://example.com/newExmPath
// new URL("./newExmPath", "http://example.com/exmPath") => http://example.com/exmPath/newExmPath
// new URL("../newExmPath", "http://example.com/exmPath") => http://example.com/newExmPath
resultUrl = new URL(themeRootURL, window.location.href).toString();
} else if (origin && validateThemeOrigin(origin)) {
// If origin is allowed, use it
resultUrl = themeRootURL.toString();
} else {
// If origin is not allow and the URL is not relative, we have to replace the origin
// with current location
resultUrl = buildCorrectUrl(themeRootURL, window.location.href);
}

if (!resultUrl.endsWith("/")) {
resultUrl = `${resultUrl}/`;
}

return `${resultUrl}UI5/`;
} catch (e) {
// Catch if URL is not correct
}
};

export default validateThemeRoot;