@genesislcap/foundation-layout 14.367.2 → 14.369.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.
Files changed (32) hide show
  1. package/dist/custom-elements.json +142 -3
  2. package/dist/dts/index.d.ts +2 -1
  3. package/dist/dts/index.d.ts.map +1 -1
  4. package/dist/dts/main/layout-item.d.ts +20 -0
  5. package/dist/dts/main/layout-item.d.ts.map +1 -1
  6. package/dist/dts/main/layout-main.d.ts +36 -8
  7. package/dist/dts/main/layout-main.d.ts.map +1 -1
  8. package/dist/dts/utils/factory-registry.d.ts +63 -0
  9. package/dist/dts/utils/factory-registry.d.ts.map +1 -0
  10. package/dist/dts/utils/index.d.ts +1 -0
  11. package/dist/dts/utils/index.d.ts.map +1 -1
  12. package/dist/dts/utils/types.d.ts +44 -3
  13. package/dist/dts/utils/types.d.ts.map +1 -1
  14. package/dist/esm/index.js +1 -0
  15. package/dist/esm/main/layout-item.js +26 -4
  16. package/dist/esm/main/layout-main.js +169 -46
  17. package/dist/esm/utils/factory-registry.js +88 -0
  18. package/dist/esm/utils/index.js +1 -0
  19. package/dist/foundation-layout.api.json +206 -9
  20. package/dist/foundation-layout.d.ts +156 -9
  21. package/docs/FRAMEWORK_COMPONENTS.md +568 -0
  22. package/docs/api/foundation-layout.componentfactory.md +46 -0
  23. package/docs/api/foundation-layout.foundationlayout.md +2 -2
  24. package/docs/api/foundation-layout.foundationlayout.registeritem.md +31 -7
  25. package/docs/api/foundation-layout.foundationlayoutitem.md +2 -0
  26. package/docs/api/foundation-layout.foundationlayoutitem.registration.md +18 -0
  27. package/docs/api/foundation-layout.getfactory.md +56 -0
  28. package/docs/api/foundation-layout.md +59 -0
  29. package/docs/api/foundation-layout.registerfactory.md +94 -0
  30. package/docs/api/foundation-layout.unregisterfactory.md +63 -0
  31. package/docs/api-report.md.api.md +20 -7
  32. package/package.json +12 -12
@@ -8,6 +8,7 @@ import { FoundationElement } from '@microsoft/fast-foundation';
8
8
  import { globalDraggingStyles, glVisualConfig, LAYOUT_ICONS, layoutStyles } from '../styles';
9
9
  import { AUTOSAVE_KEY, componentType, DEFAULT_RELOAD_BUFFER, getMissingArrayItems, instanceContainer, LAYOUT_POPOUT_CONTAINER_CLASS, LAYOUT_POPOUT_CONTROL_KEY, LayoutEmitEvents, LayoutReceiveEvents, regionConveter, } from '../utils/';
10
10
  import { LayoutRegistrationError, LayoutUsageError } from '../utils/error';
11
+ import { getFactory } from '../utils/factory-registry';
11
12
  import { logger } from '../utils/logger';
12
13
  export { layoutStyles } from '../styles';
13
14
  /*
@@ -248,6 +249,13 @@ export class FoundationLayout extends FoundationElement {
248
249
  return;
249
250
  const orderedStates = [...items].map((item) => { var _b; return (_b = item.getCurrentState) === null || _b === void 0 ? void 0 : _b.call(item); });
250
251
  const componentInstanceContainer = items[0][instanceContainer];
252
+ // TODO: Factory based components dont handle the LayoutWithState interface, so we need to handle this differently.
253
+ // For now we will just log a warning and return. We need to assess whether to deprecate that interface and handle it in TAM directly
254
+ // or whether adding support is needed
255
+ if (!componentInstanceContainer) {
256
+ logger.warn('Component instance container not found for items:', items);
257
+ return;
258
+ }
251
259
  // known use of deprecated API, but there is no other way of implementing it and we control
252
260
  // the underlying library anyway
253
261
  componentInstanceContainer.container.setState({
@@ -528,28 +536,70 @@ export class FoundationLayout extends FoundationElement {
528
536
  }
529
537
  /**
530
538
  * @public
531
- * Register a collection of `Element` and associate them with an `ID` with the layout system for later use.
539
+ * Register a collection of `Element` or a factory function and associate them with an `ID` with the layout system for later use.
532
540
  * @remarks
533
- * You would use this to register elements that you later want to load when using {@link FoundationLayout.loadLayout}.
541
+ * You can register either an array of elements or a factory function.
542
+ *
543
+ * **Element registration**: Use this to register elements that you later want to load when using {@link FoundationLayout.loadLayout}.
534
544
  * Use {@link FoundationLayout.layoutRequiredRegistrations} to see what components need to be registered for a certain config
535
545
  * and then register them using this function before calling {@link FoundationLayout.loadLayout}.
546
+ * When registering an element it is moved by reference into the internals of the layout, so if you pass elements already in the DOM then they will disappear.
547
+ * If you want to avoid this you can pass copies using `element.cloneNode(true)`.
536
548
  *
537
- * When registering an element it is moved by reference into the internals of the layout, so if you pass elements already in the DOM then they will disappear. If you want to avoid this you can pass copies using `element.cloneNode(true)`.
549
+ * **Factory registration**: This is the recommended approach for framework-rendered components (React, Angular, Vue, etc.)
550
+ * because it allows each layout instance to create a fresh component rather than cloning existing
551
+ * DOM elements (which loses event listeners and framework bindings).
552
+ * The factory function will be called each time a new instance of the component is needed. It receives
553
+ * a container element and should render the component into it. Optionally, it can return a cleanup
554
+ * function that will be called when the component is removed from the layout.
538
555
  *
539
556
  * @param registration - string of the registration ID
540
- * @param elements - Elements[] containing the reference to the elements to register for later usage
557
+ * @param elementsOrFactory - Either Elements[] containing the reference to the elements to register, or a ComponentFactory function
541
558
  * @throws {@link LayoutUsageError} if you attempt to add an item before the layout has been initialised.
542
559
  * @throws {@link LayoutRegistrationError} if you attempt to use a `registration` name which is already in use (declarative html API and JavaScript API registrations use the same "pool" of registration names).
543
560
  * @returns - string defining the name of the registered item with the layout system (config.id if set).
561
+ *
562
+ * @example
563
+ * Element registration:
564
+ * ```typescript
565
+ * const div = document.createElement('div');
566
+ * div.innerHTML = '<h1>Hello</h1>';
567
+ * layout.registerItem('my-element', [div]);
568
+ * ```
569
+ *
570
+ * @example
571
+ * Factory registration (React):
572
+ * ```typescript
573
+ * layout.registerItem('text-field', (container) => {
574
+ * const root = createRoot(container);
575
+ * root.render(<TextFieldComponent />);
576
+ * return () => root.unmount();
577
+ * });
578
+ * ```
544
579
  */
545
- registerItem(registration, elements) {
580
+ registerItem(registration, elementsOrFactory) {
546
581
  if (!this.layout.isInitialised) {
547
582
  throw new LayoutUsageError('Cannot add item via JS API until initialised');
548
583
  }
549
- return this.cacheElementsAndRegister({
550
- elements: elements,
551
- id: registration,
552
- });
584
+ // Check if a factory is already registered with this name
585
+ const existingFactory = getFactory(registration);
586
+ if (existingFactory) {
587
+ throw new LayoutRegistrationError(`Registration "${registration}" already has a factory registered via registerFactory(). ` +
588
+ `Cannot register the same name via the JavaScript API. ` +
589
+ `Use a different registration name or unregister the factory first.`);
590
+ }
591
+ if (typeof elementsOrFactory === 'function') {
592
+ return this.cacheElementsAndRegister({
593
+ factory: elementsOrFactory,
594
+ id: registration,
595
+ });
596
+ }
597
+ else {
598
+ return this.cacheElementsAndRegister({
599
+ elements: elementsOrFactory,
600
+ id: registration,
601
+ });
602
+ }
553
603
  }
554
604
  /**
555
605
  * Internal APIs
@@ -610,13 +660,14 @@ export class FoundationLayout extends FoundationElement {
610
660
  /**
611
661
  * Registers a function with golden layout to create a pane
612
662
  * @param elements - Elements[] to add to new new pane
663
+ * @param factory - ComponentFactory function to create component instances
613
664
  * @param id - optional string which is used to register the new function with golden layout. Defaults to sequentially setting the IDs for default items
614
665
  * @returns - string which is the registered ID
615
666
  * @throws - {@link LayoutRegistrationError} if the id is already in use
616
667
  * @internal
617
668
  */
618
- cacheElementsAndRegister({ elements, id }) {
619
- const reg = id || `${(this.registeredComponents += 1)}`;
669
+ cacheElementsAndRegister(config) {
670
+ const reg = config.id || `${(this.registeredComponents += 1)}`;
620
671
  if (this.layout.getRegisteredComponentTypeNames().includes(reg)) {
621
672
  throw new LayoutRegistrationError(`Cannot register item with already registered name: '${reg}'`);
622
673
  }
@@ -632,45 +683,117 @@ export class FoundationLayout extends FoundationElement {
632
683
  *
633
684
  * As part of creating each instance we attach a reference to the instance container which is used
634
685
  * to be able to optionally save state, and any state which has been saved we apply to the component.
686
+ *
687
+ * For factory functions:
688
+ * The factory is called for each new instance instead of cloning. This preserves event listeners
689
+ * and framework bindings that would be lost during cloning.
635
690
  */
636
691
  const registrationFunction = (() => {
637
- // Use appendChild to consume the elements and save them in the master copy
638
- const masterCopy = document.createDocumentFragment();
639
- masterCopy[layoutCacheDocument] = true;
640
- elements.forEach((e) => masterCopy.appendChild(e));
641
- const instances = new Map();
642
- return (container, state) => {
643
- var _b;
644
- // If this is a new instance then assign it uuid instance
645
- if (!(state === null || state === void 0 ? void 0 : state['instance'])) {
646
- state['instance'] = this.uuid.createId();
647
- }
648
- container.state['instance'] = state['instance'];
649
- container.state['originalTitle'] = (_b = state['originalTitle']) !== null && _b !== void 0 ? _b : container.title;
650
- // If this is a new instance then copy the master copy into the instances map
651
- // this is then the instance that is recalled for this version each time
652
- // the key point is "cloneNode" which makes a copy at this point
653
- if (!instances.has(state === null || state === void 0 ? void 0 : state['instance'])) {
654
- const instanceCopy = document.createDocumentFragment();
655
- Array.from(masterCopy.children).forEach((e) => {
656
- instanceCopy.appendChild(e.cloneNode(true));
692
+ if ('factory' in config) {
693
+ // Factory-based registration for framework components
694
+ const instances = new Map();
695
+ const cleanupFunctions = new Map();
696
+ const containerTracking = new Map();
697
+ return (container, state) => {
698
+ var _b;
699
+ // If this is a new instance then assign it uuid instance
700
+ if (!(state === null || state === void 0 ? void 0 : state['instance'])) {
701
+ state['instance'] = this.uuid.createId();
702
+ }
703
+ container.state['instance'] = state['instance'];
704
+ container.state['originalTitle'] = (_b = state['originalTitle']) !== null && _b !== void 0 ? _b : container.title;
705
+ // Store instance container reference for state management FIRST
706
+ const componentInstanceContainer = {
707
+ container,
708
+ instance: state['instance'],
709
+ registration: reg,
710
+ };
711
+ const instanceId = state['instance'];
712
+ // Check if this instance was previously rendered in a different container
713
+ const previousContainer = containerTracking.get(instanceId);
714
+ const hasMoved = previousContainer && previousContainer !== container;
715
+ // If moved to a different container (drag operation), cleanup and recreate to avoid stale state
716
+ if (hasMoved) {
717
+ logger.debug(`Recreating instance ${instanceId} for registration ${reg} due to container change`);
718
+ // Call cleanup function if it exists
719
+ const cleanup = cleanupFunctions.get(instanceId);
720
+ if (cleanup && typeof cleanup === 'function') {
721
+ try {
722
+ cleanup();
723
+ }
724
+ catch (error) {
725
+ logger.error(`Error calling cleanup for instance ${instanceId}:`, error);
726
+ }
727
+ }
728
+ // Remove from maps to force recreation
729
+ instances.delete(instanceId);
730
+ cleanupFunctions.delete(instanceId);
731
+ }
732
+ // Create instance if it doesn't exist (new instance or recreated after move)
733
+ if (!instances.has(instanceId)) {
734
+ const componentContainer = document.createElement('div');
735
+ componentContainer.style.width = '100%';
736
+ componentContainer.style.height = '100%';
737
+ componentContainer[instanceContainer] = componentInstanceContainer;
738
+ const cleanup = config.factory(componentContainer);
739
+ instances.set(instanceId, componentContainer);
740
+ if (cleanup) {
741
+ cleanupFunctions.set(instanceId, cleanup);
742
+ }
743
+ }
744
+ // Append the instance container to the layout container
745
+ const componentContainer = instances.get(instanceId);
746
+ if (!componentContainer) {
747
+ logger.error(`Failed to get component container for instance ${instanceId}`);
748
+ return;
749
+ }
750
+ // Ensure the property is set (in case it was lost)
751
+ componentContainer[instanceContainer] = componentInstanceContainer;
752
+ container.element.appendChild(componentContainer);
753
+ // Track which container this instance is now in
754
+ containerTracking.set(instanceId, container);
755
+ this.setupLayoutReceiveEvents(container, state);
756
+ };
757
+ }
758
+ else {
759
+ // Element-based registration (existing behavior)
760
+ const masterCopy = document.createDocumentFragment();
761
+ masterCopy[layoutCacheDocument] = true;
762
+ config.elements.forEach((e) => masterCopy.appendChild(e));
763
+ const instances = new Map();
764
+ return (container, state) => {
765
+ var _b;
766
+ // If this is a new instance then assign it uuid instance
767
+ if (!(state === null || state === void 0 ? void 0 : state['instance'])) {
768
+ state['instance'] = this.uuid.createId();
769
+ }
770
+ container.state['instance'] = state['instance'];
771
+ container.state['originalTitle'] = (_b = state['originalTitle']) !== null && _b !== void 0 ? _b : container.title;
772
+ // If this is a new instance then copy the master copy into the instances map
773
+ // this is then the instance that is recalled for this version each time
774
+ // the key point is "cloneNode" which makes a copy at this point
775
+ if (!instances.has(state === null || state === void 0 ? void 0 : state['instance'])) {
776
+ const instanceCopy = document.createDocumentFragment();
777
+ Array.from(masterCopy.children).forEach((e) => {
778
+ instanceCopy.appendChild(e.cloneNode(true));
779
+ });
780
+ instances.set(state['instance'], [...instanceCopy.children]);
781
+ }
782
+ // provide each component with a reference to the instance container
783
+ // so they can optionally save and load their own state
784
+ const componentInstanceContainer = {
785
+ container,
786
+ instance: state['instance'],
787
+ registration: reg,
788
+ };
789
+ // get the instance from the map and append it to the container
790
+ instances.get(state['instance']).forEach((component) => {
791
+ container.element.appendChild(component);
792
+ component[instanceContainer] = componentInstanceContainer;
657
793
  });
658
- instances.set(state['instance'], [...instanceCopy.children]);
659
- }
660
- // provide each component with a reference to the instance container
661
- // so they can optionally save and load their own state
662
- const componentInstanceContainer = {
663
- container,
664
- instance: state['instance'],
665
- registration: reg,
794
+ this.setupLayoutReceiveEvents(container, state);
666
795
  };
667
- // get the instance from the map and append it to the container
668
- instances.get(state['instance']).forEach((component) => {
669
- container.element.appendChild(component);
670
- component[instanceContainer] = componentInstanceContainer;
671
- });
672
- this.setupLayoutReceiveEvents(container, state);
673
- };
796
+ }
674
797
  })();
675
798
  this.layout.registerComponentFactoryFunction(reg, registrationFunction);
676
799
  return reg;
@@ -0,0 +1,88 @@
1
+ import { logger } from './logger';
2
+ /**
3
+ * Global registry for component factories.
4
+ * Maps factory keys (strings) to factory functions.
5
+ * @internal
6
+ */
7
+ const factoryRegistry = new Map();
8
+ /**
9
+ * Registers a factory function with a unique key.
10
+ * This allows framework components to be used in the declarative layout API
11
+ * without needing to pass function references through HTML attributes.
12
+ *
13
+ * @param key - Unique identifier for the factory. Should be descriptive and unique across the application.
14
+ * @param factory - The factory function that creates the component.
15
+ * @throws {Error} If a factory with the same key is already registered.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * // React example
20
+ * import { registerFactory } from '@genesislcap/foundation-layout';
21
+ * import { reactFactory } from './utils/react-layout-factory';
22
+ * import { MyComponent } from './components/MyComponent';
23
+ *
24
+ * registerFactory('my-component', reactFactory(MyComponent, { someProp: 'value' }));
25
+ * ```
26
+ *
27
+ * Then in your JSX:
28
+ * ```tsx
29
+ * <rapid-layout-item
30
+ * registration="my-item"
31
+ * title="My Component"
32
+ * />
33
+ * ```
34
+ *
35
+ * @public
36
+ */
37
+ export function registerFactory(key, factory) {
38
+ if (factoryRegistry.has(key)) {
39
+ throw new Error(`Factory with key "${key}" is already registered. Cannot register duplicate factory.`);
40
+ }
41
+ factoryRegistry.set(key, factory);
42
+ logger.debug(`Factory registered with key: ${key}`);
43
+ }
44
+ /**
45
+ * Retrieves a factory function by its key.
46
+ *
47
+ * @param key - The unique identifier for the factory.
48
+ * @returns The factory function, or undefined if not found.
49
+ *
50
+ * @public
51
+ */
52
+ export function getFactory(key) {
53
+ return factoryRegistry.get(key);
54
+ }
55
+ /**
56
+ * Removes a factory from the registry.
57
+ * This is useful for cleanup when a component is unmounted or no longer needed.
58
+ *
59
+ * @param key - The unique identifier for the factory to remove.
60
+ * @returns True if the factory was found and removed, false otherwise.
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * unregisterFactory('my-component');
65
+ * ```
66
+ *
67
+ * @public
68
+ */
69
+ export function unregisterFactory(key) {
70
+ const deleted = factoryRegistry.delete(key);
71
+ if (deleted) {
72
+ logger.debug(`Factory unregistered with key: ${key}`);
73
+ }
74
+ else {
75
+ logger.warn(`Attempted to unregister factory with key "${key}", but it was not found.`);
76
+ }
77
+ return deleted;
78
+ }
79
+ /**
80
+ * Clears all registered factories from the registry.
81
+ * This is primarily useful for testing purposes.
82
+ *
83
+ * @internal
84
+ */
85
+ export function clearFactoryRegistry() {
86
+ factoryRegistry.clear();
87
+ logger.debug('Factory registry cleared');
88
+ }
@@ -1,6 +1,7 @@
1
1
  export * from './constants';
2
2
  export * from './error';
3
3
  export * from './events';
4
+ export * from './factory-registry';
4
5
  export * from './misc';
5
6
  export * from './templates';
6
7
  export * from './types';