From fcd968127dae2e8168cbb0c93262a39cfdf1e72e Mon Sep 17 00:00:00 2001 From: Vladimir Zaets Date: Tue, 11 Feb 2025 18:59:17 -0600 Subject: [PATCH 1/5] frames-communication-prototype --- packages/uix-core/src/index.ts | 1 + packages/uix-core/src/store/data-store.ts | 27 +++ packages/uix-core/src/store/index.tsx | 1 + packages/uix-core/src/store/pubsub.ts | 47 ++++ packages/uix-core/src/store/store-manager.ts | 80 +++++++ .../uix-core/src/tunnel/tunnel-messenger.ts | 1 + packages/uix-core/src/tunnel/tunnel.ts | 37 +++- packages/uix-guest-react/CODE_OF_CONDUCT.md | 79 +++++++ packages/uix-guest-react/CONTRIBUTING.md | 19 ++ packages/uix-guest-react/COPYRIGHT | 5 + packages/uix-guest-react/LICENSE | 201 ++++++++++++++++++ packages/uix-guest-react/README.md | 1 + packages/uix-guest-react/api-extractor.json | 4 + packages/uix-guest-react/jest.config.ts | 36 ++++ packages/uix-guest-react/package.json | 54 +++++ packages/uix-guest-react/setupTests.ts | 12 ++ .../uix-guest-react/src/attach-context.ts | 36 ++++ .../uix-guest-react/src/components/Attach.tsx | 29 +++ .../uix-guest-react/src/components/index.ts | 13 ++ packages/uix-guest-react/src/hooks/index.ts | 2 + .../src/hooks/useExtensibilityState.ts | 40 ++++ .../src/hooks/useExtensionExtensibityState.ts | 8 + .../src/hooks/useHostExtensibityState.ts | 8 + packages/uix-guest-react/src/index.ts | 15 ++ packages/uix-guest-react/tsconfig.json | 27 +++ packages/uix-guest-react/tsup.config.cjs | 6 + packages/uix-guest/src/guest-ui.ts | 15 ++ packages/uix-guest/src/index.ts | 1 + .../src/components/Extensible.tsx | 3 +- .../ExtensibleStateApiProvider.tsx | 35 +++ .../ExtensibleStateBroadcaster.tsx | 37 ++++ .../ExtensibleStateProvider.tsx | 24 +++ .../ExtensibleStateProviderContext.tsx | 11 + .../src/components/ExtensibleState/index.tsx | 1 + .../src/components/GuestUIFrame.tsx | 1 + .../uix-host-react/src/components/index.ts | 1 + packages/uix-host-react/src/hooks/index.ts | 1 + .../src/hooks/useExtensibilityState.tsx | 31 +++ packages/uix-host/src/port.ts | 7 + tsconfig.json | 3 + 40 files changed, 958 insertions(+), 2 deletions(-) create mode 100644 packages/uix-core/src/store/data-store.ts create mode 100644 packages/uix-core/src/store/index.tsx create mode 100644 packages/uix-core/src/store/pubsub.ts create mode 100644 packages/uix-core/src/store/store-manager.ts create mode 100644 packages/uix-guest-react/CODE_OF_CONDUCT.md create mode 100755 packages/uix-guest-react/CONTRIBUTING.md create mode 100644 packages/uix-guest-react/COPYRIGHT create mode 100644 packages/uix-guest-react/LICENSE create mode 100644 packages/uix-guest-react/README.md create mode 100644 packages/uix-guest-react/api-extractor.json create mode 100644 packages/uix-guest-react/jest.config.ts create mode 100644 packages/uix-guest-react/package.json create mode 100644 packages/uix-guest-react/setupTests.ts create mode 100644 packages/uix-guest-react/src/attach-context.ts create mode 100644 packages/uix-guest-react/src/components/Attach.tsx create mode 100644 packages/uix-guest-react/src/components/index.ts create mode 100644 packages/uix-guest-react/src/hooks/index.ts create mode 100644 packages/uix-guest-react/src/hooks/useExtensibilityState.ts create mode 100644 packages/uix-guest-react/src/hooks/useExtensionExtensibityState.ts create mode 100644 packages/uix-guest-react/src/hooks/useHostExtensibityState.ts create mode 100644 packages/uix-guest-react/src/index.ts create mode 100644 packages/uix-guest-react/tsconfig.json create mode 100644 packages/uix-guest-react/tsup.config.cjs create mode 100644 packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateApiProvider.tsx create mode 100644 packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateBroadcaster.tsx create mode 100644 packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateProvider.tsx create mode 100644 packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateProviderContext.tsx create mode 100644 packages/uix-host-react/src/components/ExtensibleState/index.tsx create mode 100644 packages/uix-host-react/src/hooks/useExtensibilityState.tsx diff --git a/packages/uix-core/src/index.ts b/packages/uix-core/src/index.ts index 86aea7e1..989736ec 100644 --- a/packages/uix-core/src/index.ts +++ b/packages/uix-core/src/index.ts @@ -24,4 +24,5 @@ export * from "./cross-realm-object"; export * from "./logging-formatters"; export * from "./promises"; export * from "./tunnel"; +export * from "./store"; export type { Asynced } from "./object-walker"; diff --git a/packages/uix-core/src/store/data-store.ts b/packages/uix-core/src/store/data-store.ts new file mode 100644 index 00000000..bc4ddca7 --- /dev/null +++ b/packages/uix-core/src/store/data-store.ts @@ -0,0 +1,27 @@ +interface DataStoreInterface { + [key: string]: unknown; +} + +export class DataStore { + private readonly store: DataStoreInterface; + private static instance: DataStore; + + constructor() { + this.store = {}; + } + + public static getInstance(): DataStore { + if (!DataStore.instance) { + DataStore.instance = new DataStore(); + } + return DataStore.instance; + } + + public set(key: string, value: unknown) { + this.store[key] = value; + } + + public get(key: string): unknown { + return this.store[key]; + } +} diff --git a/packages/uix-core/src/store/index.tsx b/packages/uix-core/src/store/index.tsx new file mode 100644 index 00000000..31fe29a7 --- /dev/null +++ b/packages/uix-core/src/store/index.tsx @@ -0,0 +1 @@ +export * from "./store-manager"; diff --git a/packages/uix-core/src/store/pubsub.ts b/packages/uix-core/src/store/pubsub.ts new file mode 100644 index 00000000..fc64afaa --- /dev/null +++ b/packages/uix-core/src/store/pubsub.ts @@ -0,0 +1,47 @@ +export type SubscriptionType = ( + value: unknown, + metadata?: { [key: string]: unknown; subscriptionProp: string } +) => void; +export type SubscriptionsListType = SubscriptionType[]; +export type EventSubscriptionsType = { [key: string]: SubscriptionsListType }; + +export class PublishSubscribe { + private readonly subscriptions: EventSubscriptionsType; + private static instance: PublishSubscribe; + + constructor() { + this.subscriptions = { "*": [] }; + } + + public static getInstance(): PublishSubscribe { + if (!PublishSubscribe.instance) { + PublishSubscribe.instance = new PublishSubscribe(); + } + return PublishSubscribe.instance; + } + + public subscribe(property: string, callback: SubscriptionType) { + if (!this.subscriptions[property]) { + this.subscriptions[property] = []; + } + this.subscriptions[property].push(callback); + } + + public unsubscribe(property: string, callback: SubscriptionType) { + this.subscriptions[property] = this.subscriptions[property]?.filter( + (sub) => sub !== callback + ); + } + + public publish(property: string, value: unknown) { + if (!this.subscriptions[property]) { + this.subscriptions[property] = []; + } + + [...this.subscriptions[property], ...this.subscriptions["*"]].forEach( + (subscription: SubscriptionType) => { + subscription(value, { subscriptionProp: property }); + } + ); + } +} diff --git a/packages/uix-core/src/store/store-manager.ts b/packages/uix-core/src/store/store-manager.ts new file mode 100644 index 00000000..57e47c58 --- /dev/null +++ b/packages/uix-core/src/store/store-manager.ts @@ -0,0 +1,80 @@ +import { DataStore } from "./data-store"; +import { PublishSubscribe, SubscriptionType } from "./pubsub"; + +export interface ExtensibleStoreManagerInterface { + set: (key: string, value: unknown, scope?: string) => void; + get: (key: string, scope?: string) => unknown; + subscribe: ( + property: string, + callback: SubscriptionType, + scope?: string + ) => void; + unsubscribe: ( + property: string, + callback: SubscriptionType, + scope?: string + ) => void; + publish: (property: string, value: unknown) => void; +} + +interface StoreInterface { + set(key: string, value: unknown): void; + get(key: string): unknown; +} + +export class ExtensibleStoreManager implements ExtensibleStoreManagerInterface { + private readonly store: StoreInterface; + private publishSubscriber: PublishSubscribe; + private static instance: ExtensibleStoreManagerInterface; + private readonly scope: string; + + constructor() { + this.store = DataStore.getInstance(); + this.publishSubscriber = PublishSubscribe.getInstance(); + this.scope = "default"; + } + + public static getInstance(): ExtensibleStoreManagerInterface { + if (!ExtensibleStoreManager.instance) { + ExtensibleStoreManager.instance = new ExtensibleStoreManager(); + } + return ExtensibleStoreManager.instance; + } + + public set(key: string, value: unknown, scope?: string) { + const dataScope = scope ?? this.scope; + const current = this.store.get(`${dataScope}.${key}`); + if (current !== value) { + this.store.set(`${dataScope}.${key}`, value); + this.publishSubscriber.publish(`${dataScope}.${key}`, value); + } + } + + public get(key: string, scope?: string): unknown { + const dataScope = scope ?? this.scope; + return this.store.get(`${dataScope}.${key}`); + } + + public subscribe( + property: string, + callback: SubscriptionType, + scope?: string + ) { + const dataScope = scope ?? this.scope; + const prop = property !== "*" ? `${dataScope}.${property}` : property; + this.publishSubscriber.subscribe(prop, callback); + } + + public unsubscribe( + property: string, + callback: SubscriptionType, + scope?: string + ) { + const dataScope = scope ?? this.scope; + this.publishSubscriber.unsubscribe(`${dataScope}.${property}`, callback); + } + + public publish(property: string, value: unknown) { + this.publishSubscriber.publish(property, value); + } +} diff --git a/packages/uix-core/src/tunnel/tunnel-messenger.ts b/packages/uix-core/src/tunnel/tunnel-messenger.ts index 4fe44e70..db2ee51b 100644 --- a/packages/uix-core/src/tunnel/tunnel-messenger.ts +++ b/packages/uix-core/src/tunnel/tunnel-messenger.ts @@ -74,6 +74,7 @@ export class TunnelMessenger { ); } isHandshakeOffer(message: unknown): message is HandshakeOffered { + console.log("0007 isHandshakeOffer", message); return ( this.isHandshake(message) && typeof unwrap(message as HandshakeOffered).offers === "string" diff --git a/packages/uix-core/src/tunnel/tunnel.ts b/packages/uix-core/src/tunnel/tunnel.ts index 0734d2c2..5053bb47 100644 --- a/packages/uix-core/src/tunnel/tunnel.ts +++ b/packages/uix-core/src/tunnel/tunnel.ts @@ -91,6 +91,8 @@ export class Tunnel extends EventEmitter { constructor(config: TunnelConfig) { super(); this.config = config; + //@ts-ignore + this.config.instance = Math.random(); } // #endregion Constructors @@ -154,6 +156,7 @@ export class Tunnel extends EventEmitter { let frameStatusCheck: number; let timeout: number; const offerListener = (event: MessageEvent) => { + console.log("00018 subject", event, window.location.href); if ( !tunnel.isConnected && isFromOrigin(event, target.contentWindow, config.targetOrigin) && @@ -166,8 +169,10 @@ export class Tunnel extends EventEmitter { ]); tunnel.connect(channel.port2); } + return true; }; const cleanup = () => { + console.log("00030 cleanup"); clearTimeout(timeout); clearInterval(frameStatusCheck); window.removeEventListener("message", offerListener); @@ -240,21 +245,24 @@ export class Tunnel extends EventEmitter { logger: config.logger, }); const acceptListener = (event: MessageEvent) => { + console.log("0006 acceptListener", event, window.location.href); if ( !timedOut && isFromOrigin(event, source, config.targetOrigin) && messenger.isHandshakeAccepting(event.data, key) ) { + console.log("00020 acceptListener", event); cleanup(); if (!event.ports || !event.ports.length) { const portError = new Error( "Received handshake accept message, but it did not include a MessagePort to establish tunnel" ); tunnel.emitLocal("error", portError); - return; + return true; } tunnel.connect(event.ports[0]); } + return true; }; const cleanup = () => { clearInterval(retrying); @@ -300,6 +308,7 @@ export class Tunnel extends EventEmitter { connect(remote: MessagePort) { if (this._messagePort) { + console.log("311 Connect", this._emitFromMessage); this._messagePort.removeEventListener("message", this._emitFromMessage); this._messagePort.close(); } @@ -329,14 +338,33 @@ export class Tunnel extends EventEmitter { } emit(type: string | symbol, payload?: unknown): boolean { + console.log( + "00031 emitter", + type, + payload, + window.location.href, + this._messagePort, + this.isConnected + ); if (!this._messagePort) { + console.log("00032 noport-emitter"); return false; } + this._messagePort.postMessage({ type, payload }); + console.log("00033 emitter after message"); return true; } emitLocal = (type: string | symbol, payload?: unknown) => { + //@ts-ignore + console.log( + "this._listeners", + window.location.href, + this.config, + this.listeners(), + this.eventNames() + ); return emitOn.call(this, type, payload); }; @@ -376,6 +404,13 @@ export class Tunnel extends EventEmitter { // #region Private Methods private _emitFromMessage = ({ data: { type, payload } }: MessageEvent) => { + console.log( + "00033 EMIT FROM MESSAGE", + type, + payload, + window.location.href, + this + ); this.emitLocal(type, payload); }; diff --git a/packages/uix-guest-react/CODE_OF_CONDUCT.md b/packages/uix-guest-react/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..f25eeb7e --- /dev/null +++ b/packages/uix-guest-react/CODE_OF_CONDUCT.md @@ -0,0 +1,79 @@ +# Adobe Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our project and community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contribute to a positive environment for our project and community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best, not just for us as individuals but for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others’ private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies when an individual is representing the project or its community both within project spaces and in public spaces. Examples of representing a project or community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by first contacting the project team. Oversight of Adobe projects is handled by the Adobe Open Source Office, which has final say in any violations and enforcement of this Code of Conduct and can be reached at Grp-opensourceoffice@adobe.com. All complaints will be reviewed and investigated promptly and fairly. + +The project team must respect the privacy and security of the reporter of any incident. + +Project maintainers who do not follow or enforce the Code of Conduct may face temporary or permanent repercussions as determined by other members of the project's leadership or the Adobe Open Source Office. + +## Enforcement Guidelines + +Project maintainers will follow these Community Impact Guidelines in determining the consequences for any action they deem to be in violation of this Code of Conduct: + +**1. Correction** + +Community Impact: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +Consequence: A private, written warning from project maintainers describing the violation and why the behavior was unacceptable. A public apology may be requested from the violator before any further involvement in the project by violator. + +**2. Warning** + +Community Impact: A relatively minor violation through a single incident or series of actions. + +Consequence: A written warning from project maintainers that includes stated consequences for continued unacceptable behavior. Violator must refrain from interacting with the people involved for a specified period of time as determined by the project maintainers, including, but not limited to, unsolicited interaction with those enforcing the Code of Conduct through channels such as community spaces and social media. Continued violations may lead to a temporary or permanent ban. + +**3. Temporary Ban** + +Community Impact: A more serious violation of community standards, including sustained unacceptable behavior. + +Consequence: A temporary ban from any interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Failure to comply with the temporary ban may lead to a permanent ban. + +**4. Permanent Ban** + +Community Impact: Demonstrating a consistent pattern of violation of community standards or an egregious violation of community standards, including, but not limited to, sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +Consequence: A permanent ban from any interaction with the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, +available at [http://contributor-covenant.org/version/2/1][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/2/1 diff --git a/packages/uix-guest-react/CONTRIBUTING.md b/packages/uix-guest-react/CONTRIBUTING.md new file mode 100755 index 00000000..b9d04940 --- /dev/null +++ b/packages/uix-guest-react/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Contributing + +Thanks for choosing to contribute! + +The following are a set of guidelines to follow when contributing to this project. + +## Code Of Conduct + +This project adheres to the Adobe [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [Grp-opensourceoffice@adobe.com](mailto:Grp-opensourceoffice@adobe.com). + +## Contributor License Agreement + +All third-party contributions to this project must be accompanied by a signed contributor license agreement. This gives Adobe permission to redistribute your contributions as part of the project. [Sign our CLA](http://opensource.adobe.com/cla.html). You only need to submit an Adobe CLA one time, so if you have submitted one previously, you are good to go! + +## Code Reviews + +All submissions should come in the form of pull requests and need to be reviewed by project committers. Read [GitHub's pull request documentation](https://help.github.com/articles/about-pull-requests/) for more information on sending pull requests. + +Lastly, please follow the [pull request template](PULL_REQUEST_TEMPLATE.md) when submitting a pull request! diff --git a/packages/uix-guest-react/COPYRIGHT b/packages/uix-guest-react/COPYRIGHT new file mode 100644 index 00000000..e24d15d6 --- /dev/null +++ b/packages/uix-guest-react/COPYRIGHT @@ -0,0 +1,5 @@ +Copyright 2022 Adobe. All rights reserved. + +Adobe holds the copyright for all the files found in this repository. + +See the LICENSE file for licensing information. diff --git a/packages/uix-guest-react/LICENSE b/packages/uix-guest-react/LICENSE new file mode 100644 index 00000000..2dd90413 --- /dev/null +++ b/packages/uix-guest-react/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 Adobe + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/uix-guest-react/README.md b/packages/uix-guest-react/README.md new file mode 100644 index 00000000..33fac20c --- /dev/null +++ b/packages/uix-guest-react/README.md @@ -0,0 +1 @@ +This is the `@adobe/uix-host-react` package alone. See [/README.md](../../README.md) for details. diff --git a/packages/uix-guest-react/api-extractor.json b/packages/uix-guest-react/api-extractor.json new file mode 100644 index 00000000..3e2a8319 --- /dev/null +++ b/packages/uix-guest-react/api-extractor.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", + "extends": "../../configs/api-extractor.json" +} diff --git a/packages/uix-guest-react/jest.config.ts b/packages/uix-guest-react/jest.config.ts new file mode 100644 index 00000000..22c887dc --- /dev/null +++ b/packages/uix-guest-react/jest.config.ts @@ -0,0 +1,36 @@ +/* + * Copyright 2023 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +const ignores = ["/node_modules/", "__mocks__", "dist", "/__navigation__/"]; + +process.env.TZ = "UTC"; + +module.exports = { + testEnvironment: "jsdom", + "collectCoverage": true, + clearMocks: true, + transform: { + "^.+\\.(t|j)sx?$": "@swc/jest", + }, + moduleNameMapper: { + "\\.(s?css)$": "/../../node_modules/jest-css-modules", + "../extension-context.js": "/src/extension-context.ts" + }, + coverageReporters: ["cobertura", "lcov", "text"], +// reporters: ["default", "jest-junit"], + cacheDirectory: "jest-cache", + collectCoverageFrom: ["src/**/*.+(js|jsx|ts|tsx)", "!**/node_modules/**", "!**/*.d.ts"], + testPathIgnorePatterns: [...ignores], + coveragePathIgnorePatterns: ["src/.*/__tests__/", ".scss$", "mocks", "index.ts(x)?$", "src/test"], + transformIgnorePatterns: ["/node_modules/(?!@babel/runtime)"], + moduleDirectories: ["node_modules", "tests", "src/test", "src", "src/hooks"], + setupFilesAfterEnv: ['/setupTests.ts'] +}; diff --git a/packages/uix-guest-react/package.json b/packages/uix-guest-react/package.json new file mode 100644 index 00000000..44010f64 --- /dev/null +++ b/packages/uix-guest-react/package.json @@ -0,0 +1,54 @@ +{ + "name": "@adobe/uix-guest-react", + "version": "0.0.1", + "publishConfig": { + "access": "public" + }, + "description": "React wrapper for UIX-Guest", + "author": "Adobe, Inc,", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "scripts": { + "build": "tsup", + "build:esm": "tsup --format esm,cjs", + "test": "NODE_ENV=test jest", + "test:watch": "NODE_ENV=test jest --watch", + "watch": "tsup --watch --silent" + }, + "browserslist": [ + "> 0.2%, last 2 versions, not dead" + ], + "bugs": "https://github.com/adobe/uix-sdk/issues", + "dependencies": { + "@adobe/uix-core": "^1.0.0", + "@adobe/uix-guest": "^1.0.0", + "@adobe/uix-host": "^1.0.0" + }, + "devDependencies": { + "@swc/jest": "^0.2.29", + "@testing-library/dom": "^8.1.0", + "@testing-library/jest-dom": "^5.14.1", + "@testing-library/react": "^12.0.0", + "@testing-library/react-hooks": "^7.0.1", + "jest": "^29.7.0", + "jest-environment-jsdom": "^29.7.0" + }, + "files": [ + "README.md", + "dist", + "src", + "tsconfig.json" + ], + "homepage": "https://github.com/adobe/uix-sdk", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "https://github.com/adobe/uix-sdk.git" + }, + "sideEffects": false, + "source": { + ".": "./src/index.ts", + "./*.js": "./src/$1.ts", + "./**/*.js": "./src/$1/$2.ts" + } +} diff --git a/packages/uix-guest-react/setupTests.ts b/packages/uix-guest-react/setupTests.ts new file mode 100644 index 00000000..0c08e9cc --- /dev/null +++ b/packages/uix-guest-react/setupTests.ts @@ -0,0 +1,12 @@ +/* + * Copyright 2021 Adobe. All rights reserved. + * This file is licensed to you under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. You may obtain a copy + * of the License at http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS + * OF ANY KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +import "@testing-library/jest-dom"; diff --git a/packages/uix-guest-react/src/attach-context.ts b/packages/uix-guest-react/src/attach-context.ts new file mode 100644 index 00000000..13b0be75 --- /dev/null +++ b/packages/uix-guest-react/src/attach-context.ts @@ -0,0 +1,36 @@ +/* +Copyright 2022 Adobe. All rights reserved. +This file is licensed to you under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. You may obtain a copy +of the License at http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under +the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +OF ANY KIND, either express or implied. See the License for the specific language +governing permissions and limitations under the License. +*/ + +/** + * Type definition for GuestUI class + */ + +import { createContext } from "react"; +import { ExtensibleStoreManagerInterface, VirtualApi } from "@adobe/uix-core"; +import { GuestUI } from "@adobe/uix-guest"; + +/** + * Context container with Host object and extensions load status. + * + * @internal + */ +export type AttachContextType = { + connection: GuestUI; + storeManager: ExtensibleStoreManagerInterface; +}; + +/** + * @internal + */ +export const AttachContext = createContext( + {} as AttachContextType +); diff --git a/packages/uix-guest-react/src/components/Attach.tsx b/packages/uix-guest-react/src/components/Attach.tsx new file mode 100644 index 00000000..e0b5146c --- /dev/null +++ b/packages/uix-guest-react/src/components/Attach.tsx @@ -0,0 +1,29 @@ +import type { PropsWithChildren } from "react"; +import { AttachContext } from "../attach-context"; +import React, { useEffect, useState } from "react"; +import { attach, GuestConfigInterface, GuestUI } from "@adobe/uix-guest"; +import { ExtensibleStoreManager, VirtualApi } from "@adobe/uix-core"; + +type AttachType = { + config: GuestConfigInterface; +}; + +export const Attach = ({ children, config }: PropsWithChildren) => { + const [connection, setConnection] = useState( + undefined as GuestUI + ); + const [storeManager, setStoreManager] = useState(null); + + useEffect(() => { + setStoreManager(ExtensibleStoreManager.getInstance()); + attach(config).then((guestConnection) => { + return setConnection(guestConnection); + }); + }, []); + + return ( + + {children} + + ); +}; diff --git a/packages/uix-guest-react/src/components/index.ts b/packages/uix-guest-react/src/components/index.ts new file mode 100644 index 00000000..093e8818 --- /dev/null +++ b/packages/uix-guest-react/src/components/index.ts @@ -0,0 +1,13 @@ +/* +Copyright 2022 Adobe. All rights reserved. +This file is licensed to you under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. You may obtain a copy +of the License at http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under +the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +OF ANY KIND, either express or implied. See the License for the specific language +governing permissions and limitations under the License. +*/ + +export * from "./Attach.js"; diff --git a/packages/uix-guest-react/src/hooks/index.ts b/packages/uix-guest-react/src/hooks/index.ts new file mode 100644 index 00000000..e78cbcef --- /dev/null +++ b/packages/uix-guest-react/src/hooks/index.ts @@ -0,0 +1,2 @@ +export * from "./useHostExtensibityState.js"; +export * from "./useExtensionExtensibityState.js"; diff --git a/packages/uix-guest-react/src/hooks/useExtensibilityState.ts b/packages/uix-guest-react/src/hooks/useExtensibilityState.ts new file mode 100644 index 00000000..a54334aa --- /dev/null +++ b/packages/uix-guest-react/src/hooks/useExtensibilityState.ts @@ -0,0 +1,40 @@ +import { useEffect, useState, useContext, useCallback } from "react"; +import { AttachContext } from "../attach-context"; + +type RemoteStoreManagerType = { + getValue(key: string, scope?: string): Promise; + setValue(key: string, value: unknown, scope?: string): void; +}; + +export const useExtensibilityState = ( + key: string, + defaultState: unknown, + scope: string +): [unknown, (value: unknown) => void] => { + const [state, setState] = useState(defaultState); + const { connection, storeManager } = useContext(AttachContext); + + useEffect(() => { + void (async () => { + if (connection) { + storeManager.subscribe(key, setState, scope); + const hostStoreManager = connection.host + ?.storeManager as RemoteStoreManagerType; + const value = + (await hostStoreManager.getValue(key, scope)) || defaultState; + setState(value); + } + })(); + }, [connection]); + + const setRemoteState = useCallback( + (value: unknown) => { + const hostStoreManager = connection.host + ?.storeManager as RemoteStoreManagerType; + hostStoreManager.setValue(key, value, scope); + }, + [connection] + ); + + return [state, setRemoteState]; +}; diff --git a/packages/uix-guest-react/src/hooks/useExtensionExtensibityState.ts b/packages/uix-guest-react/src/hooks/useExtensionExtensibityState.ts new file mode 100644 index 00000000..d9c87ba2 --- /dev/null +++ b/packages/uix-guest-react/src/hooks/useExtensionExtensibityState.ts @@ -0,0 +1,8 @@ +import { useExtensibilityState } from "./useExtensibilityState"; + +export const useExtensionExtensibityState = ( + key: string, + defaultState: unknown +): [unknown, (value: unknown) => void] => { + return useExtensibilityState(key, defaultState, "extensions"); +}; diff --git a/packages/uix-guest-react/src/hooks/useHostExtensibityState.ts b/packages/uix-guest-react/src/hooks/useHostExtensibityState.ts new file mode 100644 index 00000000..a9dfa3b0 --- /dev/null +++ b/packages/uix-guest-react/src/hooks/useHostExtensibityState.ts @@ -0,0 +1,8 @@ +import { useExtensibilityState } from "./useExtensibilityState"; + +export const useHostExtensibilityState = ( + key: string, + defaultState: unknown +): [unknown, (value: unknown) => void] => { + return useExtensibilityState(key, defaultState, "default"); +}; diff --git a/packages/uix-guest-react/src/index.ts b/packages/uix-guest-react/src/index.ts new file mode 100644 index 00000000..c66cb405 --- /dev/null +++ b/packages/uix-guest-react/src/index.ts @@ -0,0 +1,15 @@ +/* +Copyright 2022 Adobe. All rights reserved. +This file is licensed to you under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. You may obtain a copy +of the License at http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under +the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS +OF ANY KIND, either express or implied. See the License for the specific language +governing permissions and limitations under the License. +*/ +export * from "./attach-context"; +export * from "./components/index.js"; +export * from "./hooks/index.js"; +export * from "@adobe/uix-guest"; diff --git a/packages/uix-guest-react/tsconfig.json b/packages/uix-guest-react/tsconfig.json new file mode 100644 index 00000000..b1aed004 --- /dev/null +++ b/packages/uix-guest-react/tsconfig.json @@ -0,0 +1,27 @@ +{ + "$schema": "http://json.schemastore.org/tsconfig", + "extends": "../../tsconfig-base.json", + "compilerOptions": { + "jsx": "react", + "outDir": "dist", + "rootDir": "src" + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "src/**/*.test.tsx?" + ], + "references": [ + { + "path": "../uix-core" + }, + { + "path": "../uix-host" + }, + { + "path": "../uix-guest" + } + ] +} + diff --git a/packages/uix-guest-react/tsup.config.cjs b/packages/uix-guest-react/tsup.config.cjs new file mode 100644 index 00000000..79d375d9 --- /dev/null +++ b/packages/uix-guest-react/tsup.config.cjs @@ -0,0 +1,6 @@ +const { defineConfig } = require("tsup"); +const { config } = require("../../configs/common-tsupconfig"); +export default defineConfig({ + ...config, + external: ["react"], +}); diff --git a/packages/uix-guest/src/guest-ui.ts b/packages/uix-guest/src/guest-ui.ts index 7d19ea55..aaf13cd3 100644 --- a/packages/uix-guest/src/guest-ui.ts +++ b/packages/uix-guest/src/guest-ui.ts @@ -16,6 +16,7 @@ import type { UIHostConnection, VirtualApi, } from "@adobe/uix-core"; +import { ExtensibleStoreManager } from "@adobe/uix-core"; import { Guest, GuestConfig, @@ -98,8 +99,15 @@ export class GuestUI extends Guest { /** * {@inheritDoc Guest."constructor"} */ + private readonly localMethods: { + broadcastToUiFrames: (key: string, value: unknown) => void; + }; constructor(config: GuestConfig) { super(config); + const storageManager = ExtensibleStoreManager.getInstance(); + this.localMethods = { + broadcastToUiFrames: storageManager.publish.bind(storageManager), + }; this.addEventListener("connected", () => { const resizeObserver = new ResizeObserver((entries) => { const doc = entries.find((entry) => entry.target === document.body); @@ -119,6 +127,13 @@ export class GuestUI extends Guest { this.logger.log("Will add resize observer on connect"); } + protected getLocalMethods() { + return { + ...super.getLocalMethods(), + apis: this.localMethods, + }; + } + /** * @internal */ diff --git a/packages/uix-guest/src/index.ts b/packages/uix-guest/src/index.ts index 345ebd68..d503c0c2 100644 --- a/packages/uix-guest/src/index.ts +++ b/packages/uix-guest/src/index.ts @@ -140,4 +140,5 @@ export { GuestUI as UIGuest, GuestServer, GuestServer as PrimaryGuest, + GuestConfig as GuestConfigInterface, }; diff --git a/packages/uix-host-react/src/components/Extensible.tsx b/packages/uix-host-react/src/components/Extensible.tsx index d4a74f93..713e9c59 100644 --- a/packages/uix-host-react/src/components/Extensible.tsx +++ b/packages/uix-host-react/src/components/Extensible.tsx @@ -21,6 +21,7 @@ import type { } from "@adobe/uix-host"; import { Host } from "@adobe/uix-host"; import { ExtensionContext } from "../extension-context.js"; +import { ExtensibleStateProvider } from "./ExtensibleState"; /** @public */ export interface ExtensibleProps extends Omit { @@ -132,7 +133,7 @@ export function Extensible({ extensionListFetched: extensionListFetched, }} > - {children} + {children} ); } diff --git a/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateApiProvider.tsx b/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateApiProvider.tsx new file mode 100644 index 00000000..26a0245a --- /dev/null +++ b/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateApiProvider.tsx @@ -0,0 +1,35 @@ +import type { FC } from "react"; +import { useExtensions } from "../../hooks"; +import { useContext } from "react"; +import { ExtensibleStateProviderContext } from "./ExtensibleStateProviderContext"; + +type CallerType = { + id: string; + url: URL; +}; + +export const ExtensibleStateApiProvider: FC = () => { + const extensibleStateProviderContext = useContext( + ExtensibleStateProviderContext + ); + useExtensions(() => ({ + updateOn: "all", + provides: { + storeManager: { + getValue(_: CallerType, key: string, scope?: string): unknown { + return extensibleStateProviderContext.storeManager.get(key, scope); + }, + setValue( + _: CallerType, + key: string, + value: unknown, + scope?: string + ): void { + extensibleStateProviderContext.storeManager.set(key, value, scope); + }, + }, + }, + })); + + return null; +}; diff --git a/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateBroadcaster.tsx b/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateBroadcaster.tsx new file mode 100644 index 00000000..7ade037b --- /dev/null +++ b/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateBroadcaster.tsx @@ -0,0 +1,37 @@ +import { useContext, useEffect } from "react"; +import { ExtensibleStateProviderContext } from "./ExtensibleStateProviderContext"; +import { useHost } from "../../hooks"; +import { Port, UiFrameType } from "@adobe/uix-host"; + +type RemoteApiType = { + apis: { + broadcastToUiFrames: (prop: string, value: unknown) => void; + }; +}; + +export const ExtensibleStateBroadcaster = (): null => { + const { storeManager } = useContext(ExtensibleStateProviderContext); + const { host } = useHost(); + + useEffect(() => { + if (host && storeManager) { + storeManager.subscribe( + "*", + (value: unknown, metadata: { subscriptionProp: string }) => { + host.guests.forEach((guest: Port): void => { + guest.uiFrames.forEach((frame: UiFrameType) => { + const remoteApi = + frame.connection.getRemoteApi() as RemoteApiType; + remoteApi.apis.broadcastToUiFrames( + metadata.subscriptionProp, + value + ); + }); + }); + } + ); + } + }, [host, storeManager]); + + return null; +}; diff --git a/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateProvider.tsx b/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateProvider.tsx new file mode 100644 index 00000000..ea653805 --- /dev/null +++ b/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateProvider.tsx @@ -0,0 +1,24 @@ +import React, { useEffect, useState } from "react"; +import { ExtensibleStateApiProvider } from "./ExtensibleStateApiProvider"; +import { ExtensibleStateBroadcaster } from "./ExtensibleStateBroadcaster"; +import { ExtensibleStateProviderContext } from "./ExtensibleStateProviderContext"; +import { ExtensibleStoreManager } from "@adobe/uix-core"; +import type { PropsWithChildren } from "react"; + +export const ExtensibleStateProvider = ({ + children, +}: PropsWithChildren) => { + const [storeManager, setStoreManager] = useState(null); + + useEffect(() => { + setStoreManager(ExtensibleStoreManager.getInstance()); + }, []); + + return ( + + + + {children} + + ); +}; diff --git a/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateProviderContext.tsx b/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateProviderContext.tsx new file mode 100644 index 00000000..a1dd6da7 --- /dev/null +++ b/packages/uix-host-react/src/components/ExtensibleState/ExtensibleStateProviderContext.tsx @@ -0,0 +1,11 @@ +import { createContext } from "react"; +import type { ExtensibleStoreManagerInterface } from "@adobe/uix-core"; + +export type ExtensibleStateProviderContextType = { + storeManager: ExtensibleStoreManagerInterface; +}; + +export const ExtensibleStateProviderContext = + createContext( + {} as ExtensibleStateProviderContextType + ); diff --git a/packages/uix-host-react/src/components/ExtensibleState/index.tsx b/packages/uix-host-react/src/components/ExtensibleState/index.tsx new file mode 100644 index 00000000..03e1ca81 --- /dev/null +++ b/packages/uix-host-react/src/components/ExtensibleState/index.tsx @@ -0,0 +1 @@ +export * from "./ExtensibleStateProvider"; diff --git a/packages/uix-host-react/src/components/GuestUIFrame.tsx b/packages/uix-host-react/src/components/GuestUIFrame.tsx index 135dc002..e330ecca 100644 --- a/packages/uix-host-react/src/components/GuestUIFrame.tsx +++ b/packages/uix-host-react/src/components/GuestUIFrame.tsx @@ -113,6 +113,7 @@ export const GuestUIFrame = ({ connecting .then((c) => { connection = c; + guest.uiFrames.push({ connection, path: src }); if (!mounted) { c.tunnel.destroy(); } else if (onConnect) { diff --git a/packages/uix-host-react/src/components/index.ts b/packages/uix-host-react/src/components/index.ts index 3e95e7da..85168378 100644 --- a/packages/uix-host-react/src/components/index.ts +++ b/packages/uix-host-react/src/components/index.ts @@ -14,3 +14,4 @@ export * from "./Extensible.js"; export * from "./GuestUIFrame.js"; export * from "./ExtensibleComponentBoundary.js"; export * from "./ExtensibleWrapper/index.js"; +export * from "./ExtensibleState/index.js"; diff --git a/packages/uix-host-react/src/hooks/index.ts b/packages/uix-host-react/src/hooks/index.ts index 473cdacf..3eca9492 100644 --- a/packages/uix-host-react/src/hooks/index.ts +++ b/packages/uix-host-react/src/hooks/index.ts @@ -13,3 +13,4 @@ governing permissions and limitations under the License. export * from "./useExtensions.js"; export * from "./useExtensionListFetched.js"; export * from "./useHost.js"; +export * from "./useExtensibilityState.js"; diff --git a/packages/uix-host-react/src/hooks/useExtensibilityState.tsx b/packages/uix-host-react/src/hooks/useExtensibilityState.tsx new file mode 100644 index 00000000..9dfddc0d --- /dev/null +++ b/packages/uix-host-react/src/hooks/useExtensibilityState.tsx @@ -0,0 +1,31 @@ +import { useCallback, useContext, useEffect, useState } from "react"; +import { ExtensibleStateProviderContext } from "../components/ExtensibleState/ExtensibleStateProviderContext"; + +export const useExtensibilityState = ( + key: string, + defaultState: unknown +): [unknown, (value: unknown) => void] => { + const { storeManager } = useContext(ExtensibleStateProviderContext); + const [state, setState] = useState(defaultState); + + useEffect(() => { + if (storeManager) { + const current = storeManager.get(key); + const def = current ?? defaultState; + storeManager.set(key, def); + storeManager.subscribe(key, (value: unknown) => { + setState(value); + }); + setState(def); + } + }, [storeManager]); + + const setExtensibleState = useCallback( + (value: unknown) => { + storeManager.set(key, value); + }, + [storeManager] + ); + + return [state, setExtensibleState]; +}; diff --git a/packages/uix-host/src/port.ts b/packages/uix-host/src/port.ts index b7b1ef9b..1bf07aac 100644 --- a/packages/uix-host/src/port.ts +++ b/packages/uix-host/src/port.ts @@ -145,6 +145,11 @@ const isWrapperFunction = (v: unknown): v is WrappedFunction => { ); }; +export type UiFrameType = { + connection: CrossRealmObject; + path: string; +}; + /** * A Port is the Host-maintained object representing an extension running as a * guest. It exposes methods registered by the Guest, and can provide Host @@ -185,6 +190,7 @@ export class Port // #region Properties (13) + public uiFrames: UiFrameType[]; private debug: boolean; private logger?: Console; private guestServerFrame: HTMLIFrameElement; @@ -253,6 +259,7 @@ export class Port this.sharedContext = config.sharedContext; this.configuration = config.configuration; this.extensionPoints = config.extensionPoints; + this.uiFrames = [] as UiFrameType[]; this.subscriptions.push( config.events.addEventListener("contextchange", async (event) => { this.sharedContext = ( diff --git a/tsconfig.json b/tsconfig.json index 4fca73dc..3e48b1c7 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -18,6 +18,9 @@ }, { "path": "packages/uix-host-react" + }, + { + "path": "packages/uix-guest-react" } ] } From f6b5ce8cbaa87de1ffd2d4063e50663f0b426d67 Mon Sep 17 00:00:00 2001 From: Vladimir Zaets Date: Tue, 11 Feb 2025 19:03:05 -0600 Subject: [PATCH 2/5] frames-communication-prototype --- packages/uix-core/src/tunnel/tunnel-messenger.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/uix-core/src/tunnel/tunnel-messenger.ts b/packages/uix-core/src/tunnel/tunnel-messenger.ts index db2ee51b..4fe44e70 100644 --- a/packages/uix-core/src/tunnel/tunnel-messenger.ts +++ b/packages/uix-core/src/tunnel/tunnel-messenger.ts @@ -74,7 +74,6 @@ export class TunnelMessenger { ); } isHandshakeOffer(message: unknown): message is HandshakeOffered { - console.log("0007 isHandshakeOffer", message); return ( this.isHandshake(message) && typeof unwrap(message as HandshakeOffered).offers === "string" From 368571133a23b590927171abcbd8b942385d0e6d Mon Sep 17 00:00:00 2001 From: Vladimir Zaets Date: Tue, 11 Feb 2025 19:04:38 -0600 Subject: [PATCH 3/5] frames-communication-prototype --- packages/uix-core/src/tunnel/tunnel.ts | 30 -------------------------- 1 file changed, 30 deletions(-) diff --git a/packages/uix-core/src/tunnel/tunnel.ts b/packages/uix-core/src/tunnel/tunnel.ts index 5053bb47..95ac53a0 100644 --- a/packages/uix-core/src/tunnel/tunnel.ts +++ b/packages/uix-core/src/tunnel/tunnel.ts @@ -156,7 +156,6 @@ export class Tunnel extends EventEmitter { let frameStatusCheck: number; let timeout: number; const offerListener = (event: MessageEvent) => { - console.log("00018 subject", event, window.location.href); if ( !tunnel.isConnected && isFromOrigin(event, target.contentWindow, config.targetOrigin) && @@ -172,7 +171,6 @@ export class Tunnel extends EventEmitter { return true; }; const cleanup = () => { - console.log("00030 cleanup"); clearTimeout(timeout); clearInterval(frameStatusCheck); window.removeEventListener("message", offerListener); @@ -245,13 +243,11 @@ export class Tunnel extends EventEmitter { logger: config.logger, }); const acceptListener = (event: MessageEvent) => { - console.log("0006 acceptListener", event, window.location.href); if ( !timedOut && isFromOrigin(event, source, config.targetOrigin) && messenger.isHandshakeAccepting(event.data, key) ) { - console.log("00020 acceptListener", event); cleanup(); if (!event.ports || !event.ports.length) { const portError = new Error( @@ -308,7 +304,6 @@ export class Tunnel extends EventEmitter { connect(remote: MessagePort) { if (this._messagePort) { - console.log("311 Connect", this._emitFromMessage); this._messagePort.removeEventListener("message", this._emitFromMessage); this._messagePort.close(); } @@ -338,33 +333,15 @@ export class Tunnel extends EventEmitter { } emit(type: string | symbol, payload?: unknown): boolean { - console.log( - "00031 emitter", - type, - payload, - window.location.href, - this._messagePort, - this.isConnected - ); if (!this._messagePort) { - console.log("00032 noport-emitter"); return false; } this._messagePort.postMessage({ type, payload }); - console.log("00033 emitter after message"); return true; } emitLocal = (type: string | symbol, payload?: unknown) => { - //@ts-ignore - console.log( - "this._listeners", - window.location.href, - this.config, - this.listeners(), - this.eventNames() - ); return emitOn.call(this, type, payload); }; @@ -404,13 +381,6 @@ export class Tunnel extends EventEmitter { // #region Private Methods private _emitFromMessage = ({ data: { type, payload } }: MessageEvent) => { - console.log( - "00033 EMIT FROM MESSAGE", - type, - payload, - window.location.href, - this - ); this.emitLocal(type, payload); }; From 556548c745522e4222955b10caadafb5fbe5250d Mon Sep 17 00:00:00 2001 From: Vladimir Zaets Date: Tue, 11 Feb 2025 19:05:55 -0600 Subject: [PATCH 4/5] frames-communication-prototype --- packages/uix-core/src/tunnel/tunnel.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/packages/uix-core/src/tunnel/tunnel.ts b/packages/uix-core/src/tunnel/tunnel.ts index 95ac53a0..0734d2c2 100644 --- a/packages/uix-core/src/tunnel/tunnel.ts +++ b/packages/uix-core/src/tunnel/tunnel.ts @@ -91,8 +91,6 @@ export class Tunnel extends EventEmitter { constructor(config: TunnelConfig) { super(); this.config = config; - //@ts-ignore - this.config.instance = Math.random(); } // #endregion Constructors @@ -168,7 +166,6 @@ export class Tunnel extends EventEmitter { ]); tunnel.connect(channel.port2); } - return true; }; const cleanup = () => { clearTimeout(timeout); @@ -254,11 +251,10 @@ export class Tunnel extends EventEmitter { "Received handshake accept message, but it did not include a MessagePort to establish tunnel" ); tunnel.emitLocal("error", portError); - return true; + return; } tunnel.connect(event.ports[0]); } - return true; }; const cleanup = () => { clearInterval(retrying); @@ -336,7 +332,6 @@ export class Tunnel extends EventEmitter { if (!this._messagePort) { return false; } - this._messagePort.postMessage({ type, payload }); return true; } From 532dc28ead9e16b39242c9a3570d4dc679f533cd Mon Sep 17 00:00:00 2001 From: Vladimir Zaets Date: Tue, 11 Feb 2025 19:09:07 -0600 Subject: [PATCH 5/5] frames-communication-prototype --- packages/uix-guest-react/src/attach-context.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/packages/uix-guest-react/src/attach-context.ts b/packages/uix-guest-react/src/attach-context.ts index 13b0be75..c1273beb 100644 --- a/packages/uix-guest-react/src/attach-context.ts +++ b/packages/uix-guest-react/src/attach-context.ts @@ -10,10 +10,6 @@ OF ANY KIND, either express or implied. See the License for the specific languag governing permissions and limitations under the License. */ -/** - * Type definition for GuestUI class - */ - import { createContext } from "react"; import { ExtensibleStoreManagerInterface, VirtualApi } from "@adobe/uix-core"; import { GuestUI } from "@adobe/uix-guest";