Skip to content

Commit

Permalink
warn when multiple instances of the package are found (#2137)
Browse files Browse the repository at this point in the history
  • Loading branch information
mayank99 authored Jul 12, 2024
1 parent 96e6d22 commit 7044f2c
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/cool-beds-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@itwin/itwinui-react': patch
---

Development-only warnings will now be displayed when multiple versions of iTwinUI are detected.
48 changes: 47 additions & 1 deletion packages/itwinui-react/src/core/ThemeProvider/ThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export const ThemeProvider = React.forwardRef((props, forwardedRef) => {
<Root
theme={theme}
themeOptions={themeOptions}
ref={useMergedRefs(forwardedRef, setRootElement)}
ref={useMergedRefs(forwardedRef, setRootElement, useIuiDebugRef)}
{...rest}
>
{children}
Expand Down Expand Up @@ -419,3 +419,49 @@ const FallbackStyles = ({ root }: { root: HTMLElement }) => {

return <></>;
};

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

/**
* This function stores a list of iTwinUI versions in the window object
* and displays development-only warnings when multiple versions are detected.
*/
const useIuiDebugRef = () => {
const _globalThis = globalThis as any;
_globalThis.__iui ||= { versions: new Set() };

if (process.env.NODE_ENV === 'development' && !isUnitTest) {
// Override the `add` method to automatically detect multiple versions as they're added
_globalThis.__iui.versions.add = (version: string) => {
Set.prototype.add.call(_globalThis.__iui.versions, version);

if (_globalThis.__iui.versions.size > 1) {
_globalThis.__iui._shouldWarn = true;

if (_globalThis.__iui._warnTimeout) {
clearTimeout(_globalThis.__iui._warnTimeout);
}

// Warn after 3 seconds, but only once
_globalThis.__iui._warnTimeout = setTimeout(() => {
if (_globalThis.__iui._shouldWarn) {
console.warn(
`Multiple versions of iTwinUI were detected on this page. This can lead to unexpected behavior and duplicated code in the bundle. ` +
`Make sure you're using a single iTwinUI instance across your app. https://github.com/iTwin/iTwinUI/wiki/Version-conflicts`,
);
console.groupCollapsed('iTwinUI versions detected:');
const versionsTable: any[] = [];
_globalThis.__iui.versions.forEach((version: string) => {
versionsTable.push(JSON.parse(version));
});
console.table(versionsTable);
console.groupEnd();
_globalThis.__iui._shouldWarn = false;
}
}, 3000);
}
};
}

_globalThis.__iui.versions.add(JSON.stringify(meta));
};

0 comments on commit 7044f2c

Please sign in to comment.