Commit 67a37a9e authored by Shane Eckenrode's avatar Shane Eckenrode

Add theming entrypoint with stylemanager service

parent 443c5aa6
......@@ -259,6 +259,34 @@
"styleext": "scss"
}
}
},
"utils-theming": {
"projectType": "library",
"root": "libs/utils/theming",
"sourceRoot": "libs/utils/theming/src",
"prefix": "psu",
"architect": {
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": ["libs/utils/theming/tsconfig.lib.json", "libs/utils/theming/tsconfig.spec.json"],
"exclude": ["**/node_modules/**", "!libs/utils/theming/**"]
}
},
"test": {
"builder": "@nrwl/jest:jest",
"options": {
"jestConfig": "libs/utils/theming/jest.config.js",
"tsConfig": "libs/utils/theming/tsconfig.spec.json",
"setupFile": "libs/utils/theming/src/test-setup.ts"
}
}
},
"schematics": {
"@nrwl/angular:component": {
"styleext": "scss"
}
}
}
},
"cli": {
......
# utils-theming
This library was generated with [Nx](https://nx.dev).
## Running unit tests
Run `nx test utils-theming` to execute the unit tests.
module.exports = {
name: 'utils-theming',
preset: '../../../jest.config.js',
coverageDirectory: '../../../coverage/libs/utils/theming',
snapshotSerializers: [
'jest-preset-angular/AngularSnapshotSerializer.js',
'jest-preset-angular/HTMLCommentSerializer.js'
]
};
{
"lib": {
"entryFile": "src/index.ts"
}
}
export { StyleManager, STYLE_MANAGER_CONFIG, Theme } from './lib/style-manager';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { inject, TestBed } from '@angular/core/testing';
import { StyleManager } from './style-manager';
describe('StyleManager', () => {
let styleManager: StyleManager;
beforeEach(() =>
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [StyleManager]
})
);
beforeEach(inject([StyleManager], (sm: StyleManager) => {
styleManager = sm;
}));
afterEach(() => {
const links = document.head.querySelectorAll('link');
// tslint:disable-next-line: prefer-const
for (let link of Array.prototype.slice.call(links)) {
if (link.className.includes('style-manager-')) {
document.head.removeChild(link);
}
}
});
it('should add stylesheet to head', () => {
styleManager.setStyle('test', 'test.css');
const styleEl = document.head.querySelector('.style-manager-test') as HTMLLinkElement;
expect(styleEl).not.toBeNull();
expect(styleEl.href.endsWith('test.css')).toBe(true);
});
it('should change existing stylesheet', () => {
styleManager.setStyle('test', 'test.css');
const styleEl = document.head.querySelector('.style-manager-test') as HTMLLinkElement;
expect(styleEl).not.toBeNull();
expect(styleEl.href.endsWith('test.css')).toBe(true);
styleManager.setStyle('test', 'new.css');
expect(styleEl.href.endsWith('new.css')).toBe(true);
});
it('should remove existing stylesheet', () => {
styleManager.setStyle('test', 'test.css');
let styleEl = document.head.querySelector('.style-manager-test') as HTMLLinkElement;
expect(styleEl).not.toBeNull();
expect(styleEl.href.endsWith('test.css')).toBe(true);
styleManager.removeStyle('test');
styleEl = document.head.querySelector('.style-manager-test') as HTMLLinkElement;
expect(styleEl).toBeNull();
});
});
import { Inject, Injectable, InjectionToken } from '@angular/core';
export interface Theme {
name: string;
primary: string;
isDefault?: boolean;
isDark?: boolean;
}
export const STYLE_MANAGER_CONFIG = new InjectionToken<Theme[]>('style.manager.config');
/**
* Class for managing stylesheets. Stylesheets are loaded into named slots so that they can be
* removed or changed later.
*/
@Injectable({ providedIn: 'root' })
export class StyleManager {
private _currentTheme: Theme;
private _availableThemes: Theme[];
constructor(@Inject(STYLE_MANAGER_CONFIG) private config: Theme[]) {
this.availableThemes = config;
this.currentTheme = this.availableThemes.find(theme => theme.isDefault);
}
public set currentTheme(theme: Theme) {
this._currentTheme = theme;
if (theme.isDefault) {
this.removeStyle('theme');
} else {
// This may need adjusted to allow the path to be configurable later.
this.setStyle('theme', `alt-themes/${theme.name}.css`);
}
}
public get currentTheme(): Theme {
return this._currentTheme;
}
public set availableThemes(themes: Theme[]) {
this._availableThemes = themes;
}
public get availableThemes(): Theme[] {
return this._availableThemes;
}
public setCurrentTheme(themeName: string): void {
const newTheme = this.availableThemes.find(theme => theme.name === themeName);
if (!newTheme) {
console.warn(`Couldn't find a theme with name ${themeName}.`);
} else {
this.currentTheme = newTheme;
}
}
/**
* Set the stylesheet with the specified key.
*/
private setStyle(key: string, href: string): void {
getLinkElementForKey(key).setAttribute('href', href);
}
/**
* Remove the stylesheet with the specified key.
*/
private removeStyle(key: string): void {
const existingLinkElement = getExistingLinkElementByKey(key);
if (existingLinkElement) {
document.head.removeChild(existingLinkElement);
}
}
}
function getLinkElementForKey(key: string): Element {
return getExistingLinkElementByKey(key) || createLinkElementWithKey(key);
}
function getExistingLinkElementByKey(key: string): Element {
return document.head.querySelector(`link[rel="stylesheet"].${getClassNameForKey(key)}`);
}
function createLinkElementWithKey(key: string): Element {
const linkEl = document.createElement('link');
linkEl.setAttribute('rel', 'stylesheet');
linkEl.classList.add(getClassNameForKey(key));
document.head.appendChild(linkEl);
return linkEl;
}
function getClassNameForKey(key: string): string {
return `style-manager-${key}`;
}
import 'jest-preset-angular';
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"types": ["node", "jest"]
},
"include": ["**/*.ts"]
}
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"target": "es2015",
"declaration": true,
"inlineSources": true,
"types": [],
"lib": ["dom", "es2018"]
},
"angularCompilerOptions": {
"annotateForClosureCompiler": true,
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"fullTemplateTypeCheck": true,
"strictInjectionParameters": true,
"enableResourceInlining": true
},
"exclude": ["src/test-setup.ts", "**/*.spec.ts"]
}
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../../dist/out-tsc",
"module": "commonjs",
"types": ["jest", "node"]
},
"files": ["src/test-setup.ts"],
"include": ["**/*.spec.ts", "**/*.d.ts"]
}
{
"extends": "../../../tslint.json",
"rules": {
"directive-selector": [true, "attribute", "ut", "camelCase"],
"component-selector": [true, "element", "ut", "kebab-case"]
}
}
......@@ -28,6 +28,9 @@
},
"utils-angular": {
"tags": []
},
"utils-theming": {
"tags": []
}
}
}
......@@ -20,7 +20,8 @@
"@psu/utils/security": ["libs/utils/security/src/index.ts"],
"@psu/utils/rx": ["libs/utils/rx/src/index.ts"],
"@psu/utils/browser": ["libs/utils/browser/src/index.ts"],
"@psu/utils/angular": ["libs/utils/angular/src/index.ts"]
"@psu/utils/angular": ["libs/utils/angular/src/index.ts"],
"@psu/utils/theming": ["libs/utils/theming/src/index.ts"]
}
},
"exclude": ["node_modules", "tmp"]
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment