Skip to content

Commit

Permalink
feat(theming): log a warning if core theme isn't loaded
Browse files Browse the repository at this point in the history
* Checks the user's loaded stylesheets and logs a warning if the Material core theme isn't loaded.
* Fixes a wrong `typeof` check when determining the doctype.

Fixes angular#2828.

Note: I originally went with looping through the `document.styleSheets` to check whether the selector is defined, however I had to switch back to `getComputedStyle`, because browsers don't expose the `document.styleSheets`, if the CSS file is being loaded from another domain. This would've caused the warning to be logged if the user loads over a CDN.
  • Loading branch information
crisbeto committed Mar 25, 2017
1 parent a25e7bb commit 068f416
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/lib/core/_core.scss
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,9 @@
$background: map-get($theme, background);
background-color: mat-color($background, background);
}

// Marker that is used to determine whether the user has added a theme to their page.
.mat-theme-loaded-marker {
display: none;
}
}
33 changes: 31 additions & 2 deletions src/lib/core/compatibility/compatibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
} from '@angular/core';
import {DOCUMENT} from '@angular/platform-browser';

/** Flag for whether we've checked that the theme is loaded. */
let hasCheckedThemePresence = false;

export const MATERIAL_COMPATIBILITY_MODE = new OpaqueToken('md-compatibility-mode');

Expand Down Expand Up @@ -170,14 +172,41 @@ export class CompatibilityModule {
};
}

constructor(@Optional() @Inject(DOCUMENT) document: any) {
if (isDevMode() && typeof document && !document.doctype) {
constructor(@Optional() @Inject(DOCUMENT) private _document: any) {
this._checkDoctype();
this._checkTheme();
}

private _checkDoctype(): void {
if (isDevMode() && this._document && !this._document.doctype) {
console.warn(
'Current document does not have a doctype. This may cause ' +
'some Angular Material components not to behave as expected.'
);
}
}

private _checkTheme(): void {
if (hasCheckedThemePresence || !this._document || !isDevMode()) {
return;
}

let testElement = this._document.createElement('div');

testElement.classList.add('mat-theme-loaded-marker');
this._document.body.appendChild(testElement);

if (getComputedStyle(testElement).display !== 'none') {
console.warn(
'Could not find Angular Material core theme. Most Material ' +
'components may not work as expected. For more info refer ' +
'to the theming guide: https://github.com/angular/material2/blob/master/guides/theming.md'
);
}

this._document.body.removeChild(testElement);
hasCheckedThemePresence = true;
}
}


Expand Down

0 comments on commit 068f416

Please sign in to comment.