@memberjunction/ng-shared-generic 5.30.1 → 5.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { CompositeKey } from '@memberjunction/core';
1
+ import { IMetadataProvider, CompositeKey } from '@memberjunction/core';
2
2
  import { Observable } from 'rxjs';
3
3
  import * as i0 from "@angular/core";
4
4
  /**
@@ -19,11 +19,18 @@ export interface RecentAccessItem {
19
19
  * Service for tracking and retrieving recently accessed resources.
20
20
  * Uses the User Record Logs entity to persist access history.
21
21
  */
22
+ /**
23
+ * Multi-provider note: callers under a non-default provider should set
24
+ * `service.Provider = component.ProviderToUse` before invoking any methods.
25
+ */
22
26
  export declare class RecentAccessService {
23
27
  private static readonly _globalStoreKey;
24
28
  private _recentItems$;
25
29
  private _isLoading$;
26
30
  private _isLoaded;
31
+ private _provider;
32
+ get Provider(): IMetadataProvider;
33
+ set Provider(value: IMetadataProvider | null);
27
34
  constructor();
28
35
  static get Instance(): RecentAccessService;
29
36
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"recent-access.service.d.ts","sourceRoot":"","sources":["../../src/lib/recent-access.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAqB,YAAY,EAAmC,MAAM,sBAAsB,CAAC;AAIxG,OAAO,EAAmB,UAAU,EAAE,MAAM,MAAM,CAAC;;AAEnD;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,IAAI,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,YAAY,EAAE,QAAQ,GAAG,MAAM,GAAG,WAAW,GAAG,UAAU,GAAG,QAAQ,CAAC;CACvE;AAED;;;GAGG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kBAAkB,IAAI,OAAO,CAAC,IAAI,CAAC;IAIhD;;;OAGG;YACW,kBAAkB;IA+BhC;;;;;OAKG;IACH,OAAO,CAAC,0BAA0B;IA0BlC;;OAEG;IACH,OAAO,CAAC,qBAAqB;IAmB7B;;OAEG;IACI,UAAU,IAAI,IAAI;yCAjRd,mBAAmB;6CAAnB,mBAAmB;CAqR/B"}
@@ -9,11 +9,22 @@ import * as i0 from "@angular/core";
9
9
  * Service for tracking and retrieving recently accessed resources.
10
10
  * Uses the User Record Logs entity to persist access history.
11
11
  */
12
+ /**
13
+ * Multi-provider note: callers under a non-default provider should set
14
+ * `service.Provider = component.ProviderToUse` before invoking any methods.
15
+ */
12
16
  export class RecentAccessService {
13
17
  static _globalStoreKey = '___SINGLETON__RecentAccessService';
14
18
  _recentItems$ = new BehaviorSubject([]);
15
19
  _isLoading$ = new BehaviorSubject(false);
16
20
  _isLoaded = false;
21
+ _provider = null;
22
+ get Provider() {
23
+ return this._provider ?? Metadata.Provider;
24
+ }
25
+ set Provider(value) {
26
+ this._provider = value;
27
+ }
17
28
  constructor() {
18
29
  const g = GetGlobalObjectStore();
19
30
  if (g[RecentAccessService._globalStoreKey]) {
@@ -52,7 +63,7 @@ export class RecentAccessService {
52
63
  */
53
64
  async logAccess(entityName, recordId, resourceType = 'record') {
54
65
  try {
55
- const md = new Metadata();
66
+ const md = this.Provider;
56
67
  const entityInfo = md.Entities.find(e => e.Name === entityName);
57
68
  if (!entityInfo) {
58
69
  console.warn(`RecentAccessService: Entity "${entityName}" not found in metadata`);
@@ -63,7 +74,7 @@ export class RecentAccessService {
63
74
  ? recordId.Values(',') // Values() returns joined string with specified delimiter
64
75
  : recordId;
65
76
  // Check if we already have a log entry for this user/entity/record combination
66
- const rv = new RunView();
77
+ const rv = RunView.FromMetadataProvider(this.Provider);
67
78
  const existingResult = await rv.RunView({
68
79
  EntityName: 'MJ: User Record Logs',
69
80
  ExtraFilter: `UserID='${md.CurrentUser.ID}' AND EntityID='${entityInfo.ID}' AND RecordID='${recordIdString}'`,
@@ -86,7 +97,7 @@ export class RecentAccessService {
86
97
  }
87
98
  else {
88
99
  // Create new entry
89
- const newLog = await md.GetEntityObject('MJ: User Record Logs');
100
+ const newLog = await md.GetEntityObject('MJ: User Record Logs', md.CurrentUser);
90
101
  newLog.UserID = md.CurrentUser.ID;
91
102
  newLog.EntityID = entityInfo.ID;
92
103
  newLog.RecordID = recordIdString;
@@ -117,7 +128,7 @@ export class RecentAccessService {
117
128
  }
118
129
  try {
119
130
  this._isLoading$.next(true);
120
- const md = new Metadata();
131
+ const md = this.Provider;
121
132
  // Get recent records, limited to maxItems (already ordered by LatestAt DESC in engine)
122
133
  const userRecordLogs = UserInfoEngine.Instance.UserRecordLogs.slice(0, maxItems);
123
134
  const items = [];
@@ -1 +1 @@
1
- {"version":3,"file":"recent-access.service.js","sourceRoot":"","sources":["../../src/lib/recent-access.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAyB,MAAM,sBAAsB,CAAC;AACxG,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAyB,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAc,MAAM,MAAM,CAAC;;AAiBnD;;;GAGG;AAIH,MAAM,OAAO,mBAAmB;IACtB,MAAM,CAAU,eAAe,GAAG,mCAAmC,CAAC;IACtE,aAAa,GAAG,IAAI,eAAe,CAAqB,EAAE,CAAC,CAAC;IAC5D,WAAW,GAAG,IAAI,eAAe,CAAU,KAAK,CAAC,CAAC;IAClD,SAAS,GAAG,KAAK,CAAC;IAE1B;QACE,MAAM,CAAC,GAAG,oBAAoB,EAAG,CAAC;QAClC,IAAI,CAAC,CAAC,mBAAm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,UAAU;QACf,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;IACzB,CAAC;6GA5QU,mBAAmB;gEAAnB,mBAAmB,WAAnB,mBAAmB,mBAFlB,MAAM;;iFAEP,mBAAmB;cAH/B,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable } from '@angular/core';\nimport { Metadata, RunView, CompositeKey, LogError, EntityRecordNameInput } from '@memberjunction/core';\nimport { GetGlobalObjectStore } from '@memberjunction/global';\nimport { MJUserRecordLogEntity, UserInfoEngine } from '@memberjunction/core-entities';\nimport { UUIDsEqual } from '@memberjunction/global';\nimport { BehaviorSubject, Observable } from 'rxjs';\n\n/**\n * Represents a recently accessed resource\n */\nexport interface RecentAccessItem {\n id: string;\n entityId: string;\n entityName: string;\n recordId: string;\n recordName?: string;\n latestAt: Date;\n totalCount: number;\n /** Resource type for special handling (record, view, dashboard, artifact) */\n resourceType: 'record' | 'view' | 'dashboard' | 'artifact' | 'report';\n}\n\n/**\n * Service for tracking and retrieving recently accessed resources.\n * Uses the User Record Logs entity to persist access history.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class RecentAccessService {\n private static readonly _globalStoreKey = '___SINGLETON__RecentAccessService';\n private _recentItems$ = new BehaviorSubject<RecentAccessItem[]>([]);\n private _isLoading$ = new BehaviorSubject<boolean>(false);\n private _isLoaded = false;\n\n constructor() {\n const g = GetGlobalObjectStore()!;\n if (g[RecentAccessService._globalStoreKey]) {\n return g[RecentAccessService._globalStoreKey] as RecentAccessService;\n }\n g[RecentAccessService._globalStoreKey] = this;\n }\n\n public static get Instance(): RecentAccessService {\n return GetGlobalObjectStore()![RecentAccessService._globalStoreKey] as RecentAccessService;\n }\n\n /**\n * Observable of recent access items, sorted by most recent first\n */\n public get RecentItems(): Observable<RecentAccessItem[]> {\n return this._recentItems$.asObservable();\n }\n\n /**\n * Current value of recent items\n */\n public get RecentItemsValue(): RecentAccessItem[] {\n return this._recentItems$.value;\n }\n\n /**\n * Observable loading state\n */\n public get IsLoading(): Observable<boolean> {\n return this._isLoading$.asObservable();\n }\n\n /**\n * Logs access to a record. Creates or updates the User Record Log entry.\n * This is a fire-and-forget operation - errors are logged but don't interrupt the user.\n *\n * @param entityName - The name of the entity being accessed\n * @param recordId - The record ID (single value or CompositeKey string)\n * @param resourceType - The type of resource being accessed\n */\n public async logAccess(\n entityName: string,\n recordId: string | CompositeKey,\n resourceType: 'record' | 'view' | 'dashboard' | 'artifact' | 'report' = 'record'\n ): Promise<void> {\n try {\n const md = new Metadata();\n const entityInfo = md.Entities.find(e => e.Name === entityName);\n if (!entityInfo) {\n console.warn(`RecentAccessService: Entity \"${entityName}\" not found in metadata`);\n return;\n }\n\n // Convert CompositeKey to string if needed\n const recordIdString = recordId instanceof CompositeKey\n ? recordId.Values(',') // Values() returns joined string with specified delimiter\n : recordId;\n\n // Check if we already have a log entry for this user/entity/record combination\n const rv = new RunView();\n const existingResult = await rv.RunView<MJUserRecordLogEntity>({\n EntityName: 'MJ: User Record Logs',\n ExtraFilter: `UserID='${md.CurrentUser.ID}' AND EntityID='${entityInfo.ID}' AND RecordID='${recordIdString}'`,\n ResultType: 'entity_object',\n MaxRows: 1\n });\n\n if (!existingResult.Success) {\n console.error('RecentAccessService: Failed to check existing log', existingResult.ErrorMessage);\n return;\n }\n\n if (existingResult.Results && existingResult.Results.length > 0) {\n // Update existing entry\n const existing = existingResult.Results[0];\n existing.LatestAt = new Date();\n existing.TotalCount = (existing.TotalCount || 0) + 1;\n\n const saveResult = await existing.Save();\n if (!saveResult) {\n console.error('RecentAccessService: Failed to update log entry');\n }\n } else {\n // Create new entry\n const newLog = await md.GetEntityObject<MJUserRecordLogEntity>('MJ: User Record Logs');\n newLog.UserID = md.CurrentUser.ID;\n newLog.EntityID = entityInfo.ID;\n newLog.RecordID = recordIdString;\n // EarliestAt and LatestAt have default values of getdate() in the DB\n // TotalCount defaults to 0, so we set it to 1\n newLog.TotalCount = 1;\n\n const saveResult = await newLog.Save();\n if (!saveResult) {\n console.error('RecentAccessService: Failed to create log entry');\n }\n }\n\n // Refresh the recent items list in background\n this.refreshRecentItems();\n } catch (error) {\n // Don't throw - this is non-critical functionality\n console.error('RecentAccessService: Error logging access', error);\n }\n }\n\n /**\n * Loads recent access items for the current user using UserInfoEngine (cached).\n * @param maxItems - Maximum number of items to return (default 15)\n * @param forceRefresh - Force refresh even if already loaded\n */\n public async loadRecentItems(maxItems: number = 15, forceRefresh: boolean = false): Promise<RecentAccessItem[]> {\n if (this._isLoaded && !forceRefresh) {\n return this._recentItems$.value;\n }\n\n try {\n this._isLoading$.next(true);\n\n const md = new Metadata();\n\n // Get recent records, limited to maxItems (already ordered by LatestAt DESC in engine)\n const userRecordLogs = UserInfoEngine.Instance.UserRecordLogs.slice(0, maxItems);\n\n const items: RecentAccessItem[] = [];\n\n for (const log of userRecordLogs) {\n const entityInfo = md.Entities.find(e => UUIDsEqual(e.ID, log.EntityID));\n if (!entityInfo) continue;\n\n // Determine resource type based on entity name\n const resourceType = this.determineResourceType(entityInfo.Name);\n\n items.push({\n id: log.ID,\n entityId: log.EntityID,\n entityName: entityInfo.Name,\n recordId: log.RecordID,\n latestAt: log.LatestAt,\n totalCount: log.TotalCount,\n resourceType\n });\n }\n\n // Batch-resolve record names for all items\n await this.resolveRecordNames(items, md);\n\n this._recentItems$.next(items);\n this._isLoaded = true;\n\n return items;\n } catch (error) {\n LogError('RecentAccessService: Error loading recent items', undefined, error);\n return [];\n } finally {\n this._isLoading$.next(false);\n }\n }\n\n /**\n * Refresh recent items in background\n */\n public async refreshRecentItems(): Promise<void> {\n await this.loadRecentItems(15, true);\n }\n\n /**\n * Batch-resolve record names for a list of recent access items using GetEntityRecordNames().\n * Mutates the items in-place to set recordName where resolved.\n */\n private async resolveRecordNames(items: RecentAccessItem[], md: Metadata): Promise<void> {\n const nameInputs: EntityRecordNameInput[] = [];\n const indexMap = new Map<string, number>();\n\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const compositeKey = this.buildCompositeKeyForRecord(item.entityName, item.recordId, md);\n if (!compositeKey) continue;\n\n nameInputs.push({ EntityName: item.entityName, CompositeKey: compositeKey });\n indexMap.set(`${item.entityName}||${compositeKey.ToConcatenatedString()}`, i);\n }\n\n if (nameInputs.length === 0) return;\n\n try {\n const nameResults = await md.GetEntityRecordNames(nameInputs);\n for (const result of nameResults) {\n if (result.Success && result.RecordName) {\n const key = `${result.EntityName}||${result.CompositeKey.ToConcatenatedString()}`;\n const index = indexMap.get(key);\n if (index !== undefined) {\n items[index].recordName = result.RecordName;\n }\n }\n }\n } catch (error) {\n console.warn('RecentAccessService: Failed to resolve record names', error);\n }\n }\n\n /**\n * Build a CompositeKey for a record. RecordID may be stored as either:\n * - Concatenated format: \"FieldName|Value\" or \"Field1|Val1||Field2|Val2\"\n * - Plain value: just the raw value (e.g. a GUID)\n * Detects the format and constructs the key accordingly.\n */\n private buildCompositeKeyForRecord(entityName: string, recordId: string, md: Metadata): CompositeKey | null {\n if (!recordId) return null;\n\n // If recordId contains '|', it's in concatenated format\n if (recordId.includes('|')) {\n try {\n const compositeKey = new CompositeKey();\n compositeKey.LoadFromConcatenatedString(recordId);\n if (compositeKey.KeyValuePairs.length > 0) return compositeKey;\n } catch {\n // Fall through to entity-based lookup\n }\n }\n\n // Plain value — look up entity primary key field(s) to construct the key\n const entityInfo = md.Entities.find(e => e.Name === entityName);\n if (!entityInfo) return null;\n\n const pkField = entityInfo.FirstPrimaryKey;\n if (!pkField) return null;\n\n const compositeKey = new CompositeKey();\n compositeKey.KeyValuePairs = [{ FieldName: pkField.Name, Value: recordId }];\n return compositeKey;\n }\n\n /**\n * Determines the resource type based on entity name\n */\n private determineResourceType(entityName: string): 'record' | 'view' | 'dashboard' | 'artifact' | 'report' {\n const normalizedName = entityName.toLowerCase();\n\n if (normalizedName === 'user views') {\n return 'view';\n }\n if (normalizedName === 'dashboards') {\n return 'dashboard';\n }\n if (normalizedName === 'mj: conversation artifacts' || normalizedName === 'conversation artifacts') {\n return 'artifact';\n }\n if (normalizedName === 'reports') {\n return 'report';\n }\n\n return 'record';\n }\n\n /**\n * Clears the cached recent items (useful for logout)\n */\n public clearCache(): void {\n this._recentItems$.next([]);\n this._isLoaded = false;\n }\n}\n"]}
1
+ {"version":3,"file":"recent-access.service.js","sourceRoot":"","sources":["../../src/lib/recent-access.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAqB,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAyB,MAAM,sBAAsB,CAAC;AAC3H,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAyB,cAAc,EAAE,MAAM,+BAA+B,CAAC;AACtF,OAAO,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAc,MAAM,MAAM,CAAC;;AAiBnD;;;GAGG;AACH;;;GAGG;AAIH,MAAM,OAAO,mBAAmB;IACtB,MAAM,CAAU,eAAe,GAAG,mCAAmC,CAAC;IACtE,aAAa,GAAG,IAAI,eAAe,CAAqB,EAAE,CAAC,CAAC;IAC5D,WAAW,GAAG,IAAI,eAAe,CAAU,KAAK,CAAC,CAAC;IAClD,SAAS,GAAG,KAAK,CAAC;IAElB,SAAS,GAA6B,IAAI,CAAC;IACnD,IAAW,QAAQ;QACjB,OAAO,IAAI,CAAC,SAAS,IAAI,QAAQ,CAAC,QAAQ,CAAC;IAC7C,CAAC;IACD,IAAW,QAAQ,CAAC,KAA+B;QACjD,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;IACzB,CAAC;IAED;QACE,MAAM,CAAC,GAAG,oBAAoB,EAAG,CAAC;QAClC,IAAI,CAAC,CAAC,mBAAmB,CAAC,eAAe,CAAC,EAAE,CAAC;YAC3C,OAAO,CAAC,CAAC,mBA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,UAAU;QACf,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC5B,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;IACzB,CAAC;6GApRU,mBAAmB;gEAAnB,mBAAmB,WAAnB,mBAAmB,mBAFlB,MAAM;;iFAEP,mBAAmB;cAH/B,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable } from '@angular/core';\nimport { IMetadataProvider, Metadata, RunView, CompositeKey, LogError, EntityRecordNameInput } from '@memberjunction/core';\nimport { GetGlobalObjectStore } from '@memberjunction/global';\nimport { MJUserRecordLogEntity, UserInfoEngine } from '@memberjunction/core-entities';\nimport { UUIDsEqual } from '@memberjunction/global';\nimport { BehaviorSubject, Observable } from 'rxjs';\n\n/**\n * Represents a recently accessed resource\n */\nexport interface RecentAccessItem {\n id: string;\n entityId: string;\n entityName: string;\n recordId: string;\n recordName?: string;\n latestAt: Date;\n totalCount: number;\n /** Resource type for special handling (record, view, dashboard, artifact) */\n resourceType: 'record' | 'view' | 'dashboard' | 'artifact' | 'report';\n}\n\n/**\n * Service for tracking and retrieving recently accessed resources.\n * Uses the User Record Logs entity to persist access history.\n */\n/**\n * Multi-provider note: callers under a non-default provider should set\n * `service.Provider = component.ProviderToUse` before invoking any methods.\n */\n@Injectable({\n providedIn: 'root'\n})\nexport class RecentAccessService {\n private static readonly _globalStoreKey = '___SINGLETON__RecentAccessService';\n private _recentItems$ = new BehaviorSubject<RecentAccessItem[]>([]);\n private _isLoading$ = new BehaviorSubject<boolean>(false);\n private _isLoaded = false;\n\n private _provider: IMetadataProvider | null = null;\n public get Provider(): IMetadataProvider {\n return this._provider ?? Metadata.Provider;\n }\n public set Provider(value: IMetadataProvider | null) {\n this._provider = value;\n }\n\n constructor() {\n const g = GetGlobalObjectStore()!;\n if (g[RecentAccessService._globalStoreKey]) {\n return g[RecentAccessService._globalStoreKey] as RecentAccessService;\n }\n g[RecentAccessService._globalStoreKey] = this;\n }\n\n public static get Instance(): RecentAccessService {\n return GetGlobalObjectStore()![RecentAccessService._globalStoreKey] as RecentAccessService;\n }\n\n /**\n * Observable of recent access items, sorted by most recent first\n */\n public get RecentItems(): Observable<RecentAccessItem[]> {\n return this._recentItems$.asObservable();\n }\n\n /**\n * Current value of recent items\n */\n public get RecentItemsValue(): RecentAccessItem[] {\n return this._recentItems$.value;\n }\n\n /**\n * Observable loading state\n */\n public get IsLoading(): Observable<boolean> {\n return this._isLoading$.asObservable();\n }\n\n /**\n * Logs access to a record. Creates or updates the User Record Log entry.\n * This is a fire-and-forget operation - errors are logged but don't interrupt the user.\n *\n * @param entityName - The name of the entity being accessed\n * @param recordId - The record ID (single value or CompositeKey string)\n * @param resourceType - The type of resource being accessed\n */\n public async logAccess(\n entityName: string,\n recordId: string | CompositeKey,\n resourceType: 'record' | 'view' | 'dashboard' | 'artifact' | 'report' = 'record'\n ): Promise<void> {\n try {\n const md = this.Provider;\n const entityInfo = md.Entities.find(e => e.Name === entityName);\n if (!entityInfo) {\n console.warn(`RecentAccessService: Entity \"${entityName}\" not found in metadata`);\n return;\n }\n\n // Convert CompositeKey to string if needed\n const recordIdString = recordId instanceof CompositeKey\n ? recordId.Values(',') // Values() returns joined string with specified delimiter\n : recordId;\n\n // Check if we already have a log entry for this user/entity/record combination\n const rv = RunView.FromMetadataProvider(this.Provider);\n const existingResult = await rv.RunView<MJUserRecordLogEntity>({\n EntityName: 'MJ: User Record Logs',\n ExtraFilter: `UserID='${md.CurrentUser.ID}' AND EntityID='${entityInfo.ID}' AND RecordID='${recordIdString}'`,\n ResultType: 'entity_object',\n MaxRows: 1\n });\n\n if (!existingResult.Success) {\n console.error('RecentAccessService: Failed to check existing log', existingResult.ErrorMessage);\n return;\n }\n\n if (existingResult.Results && existingResult.Results.length > 0) {\n // Update existing entry\n const existing = existingResult.Results[0];\n existing.LatestAt = new Date();\n existing.TotalCount = (existing.TotalCount || 0) + 1;\n\n const saveResult = await existing.Save();\n if (!saveResult) {\n console.error('RecentAccessService: Failed to update log entry');\n }\n } else {\n // Create new entry\n const newLog = await md.GetEntityObject<MJUserRecordLogEntity>('MJ: User Record Logs', md.CurrentUser);\n newLog.UserID = md.CurrentUser.ID;\n newLog.EntityID = entityInfo.ID;\n newLog.RecordID = recordIdString;\n // EarliestAt and LatestAt have default values of getdate() in the DB\n // TotalCount defaults to 0, so we set it to 1\n newLog.TotalCount = 1;\n\n const saveResult = await newLog.Save();\n if (!saveResult) {\n console.error('RecentAccessService: Failed to create log entry');\n }\n }\n\n // Refresh the recent items list in background\n this.refreshRecentItems();\n } catch (error) {\n // Don't throw - this is non-critical functionality\n console.error('RecentAccessService: Error logging access', error);\n }\n }\n\n /**\n * Loads recent access items for the current user using UserInfoEngine (cached).\n * @param maxItems - Maximum number of items to return (default 15)\n * @param forceRefresh - Force refresh even if already loaded\n */\n public async loadRecentItems(maxItems: number = 15, forceRefresh: boolean = false): Promise<RecentAccessItem[]> {\n if (this._isLoaded && !forceRefresh) {\n return this._recentItems$.value;\n }\n\n try {\n this._isLoading$.next(true);\n\n const md = this.Provider;\n\n // Get recent records, limited to maxItems (already ordered by LatestAt DESC in engine)\n const userRecordLogs = UserInfoEngine.Instance.UserRecordLogs.slice(0, maxItems);\n\n const items: RecentAccessItem[] = [];\n\n for (const log of userRecordLogs) {\n const entityInfo = md.Entities.find(e => UUIDsEqual(e.ID, log.EntityID));\n if (!entityInfo) continue;\n\n // Determine resource type based on entity name\n const resourceType = this.determineResourceType(entityInfo.Name);\n\n items.push({\n id: log.ID,\n entityId: log.EntityID,\n entityName: entityInfo.Name,\n recordId: log.RecordID,\n latestAt: log.LatestAt,\n totalCount: log.TotalCount,\n resourceType\n });\n }\n\n // Batch-resolve record names for all items\n await this.resolveRecordNames(items, md);\n\n this._recentItems$.next(items);\n this._isLoaded = true;\n\n return items;\n } catch (error) {\n LogError('RecentAccessService: Error loading recent items', undefined, error);\n return [];\n } finally {\n this._isLoading$.next(false);\n }\n }\n\n /**\n * Refresh recent items in background\n */\n public async refreshRecentItems(): Promise<void> {\n await this.loadRecentItems(15, true);\n }\n\n /**\n * Batch-resolve record names for a list of recent access items using GetEntityRecordNames().\n * Mutates the items in-place to set recordName where resolved.\n */\n private async resolveRecordNames(items: RecentAccessItem[], md: IMetadataProvider): Promise<void> {\n const nameInputs: EntityRecordNameInput[] = [];\n const indexMap = new Map<string, number>();\n\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n const compositeKey = this.buildCompositeKeyForRecord(item.entityName, item.recordId, md);\n if (!compositeKey) continue;\n\n nameInputs.push({ EntityName: item.entityName, CompositeKey: compositeKey });\n indexMap.set(`${item.entityName}||${compositeKey.ToConcatenatedString()}`, i);\n }\n\n if (nameInputs.length === 0) return;\n\n try {\n const nameResults = await md.GetEntityRecordNames(nameInputs);\n for (const result of nameResults) {\n if (result.Success && result.RecordName) {\n const key = `${result.EntityName}||${result.CompositeKey.ToConcatenatedString()}`;\n const index = indexMap.get(key);\n if (index !== undefined) {\n items[index].recordName = result.RecordName;\n }\n }\n }\n } catch (error) {\n console.warn('RecentAccessService: Failed to resolve record names', error);\n }\n }\n\n /**\n * Build a CompositeKey for a record. RecordID may be stored as either:\n * - Concatenated format: \"FieldName|Value\" or \"Field1|Val1||Field2|Val2\"\n * - Plain value: just the raw value (e.g. a GUID)\n * Detects the format and constructs the key accordingly.\n */\n private buildCompositeKeyForRecord(entityName: string, recordId: string, md: IMetadataProvider): CompositeKey | null {\n if (!recordId) return null;\n\n // If recordId contains '|', it's in concatenated format\n if (recordId.includes('|')) {\n try {\n const compositeKey = new CompositeKey();\n compositeKey.LoadFromConcatenatedString(recordId);\n if (compositeKey.KeyValuePairs.length > 0) return compositeKey;\n } catch {\n // Fall through to entity-based lookup\n }\n }\n\n // Plain value — look up entity primary key field(s) to construct the key\n const entityInfo = md.Entities.find(e => e.Name === entityName);\n if (!entityInfo) return null;\n\n const pkField = entityInfo.FirstPrimaryKey;\n if (!pkField) return null;\n\n const compositeKey = new CompositeKey();\n compositeKey.KeyValuePairs = [{ FieldName: pkField.Name, Value: recordId }];\n return compositeKey;\n }\n\n /**\n * Determines the resource type based on entity name\n */\n private determineResourceType(entityName: string): 'record' | 'view' | 'dashboard' | 'artifact' | 'report' {\n const normalizedName = entityName.toLowerCase();\n\n if (normalizedName === 'user views') {\n return 'view';\n }\n if (normalizedName === 'dashboards') {\n return 'dashboard';\n }\n if (normalizedName === 'mj: conversation artifacts' || normalizedName === 'conversation artifacts') {\n return 'artifact';\n }\n if (normalizedName === 'reports') {\n return 'report';\n }\n\n return 'record';\n }\n\n /**\n * Clears the cached recent items (useful for logout)\n */\n public clearCache(): void {\n this._recentItems$.next([]);\n this._isLoaded = false;\n }\n}\n"]}
@@ -109,6 +109,11 @@ export declare class ThemeService {
109
109
  /**
110
110
  * Apply the base theme attribute to <html>.
111
111
  * 'dark' sets data-theme="dark"; 'light' removes it (matching existing convention).
112
+ *
113
+ * Also mirrors the base theme to localStorage under PRELOAD_BASE_THEME_KEY
114
+ * so the inline pre-bootstrap theme-preload script in index.html can apply
115
+ * the correct theme on first paint of the next page load — eliminating
116
+ * the brief light-mode flash dark-mode users would otherwise see.
112
117
  */
113
118
  private applyBaseThemeAttribute;
114
119
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"theme.service.d.ts","sourceRoot":"","sources":["../../src/lib/theme.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAmB,UAAU,EAAE,MAAM,MAAM,CAAC;;AAGnD;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC5B,4DAA4D;IAC5D,EAAE,EAAE,MAAM,CAAC;IACX,sEAAsE;IACtE,IAAI,EAAE,MAAM,CAAC;IACb,8CAA8C;IAC9C,SAAS,EAAE,OAAO,GAAG,MAAM,CAAC;IAC5B,0EAA0E;IAC1E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oDAAoD;IACpD,SAAS,EAAE,OAAO,CAAC;IACnB,iDAAiD;IACjD,WAAW,CAAC,EAAE,MAAM,CAAC;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,MAAM,CAAC,CAE7C;IAED;;OAEG;IACH,IAAW,UAAU,IAAI,MAAM,CAE9B;IAED;;OAEG;IACH,IAAW,YAAY,IAAI,MAAM,CAEhC;IAED;;OAEG;IACH,IAAW,aAAa,IAAI,OAAO,CAElC;IAED;;OAEG;IACH,IAAW,eAAe,IAAI,eAAe,EAAE,CAE9C;IAED;;;OAGG;IACI,kBAAkB,CAAC,EAAE,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS;IAQlE;;;OAGG;IACI,aAAa,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI;IAIlD;;OAEG;IACI,cAAc,CAAC,MAAM,EAAE,eAAe,EAAE,GAAG,IAAI;IAUtD;;;OAGG;IACU,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBxC;;;OAGG;IACU,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAaxD;;OAEG;IACI,KAAK,IAAI,IAAI;IA+BpB;;;;OAIG;YACW,UAAU;IA0BxB;;;;;;;;OAQG;IACH,OAAO,CAAC,uBAAuB;IAe/B;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAUzB;;;;;OAKG;IACH,OAAO,CAAC,YAAY;IAkCpB;;;OAGG;IACH,OAAO,CAAC,mBAAmB;IAU3B;;;;OAIG;IACH,OAAO,CAAC,YAAY;IAcpB;;OAEG;IACH,OAAO,CAAC,cAAc;IAOtB;;OAEG;IACH,OAAO,CAAC,wBAAwB;IAUhC;;OAEG;YACW,mBAAmB;IAWjC;;;;OAIG;YACW,WAAW;IAsBzB;;OAEG;YACW,WAAW;yCAlXhB,YAAY;6CAAZ,YAAY;CA0XxB"}
@@ -6,6 +6,20 @@ import * as i0 from "@angular/core";
6
6
  * Setting key for theme preference in MJ: User Settings entity
7
7
  */
8
8
  const THEME_SETTING_KEY = 'Explorer.Theme';
9
+ /**
10
+ * localStorage key the inline theme-preload script reads on first paint
11
+ * (before Angular boots) to apply the correct theme without flashing.
12
+ *
13
+ * The value is the **base theme** ('dark' or 'light'), NOT the full theme
14
+ * preference (which can be 'system' or a custom theme ID like 'izzy-dark').
15
+ * The preload script needs an unambiguous answer: should I set
16
+ * data-theme="dark" or not? Storing the base theme is the simplest
17
+ * contract: the script does `if (value === 'dark') setAttribute(...)`.
18
+ *
19
+ * Mirrored by ThemeService whenever the applied base theme changes,
20
+ * cleared on logout via Reset().
21
+ */
22
+ const PRELOAD_BASE_THEME_KEY = 'mj-theme';
9
23
  /**
10
24
  * Built-in light theme definition
11
25
  */
@@ -163,6 +177,13 @@ export class ThemeService {
163
177
  // Remove theme attributes
164
178
  document.documentElement.removeAttribute('data-theme');
165
179
  document.documentElement.removeAttribute('data-theme-overlay');
180
+ // NOTE: we deliberately do NOT clear PRELOAD_BASE_THEME_KEY here.
181
+ // The unified theme key ('mj-theme') is the single source of truth
182
+ // shared with the login-screen toggle and the inline pre-paint script.
183
+ // Clearing it on logout would force the login screen back to OS
184
+ // default and cause a theme flash for the post-logout/pre-login
185
+ // window. The auth provider's clearClientCaches() preserves it for
186
+ // exactly this reason (see preservedLocalStorageKeys).
166
187
  // Disable all custom CSS links
167
188
  this.disableAllCustomCss();
168
189
  }
@@ -199,6 +220,11 @@ export class ThemeService {
199
220
  /**
200
221
  * Apply the base theme attribute to <html>.
201
222
  * 'dark' sets data-theme="dark"; 'light' removes it (matching existing convention).
223
+ *
224
+ * Also mirrors the base theme to localStorage under PRELOAD_BASE_THEME_KEY
225
+ * so the inline pre-bootstrap theme-preload script in index.html can apply
226
+ * the correct theme on first paint of the next page load — eliminating
227
+ * the brief light-mode flash dark-mode users would otherwise see.
202
228
  */
203
229
  applyBaseThemeAttribute(baseTheme) {
204
230
  if (baseTheme === 'dark') {
@@ -207,6 +233,14 @@ export class ThemeService {
207
233
  else {
208
234
  document.documentElement.removeAttribute('data-theme');
209
235
  }
236
+ try {
237
+ window.localStorage.setItem(PRELOAD_BASE_THEME_KEY, baseTheme);
238
+ }
239
+ catch (e) {
240
+ // localStorage exceptions (private mode, quota) are non-fatal here —
241
+ // the app still works, the user just may see a brief theme flash on
242
+ // their next reload.
243
+ }
210
244
  }
211
245
  /**
212
246
  * Shorthand for built-in theme application (no custom CSS)
@@ -1 +1 @@
1
- {"version":3,"file":"theme.service.js","sourceRoot":"","sources":["../../src/lib/theme.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAc,MAAM,MAAM,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;;AAwB/D;;GAEG;AACH,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAE3C;;GAEG;AACH,MAAM,WAAW,GAAoB;IACjC,EAAE,EAAE,OAAO;IACX,IAAI,EAAE,OAAO;IACb,SAAS,EAAE,OAAO;IAClB,SAAS,EAAE,IAAI;IACf,WAAW,EAAE,qBAAqB;CACrC,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,GAAoB;IAChC,EAAE,EAAE,MAAM;IACV,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,MAAM;IACjB,SAAS,EAAE,IAAI;IACf,WAAW,EAAE,oBAAoB;CACpC,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AAEH,MAAM,OAAO,YAAY;IACb,YAAY,GAAG,IAAI,eAAe,CAAS,QAAQ,CAAC,CAAC;IACrD,cAAc,GAAG,IAAI,eAAe,CAAS,OAAO,CAAC,CAAC;IACtD,YAAY,GAAG,KAAK,CAAC;IACrB,gBAAgB,GAA0B,IAAI,CAAC;IAC/C,uBAAuB,GAAwB,IAAI,CAAC;IAE5D,wEAAwE;IAChE,aAAa,GAAG,IAAI,GAAG,CAA0B;QACrD,CAAC,OAAO,EAAE,WAAW,CAAC;QACtB,CAAC,MAAM,EAAE,UAAU,CAAC;KACvB,CAAC,CAAC;IAEH,0EAA0E;IAClE,cAAc,GAAG,IAAI,GAAG,EAA2B,CAAC;IAE5D;;O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+BAA+B,EAAE,KAAK,CAAC,CAAC;QACzD,CAAC;IACL,CAAC;sGArWQ,YAAY;gEAAZ,YAAY,WAAZ,YAAY,mBADC,MAAM;;iFACnB,YAAY;cADxB,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["import { Injectable } from '@angular/core';\nimport { BehaviorSubject, Observable } from 'rxjs';\nimport { UserInfoEngine } from '@memberjunction/core-entities';\n\n/**\n * Defines a theme available in the application.\n * Built-in themes (light/dark) have no CssUrl.\n * Custom themes specify a BaseTheme to inherit from and a CssUrl with overrides.\n */\nexport interface ThemeDefinition {\n /** Unique identifier (e.g. 'light', 'dark', 'izzy-dark') */\n Id: string;\n /** Human-readable display name (e.g. 'Light', 'Dark', 'Izzy Dark') */\n Name: string;\n /** Which built-in theme this inherits from */\n BaseTheme: 'light' | 'dark';\n /** URL to the CSS file with token overrides (omit for built-in themes) */\n CssUrl?: string;\n /** Whether this is a built-in theme (light/dark) */\n IsBuiltIn: boolean;\n /** Optional description shown in theme picker */\n Description?: string;\n /** Optional preview swatch colors for a future theme picker UI */\n PreviewColors?: string[];\n}\n\n/**\n * Setting key for theme preference in MJ: User Settings entity\n */\nconst THEME_SETTING_KEY = 'Explorer.Theme';\n\n/**\n * Built-in light theme definition\n */\nconst LIGHT_THEME: ThemeDefinition = {\n Id: 'light',\n Name: 'Light',\n BaseTheme: 'light',\n IsBuiltIn: true,\n Description: 'Default light theme'\n};\n\n/**\n * Built-in dark theme definition\n */\nconst DARK_THEME: ThemeDefinition = {\n Id: 'dark',\n Name: 'Dark',\n BaseTheme: 'dark',\n IsBuiltIn: true,\n Description: 'Default dark theme'\n};\n\n/**\n * Service to manage application themes with pluggable custom theme support.\n *\n * Built-in themes (light/dark) work identically to before. Custom themes\n * inherit from a base theme and overlay additional CSS token overrides via\n * a dynamically loaded stylesheet.\n *\n * CSS resolution for custom themes (e.g. \"Izzy Dark\" extending dark):\n * 1. `:root` light defaults (from _tokens.scss in this package)\n * 2. `[data-theme=\"dark\"]` dark overrides (from _tokens.scss in this package)\n * 3. `[data-theme-overlay=\"izzy-dark\"]` custom overrides (loaded dynamically)\n *\n * Follows the DeveloperModeService pattern:\n * - Settings persisted via UserInfoEngine\n * - BehaviorSubject for reactive state\n * - Initialize after login, Reset on logout\n */\n@Injectable({ providedIn: 'root' })\nexport class ThemeService {\n private _preference$ = new BehaviorSubject<string>('system');\n private _appliedTheme$ = new BehaviorSubject<string>('light');\n private _initialized = false;\n private systemMediaQuery: MediaQueryList | null = null;\n private boundSystemThemeHandler: (() => void) | null = null;\n\n /** Registry of available themes, seeded with built-in light and dark */\n private themeRegistry = new Map<string, ThemeDefinition>([\n ['light', LIGHT_THEME],\n ['dark', DARK_THEME]\n ]);\n\n /** Cache of loaded <link> elements by theme ID to avoid re-downloading */\n private loadedCssLinks = new Map<string, HTMLLinkElement>();\n\n /**\n * Observable for user's theme preference (theme ID or 'system')\n */\n public get Preference$(): Observable<string> {\n return this._preference$.asObservable();\n }\n\n /**\n * Observable for the actually applied theme (resolved theme ID)\n */\n public get AppliedTheme$(): Observable<string> {\n return this._appliedTheme$.asObservable();\n }\n\n /**\n * Current theme preference (synchronous access)\n */\n public get Preference(): string {\n return this._preference$.value;\n }\n\n /**\n * Currently applied theme ID (synchronous access)\n */\n public get AppliedTheme(): string {\n return this._appliedTheme$.value;\n }\n\n /**\n * Whether the service has been initialized\n */\n public get IsInitialized(): boolean {\n return this._initialized;\n }\n\n /**\n * All registered themes, for UI consumption (e.g. theme picker menus)\n */\n public get AvailableThemes(): ThemeDefinition[] {\n return Array.from(this.themeRegistry.values());\n }\n\n /**\n * Look up a theme definition by ID.\n * Returns undefined if the theme ID is not registered.\n */\n public GetThemeDefinition(id: string): ThemeDefinition | undefined {\n return this.themeRegistry.get(id);\n }\n\n // ========================================\n // THEME REGISTRATION\n // ========================================\n\n /**\n * Register a custom theme. If a theme with the same ID already exists,\n * it is replaced (allowing override of built-in themes if desired).\n */\n public RegisterTheme(theme: ThemeDefinition): void {\n this.themeRegistry.set(theme.Id, theme);\n }\n\n /**\n * Register multiple custom themes at once.\n */\n public RegisterThemes(themes: ThemeDefinition[]): void {\n for (const theme of themes) {\n this.RegisterTheme(theme);\n }\n }\n\n // ========================================\n // LIFECYCLE\n // ========================================\n\n /**\n * Initialize the theme service.\n * Call after login when UserInfoEngine is available.\n */\n public async Initialize(): Promise<void> {\n if (this._initialized) {\n return;\n }\n\n this.setupSystemThemeListener();\n\n const savedPreference = await this.loadSetting();\n this._preference$.next(savedPreference);\n\n const resolvedThemeId = this.resolveTheme(savedPreference);\n await this.applyTheme(resolvedThemeId);\n\n this._initialized = true;\n }\n\n /**\n * Set the theme preference and apply it.\n * @param preference - A registered theme ID or 'system'\n */\n public async SetTheme(preference: string): Promise<void> {\n if (preference === this._preference$.value) {\n return;\n }\n\n this._preference$.next(preference);\n\n const resolvedThemeId = this.resolveTheme(preference);\n await this.applyTheme(resolvedThemeId);\n\n await this.saveSetting(preference);\n }\n\n /**\n * Reset the service (call on logout)\n */\n public Reset(): void {\n if (this.systemMediaQuery && this.boundSystemThemeHandler) {\n this.systemMediaQuery.removeEventListener('change', this.boundSystemThemeHandler);\n }\n this.systemMediaQuery = null;\n this.boundSystemThemeHandler = null;\n\n this._preference$.next('system');\n this._appliedTheme$.next('light');\n this._initialized = false;\n\n // Remove theme attributes\n document.documentElement.removeAttribute('data-theme');\n document.documentElement.removeAttribute('data-theme-overlay');\n\n // Disable all custom CSS links\n this.disableAllCustomCss();\n }\n\n // ========================================\n // THEME APPLICATION\n // ========================================\n\n /**\n * Apply a resolved theme ID to the DOM.\n * Sets `data-theme` based on BaseTheme and `data-theme-overlay` for custom themes.\n * Loads custom CSS if needed, disables previous custom CSS.\n */\n private async applyTheme(themeId: string): Promise<void> {\n const themeDef = this.themeRegistry.get(themeId);\n\n // Fall back to 'light' if the theme ID isn't recognized\n if (!themeDef) {\n this.applyBuiltInTheme('light');\n this._appliedTheme$.next('light');\n return;\n }\n\n // Set the base theme attribute (drives existing [data-theme=\"dark\"] selectors)\n this.applyBaseThemeAttribute(themeDef.BaseTheme);\n\n if (themeDef.IsBuiltIn) {\n // Built-in theme: remove overlay, disable custom CSS\n document.documentElement.removeAttribute('data-theme-overlay');\n this.disableAllCustomCss();\n } else if (themeDef.CssUrl) {\n // Custom theme: load/enable CSS and set overlay attribute\n await this.loadThemeCss(themeDef);\n document.documentElement.setAttribute('data-theme-overlay', themeDef.Id);\n }\n\n this._appliedTheme$.next(themeId);\n }\n\n /**\n * Apply the base theme attribute to <html>.\n * 'dark' sets data-theme=\"dark\"; 'light' removes it (matching existing convention).\n */\n private applyBaseThemeAttribute(baseTheme: 'light' | 'dark'): void {\n if (baseTheme === 'dark') {\n document.documentElement.setAttribute('data-theme', 'dark');\n } else {\n document.documentElement.removeAttribute('data-theme');\n }\n }\n\n /**\n * Shorthand for built-in theme application (no custom CSS)\n */\n private applyBuiltInTheme(baseTheme: 'light' | 'dark'): void {\n this.applyBaseThemeAttribute(baseTheme);\n document.documentElement.removeAttribute('data-theme-overlay');\n this.disableAllCustomCss();\n }\n\n // ========================================\n // DYNAMIC CSS LOADING\n // ========================================\n\n /**\n * Load (or re-enable) a custom theme's CSS file.\n * Injects a <link> element into <head> with a data-mj-theme attribute.\n * Caches the link element to avoid re-downloading on theme switches.\n * Returns a Promise that resolves once the stylesheet is loaded.\n */\n private loadThemeCss(theme: ThemeDefinition): Promise<void> {\n if (!theme.CssUrl) {\n return Promise.resolve();\n }\n\n // Disable all other custom CSS first\n this.disableAllCustomCss();\n\n // Check cache — if already loaded, just re-enable\n const existingLink = this.loadedCssLinks.get(theme.Id);\n if (existingLink) {\n existingLink.disabled = false;\n return Promise.resolve();\n }\n\n // Create and inject new <link> element\n return new Promise<void>((resolve, reject) => {\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = theme.CssUrl!;\n link.setAttribute('data-mj-theme', theme.Id);\n\n link.onload = () => resolve();\n link.onerror = () => {\n console.warn(`Failed to load theme CSS: ${theme.CssUrl}`);\n // Still resolve so the theme switch isn't blocked\n resolve();\n };\n\n document.head.appendChild(link);\n this.loadedCssLinks.set(theme.Id, link);\n });\n }\n\n /**\n * Disable (not remove) all custom theme CSS <link> elements.\n * Disabling rather than removing avoids re-downloading when switching back.\n */\n private disableAllCustomCss(): void {\n for (const link of this.loadedCssLinks.values()) {\n link.disabled = true;\n }\n }\n\n // ========================================\n // THEME RESOLUTION\n // ========================================\n\n /**\n * Resolve a preference string to an actual theme ID.\n * 'system' resolves to 'light' or 'dark' based on OS preference.\n * Unrecognized IDs fall back to 'light'.\n */\n private resolveTheme(preference: string): string {\n if (preference === 'system') {\n return this.getSystemTheme();\n }\n\n // If the preference is a registered theme, use it directly\n if (this.themeRegistry.has(preference)) {\n return preference;\n }\n\n // Unrecognized theme ID — fall back to light\n return 'light';\n }\n\n /**\n * Get system theme preference from OS\n */\n private getSystemTheme(): 'light' | 'dark' {\n if (typeof window === 'undefined') {\n return 'light';\n }\n return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n }\n\n /**\n * Setup listener for system theme changes\n */\n private setupSystemThemeListener(): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n this.systemMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n this.boundSystemThemeHandler = () => this.onSystemThemeChange();\n this.systemMediaQuery.addEventListener('change', this.boundSystemThemeHandler);\n }\n\n /**\n * Handle system theme change (only applies if in 'system' mode)\n */\n private async onSystemThemeChange(): Promise<void> {\n if (this._preference$.value === 'system') {\n const newThemeId = this.getSystemTheme();\n await this.applyTheme(newThemeId);\n }\n }\n\n // ========================================\n // PERSISTENCE\n // ========================================\n\n /**\n * Load theme preference from User Settings.\n * Accepts any registered theme ID or 'system'.\n * Falls back to 'system' if saved value is not recognized.\n */\n private async loadSetting(): Promise<string> {\n try {\n const engine = UserInfoEngine.Instance;\n const settingValue = engine.GetSetting(THEME_SETTING_KEY);\n\n if (!settingValue) {\n return 'system';\n }\n\n // Accept 'system' or any registered theme ID\n if (settingValue === 'system' || this.themeRegistry.has(settingValue)) {\n return settingValue;\n }\n\n // Saved theme no longer registered — fall back\n return 'system';\n } catch (error) {\n console.warn('Failed to load theme setting:', error);\n return 'system';\n }\n }\n\n /**\n * Save theme preference to User Settings\n */\n private async saveSetting(preference: string): Promise<void> {\n try {\n const engine = UserInfoEngine.Instance;\n await engine.SetSetting(THEME_SETTING_KEY, preference);\n } catch (error) {\n console.warn('Failed to save theme setting:', error);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"theme.service.js","sourceRoot":"","sources":["../../src/lib/theme.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAc,MAAM,MAAM,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;;AAwB/D;;GAEG;AACH,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAE3C;;;;;;;;;;;;GAYG;AACH,MAAM,sBAAsB,GAAG,UAAU,CAAC;AAE1C;;GAEG;AACH,MAAM,WAAW,GAAoB;IACjC,EAAE,EAAE,OAAO;IACX,IAAI,EAAE,OAAO;IACb,SAAS,EAAE,OAAO;IAClB,SAAS,EAAE,IAAI;IACf,WAAW,EAAE,qBAAqB;CACrC,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,GAAoB;IAChC,EAAE,EAAE,MAAM;IACV,IAAI,EAAE,MAAM;IACZ,SAAS,EAAE,MAAM;IACjB,SAAS,EAAE,IAAI;IACf,WAAW,EAAE,oBAAoB;CACpC,CAAC;AAEF;;;;;;;;;;;;;;;;GAgBG;AAEH,MAAM,OAAO,YAAY;IACb,YAAY,GAAG,IAAI,eAAe,CAAS,QAAQ,CAAC,CAAC;IACrD,cAAc,GAAG,IAAI,eAAe,CAAS,OAAO,CAAC,CAAC;IACtD,YAAY,GAAG,KAAK,CAAC;IACrB,gBAAgB,GAA0B,IAAI,CAAC;IAC/C,uBAAuB,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AAC,GAAG,CAAC,YAAY,CAAC,EAAE,CAAC;gBACpE,OAAO,YAAY,CAAC;YACxB,CAAC;YAED,+CAA+C;YAC/C,OAAO,QAAQ,CAAC;QACpB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,KAAK,CAAC,CAAC;YACrD,OAAO,QAAQ,CAAC;QACpB,CAAC;IACL,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,WAAW,CAAC,UAAkB;QACxC,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,cAAc,CAAC,QAAQ,CAAC;YACvC,MAAM,MAAM,CAAC,UAAU,CAAC,iBAAiB,EAAE,UAAU,CAAC,CAAC;QAC3D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,IAAI,CAAC,+BAA+B,EAAE,KAAK,CAAC,CAAC;QACzD,CAAC;IACL,CAAC;sGAzXQ,YAAY;gEAAZ,YAAY,WAAZ,YAAY,mBADC,MAAM;;iFACnB,YAAY;cADxB,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["import { Injectable } from '@angular/core';\nimport { BehaviorSubject, Observable } from 'rxjs';\nimport { UserInfoEngine } from '@memberjunction/core-entities';\n\n/**\n * Defines a theme available in the application.\n * Built-in themes (light/dark) have no CssUrl.\n * Custom themes specify a BaseTheme to inherit from and a CssUrl with overrides.\n */\nexport interface ThemeDefinition {\n /** Unique identifier (e.g. 'light', 'dark', 'izzy-dark') */\n Id: string;\n /** Human-readable display name (e.g. 'Light', 'Dark', 'Izzy Dark') */\n Name: string;\n /** Which built-in theme this inherits from */\n BaseTheme: 'light' | 'dark';\n /** URL to the CSS file with token overrides (omit for built-in themes) */\n CssUrl?: string;\n /** Whether this is a built-in theme (light/dark) */\n IsBuiltIn: boolean;\n /** Optional description shown in theme picker */\n Description?: string;\n /** Optional preview swatch colors for a future theme picker UI */\n PreviewColors?: string[];\n}\n\n/**\n * Setting key for theme preference in MJ: User Settings entity\n */\nconst THEME_SETTING_KEY = 'Explorer.Theme';\n\n/**\n * localStorage key the inline theme-preload script reads on first paint\n * (before Angular boots) to apply the correct theme without flashing.\n *\n * The value is the **base theme** ('dark' or 'light'), NOT the full theme\n * preference (which can be 'system' or a custom theme ID like 'izzy-dark').\n * The preload script needs an unambiguous answer: should I set\n * data-theme=\"dark\" or not? Storing the base theme is the simplest\n * contract: the script does `if (value === 'dark') setAttribute(...)`.\n *\n * Mirrored by ThemeService whenever the applied base theme changes,\n * cleared on logout via Reset().\n */\nconst PRELOAD_BASE_THEME_KEY = 'mj-theme';\n\n/**\n * Built-in light theme definition\n */\nconst LIGHT_THEME: ThemeDefinition = {\n Id: 'light',\n Name: 'Light',\n BaseTheme: 'light',\n IsBuiltIn: true,\n Description: 'Default light theme'\n};\n\n/**\n * Built-in dark theme definition\n */\nconst DARK_THEME: ThemeDefinition = {\n Id: 'dark',\n Name: 'Dark',\n BaseTheme: 'dark',\n IsBuiltIn: true,\n Description: 'Default dark theme'\n};\n\n/**\n * Service to manage application themes with pluggable custom theme support.\n *\n * Built-in themes (light/dark) work identically to before. Custom themes\n * inherit from a base theme and overlay additional CSS token overrides via\n * a dynamically loaded stylesheet.\n *\n * CSS resolution for custom themes (e.g. \"Izzy Dark\" extending dark):\n * 1. `:root` light defaults (from _tokens.scss in this package)\n * 2. `[data-theme=\"dark\"]` dark overrides (from _tokens.scss in this package)\n * 3. `[data-theme-overlay=\"izzy-dark\"]` custom overrides (loaded dynamically)\n *\n * Follows the DeveloperModeService pattern:\n * - Settings persisted via UserInfoEngine\n * - BehaviorSubject for reactive state\n * - Initialize after login, Reset on logout\n */\n@Injectable({ providedIn: 'root' })\nexport class ThemeService {\n private _preference$ = new BehaviorSubject<string>('system');\n private _appliedTheme$ = new BehaviorSubject<string>('light');\n private _initialized = false;\n private systemMediaQuery: MediaQueryList | null = null;\n private boundSystemThemeHandler: (() => void) | null = null;\n\n /** Registry of available themes, seeded with built-in light and dark */\n private themeRegistry = new Map<string, ThemeDefinition>([\n ['light', LIGHT_THEME],\n ['dark', DARK_THEME]\n ]);\n\n /** Cache of loaded <link> elements by theme ID to avoid re-downloading */\n private loadedCssLinks = new Map<string, HTMLLinkElement>();\n\n /**\n * Observable for user's theme preference (theme ID or 'system')\n */\n public get Preference$(): Observable<string> {\n return this._preference$.asObservable();\n }\n\n /**\n * Observable for the actually applied theme (resolved theme ID)\n */\n public get AppliedTheme$(): Observable<string> {\n return this._appliedTheme$.asObservable();\n }\n\n /**\n * Current theme preference (synchronous access)\n */\n public get Preference(): string {\n return this._preference$.value;\n }\n\n /**\n * Currently applied theme ID (synchronous access)\n */\n public get AppliedTheme(): string {\n return this._appliedTheme$.value;\n }\n\n /**\n * Whether the service has been initialized\n */\n public get IsInitialized(): boolean {\n return this._initialized;\n }\n\n /**\n * All registered themes, for UI consumption (e.g. theme picker menus)\n */\n public get AvailableThemes(): ThemeDefinition[] {\n return Array.from(this.themeRegistry.values());\n }\n\n /**\n * Look up a theme definition by ID.\n * Returns undefined if the theme ID is not registered.\n */\n public GetThemeDefinition(id: string): ThemeDefinition | undefined {\n return this.themeRegistry.get(id);\n }\n\n // ========================================\n // THEME REGISTRATION\n // ========================================\n\n /**\n * Register a custom theme. If a theme with the same ID already exists,\n * it is replaced (allowing override of built-in themes if desired).\n */\n public RegisterTheme(theme: ThemeDefinition): void {\n this.themeRegistry.set(theme.Id, theme);\n }\n\n /**\n * Register multiple custom themes at once.\n */\n public RegisterThemes(themes: ThemeDefinition[]): void {\n for (const theme of themes) {\n this.RegisterTheme(theme);\n }\n }\n\n // ========================================\n // LIFECYCLE\n // ========================================\n\n /**\n * Initialize the theme service.\n * Call after login when UserInfoEngine is available.\n */\n public async Initialize(): Promise<void> {\n if (this._initialized) {\n return;\n }\n\n this.setupSystemThemeListener();\n\n const savedPreference = await this.loadSetting();\n this._preference$.next(savedPreference);\n\n const resolvedThemeId = this.resolveTheme(savedPreference);\n await this.applyTheme(resolvedThemeId);\n\n this._initialized = true;\n }\n\n /**\n * Set the theme preference and apply it.\n * @param preference - A registered theme ID or 'system'\n */\n public async SetTheme(preference: string): Promise<void> {\n if (preference === this._preference$.value) {\n return;\n }\n\n this._preference$.next(preference);\n\n const resolvedThemeId = this.resolveTheme(preference);\n await this.applyTheme(resolvedThemeId);\n\n await this.saveSetting(preference);\n }\n\n /**\n * Reset the service (call on logout)\n */\n public Reset(): void {\n if (this.systemMediaQuery && this.boundSystemThemeHandler) {\n this.systemMediaQuery.removeEventListener('change', this.boundSystemThemeHandler);\n }\n this.systemMediaQuery = null;\n this.boundSystemThemeHandler = null;\n\n this._preference$.next('system');\n this._appliedTheme$.next('light');\n this._initialized = false;\n\n // Remove theme attributes\n document.documentElement.removeAttribute('data-theme');\n document.documentElement.removeAttribute('data-theme-overlay');\n\n // NOTE: we deliberately do NOT clear PRELOAD_BASE_THEME_KEY here.\n // The unified theme key ('mj-theme') is the single source of truth\n // shared with the login-screen toggle and the inline pre-paint script.\n // Clearing it on logout would force the login screen back to OS\n // default and cause a theme flash for the post-logout/pre-login\n // window. The auth provider's clearClientCaches() preserves it for\n // exactly this reason (see preservedLocalStorageKeys).\n\n // Disable all custom CSS links\n this.disableAllCustomCss();\n }\n\n // ========================================\n // THEME APPLICATION\n // ========================================\n\n /**\n * Apply a resolved theme ID to the DOM.\n * Sets `data-theme` based on BaseTheme and `data-theme-overlay` for custom themes.\n * Loads custom CSS if needed, disables previous custom CSS.\n */\n private async applyTheme(themeId: string): Promise<void> {\n const themeDef = this.themeRegistry.get(themeId);\n\n // Fall back to 'light' if the theme ID isn't recognized\n if (!themeDef) {\n this.applyBuiltInTheme('light');\n this._appliedTheme$.next('light');\n return;\n }\n\n // Set the base theme attribute (drives existing [data-theme=\"dark\"] selectors)\n this.applyBaseThemeAttribute(themeDef.BaseTheme);\n\n if (themeDef.IsBuiltIn) {\n // Built-in theme: remove overlay, disable custom CSS\n document.documentElement.removeAttribute('data-theme-overlay');\n this.disableAllCustomCss();\n } else if (themeDef.CssUrl) {\n // Custom theme: load/enable CSS and set overlay attribute\n await this.loadThemeCss(themeDef);\n document.documentElement.setAttribute('data-theme-overlay', themeDef.Id);\n }\n\n this._appliedTheme$.next(themeId);\n }\n\n /**\n * Apply the base theme attribute to <html>.\n * 'dark' sets data-theme=\"dark\"; 'light' removes it (matching existing convention).\n *\n * Also mirrors the base theme to localStorage under PRELOAD_BASE_THEME_KEY\n * so the inline pre-bootstrap theme-preload script in index.html can apply\n * the correct theme on first paint of the next page load — eliminating\n * the brief light-mode flash dark-mode users would otherwise see.\n */\n private applyBaseThemeAttribute(baseTheme: 'light' | 'dark'): void {\n if (baseTheme === 'dark') {\n document.documentElement.setAttribute('data-theme', 'dark');\n } else {\n document.documentElement.removeAttribute('data-theme');\n }\n try {\n window.localStorage.setItem(PRELOAD_BASE_THEME_KEY, baseTheme);\n } catch (e) {\n // localStorage exceptions (private mode, quota) are non-fatal here —\n // the app still works, the user just may see a brief theme flash on\n // their next reload.\n }\n }\n\n /**\n * Shorthand for built-in theme application (no custom CSS)\n */\n private applyBuiltInTheme(baseTheme: 'light' | 'dark'): void {\n this.applyBaseThemeAttribute(baseTheme);\n document.documentElement.removeAttribute('data-theme-overlay');\n this.disableAllCustomCss();\n }\n\n // ========================================\n // DYNAMIC CSS LOADING\n // ========================================\n\n /**\n * Load (or re-enable) a custom theme's CSS file.\n * Injects a <link> element into <head> with a data-mj-theme attribute.\n * Caches the link element to avoid re-downloading on theme switches.\n * Returns a Promise that resolves once the stylesheet is loaded.\n */\n private loadThemeCss(theme: ThemeDefinition): Promise<void> {\n if (!theme.CssUrl) {\n return Promise.resolve();\n }\n\n // Disable all other custom CSS first\n this.disableAllCustomCss();\n\n // Check cache — if already loaded, just re-enable\n const existingLink = this.loadedCssLinks.get(theme.Id);\n if (existingLink) {\n existingLink.disabled = false;\n return Promise.resolve();\n }\n\n // Create and inject new <link> element\n return new Promise<void>((resolve, reject) => {\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = theme.CssUrl!;\n link.setAttribute('data-mj-theme', theme.Id);\n\n link.onload = () => resolve();\n link.onerror = () => {\n console.warn(`Failed to load theme CSS: ${theme.CssUrl}`);\n // Still resolve so the theme switch isn't blocked\n resolve();\n };\n\n document.head.appendChild(link);\n this.loadedCssLinks.set(theme.Id, link);\n });\n }\n\n /**\n * Disable (not remove) all custom theme CSS <link> elements.\n * Disabling rather than removing avoids re-downloading when switching back.\n */\n private disableAllCustomCss(): void {\n for (const link of this.loadedCssLinks.values()) {\n link.disabled = true;\n }\n }\n\n // ========================================\n // THEME RESOLUTION\n // ========================================\n\n /**\n * Resolve a preference string to an actual theme ID.\n * 'system' resolves to 'light' or 'dark' based on OS preference.\n * Unrecognized IDs fall back to 'light'.\n */\n private resolveTheme(preference: string): string {\n if (preference === 'system') {\n return this.getSystemTheme();\n }\n\n // If the preference is a registered theme, use it directly\n if (this.themeRegistry.has(preference)) {\n return preference;\n }\n\n // Unrecognized theme ID — fall back to light\n return 'light';\n }\n\n /**\n * Get system theme preference from OS\n */\n private getSystemTheme(): 'light' | 'dark' {\n if (typeof window === 'undefined') {\n return 'light';\n }\n return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';\n }\n\n /**\n * Setup listener for system theme changes\n */\n private setupSystemThemeListener(): void {\n if (typeof window === 'undefined') {\n return;\n }\n\n this.systemMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');\n this.boundSystemThemeHandler = () => this.onSystemThemeChange();\n this.systemMediaQuery.addEventListener('change', this.boundSystemThemeHandler);\n }\n\n /**\n * Handle system theme change (only applies if in 'system' mode)\n */\n private async onSystemThemeChange(): Promise<void> {\n if (this._preference$.value === 'system') {\n const newThemeId = this.getSystemTheme();\n await this.applyTheme(newThemeId);\n }\n }\n\n // ========================================\n // PERSISTENCE\n // ========================================\n\n /**\n * Load theme preference from User Settings.\n * Accepts any registered theme ID or 'system'.\n * Falls back to 'system' if saved value is not recognized.\n */\n private async loadSetting(): Promise<string> {\n try {\n const engine = UserInfoEngine.Instance;\n const settingValue = engine.GetSetting(THEME_SETTING_KEY);\n\n if (!settingValue) {\n return 'system';\n }\n\n // Accept 'system' or any registered theme ID\n if (settingValue === 'system' || this.themeRegistry.has(settingValue)) {\n return settingValue;\n }\n\n // Saved theme no longer registered — fall back\n return 'system';\n } catch (error) {\n console.warn('Failed to load theme setting:', error);\n return 'system';\n }\n }\n\n /**\n * Save theme preference to User Settings\n */\n private async saveSetting(preference: string): Promise<void> {\n try {\n const engine = UserInfoEngine.Instance;\n await engine.SetSetting(THEME_SETTING_KEY, preference);\n } catch (error) {\n console.warn('Failed to save theme setting:', error);\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memberjunction/ng-shared-generic",
3
- "version": "5.30.1",
3
+ "version": "5.31.0",
4
4
  "description": "MemberJunction: Generic Angular Shared Package - utility services and reusable elements used in any Angular application.",
5
5
  "main": "./dist/public-api.js",
6
6
  "typings": "./dist/public-api.d.ts",
@@ -31,9 +31,10 @@
31
31
  "rxjs": "^7.8.2"
32
32
  },
33
33
  "dependencies": {
34
- "@memberjunction/core": "5.30.1",
35
- "@memberjunction/core-entities": "5.30.1",
36
- "@memberjunction/global": "5.30.1",
34
+ "@memberjunction/core": "5.31.0",
35
+ "@memberjunction/ng-base-types": "5.31.0",
36
+ "@memberjunction/core-entities": "5.31.0",
37
+ "@memberjunction/global": "5.31.0",
37
38
  "tslib": "^2.8.1"
38
39
  },
39
40
  "sideEffects": false,