@api-client/ui 0.5.30 → 0.5.32

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.
@@ -58,9 +58,9 @@ export enum IntentFlags {
58
58
  ByReference = 1 << 2,
59
59
  }
60
60
 
61
- export interface Intent {
61
+ export interface Intent<T = unknown> {
62
62
  action: string
63
- data?: unknown
63
+ data?: T
64
64
  category?: string[]
65
65
  flags?: number
66
66
  /**
@@ -98,6 +98,24 @@ interface ActivityStackEntry {
98
98
  action: string
99
99
  }
100
100
 
101
+ /**
102
+ * Type for activity constructor with static action property.
103
+ */
104
+ export interface ActivityConstructor {
105
+ new (parent: Application): Activity
106
+ action?: string
107
+ }
108
+
109
+ /**
110
+ * Enhanced activity registration options.
111
+ */
112
+ export interface ActivityRegistrationOptions {
113
+ /** Whether to override existing registrations */
114
+ override?: boolean
115
+ /** Optional validation function for intents */
116
+ validateIntent?: (intent: Intent) => boolean
117
+ }
118
+
101
119
  /**
102
120
  * Manages application activities.
103
121
  *
@@ -139,12 +157,31 @@ export class ActivityManager {
139
157
  // this.reflectEvent = this.reflectEvent.bind(this)
140
158
  }
141
159
 
142
- registerActivity(action: string, activityClass: typeof Activity): void {
143
- if (this.activityClasses.has(action)) {
160
+ /**
161
+ * Registers an activity class with enhanced options.
162
+ * @param action The action name to register the activity for.
163
+ * @param activityClass The activity class constructor.
164
+ * @param options Optional registration configuration.
165
+ */
166
+ registerActivity(
167
+ action: string,
168
+ activityClass: ActivityConstructor,
169
+ options: ActivityRegistrationOptions = {}
170
+ ): void {
171
+ const { override = false } = options
172
+
173
+ if (this.activityClasses.has(action) && !override) {
144
174
  // eslint-disable-next-line no-console
145
175
  console.warn(`Activity with action "${action}" already registered.`, new Error().stack)
176
+ return
146
177
  }
147
- this.activityClasses.set(action, activityClass)
178
+
179
+ // Validate that the class extends Activity
180
+ if (typeof activityClass !== 'function') {
181
+ throw new Error(`Invalid activity class for action "${action}": must be a constructor function`)
182
+ }
183
+
184
+ this.activityClasses.set(action, activityClass as typeof Activity)
148
185
  }
149
186
 
150
187
  // protected reflectEvent<T extends Event>(event: T): T {
@@ -302,6 +339,9 @@ export class ActivityManager {
302
339
  await stackEntry.activity.onDestroy()
303
340
  stackEntry.activity.lifecycle = ActivityLifecycle.Destroyed
304
341
 
342
+ // Clean up resources to prevent memory leaks
343
+ this.cleanupActivity(stackEntry.activity)
344
+
305
345
  await this.manageActivityResult(stackEntry.activity, stackEntry.intent)
306
346
 
307
347
  // Resume the previous activity
@@ -343,10 +383,10 @@ export class ActivityManager {
343
383
  private async bringLastActivityToFront(): Promise<void> {
344
384
  if (this.modalActivityStack.length > 0) {
345
385
  const previousEntry = this.modalActivityStack[this.activityStack.length - 1]
346
- await this.updateCurrentActivity(previousEntry.activity, false)
386
+ await this.updateCurrentActivity(previousEntry.activity, false, previousEntry.intent)
347
387
  } else if (this.activityStack.length > 0) {
348
388
  const previousEntry = this.activityStack[this.activityStack.length - 1]
349
- await this.updateCurrentActivity(previousEntry.activity, false)
389
+ await this.updateCurrentActivity(previousEntry.activity, false, previousEntry.intent)
350
390
  } else {
351
391
  this.currentActivity = undefined // No more activities
352
392
  }
@@ -404,7 +444,7 @@ export class ActivityManager {
404
444
  *
405
445
  * @param activity The activity to bring to the foreground.
406
446
  */
407
- private async updateCurrentActivity(activity: Activity, isModal: boolean): Promise<void> {
447
+ private async updateCurrentActivity(activity: Activity, isModal: boolean, intent?: Intent): Promise<void> {
408
448
  this.setupStyles(activity, this.currentActivity)
409
449
  if (
410
450
  this.currentActivity &&
@@ -416,56 +456,38 @@ export class ActivityManager {
416
456
  await this.currentActivity.onPause()
417
457
  this.currentActivity.lifecycle = ActivityLifecycle.Paused
418
458
  }
419
- if (activity.lifecycle === ActivityLifecycle.Paused) {
420
- await activity.onResume()
421
- if (this.isDestroyed(activity)) {
422
- return
423
- }
424
- activity.lifecycle = ActivityLifecycle.Resumed
425
- activity.requestUpdate()
426
- } else if (activity.lifecycle === ActivityLifecycle.Stopped) {
427
- await activity.onRestart()
428
- activity.lifecycle = ActivityLifecycle.Resumed
429
- } else if (activity.lifecycle === ActivityLifecycle.Destroyed) {
430
- throw new Error(`Invalid state. The activity is already destroyed.`)
431
- } else if (activity.lifecycle === ActivityLifecycle.Created) {
432
- await activity.onStart()
433
- if (this.isDestroyed(activity)) {
434
- return
435
- }
436
- activity.lifecycle = ActivityLifecycle.Started
437
- await activity.onResume()
438
- if (this.isDestroyed(activity)) {
439
- return
440
- }
441
- activity.lifecycle = ActivityLifecycle.Resumed
442
- activity.requestUpdate()
443
- } else if (activity.lifecycle === ActivityLifecycle.Started) {
444
- await activity.onResume()
445
- if (this.isDestroyed(activity)) {
446
- return
447
- }
448
- activity.lifecycle = ActivityLifecycle.Resumed
449
- activity.requestUpdate()
450
- } else if (activity.lifecycle === ActivityLifecycle.Initialized) {
451
- // TODO: Figure out intent passing here.
452
- await activity.onCreate()
453
- activity.lifecycle = ActivityLifecycle.Created
454
- if (this.isDestroyed(activity)) {
455
- // the activity finished and the manager already took care of this situation.
456
- return
457
- }
458
- await activity.onStart()
459
- if (this.isDestroyed(activity)) {
460
- return
461
- }
462
- activity.lifecycle = ActivityLifecycle.Started
463
- await activity.onResume()
464
- if (this.isDestroyed(activity)) {
465
- return
466
- }
467
- activity.lifecycle = ActivityLifecycle.Resumed
468
- activity.requestUpdate()
459
+ switch (activity.lifecycle) {
460
+ case ActivityLifecycle.Paused:
461
+ if (!(await this.transitionStartedToResumed(activity))) {
462
+ return
463
+ }
464
+ break
465
+
466
+ case ActivityLifecycle.Stopped:
467
+ await this.safeExecuteLifecycleMethod(() => activity.onRestart(), activity, 'onRestart')
468
+ activity.lifecycle = ActivityLifecycle.Resumed
469
+ break
470
+
471
+ case ActivityLifecycle.Destroyed:
472
+ throw new Error(`Invalid state. The activity is already destroyed.`)
473
+
474
+ case ActivityLifecycle.Created:
475
+ if (!(await this.transitionCreatedToResumed(activity))) {
476
+ return
477
+ }
478
+ break
479
+
480
+ case ActivityLifecycle.Started:
481
+ if (!(await this.transitionStartedToResumed(activity))) {
482
+ return
483
+ }
484
+ break
485
+
486
+ case ActivityLifecycle.Initialized:
487
+ if (!(await this.transitionInitializedToResumed(activity, intent))) {
488
+ return
489
+ }
490
+ break
469
491
  }
470
492
  if (!isModal) {
471
493
  // With a modal activity, it renders directly to the `<body>` and renders outside
@@ -474,17 +496,130 @@ export class ActivityManager {
474
496
  }
475
497
  }
476
498
 
499
+ /**
500
+ * Safely executes an async lifecycle method with error handling.
501
+ * @param lifecycleMethod The lifecycle method to execute.
502
+ * @param activity The activity instance.
503
+ * @param methodName The name of the method for error reporting.
504
+ * @returns Promise that resolves when the method completes or rejects with wrapped error.
505
+ */
506
+ private async safeExecuteLifecycleMethod(
507
+ lifecycleMethod: () => void | Promise<void>,
508
+ activity: Activity,
509
+ methodName: string
510
+ ): Promise<void> {
511
+ try {
512
+ await lifecycleMethod()
513
+ } catch (error) {
514
+ const activityName = activity.constructor.name
515
+ const wrappedError = new Error(
516
+ `Error in ${activityName}.${methodName}(): ${error instanceof Error ? error.message : String(error)}`
517
+ )
518
+ wrappedError.cause = error
519
+ // Allow the activity to handle its own errors, but still propagate
520
+ this.#parent.dispatchEvent(
521
+ new CustomEvent('activity-lifecycle-error', {
522
+ detail: { activity, methodName, error: wrappedError },
523
+ })
524
+ )
525
+ throw wrappedError
526
+ }
527
+ }
528
+
477
529
  /**
478
530
  * Allows navigating back through the activity stack.
479
531
  * Call `ActivityManager.navigateBack()` when the user performs a back action
480
532
  * (e.g., clicks a back button).
533
+ * @returns Promise that resolves to true if navigation was successful, false if at root.
481
534
  */
482
- async navigateBack(): Promise<void> {
535
+ async navigateBack(): Promise<boolean> {
536
+ // Handle modal activities first
537
+ if (this.modalActivityStack.length > 0) {
538
+ const topModal = this.modalActivityStack[this.modalActivityStack.length - 1]
539
+ await this.finishActivity(topModal.activity)
540
+ return true
541
+ }
542
+
543
+ // Handle regular activities
483
544
  if (this.activityStack.length > 1 && this.currentActivity) {
484
- // Finish current, which will resume previous
485
545
  await this.finishActivity(this.currentActivity)
546
+ return true
547
+ }
548
+
549
+ // At root, cannot navigate back
550
+ return false
551
+ }
552
+
553
+ /**
554
+ * Navigates to a specific activity in the stack, clearing activities above it.
555
+ * @param action The action of the activity to navigate to.
556
+ * @returns Promise that resolves to true if navigation was successful.
557
+ */
558
+ async navigateToActivity(action: string): Promise<boolean> {
559
+ const index = this.activityStack.findIndex((entry) => entry.action === action)
560
+ if (index === -1) {
561
+ return false
562
+ }
563
+
564
+ // Finish all activities above the target
565
+ const activitiesToFinish = this.activityStack.slice(index + 1)
566
+ for (const entry of activitiesToFinish) {
567
+ await this.finishActivity(entry.activity)
568
+ }
569
+
570
+ // Bring the target activity to the front
571
+ const targetEntry = this.activityStack[index]
572
+ await this.updateCurrentActivity(targetEntry.activity, false, targetEntry.intent)
573
+ return true
574
+ }
575
+
576
+ /**
577
+ * Clears the entire activity stack and starts a new root activity.
578
+ * @param intent The intent for the new root activity.
579
+ */
580
+ async clearStackAndStart(intent: Intent): Promise<void> {
581
+ // Finish all activities
582
+ const allActivities = [...this.activityStack, ...this.modalActivityStack]
583
+ for (const entry of allActivities) {
584
+ if (entry.activity.lifecycle !== ActivityLifecycle.Destroyed) {
585
+ await this.finishActivity(entry.activity)
586
+ }
587
+ }
588
+
589
+ // Clear stacks
590
+ this.activityStack.length = 0
591
+ this.modalActivityStack.length = 0
592
+ this.currentActivity = undefined
593
+
594
+ // Start new root activity
595
+ await this.startActivity(intent)
596
+ }
597
+
598
+ /**
599
+ * Creates an intent with better type safety and validation.
600
+ * @param action The action name.
601
+ * @param data Optional intent data.
602
+ * @param options Optional intent configuration.
603
+ * @returns A properly formed intent.
604
+ */
605
+ createIntent<T = unknown>(
606
+ action: string,
607
+ data?: T,
608
+ options: {
609
+ category?: string[]
610
+ flags?: number
611
+ requestCode?: number
612
+ } = {}
613
+ ): Intent<T> {
614
+ if (!this.isActionRegistered(action)) {
615
+ throw new Error(`Cannot create intent for unregistered action: ${action}`)
616
+ }
617
+
618
+ return {
619
+ action,
620
+ data,
621
+ ...options,
486
622
  }
487
- // Else do nothing (or display a message, or exit the app)
488
623
  }
489
624
 
490
625
  createRequestCode(): number {
@@ -496,4 +631,142 @@ export class ActivityManager {
496
631
  findActiveActivity(action: string): Activity | undefined {
497
632
  return this.activityStack.find((entry) => entry.action === action)?.activity
498
633
  }
634
+
635
+ /**
636
+ * Transitions an activity from Created to Resumed state.
637
+ * @param activity The activity to transition.
638
+ * @returns true if successful, false if activity was destroyed during transition.
639
+ */
640
+ private async transitionCreatedToResumed(activity: Activity): Promise<boolean> {
641
+ await this.safeExecuteLifecycleMethod(() => activity.onStart(), activity, 'onStart')
642
+ if (this.isDestroyed(activity)) {
643
+ return false
644
+ }
645
+ activity.lifecycle = ActivityLifecycle.Started
646
+
647
+ await this.safeExecuteLifecycleMethod(() => activity.onResume(), activity, 'onResume')
648
+ if (this.isDestroyed(activity)) {
649
+ return false
650
+ }
651
+ activity.lifecycle = ActivityLifecycle.Resumed
652
+ activity.requestUpdate()
653
+ return true
654
+ }
655
+
656
+ /**
657
+ * Transitions an activity from Started to Resumed state.
658
+ * @param activity The activity to transition.
659
+ * @returns true if successful, false if activity was destroyed during transition.
660
+ */
661
+ private async transitionStartedToResumed(activity: Activity): Promise<boolean> {
662
+ await this.safeExecuteLifecycleMethod(() => activity.onResume(), activity, 'onResume')
663
+ if (this.isDestroyed(activity)) {
664
+ return false
665
+ }
666
+ activity.lifecycle = ActivityLifecycle.Resumed
667
+ activity.requestUpdate()
668
+ return true
669
+ }
670
+
671
+ /**
672
+ * Transitions an activity from Initialized to Resumed state.
673
+ * @param activity The activity to transition.
674
+ * @param intent The intent used to create the activity.
675
+ * @returns true if successful, false if activity was destroyed during transition.
676
+ */
677
+ private async transitionInitializedToResumed(activity: Activity, intent?: Intent): Promise<boolean> {
678
+ await this.safeExecuteLifecycleMethod(() => activity.onCreate(intent), activity, 'onCreate')
679
+ activity.lifecycle = ActivityLifecycle.Created
680
+ if (this.isDestroyed(activity)) {
681
+ return false
682
+ }
683
+
684
+ return await this.transitionCreatedToResumed(activity)
685
+ }
686
+
687
+ /**
688
+ * Cleans up resources for destroyed activities to prevent memory leaks.
689
+ * @param activity The activity to clean up.
690
+ */
691
+ private cleanupActivity(activity: Activity): void {
692
+ // Remove any event listeners that might create memory leaks
693
+ // This changes the entire prototype chain of the activity,
694
+ // effectively making it a new object. We can't do that as the activity will loose some
695
+ // of its properties, so we don't do it for now.
696
+ // if (activity instanceof EventTarget) {
697
+ // // Clear all event listeners by replacing the activity with a new EventTarget
698
+ // // This is a defensive approach since we can't enumerate listeners
699
+ // Object.setPrototypeOf(activity, EventTarget.prototype)
700
+ // }
701
+
702
+ // Clear any references that might prevent garbage collection
703
+ activity.renderRoot = undefined
704
+ }
705
+
706
+ /**
707
+ * Validates that an activity stack is in a consistent state.
708
+ * @param stack The activity stack to validate.
709
+ * @returns Array of validation errors, empty if valid.
710
+ */
711
+ private validateStackConsistency(stack: ActivityStackEntry[]): string[] {
712
+ const errors: string[] = []
713
+ const seenIds = new Set<string>()
714
+
715
+ for (const entry of stack) {
716
+ if (seenIds.has(entry.id)) {
717
+ errors.push(`Duplicate activity ID found: ${entry.id}`)
718
+ }
719
+ seenIds.add(entry.id)
720
+
721
+ if (!entry.activity || !entry.id || !entry.action) {
722
+ errors.push(`Invalid stack entry: missing required properties`)
723
+ }
724
+
725
+ if (entry.activity.lifecycle === ActivityLifecycle.Destroyed) {
726
+ errors.push(`Destroyed activity found in stack: ${entry.id}`)
727
+ }
728
+ }
729
+
730
+ return errors
731
+ }
732
+
733
+ /**
734
+ * Gets diagnostic information about the current state of the activity manager.
735
+ * Useful for debugging and monitoring.
736
+ * @returns Object containing current state information.
737
+ */
738
+ getDiagnostics(): {
739
+ totalActivities: number
740
+ modalActivities: number
741
+ currentActivity?: string
742
+ topActivity?: string
743
+ stackValidation: string[]
744
+ modalStackValidation: string[]
745
+ } {
746
+ return {
747
+ totalActivities: this.activityStack.length,
748
+ modalActivities: this.modalActivityStack.length,
749
+ currentActivity: this.currentActivity?.constructor.name,
750
+ topActivity: this.getTopActivity()?.constructor.name,
751
+ stackValidation: this.validateStackConsistency(this.activityStack),
752
+ modalStackValidation: this.validateStackConsistency(this.modalActivityStack),
753
+ }
754
+ }
755
+
756
+ /**
757
+ * Gets all registered activity actions.
758
+ * @returns Array of registered action names.
759
+ */
760
+ getRegisteredActions(): string[] {
761
+ return Array.from(this.activityClasses.keys())
762
+ }
763
+
764
+ /**
765
+ * Checks if an action is registered.
766
+ * @param action The action to check.
767
+ * @returns true if the action is registered, false otherwise.
768
+ */
769
+ isActionRegistered(action: string): boolean {
770
+ return this.activityClasses.has(action)
771
+ }
499
772
  }
@@ -1,7 +1,7 @@
1
- import { nothing, render, type RootPart, type TemplateResult } from 'lit'
1
+ import { nothing, type TemplateResult } from 'lit'
2
2
  import type { Application } from '../Application.js'
3
3
  import type { Activity } from '../Activity.js'
4
- import { Renderer, renderFn } from './Renderer.js'
4
+ import { Renderer } from './Renderer.js'
5
5
  import { ModalActivity } from '../ModalActivity.js'
6
6
 
7
7
  export class ApplicationRenderer extends Renderer {
@@ -12,46 +12,42 @@ export class ApplicationRenderer extends Renderer {
12
12
  this.renderedFirst = new WeakMap()
13
13
  }
14
14
 
15
- [renderFn](): void {
16
- const { app, renderRoot } = this
17
- let host: Application | Activity
18
- let root: HTMLElement | null = renderRoot
19
- let content: TemplateResult | typeof nothing
20
- const activity = app.manager.getTopActivity()
21
- if (activity) {
22
- host = activity
23
- if (activity.renderRoot) {
24
- root = activity.renderRoot
25
- }
26
- if (activity instanceof ModalActivity) {
27
- content = activity.renderDialog()
28
- } else {
29
- content = activity.render()
15
+ private _handleFirstRender(target: Application | Activity, clearRoot: boolean, root: HTMLElement): void {
16
+ if (!this.renderedFirst.has(target)) {
17
+ this.renderedFirst.set(target, true)
18
+ if (clearRoot) {
19
+ this._clearRoot(root)
30
20
  }
21
+ queueMicrotask(() => target.onFirstRender())
22
+ }
23
+ }
24
+
25
+ protected renderer(): void {
26
+ const { app, renderRoot: defaultRenderRoot } = this
27
+ const activity = app.manager.getTopActivity()
28
+
29
+ const host: Application | Activity = activity || app
30
+ const root: HTMLElement | null = activity?.renderRoot || defaultRenderRoot
31
+
32
+ let content: TemplateResult | typeof nothing
33
+ if (activity instanceof ModalActivity) {
34
+ content = activity.renderDialog()
31
35
  } else {
32
- host = app
33
- content = app.render()
36
+ content = host.render()
34
37
  }
35
38
  if (!root) {
36
39
  // eslint-disable-next-line no-console
37
40
  console.warn(`The "renderRoot" is not set up.`)
38
41
  return
39
42
  }
40
- if (!this.renderedFirst.has(app)) {
41
- this.renderedFirst.set(app, true)
42
- Array.from(root.childNodes).forEach((node) => root.parentNode?.removeChild(node))
43
- setTimeout(() => app.onFirstRender())
44
- }
45
- // host might !== app
46
- if (!this.renderedFirst.has(host)) {
47
- setTimeout(() => host.onFirstRender())
43
+ this._handleFirstRender(app, true, root)
44
+ if (!this.firstRendered) {
45
+ this.firstRenderedFlag = true
48
46
  }
49
- const litPart = root as HTMLElement & { _$litPart$?: RootPart }
50
- if (litPart._$litPart$ && litPart._$litPart$.options) {
51
- litPart._$litPart$.options.host = host
47
+ if (host !== app) {
48
+ this._handleFirstRender(host, false, root)
52
49
  }
53
- render(content, root, { host })
54
- this.resolveUpdatePromise()
50
+ this._render(content, root, host)
55
51
  this.app.onRendered()
56
52
  }
57
53
  }
@@ -1,33 +1,24 @@
1
- import { render, RenderOptions, RootPart } from 'lit'
2
1
  import type { Fragment } from '../Fragment.js'
3
- import { Renderer, renderFn } from './Renderer.js'
2
+ import { Renderer } from './Renderer.js'
4
3
 
5
4
  export class FragmentRenderer extends Renderer {
6
5
  constructor(protected fragment: Fragment) {
7
6
  super()
8
7
  }
9
8
 
10
- [renderFn](): void {
9
+ protected renderer(): void {
11
10
  const root = this.renderRoot
12
11
  if (!root) {
13
12
  // return quietly. Fragments can be rendered directly.
14
13
  return
15
14
  }
16
- const fragment = this.fragment
17
- const host = fragment.getSingleVisibleFragment() || fragment
15
+ const host = this.fragment.getSingleVisibleFragment() ?? this.fragment
18
16
  if (!this.firstRendered) {
19
17
  this.firstRenderedFlag = true
20
18
  // cleanup any pre-existing content.
21
- Array.from(root.childNodes).forEach((node) => root.parentNode?.removeChild(node))
22
- setTimeout(() => host.onFirstRender())
19
+ this._clearRoot(root)
20
+ queueMicrotask(() => host.onFirstRender())
23
21
  }
24
- const litPart = root as unknown as HTMLElement & { _$litPart$?: RootPart }
25
- if (litPart._$litPart$) {
26
- ;(litPart._$litPart$.options as RenderOptions).host = host
27
- }
28
- // console.log(host, root)
29
- render(host.render(), root, { host })
30
- this.resolveUpdatePromise()
31
- // this.app.onRendered()
22
+ this._render(host.render(), root, host)
32
23
  }
33
24
  }