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

automatically load css at runtime as fallback #1734

Merged
merged 21 commits into from
Dec 19, 2023
Merged
Show file tree
Hide file tree
Changes from 19 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
7 changes: 7 additions & 0 deletions .changeset/five-frogs-complain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@itwin/itwinui-react': minor
---

`ThemeProvider` will now attempt to automatically load `styles.css` if using `theme="inherit"` (or `includeCss` if using other themes).

While applications are still advised to manually import `styles.css`, this new behavior is intended to ease the migration for applications that may be using an older version of iTwinUI but want to consume dependencies that rely on iTwinUI v3.
54 changes: 54 additions & 0 deletions packages/itwinui-react/src/core/ThemeProvider/ThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import {
useIsomorphicLayoutEffect,
useControlledState,
useLatestRef,
importCss,
isJest,
} from '../utils/index.js';
import type { PolymorphicForwardRefComponent } from '../utils/index.js';
import { ThemeContext } from './ThemeContext.js';
Expand Down Expand Up @@ -84,6 +86,16 @@ type ThemeProviderOwnProps = Pick<RootProps, 'theme'> & {
* </ThemeProvider>
*/
portalContainer?: HTMLElement;
/**
* This prop will be used to determine if `styles.css` should be automatically imported at runtime.
*
* When using `theme='inherit'`, styles will be automatically loaded if not already found.
* This default behavior is useful for packages that want to support incremental adoption of latest iTwinUI,
* without requiring consuming applications (that might still be using an older version) to manually import the CSS.
*
* If true or false is passed, it will override the default behavior.
*/
includeCss?: boolean;
r100-stack marked this conversation as resolved.
Show resolved Hide resolved
};

/**
Expand Down Expand Up @@ -120,6 +132,7 @@ export const ThemeProvider = React.forwardRef((props, forwardedRef) => {
children,
themeOptions = {},
portalContainer: portalContainerProp,
includeCss = themeProp === 'inherit',
...rest
} = props;

Expand Down Expand Up @@ -158,6 +171,8 @@ export const ThemeProvider = React.forwardRef((props, forwardedRef) => {

return (
<ThemeContext.Provider value={contextValue}>
{includeCss && rootElement ? <FallbackStyles root={rootElement} /> : null}

<Root
theme={theme}
themeOptions={themeOptions}
Expand Down Expand Up @@ -272,3 +287,42 @@ const useParentThemeAndContext = (rootElement: HTMLElement | null) => {
context: parentContext,
} as const;
};

// ----------------------------------------------------------------------------

/**
* When `@itwin/itwinui-react/styles.css` is not imported, we will attempt to
* dynamically import it (if possible) and fallback to loading it from a CDN.
*/
const FallbackStyles = ({ root }: { root: HTMLElement }) => {
useIsomorphicLayoutEffect(() => {
// bail if styles are already loaded
if (getComputedStyle(root).getPropertyValue('--_iui-v3-loaded') === 'yes') {
return;
}

// bail if jest because it doesn't care about CSS 🤷
if (isJest) {
return;
}

(async () => {
try {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
await import('../../../styles.css');
} catch (error) {
console.log('Error loading styles.css locally', error);
const css = await importCss(
'https://cdn.jsdelivr.net/npm/@itwin/itwinui-react@3/styles.css',
);
document.adoptedStyleSheets = [
...document.adoptedStyleSheets,
css.default,
];
}
})();
}, [root]);

return <></>;
};
33 changes: 33 additions & 0 deletions packages/itwinui-react/src/core/utils/functions/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,36 @@
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/

/**
* Wrapper around native CSS module scripts (import attributes) for dynamic imports.
* In unsupported browsers, it gracefully degrades to import assertions, and then `fetch`.
*
* Returns a constructable CSSStyleSheet object that can be adopted.
*
* @see https://web.dev/articles/css-module-scripts
* @see https://github.com/tc39/proposal-import-attributes
*/
export const importCss = async (
url: string,
): Promise<{ default: CSSStyleSheet }> => {
try {
return await new Function(
`return import("${url}", { with: { type: "css" } })`,
)();
} catch {
try {
return await new Function(
`return import("${url}", { assert: { type: "css" } })`,
)();
} catch {
return await fetch(url)
.then((res) => res.text())
.then((cssText) => {
const stylesheet = new CSSStyleSheet();
stylesheet.replaceSync(cssText);
return { default: stylesheet };
});
}
}
};
6 changes: 6 additions & 0 deletions packages/itwinui-react/src/styles.js/styles.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,9 @@

@import '@itwin/itwinui-variables' layer(itwinui.v3);
@import '@itwin/itwinui-css' layer(itwinui.v3);

@layer itwinui.v3 {
.iui-root {
--_iui-v3-loaded: yes;
r100-stack marked this conversation as resolved.
Show resolved Hide resolved
}
}
1 change: 1 addition & 0 deletions playgrounds/next/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
transpilePackages: ['@itwin/itwinui-react'],
};

export default nextConfig;
Loading