dynamic-theme-lib
Version:
A flexible and powerful theme management library for Angular applications that allows dynamic color management and theme switching.
305 lines (295 loc) • 13.9 kB
JavaScript
import * as i0 from '@angular/core';
import { Injectable, Component, PLATFORM_ID, Inject, Directive, Input, NgModule } from '@angular/core';
import { isPlatformBrowser, CommonModule } from '@angular/common';
import * as i1 from '@angular/common/http';
import { HttpClientModule } from '@angular/common/http';
import { BehaviorSubject, of } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
class DynamicThemeLibService {
constructor() { }
}
DynamicThemeLibService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: DynamicThemeLibService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
DynamicThemeLibService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: DynamicThemeLibService, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: DynamicThemeLibService, decorators: [{
type: Injectable,
args: [{
providedIn: 'root'
}]
}], ctorParameters: function () { return []; } });
class DynamicThemeLibComponent {
constructor() { }
ngOnInit() {
}
}
DynamicThemeLibComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: DynamicThemeLibComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
DynamicThemeLibComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.2.17", type: DynamicThemeLibComponent, selector: "lib-dynamic-theme-lib", ngImport: i0, template: `
<p>
dynamic-theme-lib works!
</p>
`, isInline: true });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: DynamicThemeLibComponent, decorators: [{
type: Component,
args: [{
selector: 'lib-dynamic-theme-lib',
template: `
<p>
dynamic-theme-lib works!
</p>
`,
styles: []
}]
}], ctorParameters: function () { return []; } });
class ColourService {
constructor(http, platformId) {
this.http = http;
this.platformId = platformId;
this.colorMap = {}; // Store color configurations
this.storageKey = 'colorConfig'; // Key for storing colors in sessionStorage
this.configUrl = 'assets/colors/color-config.json';
this.colorsSubject = new BehaviorSubject({});
this.colors$ = this.colorsSubject.asObservable(); // Expose as observable for real-time updates
this.isBrowser = isPlatformBrowser(this.platformId); // Check if the platform is a browser
this.loadColorConfig();
console.log("Color service getting called");
}
/**
* Method to fetch the color configuration and load colors from sessionStorage or JSON.
*/
loadColorConfig() {
console.log("Load config getting called");
if (this.isBrowser) {
// Check if color config is stored in sessionStorage
const storedColors = sessionStorage.getItem(this.storageKey);
if (storedColors) {
console.log("From session...");
try {
this.colorMap = JSON.parse(storedColors);
this.colorsSubject.next(this.colorMap); // Emit new values
console.log('Colors loaded from session storage:', this.colorMap);
return;
}
catch (error) {
console.warn('Error parsing stored colors, falling back to config file:', error);
sessionStorage.removeItem(this.storageKey);
}
}
}
// If not found in storage or non-browser environment, fetch from JSON file
this.http.get(this.configUrl).pipe(tap((data) => {
console.log('Colors loaded from config file:', data);
}), catchError((error) => {
console.error('Error loading color config:', error);
// Return default colors if config file fails to load
return of({
'primary-color': '#007bff',
'secondary-color': '#6c757d',
'background-color': '#ffffff',
'text-color': '#212529'
});
})).subscribe((data) => {
this.colorMap = data;
this.colorsSubject.next(this.colorMap); // Emit new values to subscribers
if (this.isBrowser) {
try {
sessionStorage.setItem(this.storageKey, JSON.stringify(data));
}
catch (error) {
console.warn('Error storing colors in session storage:', error);
}
}
});
}
/**
* Method to update color for a specific variable and store it.
* @param variableName The key for the color variable (e.g., 'primary-color')
* @param colorValue The new color value (e.g., '#ff5733')
*/
setColor(variableName, colorValue) {
if (!variableName || !colorValue) {
console.warn('Invalid color update request:', { variableName, colorValue });
return;
}
this.colorMap[variableName] = colorValue;
// Store updated colorMap in sessionStorage for persistence during the session
if (this.isBrowser) {
try {
sessionStorage.setItem(this.storageKey, JSON.stringify(this.colorMap));
}
catch (error) {
console.warn('Error storing updated colors:', error);
}
}
this.colorsSubject.next(Object.assign({}, this.colorMap));
console.log(`Color updated: ${variableName} = ${colorValue}`);
}
/**
* Method to get the color for a specific variable.
* @param variableName The key for the color variable (e.g., 'primary-color')
* @returns The color value for the given variable or an empty string if not found
*/
getColor(variableName) {
const color = this.colorMap[variableName];
if (!color) {
console.warn(`Color not found for: ${variableName}`);
return '';
}
return color;
}
/**
* Method to get all colors (useful for UI configuration or preview page).
* @returns All color configurations
*/
getAllColors() {
return Object.assign({}, this.colorMap);
}
reloadColors() {
this.loadColorConfig();
}
}
ColourService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: ColourService, deps: [{ token: i1.HttpClient }, { token: PLATFORM_ID }], target: i0.ɵɵFactoryTarget.Injectable });
ColourService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: ColourService, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: ColourService, decorators: [{
type: Injectable,
args: [{
providedIn: 'root',
}]
}], ctorParameters: function () { return [{ type: i1.HttpClient }, { type: undefined, decorators: [{
type: Inject,
args: [PLATFORM_ID]
}] }]; } });
class BackgroundColorDirective {
constructor(el, colorService) {
this.el = el;
this.colorService = colorService;
this.libBackgroundColour = '';
this.currentColor = '';
}
ngOnInit() {
// Subscribe to color changes and update dynamically
this.colorSubscription = this.colorService.colors$.subscribe(() => {
this.applyColor();
});
// Initial color application
this.applyColor();
}
ngOnChanges(changes) {
if (changes['libBackgroundColour'] && !changes['libBackgroundColour'].firstChange) {
this.applyColor();
}
}
applyColor() {
if (!this.libBackgroundColour) {
console.warn('No background color variable specified');
return;
}
const newColor = this.colorService.getColor(this.libBackgroundColour);
if (newColor && newColor !== this.currentColor) {
this.currentColor = newColor;
this.el.nativeElement.style.backgroundColor = newColor;
}
}
ngOnDestroy() {
if (this.colorSubscription) {
this.colorSubscription.unsubscribe();
}
}
}
BackgroundColorDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: BackgroundColorDirective, deps: [{ token: i0.ElementRef }, { token: ColourService }], target: i0.ɵɵFactoryTarget.Directive });
BackgroundColorDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "12.2.17", type: BackgroundColorDirective, selector: "[libBackgroundColour]", inputs: { libBackgroundColour: "libBackgroundColour" }, usesOnChanges: true, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: BackgroundColorDirective, decorators: [{
type: Directive,
args: [{
selector: '[libBackgroundColour]'
}]
}], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: ColourService }]; }, propDecorators: { libBackgroundColour: [{
type: Input
}] } });
class TextColorDirective {
constructor(el, colorService) {
this.el = el;
this.colorService = colorService;
this.libTextColour = ''; // The input property for text color name
this.currentColor = '';
}
ngOnInit() {
// Subscribe to color changes and update dynamically
this.colorSubscription = this.colorService.colors$.subscribe(() => {
this.applyColor();
});
// Initial color application
this.applyColor();
}
ngOnChanges(changes) {
if (changes['libTextColour'] && !changes['libTextColour'].firstChange) {
this.applyColor();
}
}
applyColor() {
if (!this.libTextColour) {
console.warn('No text color variable specified');
return;
}
const newColor = this.colorService.getColor(this.libTextColour);
if (newColor && newColor !== this.currentColor) {
this.currentColor = newColor;
this.el.nativeElement.style.color = newColor;
}
}
ngOnDestroy() {
// Unsubscribe to avoid memory leaks
if (this.colorSubscription) {
this.colorSubscription.unsubscribe();
}
}
}
TextColorDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: TextColorDirective, deps: [{ token: i0.ElementRef }, { token: ColourService }], target: i0.ɵɵFactoryTarget.Directive });
TextColorDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "12.2.17", type: TextColorDirective, selector: "[libTextColour]", inputs: { libTextColour: "libTextColour" }, usesOnChanges: true, ngImport: i0 });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: TextColorDirective, decorators: [{
type: Directive,
args: [{
selector: '[libTextColour]'
}]
}], ctorParameters: function () { return [{ type: i0.ElementRef }, { type: ColourService }]; }, propDecorators: { libTextColour: [{
type: Input
}] } });
class DynamicThemeLibModule {
}
DynamicThemeLibModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: DynamicThemeLibModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
DynamicThemeLibModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: DynamicThemeLibModule, declarations: [DynamicThemeLibComponent,
BackgroundColorDirective,
TextColorDirective], imports: [CommonModule,
HttpClientModule], exports: [DynamicThemeLibComponent,
BackgroundColorDirective,
TextColorDirective] });
DynamicThemeLibModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: DynamicThemeLibModule, providers: [ColourService], imports: [[
CommonModule,
HttpClientModule
]] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.17", ngImport: i0, type: DynamicThemeLibModule, decorators: [{
type: NgModule,
args: [{
declarations: [
DynamicThemeLibComponent,
BackgroundColorDirective,
TextColorDirective
],
imports: [
CommonModule,
HttpClientModule
],
exports: [
DynamicThemeLibComponent,
BackgroundColorDirective,
TextColorDirective,
],
providers: [ColourService]
}]
}] });
/*
* Public API Surface of dynamic-theme-lib
*/
/**
* Generated bundle index. Do not edit.
*/
export { BackgroundColorDirective, ColourService, DynamicThemeLibComponent, DynamicThemeLibModule, DynamicThemeLibService, TextColorDirective };
//# sourceMappingURL=dynamic-theme-lib.js.map